好的,这是我目前的程序:
bif="bg.jpg"
mif="pkmn.png"
import pygame
import sys
from pygame.locals import *
pygame.init()
screen=pygame.display.set_mode ((600,375),0,32)
background=pygame.image.load(bif).convert()
mouse_c=pygame.image.load(mif).convert_alpha()
x,y=0,0
movex, movey=0,0
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type==KEYDOWN:
if event.key==K_LEFT:
movex=-1
elif event.key==K_RIGHT:
movex=+1
elif event.key==K_UP:
movey=-1
elif event.key==K_DOWN:
movey=+1
if event.type==KEYUP:
if event.key==K_LEFT:
movex=0
elif event.key==K_RIGHT:
movex=0
elif event.key==K_UP:
movey=0
elif event.key==K_DOWN:
movey=0
x+=movex
y+=movey
screen.blit(background,(0,0))
screen.blit(mouse_c,(x,y))
pygame.display.update()问题是,即使我可以向各个方向移动,例如我按右箭头键,它向右移动,如果我一直按住右箭头键,按住左箭头键,它就会向左移动,问题是:当我放开右键时,即使是向左键,我的精灵也停止了。
我知道问题是,无论是向右还是向左,x都是0。
我想要能够保持右和右,然后保持左和左,但释放左和右,因为我持有右
我希望我能解释一下,我已经尝试了所有的方法,到处搜索,请帮助我,如果有人能修改我的代码,并展示给我看,这样我就可以分析它了,那就太好了。
谢谢
发布于 2013-06-02 00:52:10
试试这个:
import pygame
import sys
from pygame.locals import *
bif="bg.jpg"
mif="pkmn.png"
pygame.init()
FPS = 30 # changed for FPS
FPSCLOCK = pygame.time.Clock() # changed for FPS
screen = pygame.display.set_mode ((600,375),0,32)
background = pygame.image.load(bif).convert()
mouse_c = pygame.image.load(mif).convert_alpha()
move_speed = 5 # changed for FPS
x, y = 0, 0
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pressed = pygame.key.get_pressed()
if pressed[K_LEFT]:
x -= move_speed
if pressed[K_RIGHT]:
x += move_speed
if pressed[K_UP]:
y -= move_speed
if pressed[K_DOWN]:
y += move_speed
screen.blit(background,(0,0))
screen.blit(mouse_c,(x,y))
pygame.display.update()
FPSCLOCK.tick(FPS) # changed for FPS编辑1: I正在运行您的代码,并且注意到您没有任何FPS监视--您只是以CPU能够处理的最大速度运行代码。这将导致以后的问题,所以我添加了代码,以确保您的FPS不会超过30。
编辑2:,我的旧代码太复杂了;既然您已经同意,保持左和右不应该做任何事情;这将是有效的。(而且它也会更易读,这有助于保护您不受bug的影响)
https://stackoverflow.com/questions/16878588
复制相似问题