简体   繁体   中英

Pygame display only updates when I quit

Fiddling around with pygame and I'm not sure what's happening. code is just supposed to make a red box and bounce it around a gray screen. It works, but only when I quit the display.

I've checked out questions that are similar but none seem to have an answer that applies to me (might be wrong about that). Does anyone know how this code could be improved?

import pygame
from pygame.locals import *
from rect import *
##from pygame.font import *

RED = (255, 0, 0)
GRAY = (150, 150, 150)

width = 500
height = 200

pygame.init()

screen = pygame.display.set_mode((width, height))

rect = Rect(100, 50, 50, 50)
v = [2, 2]

##moving = False
running = True

while running:
    for event in pygame.event.get():
        if event.type == QUIT:
            running = False
   
    rect.move_ip(v)

    if rect.left < 0 or rect.right > width:
        v[0] *= -1
    if rect.top < 0 or rect.bottom > height:
        v[1] *= -1

    screen.fill(GRAY)
    pygame.draw.rect(screen, RED, rect)
    pygame.display.flip()
    
pygame.quit()

It seems that the problem is the program running too fast. Since so little work is being done in each loop, the rectangle ends up moving around too quickly to clearly see what is happening.

You can restrict the speed of the program using a pygame.time.Clock object. Before the start of your loop, probably right after your screen definition, you can construct a clock.

clock = pygame.time.Clock()

Then in your main loop, as the very first step each iteration (right after while running: ) you can put clock.tick(60) to restrict the loop to running 60 times per second (60fps). This makes the program run smoothly, and you get the nice bouncing rectangle!

The tick method works well, but on my system it seems to have small hitches every so often. If you also experience this or if you want to be more accurate, you can use clock.tick_busy_loop(60) instead.

Both of these tick methods work the same way: By measuring the amount of time that passed since the last call to clock.tick() and delaying a certain additional amount based on that so that the target fps will be met.

More info on Clock at Pygame docs .

I also needed to import pygame.rect instead of just import rect , but if you're not getting an import error you should be fine.

I've figured it out. Stupidly I had another file in my test directory named "rect.py", I changed the file name and my code to from pygame.rect import * and it's working fine now. Thank you Baked Potato for the help and for making me wonder where x=50, y=60, w=200, h=80 left=50, top=60, right=250, bottom=140 center=(150, 100) was coming from!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM