I followed a simple pygame tutorial on 2 different OS's and the program runs at very different speeds on each OS. I am running windows 8.1 as a guest in virtualbox with Mac OSX 10.9 as the host. In the mac, the program runs what I would assume to be normal speed. In the windows computer, it runs really fast. Too fast. It actually slows down the rest of the OS. When I click the close button it takes a few seconds to close. The code and the version of python are the same on both OS's. Python 3.3.4. Here is the code:

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

It is a simple program that just loads a ball image and has the ball move across the screen. Once it hits the edge of the screen, it bounces in the opposite direction. Simple enough. In the guest Windows OS, it flies across the screen way too quickly. In my host OS (mac OSX), it runs fine. I have no idea if this is a Windows issue, a python/pygame issue, or a virtualbox issue...

有帮助吗?

解决方案

To set a constant framerate in pygame, use Clock.tick

FRAMERATE = 30
clock = pygame.time.Clock()

while True:
    clock.tick(FRAMERATE)
    for event in pygame.event.get():
        ...

From the documentation:

[tick] should be called once per frame. It will compute how many milliseconds have passed since the previous call.

If you pass the optional framerate argument the function will delay to keep the game running slower than the given ticks per second. This can be used to help limit the runtime speed of a game. By calling Clock.tick(40) once per frame, the program will never run at more than 40 frames per second.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top