我正在制作一个pygame游戏,玩家并不总是移动到我按下的箭头键。这是移动播放器的代码。
def playerstuff(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
self.XChange = 3
if event.key == pygame.K_LEFT:
self.XChange = -3
if event.key == pygame.K_DOWN:
self.TownYChange = -5
if event.key == pygame.K_UP:
self.TownYChange = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
self.XChange = 0
if event.key == pygame.K_LEFT:
self.XChange = 0
if event.key == pygame.K_DOWN:
self.TownYChange = 0
if event.key == pygame.K_UP:
self.TownYChange = 0
if self.TownYChange != 0:
self.TownY += self.TownYChange
gameDisplay.blit(Town,(0,self.TownY))
self.Xpos += self.XChange
gameDisplay.blit(Town,(self.Xpos,self.Ypos),pygame.Rect(self.Xpos,self.Ypos,40,50))
gameDisplay.blit(Idle_man,(self.Xpos,self.Ypos))
pygame.display.update()
这是制作关卡并执行其他操作的代码
def game():
gameDisplay.blit(Town,(0,0))
player1 = Player(width/2,height/2 - 20)
while True:
player1.playerstuff()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
clock.tick(60)
pygame.display.update()
我也遇到过这条线的问题:
gameDisplay.blit(Town,(self.Xpos,self.Ypos),pygame.Rect(self.Xpos,self.Ypos,40,50))
我想用这一行来删除角色并重绘他。 这条线做了我想做的事情,但是当我踩到背景的绿色部分时,它会用灰色填充玩家周围的空间。
答案 0 :(得分:0)
您可能会在全局事件队列中丢弃事件。您检查事件队列两次,一次在playerstuff()
,一次在您的全局游戏循环中,但第二次您不处理按键事件。
def game():
gameDisplay.blit(Town,(0,0))
player1 = Player(width/2,height/2 - 20)
while True:
player1.playerstuff() # you check the event queue in this method already
for event in pygame.event.get():
# gets all the events that are currently in the queue, meaning all
# that occured since you last checked the queue in playerstuff()
if event.type == pygame.QUIT:
pygame.quit()
quit()
# if event.type was a keypress, you dismiss the event here,
# causing you to "lose" keystrokes
clock.tick(60)
pygame.display.update()
解决方案是只有一个全局事件队列并处理那里的所有按键。