问题描述
我正在为我学校的计算机俱乐部制作一些Mario. (以及,作为团队的一部分.)无论如何,我在使用"keyup/keydown"命令时遇到了一些麻烦.这是我的代码:
I'm making a little Mario for my school's Computer Club. (well, as part of a team.)Anyway, I'm having some trouble with the "keyup/keydown" commands. Here's my code:
# 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命令发生,然后再次移动.所以基本上我必须快速按下按钮才能移动.
Basically, the problem is that when I press a key down, it waits for the keyup command to happen before moving again. So basically I have to rapidly press down the buttons to move.
我删除了一些代码,所以如果有什么遗漏,请告诉我,我会告诉你是否有.
I deleted some of the code, so if something is missing, let me know and I'll tell you whether or not I have it.
推荐答案
缩进问题.您需要在主游戏循环中而不是在事件循环中测试关键状态.您需要UNINDENT键状态测试一级.
Indenting problem. You need to test your key states in you main game loop not in your event loop. You need to UNINDENT your keystate test one level.
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)
这篇关于Pygame Keyup/Keydown的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!