Random Numbers
Part of the Python in a Game Window section of Coddy's Pygame journey. Lesson 28 of 32.
Python's random module picks numbers by chance. Import it at the top of the program, above or below import pygame:
import randomrandom.randint(a, b) gives a whole number from a to b, both ends included. random.choice(items) picks one item of a list:
x = random.randint(20, 620)
size = random.choice([3, 4, 5])Each call picks again, so call it at the moment you need a new value. A star placed by Space:
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
x = random.randint(20, 620)
y = random.randint(60, 300)
stars.append((x, y))Note the double brackets in stars.append((x, y)): append takes one item, and the item is the tuple (x, y). Pick x and y once before the game loop instead, and every star lands on the same spot.
Challenge
MediumLet Space scatter stars:
- Add
import randomat the top. - When a
KEYDOWNevent forK_SPACEarrives, pickx = random.randint(20, 620)andy = random.randint(60, 300), and append(x, y)tostars. - Clicks still add stars as before.
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 = []
font = pygame.font.Font(None, 36)
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.
for star in stars:
pygame.draw.circle(screen, (255, 255, 255), star, 5)
text = font.render(f"Stars: {len(stars)}", True, (230, 230, 240))
screen.blit(text, (20, 20))
pygame.display.flip()
clock.tick(60)
pygame.quit()
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python in a Game Window
Practice on your own: Pygame playground