Twinkle
Part of the Python in a Game Window section of Coddy's Pygame journey. Lesson 30 of 32.
Real stars flicker. Here each star dims for a single frame now and then, by chance. On every frame, each star rolls a number from 1 to 30, and on a 1 it is drawn dim:
for star in stars:
colour = (255, 255, 255)
if random.randint(1, 30) == 1:
colour = (110, 120, 170)
pygame.draw.circle(screen, colour, star, 3)colour starts white for each star, and the if changes it only on a 1. One frame in 30 is about twice a second for each star, and every star rolls its own number, so they flicker at different moments. That small, uneven change is what makes the sky look alive.
Add import random at the top of the program. A random roll belongs in the draw loop here because the choice must be made again on every frame, for every star.
Challenge
MediumMake the stars twinkle:
- Add
import randomat the top. - In the star loop, start each star's
colouras white(255, 255, 255). - When
random.randint(1, 30) == 1, make it dim(110, 120, 170). - Draw the star with
colour.
Try it yourself
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Night Sky")
clock = pygame.time.Clock()
# Set things up here, before the game loop.
stars = []
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
stars.append(event.pos)
# Change things here, once a frame.
screen.fill((20, 24, 48))
# Draw here, after the fill.
pygame.draw.circle(screen, (240, 230, 160), (560, 80), 40)
pygame.draw.rect(screen, (14, 16, 30), (0, 430, 640, 50))
for star in stars:
pygame.draw.circle(screen, (255, 255, 255), star, 3)
pygame.display.flip()
clock.tick(60)
pygame.quit()
All lessons in Python in a Game Window
Practice on your own: Pygame playground