如何在Pygame中实现随机颜色正方形先放大再缩小后留黑屏
实现Pygame中小→大→小的随机颜色正方形动画
Hey there! Let's get your Pygame animation working the way you want—small square → grow to full size → shrink back to tiny → final black screen. Your original code had a reversed loop for the growing phase and some messy logic in the shrinking step, which is why you were seeing it shrink first instead of grow.
Fixed Code
import pygame import random pygame.init() black = (0, 0, 0) screen_size = (700, 700) screen = pygame.display.set_mode(screen_size) clock = pygame.time.Clock() # Controls how fast the animation plays # Step 1: Grow square from tiny to full screen for size in range(0, screen_size[0] + 1): # Make sure the window doesn't freeze (let users close it normally) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit() # Pick a random RGB color rand_color = (random.randint(0,255), random.randint(0,255), random.randint(0,255)) # Draw the square starting at top-left corner, current size pygame.draw.rect(screen, rand_color, (0, 0, size, size)) pygame.display.flip() clock.tick(60) # Change this to 30 for slower, 120 for faster animation # Optional: Pause at full size for half a second pygame.time.wait(500) # Step 2: Shrink square from full screen back to tiny for size in range(screen_size[0], -1, -1): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit() rand_color = (random.randint(0,255), random.randint(0,255), random.randint(0,255)) # Clear the screen to black first so we don't leave leftover square bits screen.fill(black) pygame.draw.rect(screen, rand_color, (0, 0, size, size)) pygame.display.flip() clock.tick(60) # Final step: Show black screen for 2 seconds before quitting screen.fill(black) pygame.display.flip() pygame.time.wait(2000) pygame.quit()
What Changed & Why
- Growing Loop: We use
range(0, 701)to start at size 0 and count up to 700—this makes the square grow from nothing to full screen, which was the first part you were missing. - Proper Event Handling: Added small event loops in each phase so the window doesn't become unresponsive. You can close it anytime by clicking the X now.
- Clean Shrinking: Instead of messy nested loops, we reverse the range to count down from 700 to 0. We also fill the screen with black each time before drawing the smaller square, so the shrinking looks smooth instead of leaving trails.
- Controlled Speed: The
clock.tick(60)keeps the animation at a consistent 60 frames per second—tweak this number if you want it faster or slower. - Final Black Screen: After shrinking, we fill the screen one last time and pause for 2 seconds so you can see the final black state before the program quits.
内容的提问来源于stack exchange,提问作者kitty kat 0057
相关产品推荐
相关产品推荐

