我目前正在尝试在项目中使用 pygame,但无论我做什么,我都无法让窗口保持打开状态。我把它放在一个 while 循环中,唯一打破循环的应该是用户关闭窗口。我个人也没有看到任何缩进问题。我可以在这里做什么来让我的窗口保持打开状态?相关代码如下
def create_grid(rows, width):
grid = []
gap = width // rows
for i in range(rows):
grid.append([])
for j in range(rows):
node = Node(i, j, gap, rows)
grid[i].append(node)
return grid
def draw_grid(win, rows, width):
gap = width // rows
for i in range(rows):
pygame.draw.line(win, GREY, (0, i * gap), (width, i * gap))
for j in range(rows):
pygame.draw.line(win, GREY, (j * gap, 0), (j * gap, width))
def draw(win, grid, rows, width):
win.fill(WHITE)
for row in grid:
for node in row:
node.draw(win)
draw_grid(win, rows, width)
pygame.display.update()
def get_mouse_pos(pos, rows, width):
gap = width // rows
y, x = pos
row = y // gap
col = x // gap
return row, col
def main(win, width):
ROWS = 50
grid = draw_grid(ROWS, width)
start = None
end = None
run = True
started = False
while run:
draw(win, grid, ROWS, width)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if started:
continue
if pygame.mouse.get_pressed()[0]:
pos = pygame.mouse.get_pos()
row, col = get_mouse_pos(pos, ROWS, width)
node = grid[row][col]
if not start:
start = node
start.create_start()
elif not end:
end = node
end.create_end()
elif node != end and node != start:
node.create_barrier()
elif pygame.mouse.get_pressed()[2]:
pass
pygame.quit()
main(WIN, WIDTH)
您不应该在主循环中调用 create_grid 吗?我做了一些更改,请告诉我它是否有效。您可以根据您的要求进行一些调整。
def main(win, width):
ROWS = 50
grid = create_grid(ROWS, width)
start = None
end = None
run = True
started = False
while run:
draw(win, grid, ROWS, width)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if started:
continue
if pygame.mouse.get_pressed()[0]:
pos = pygame.mouse.get_pos()
row, col = get_mouse_pos(pos, ROWS, width)
node = grid[row][col]
if not start:
start = node
start.create_start()
elif not end:
end = node
end.create_end()
elif node != end and node != start:
node.create_barrier()
elif pygame.mouse.get_pressed()[2]:
pass
pygame.quit()
main(WIN, WIDTH)