我正在尝试为我的简单数独解算器程序添加图形。我希望程序在求解数独棋盘时实时更新显示的数独棋盘(我想我应该在每个正确求解的数字之后调用draw_number
函数,然后延迟程序,这样它就会绘制数字,暂停,然后继续求解)。
然而,取而代之的是,程序在冻结时解决了整个问题,然后在完成时立即显示整个解决方案。
下面是一个小规模的示例,展示了我想要做的事情,它说明了这个问题:
import pygame
pygame.init()
window = pygame.display.set_mode((600, 600))
board = [
[1,2,3],
[7,5,6],
[4,9,8],
]
def draw_number(r, c, num):
font = pygame.font.Font('freesansbold.ttf', 26)
text = font.render(str(num), True, (0, 0, 0), (255, 255, 255))
text_rect = text.get_rect()
text_rect.center = ((c+1)*48+11, (r+1)*48+11)
window.blit(text, text_rect)
print("Drawing " + str(num) + " at " + str(r+1) + ", " + str(c+1))
pygame.display.update()
run = True
while run:
for i in board:
for j in range(0, 3):
draw_number(board.index(i), j, board[board.index(i)][j])
pygame.display.update()
pygame.time.delay(20)
run = False
pygame.time.delay(5000)
当我们运行此命令时,简单的3x3网格应该单独绘制,并带有暂停,但它会完成for循环,然后暂停5000ms,然后显示结果一秒钟,然后关闭程序。
我知道我在这里做错了什么,但我还是个新手,不确定正确的方法是什么。
发布于 2020-01-24 00:40:30
问题是,当您执行pygame.time.delay()时,它会冻结整个pygame窗口。为了防止出现这种情况,您需要导入time模块,然后使用time.sleep(秒)而不是pygame.time.delay(),下面是一些代码:
import pygame
import time
然后(跳过不相关的部分):
run = True
while run:
for i in board:
for j in range(0, 3):
draw_number(board.index(i), j, board[board.index(i)][j])
time.sleep(5)
发布于 2020-01-24 03:03:24
PyGame对程序使用事件驱动模型。代码不应该调用time.sleep()
或pygame.time.delay()
等,因为它会暂停程序。如果暂停的时间足够长,窗口管理器将认为程序已停止响应。
解决这个问题的一种简单方法是使用pygame.time.get_ticks()
对操作计时,它会返回自pygame程序启动以来不断增加的毫秒数。设计你的程序,让它看着时钟来决定下一步要做什么。
假设你只想每3秒执行一次操作。查看开始时间,执行操作,但在3000毫秒过去之前,不要再做任何事情(除了轮询事件和更新屏幕)。
例如:
def doTheThing():
pass # TODO: some super-interesting function
time_we_did_the_thing = 0 # When did we last do the thing
clock = pygame.time.Clock()
running = True
while running:
# check for events
for event in pygame.event.get():
if ( event.type == pygame.QUIT ):
running = False
# paint the screen
screen.fill( ( 0, 40, 200 ) ) # bluish
# Do the thing, but only every 3 seconds
time_now = pygame.time.get_ticks()
if ( time_now > time_we_did_the_thing + 3000 ):
doTheThing()
time_we_did_the_thing = time_now
# flush the screen-updates
pygame.display.flip()
clock.tick_busy_loop(60) # max FPS=60
pygame.quit()
https://stackoverflow.com/questions/59888769
复制