我正在为学校的电脑俱乐部制作一个小马里奥。(作为团队的一部分。)无论如何,我在使用"keyup/keydown"命令时遇到了一些问题。这是我的代码:
# 1 - Import library
import pygame
from pygame.locals import *
# 2 - Initialize the game
pygame.init()
width, height = 1280, 1000
screen=pygame.display.set_mode((width, height))
keys = [False, False, False, False]
playerpos=[100,100]
# 3 - Load images
player = pygame.image.load("images/totallynotgodzilla.png")
# 3.1 - Load Audio
music = pygame.mixer.Sound("audio/skyrim.wav")
# 4 - keep looping through
while 1:
# 5 - clear the screen before drawing it again
screen.fill(0)
# 6 - draw the screen elements
screen.blit(player, playerpos)
# 7 - update the screen
pygame.display.flip()
# 8 - loop through the events
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key==K_w:
keys[0]=True
elif event.key==K_a:
keys[1]=True
elif event.key==K_s:
keys[2]=True
elif event.key==K_d:
keys[3]=True
if event.type == pygame.KEYUP:
if event.key==pygame.K_w:
keys[0]=False
elif event.key==pygame.K_a:
keys[1]=False
elif event.key==pygame.K_s:
keys[2]=False
elif event.key==pygame.K_d:
keys[3]=False
# 9 - Move player
if keys[0]:
playerpos[1]-=5
elif keys[2]:
playerpos[1]+=5
if keys[1]:
playerpos[0]-=5
elif keys[3]:
playerpos[0]+=5
基本上,问题是当我按下一个键时,它会等待keyup命令发生,然后再移动。所以基本上我必须快速按下按钮才能移动。
我删除了一些代码,所以如果缺少什么,请告诉我,我会告诉你我是否有。
缩进问题。你需要在主游戏循环中测试你的关键状态,而不是在事件循环中。您需要将密钥状态测试统一到一个级别。
while 1:
# do init stuff
screen.fill(0)
# .... (all main loop init stuff here)
for event in pygame.event.get():
# test events, set key states
if event.type == pygame.KEYDOWN:
if event.key==K_w:
keys[0]=True
# .... (all event stuff)
# Indent moves back to main game loop
# test key states here...
if keys[0]:
playerpos[1]-=5
elif keys[2]:
playerpos[1]+=5
# .... (and so on)