Menu
CoddyTech

A Full Sky

Part of the Python in a Game Window section of Coddy's Pygame journey. Lesson 32 of 32.

The game ends when the sky holds twenty stars. Two things change: clicks stop adding stars, and a message says so. Both read the same list:

if event.type == pygame.MOUSEBUTTONDOWN and len(stars) < 20:
    stars.append(event.pos)
if len(stars) == 20:
    message = font.render("The sky is full!", True, (230, 230, 240))
    screen.blit(message, message.get_rect(center=(320, 240)))

message.get_rect(center=(320, 240)) is the rectangle of the text picture, placed with its middle at (320, 240). Blitting at it puts the text in the centre of the window, whatever its length.

Test == 20 here, not > 20: the limit stops the list at 20, so it never holds more.

With the sky full there is nothing left to do but look at it. Section 2 shows how to start a game over with a key, and how to end a game with a win or a loss.

challenge icon

Challenge

Medium

Finish Night Sky:

  1. Append a star on a click only while len(stars) < 20.
  2. When len(stars) == 20, show The sky is full! in (230, 230, 240), centred at (320, 240).

Try it yourself

import random
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.
    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:
        colour = (255, 255, 255)
        if random.randint(1, 30) == 1:
            colour = (110, 120, 170)
        pygame.draw.circle(screen, colour, star, 3)
    text = font.render(f"Stars: {len(stars)}/20", True, (230, 230, 240))
    screen.blit(text, (20, 20))

    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in Python in a Game Window

Practice on your own: Pygame playground