Pygame使用键盘输入移动形状
我创建了第一个pygame程序,目的是让一个矩形在屏幕上移动。但是我搞不懂为什么这个形状实际上没有移动。我之前用一个简单的代码是可以工作的。
shape = shape.move(speed)
但是现在加了键盘输入后,这个形状就不动了。我用了一些打印语句来确认函数checkKeys能正确识别我的按键(还有它们对速度的影响),结果是可以的。不过这个形状还是不动。
import sys, pygame
pygame.init()
size = width, height = 320, 240
black = (0, 0, 0)
red = (255, 0, 0)
pygame.display.set_caption("Object Move Test")
clock = pygame.time.Clock()
def main():
screen = pygame.display.set_mode(size)
shape = pygame.draw.rect(screen, (255, 0, 0), (200, 100, 10, 10,))
ballrect = pygame.Surface((10,10), 0, shape)
def checkKeys(speedY, speedX, shape):
key = pygame.key
pygame.event.pump()
if key.get_pressed()[pygame.K_UP] and speedY < 1:
speedY = speedY - 1
#print 'UP'
if key.get_pressed()[pygame.K_DOWN] and speedY > -1:
speedY = speedY - 1
#print 'DOWN'
if key.get_pressed()[pygame.K_LEFT] and speedX > -1:
speedX = speedX - 1
#print 'LEFT'
if key.get_pressed()[pygame.K_RIGHT] and speedX < 1:
speedX = speedX + 1
#print speedX
speed = [speedX, speedY]
#print speed
moveShape(speed, shape)
def moveShape(speed, shape):
print speed
shape = shape.move(speed)
if shape.left < 0 or shape.right > width:
speed[0] = -speed[0]
if shape.top < 0 or shape.bottom > height:
speed[1] = -speed[1]
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
speedX, speedY = (0, )*2
speed = [speedX, speedY]
screen.fill((255,255,255))
clock.tick(20)
checkKeys(speedX, speedY, shape)
screen.blit(ballrect, shape)
pygame.display.flip()
if __name__ == '__main__':
main()
1 个回答
2
我对 pygame
不是很熟悉,所以这只是我的猜测。不过,我觉得最像问题的地方是这行代码(在 moveShape
的定义里面):
shape = shape.move(speed)
这个问题的原因是 shape
是 moveShape
这个函数里面的一个局部变量,但我猜你是想通过赋值来更新一个非局部的 shape
对象(也就是在你 main()
函数顶部声明的那个)。当你调用 shape.move(speed)
时,返回的值是一个新的 pygame
Rect
对象,这个新对象被命名为 shape
。但是这个赋值是在 moveShape
函数里面进行的,所以这个更新在函数外部是看不到的。
看起来你可以用一个“就地”版本来替换这一行代码(http://www.pygame.org/docs/ref/rect.html#pygame.Rect.move_ip),这样可以直接改变对象,而不需要返回一个新的对象:
shape.move_ip(speed)
也许这样对你有帮助?