Pygame用键盘输入移动形状

时间:2014-04-29 16:21:16

标签: python pygame

创建第一个pygame程序,在屏幕周围移动一个矩形。无法弄清楚为什么形状实际上没有移动。我之前用一个简单的

工作了
  shape = shape.move(speed)

但现在使用键盘输入时,形状不会移动。我使用了一些print语句来确保函数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 个答案:

答案 0 :(得分:2)

我对pygame不太熟悉,所以这只是猜测。但是,对我来说最像问题的是这一行(在moveShape的定义内):

shape = shape.move(speed)

这是一个问题的原因是shapemoveShape中的局部变量的名称,但是我猜测你打算通过equals赋值更新非局部shape main() 1}} object(在shape.move(speed)定义顶部声明的对象。当你调用pygame时,返回值是一个新的Rect shape对象,它被赋值名称moveShape。但此分配发生在shape.move_ip(speed) 函数内部,因此更新在该范围之外不可见。

看起来你可以用&#34; inplace&#34;替换这一行。版本(http://www.pygame.org/docs/ref/rect.html#pygame.Rect.move_ip)将更改对象而不返回新对象:

{{1}}

也许那会对你有用吗?