Menu
CoddyTech

Score the Gems

Part of the The Game Loop section of Coddy's Pygame journey. Lesson 15 of 35.

A game needs a score. Keep it in a variable made before the loop, score = 0, and add 1 with score += 1 each time the player catches a gem.

This game shows the score as a row of small squares, one per point. A for loop draws a row of anything: here, three circles 30 pixels apart.

for i in range(3):
    pygame.draw.circle(screen, (255, 200, 0), (20 + 30 * i, 20), 10)

On the first pass i is 0, then 1, then 2, so each circle sits 30 pixels further right. With range(score) the row grows by one each time the score does.

challenge icon

Challenge

Easy

Count the gems and show the count at the top.

  1. Add score = 0 before the loop, and add 1 to it when a click hits the gem.
  2. After drawing the gem, for each i in range(score), draw a pink (240, 110, 180) rect at (10 + 10 * i, 14, 8, 8).

Press Play and catch three gems: three pink marks line up at the top left. Then Check.

Try it yourself

import random
import pygame

pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Gem Hunt")
clock = pygame.time.Clock()

gx, gy = 225, 165

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            x, y = event.pos
            if gx <= x <= gx + 30 and gy <= y <= gy + 30:
                gx = random.randint(15, 435)
                gy = random.randint(55, 315)

    screen.fill((30, 30, 46))
    gem_points = [(gx + 15, gy), (gx + 30, gy + 15), (gx + 15, gy + 30), (gx, gy + 15)]
    pygame.draw.polygon(screen, (80, 220, 255), gem_points)
    mouse_x, mouse_y = pygame.mouse.get_pos()
    pygame.draw.circle(screen, (240, 240, 240), (mouse_x, mouse_y), 10, 2)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in The Game Loop

Practice on your own: Pygame playground