Ball

A ball sprite bounces off the screen edges. Teaches sprites, point coordinates and a loop.

Open in Tokbit Level: Intermediate. 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

Flowchart of the Ball example

Python program

The same program as Python code. In Tokbit you see it when you switch from Diagram to Python above the flowchart.

"""A ball bounces off the screen edges. Teaches a sprite and moving in a loop."""
# Tokbit screen functions, not in plain Python:
from tokbit import (
    cls, at, color, background, border, sleep, beep, sprite, sprite_at,
    sprite_color, BLACK, WHITE, BLUE, YELLOW,
)

background(BLACK)
border(BLUE)
cls()
color(WHITE)
at(1, 1)
print("The ball bounces off the edges.", end="")
sprite(0, "ball")
sprite_color(0, YELLOW)
x: int = 20
y: int = 40
dx: int = 3
dy: int = 2
while True:
    x = x + dx
    y = y + dy
    # At the edge the direction flips: 304 = 320 minus the sprite width 16.
    if x <= 0 or x >= 304:
        dx = -dx
        beep(330, 20)
    if y <= 0 or y >= 184:
        dy = -dy
        beep(440, 20)
    sprite_at(0, x, y)
    # A short pause sets the speed of the motion.
    sleep(20)

Follow-up tasks

Tasks in which you change the example (with a model solution):

All examples