import pygame
# Initializations
game = True
pygame.init()
FPS = 30
clock = pygame.time.Clock()
# Screen
screen = pygame.display.set_mode((600,800))
screen.fill((0,0,0))
# Player
pX = 300
pY = 400
pClr = ((255,255,255))
def Player(plr):
pygame.draw.rect(screen, pClr, plr)
while game:
player = pygame.Rect(pX,pY,25,25)
for event in pygame.event.get():
if event.type == pygame.QUIT:
game = False
if event.type == pygame.KEYDOWN:
while event.key == pygame.K_RIGHT:
pX -= 50
Player(player)
clock.tick(FPS)
pygame.display.update()
由于某种原因,当我按右键时,它不会移动播放器,但在打印时它工作得很好。很抱歉在这里问这个初学者问题。
尝试重新绘制希望它移动的玩家,但无济于事。
将此行中的
while
更改为 if
while event.key == pygame.K_RIGHT:
像这样:
if event.key == pygame.K_RIGHT:
因为
event.key
值不会改变此帧,所以带有 while
的代码只会运行无限循环。
并且您需要添加
screen.fill((0, 0, 0)
在绘制任何东西之前,因为否则矩形会显示一条轨迹
import pygame
# Initializations
game = True
pygame.init()
FPS = 30
clock = pygame.time.Clock()
# Screen
screen = pygame.display.set_mode((600,800))
screen.fill((0,0,0))
# Player
pX = 300
pY = 400
pClr = ((255,255,255))
def Player(plr):
pygame.draw.rect(screen, pClr, plr)
while game:
player = pygame.Rect(pX,pY,25,25)
for event in pygame.event.get():
if event.type == pygame.QUIT:
game = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
pX -= 50
screen.fill((0, 0, 0))
Player(player)
clock.tick(FPS)
pygame.display.update()
pygame.display.quit()
pygame.quit()