Catch the Heart
A ship steered with the arrows catches falling hearts. Teaches telling when two sprites touch, arrow-key controls, a function with a return value and lives.
Open in Tokbit Level: Expert. Free in the browser, nothing to install, no account needed.
Run the example in Tokbit and step through it: before each step say what will happen and check it in the Variables panel. Then change it your way.
Flowchart
Python program
The same program as Python code. In Tokbit you see it when you switch from Diagram to Python above the flowchart.
"""Catch falling hearts with a ship. Teaches a sprite game, collisions and score."""
from random import randint
# Tokbit screen functions, not in plain Python:
from tokbit import (
cls, at, color, background, border, key, sleep, beep, sprite, sprite_at,
sprite_color, sprite_hide, sprite_hit, BLACK, WHITE, RED, CYAN, LIGHT_BLUE,
)
def move(x: int, k: str) -> int:
"""The ship's new position from the arrow key, no further than the screen edge."""
if k == "left":
return max(0, x - 16)
if k == "right":
return min(304, x + 16)
return x
def draw_field():
"""Black screen, the ship and heart sprites and the control hint."""
background(BLACK)
border(BLACK)
cls()
sprite(0, "ship")
sprite_color(0, CYAN)
sprite(1, "heart")
sprite_color(1, RED)
color(LIGHT_BLUE)
at(0, 2)
print("Left and right arrows, catch the hearts!", end="")
def show_status(score: int, lives: int):
"""Prints the score and lives left at the top."""
color(WHITE)
at(0, 0)
print("Score:", score, " ", "Lives:", lives, " ", end="")
def game_over(score: int):
"""End of the game: hides the heart and prints the final score."""
sprite_hide(1)
color(WHITE)
at(15, 11)
print("GAME OVER", end="")
at(14, 13)
print("Score:", score, end="")
at(0, 15)
draw_field()
lx: int = 152
hx: int = randint(0, 304)
hy: int = 0
score: int = 0
lives: int = 3
# Game loop: move the ship and the heart, check the catch and score while lives last.
while lives > 0:
lx = move(lx, key())
hy = hy + 2 + score // 5
sprite_at(0, lx, 176)
sprite_at(1, hx, hy)
if sprite_hit(0, 1):
score = score + 1
beep(880, 30)
hx = randint(0, 304)
hy = 0
else:
if hy > 199:
lives = lives - 1
beep(110, 150)
hx = randint(0, 304)
hy = 0
show_status(score, lives)
sleep(30)
game_over(score)