我试图使一个块向上移动,向下,向右和向左。在教程中,我遵循这段代码工作正常。我已经检查了这段代码很多次,但无法找到任何错误。
代码编译正确,但它没有按预期工作,也没有在终端窗口中显示任何错误。
import pygame
import time
pygame.init()
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
display_width = 800
display_height = 600
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('slither')
clock = pygame.time.Clock()
block_size = 10
FPS = 30
font = pygame.font.SysFont(None,25)
def message_to_screen(msg,color):
screen_text = font.render(msg,True,color)
gameDisplay.blit(screen_text, [display_width/2, display_height/2])
def gameLoop():
gameExit = False
gameOver = False
lead_x = display_width/2
lead_y = display_height/2
lead_x_change = 0
lead_y_change = 0
while not gameExit:
while gameOver == True:
gameDisplay.fill(white)
message_to_screen("Game over press c to play again or Q to quit",True,red)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
gameExit = True
gameOver = False
if event.key == pygame.K_c:
gameLoop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
lead_x_change = block_size
lead_y_change = 0
elif event.key == pygame.K_LEFT:
lead_x_change = -block_size
lead_y_change = 0
elif event.key == pygame.K_UP:
lead_y_change = -block_size
lead_x_change = 0
elif event.key == pygame.K_DOWN:
lead_y_change = block_size
lead_x_change = 0
if lead_x <=0 or lead_x >= display_width or lead_y <= 0 or lead_y >= display_height:
gameExit = True
lead_x += lead_x_change
lead_y += lead_y_change
gameDisplay.fill(white)
pygame.draw.rect(gameDisplay,red,[lead_x,lead_y,block_size,block_size])
pygame.display.update()
clock.tick(FPS)
pygame.quit()
quit()
gameLoop()
1条答案
按热度按时间8fsztsew1#
问题是多个事件循环。注意,
pygame.event.get()
从que中删除事件。因此只有第一个循环获取事件,第二个循环不会获取任何事件。每帧只获取一次事件:此外,永远不要递归地调用游戏循环,也不要在游戏循环中实现游戏循环。你有一个游戏循环,使用它。如果游戏结束,然后设置
gameOver = True
。根据gameOver
的状态绘制场景:当游戏结束并按下c键时重置游戏状态
gameloop
: