[英]Pygame.display.update() not updating on every iteration of while loop
我正在使用 PyGame 创建一个跳棋游戏,并且在每个玩家移动后屏幕更新都有问题。 本质上,我使用了一个名为“board”的矩阵,它是屏幕上所有位置的底层数据结构。 每次有人移动时,棋盘矩阵都会更新并使用 draw_board() 显示在屏幕上。 屏幕应该在 while 循环的每次迭代后更新,但由于某种原因,它仅在两个玩家都移动后才会改变(while 循环的两次迭代)。 我一直试图解决这个问题几个小时,但无法弄清楚。 这是我的代码。 抱歉,如果不清楚或有太多内容,我不确定如何捕捉整个问题。
board = matrix of 0 (empty space), 1 (red piece), 2 (blue piece)
def draw_board(board):
'''
Updates the position of the pieces on the board after every move, by copying the board array
'''
draw_background() # we must make the board blank before drawing the pieces again, or else the old positions will remain drawn
screen = pygame.display.get_surface()
radius = 20
i = 0
for row in board:
j = 0
for space in row:
if space == 1:
pygame.draw.circle(screen, red, getPixels(j,i), radius)
elif space == 2:
pygame.draw.circle(screen, blue, getPixels(j,i), radius)
j+=1
i+=1
while True:
# human's turn
if game.turn == 'red':
awaiting_red = True
while awaiting_red:
for event in pygame.event.get():
if event.type == pygame.QUIT: # if window close button clicked then leave game loop
break
if event.type == pygame.MOUSEBUTTONDOWN and second_click == False: # click piece to move
# some code removed here to select a piece
second_click = True
elif event.type == pygame.MOUSEBUTTONDOWN and second_click == True: # click new position for piece
# some code removed here to select a new position
my_color = board[piece_selected.sprite.y_pos][piece_selected.sprite.x_pos]
board[piece_selected.sprite.y_pos][piece_selected.sprite.x_pos] = 0
board[space_selected.sprite.y_pos][space_selected.sprite.x_pos] = my_color
second_click = False
awaiting_red = False
# computer's turn
elif game.turn == 'blue':
move = game.get_move(board)
# updating the board matrix
for i in range(8): # x position
for j in range(8): # y position
new_space = move[0][j][i]
board[j][i] = new_space
# for some reason the screen doesn't update until after both players have made moves?? can't figure out how to fix this
draw_board(board)
pygame.display.update()
game.change_turn()
pygame.quit()
任何帮助表示赞赏。 谢谢!
这发生在我试图创建原始 Countdown 应用程序的精确副本时。 发生这种情况是因为我在循环中到处使用time.sleep
。 所以我通过在time.sleep
之前和之后更新屏幕来修复它,并且只要我可以。 这样做也可能会修复您的程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.