我正在嘗試在 pygame (python 3) 中重新創建蛇,我想做的是每一幀,通過檢查按鍵來檢查蛇的速度,但它很少意識到我正在按下一個鍵,我做錯了什么/我應該怎么做(代碼在下面),我不明白為什么這不起作用,因為其他所有東西都可以立即運行,例如 clear 函數,甚至 handle() 做的事情非常相似,所以它使得我不知道為什么它不起作用import pygamefrom pygame.locals import *import mathimport randompygame.init()display = pygame.display.set_mode((512, 512))pygame.display.set_caption("Snake")display.fill((255, 255, 255))def handle(): global x, y for event in pygame.event.get(): if event.type == QUIT: pygame.quit()def make_apple(): x, y = random.randint(0, 502), random.randint(0, 502) pygame.draw.rect(display, (255, 0, 0), (x, y, 10, 10)) return x, y# -- COLLISION DETECTION -- #def r(fox, foy, cR, sox, soy): dx = abs(fox - sox) dy = abs(foy - soy) if dx < cR and dy < cR: return True else: return Falsedef clear(aX, aY): global x, y display.fill((255, 255, 255)) pygame.draw.rect(display, (255, 0, 0), (aX, aY, 10, 10)) draw_snake(x, y)def draw_snake(x, y): pygame.draw.rect(display, (0, 255, 0), (x, y, 10, 10))def set_vel(): for event in pygame.event.get(): if event.type == KEYDOWN: print("KEY") if event.key == K_LEFT: yVel = 0 xVel = -1 elif event.key == K_RIGHT: yVel = 0 xVel = 1 elif event.key == K_UP: yVel = -1 xVel = 0 elif event.key == K_DOWN: yVel = 1 xVel = 0 return xVel, yVel return 0, 0def update_pos(x, y, xV, yV): x += xV y += yV return x, yaX, aY = make_apple()x, y = 256, 256length = 1eaten = Falsewhile True: velX, velY = set_vel() clear(aX, aY) handle() x, y = update_pos(x, y, velX, velY) if eaten: aX, aY = make_apple() eaten = False pygame.display.update() if r(x, y, 3, aX, aY): display.fill((255, 255, 255)) eaten = True
查看完整描述