所以这就是我到目前为止所拥有的...

import pygame


BLACK    = (   0,   0,   0)
WHITE    = ( 255, 255, 255)
GREEN    = (   0, 255,   0)
RED      = ( 255,   0,   0)


width  = 20
height = 20


margin = 5

grid = []
for row in range(10):

    grid.append([])
    for column in range(10):
        grid[row].append(0) 

pygame.init()


size = [255, 255]
screen = pygame.display.set_mode(size)



done = False


clock = pygame.time.Clock()

#Main Program Loop
while done == False:
    for event in pygame.event.get(): 
        if event.type == pygame.QUIT: 
            done = True
        elif event.type == pygame.MOUSEBUTTONDOWN:

            pos = pygame.mouse.get_pos()

            column = pos[0] // (width + margin)
            row = pos[1] // (height + margin)

            grid[row][column] = 1
            grid[row+1][column+1] = 1
            grid[row-1][column-1] = 1
            grid[row-1][column] = 1
            grid[row+1][column] = 1
            grid[row][column+1] = 1
            grid[row][column-1] = 1
            grid[row-1][column+1] = 1
            grid[row+1][column-1] = 1

            print("Click ", pos, "Grid coordinates: ", row, column)

    # Set the screen background
    screen.fill(BLACK)


    for row in range(10):
       for column in range(10):
            color = WHITE
            if grid[row][column] == 1:
                color = RED
            pygame.draw.rect(screen,
                             color,
                             [(margin+width)*column+margin,
                              (margin+height)*row+margin,
                              width,
                              height])


    clock.tick(90)



    pygame.display.flip()

pygame.quit()

现在,当我单击边缘或拐角附近的任意位置时,它将继续显示在网格的另一侧,而当我直接单击拐角时,程序将崩溃。 有任何想法吗? 单击角落和边缘时,如何使其正常工作? 谢谢

===============>>#1 票数:0

您的代码根本不处理任何特殊情况。

当您的行或列等于0并从中减去1时,结果相反。 之所以发生这种情况,是因为正如jonrsharpe所评论的,索引-1代表最后一项。 因此grid [-1] [-1]表示grid [9] [9]。 解决该问题的最简单方法是在必要时添加一些if语句,例如:

if row > 0 and column > 0:
     grid[row-1][column-1] = 1

程序崩溃,显示一个非常具体的错误:

IndexError:列表索引超出范围

它与上一个问题非常相似,仅这次,当您选择row == 9或column == 9时,程序还会尝试访问grind [row + 1] [x]或grind [x] [column + 1]不存在。 因此,您还需要检查它是否不是最后一个索引:

if row < 9 and column < 9:
     grid[row+1][column+1] = 1

因此,这是您的简单解决方法:

grid[row][column] = 1
if row < 9 and column < 9:
    grid[row+1][column+1] = 1
if row > 0 and column > 0:
    grid[row-1][column-1] = 1
if row > 0:
    grid[row-1][column] = 1
if row < 9:
    grid[row+1][column] = 1
if column < 9:
    grid[row][column+1] = 1
if column > 0:
    grid[row][column-1] = 1
if row > 0 and column < 9:
    grid[row-1][column+1] = 1
if row < 9 and column > 0:
    grid[row+1][column-1] = 1

  ask by Ferubs translate from so

未解决问题?本站智能推荐: