MmmHmm
MmmHmm

Reputation: 3785

pygame only updates when mouse active over game window?

Just getting started with pygame (python 2.7, win7, i3) and looking at the tutorial here: http://www.pygame.org/docs/tut/intro/intro.html

When I run the code example:

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()

...from IDLE or powershell, the game window only updates when the mouse is actively moving over the game window. I was expecting that the ball would simply bounce around on its own. Is this mouse--position related performance due to the way pygame/SDL deal with graphics modes? Is it related to the hardware? Is there a way to improve the performance through the code? I'd like to get the proverbial ball rolling with pygame and this seems... odd. Thank you.

edit:

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()

Upvotes: 3

Views: 2420

Answers (1)

emorphus
emorphus

Reputation: 560

You have the update code INSIDE the function! Move it out like this and it will work.

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()

Upvotes: 3

Related Questions