pygame仅在鼠标在游戏窗口上激活时才会更新?

时间:2016-04-23 01:45:01

标签: python-2.7 pygame

刚开始使用pygame(python 2.7,win7,i3)并在这里查看教程:http://www.pygame.org/docs/tut/intro/intro.html

当我运行代码示例时:

import sys, pygame
pygame.init()

size = width, height = 320, 240
speed = [2, 2]
black = 0, 0, 0

screen = pygame.display.set_mode(size)

ball = pygame.image.load('ball.bmp')
ballrect = ball.get_rect()

while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()

        ballrect = ballrect.move(speed)
        if ballrect.left < 0 or ballrect.right > width:
            speed[0] = -speed[0]
        if ballrect.top < 0 or ballrect.bottom > height:
            speed[1] = -speed[1]

        screen.fill(black)
        screen.blit(ball, ballrect)
        pygame.display.flip()

...来自IDLE或powershell,游戏窗口仅在鼠标主动移动到游戏窗口时才会更新。我期待球会自行弹跳。由于pygame / SDL处理图形模式的方式,鼠标位置是否相关?它与硬件有关吗?有没有办法通过代码提高性能?我想让这个众所周知的球与pygame一起滚动,这看起来很奇怪。谢谢。

编辑:

while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()

    ballrect = ballrect.move(speed)
    if ballrect.left < 0 or ballrect.right > width:
        speed[0] = -speed[0]
    if ballrect.top < 0 or ballrect.bottom > height:
        speed[1] = -speed[1]

    screen.fill(black)
    screen.blit(ball, ballrect)
    pygame.display.flip()

1 个答案:

答案 0 :(得分:1)

你有更新代码INSIDE功能!像这样把它移出来它会起作用。

while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()

        ballrect = ballrect.move(speed)
        if ballrect.left < 0 or ballrect.right > width:
            speed[0] = -speed[0]
        if ballrect.top < 0 or ballrect.bottom > height:
            speed[1] = -speed[1]

    screen.fill(black)
    screen.blit(ball, ballrect)
    pygame.display.flip()