Night flight

A demo in the style of old home computers: scrolling text, stars in three layers, a drawn moon and mountains, a rocket and UFOs on a wave and fireworks, all to the beat of the music. Teaches functions, lists, sin, sprites and drawing.

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

Flowchart of the Night flight 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 demo in the style of the Amiga and C64: five scenes, the music is the animation's clock. Teaches functions, lists, sin, sprites and drawing."""
from random import randint, choice
from math import sin, cos, radians
# Tokbit screen functions, not in plain Python:
from tokbit import (
    cls, at, color, background, border, sleep, beep, note, sprite, sprite_at,
    sprite_color, sprite_hide, sprite_shape, plot, line, circle, BLACK, WHITE,
    RED, CYAN, PURPLE, GREEN, BLUE, YELLOW, ORANGE, DARK_GREY, GREY,
    LIGHT_GREEN, LIGHT_BLUE, LIGHT_GREY,
)

def wave_table() -> list[int]:
    """A demoscene trick: wave values (sine) are computed once at the start, then only read from the list."""
    t: list[int] = []
    for i in range(64):
        t.append(round(40 * sin(radians(i * 360 / 64))))
    return t

def frame_note(chords: list[list[str]], frame: int, octave: int) -> str:
    """Music is the demo's clock: each frame plays one note of a broken chord, shifted by the given number of octaves."""
    chord: list[str] = chords[frame // 8 % len(chords)]
    pitch: str = chord[[0, 1, 2, 1][frame % 4]]
    height: str = ""
    for i in range(len(pitch) - 1):
        height = height + pitch[i]
    return height + str(int(pitch[len(pitch) - 1]) + octave)

def stars(hx: list[int], hy: list[int], frame: int):
    """Moves and draws the stars in three layers at different speeds."""
    chars: list[str] = [".", "+", "*"]
    colors: list[int] = [DARK_GREY, GREY, WHITE]
    for i in range(len(hx)):
        layer: int = i % 3
        # Parallax: near stars (layer 2) move every frame, far ones only every fourth.
        if frame % [4, 2, 1][layer] == 0:
            hx[i] = hx[i] - 1
            if hx[i] < 0:
                hx[i] = 39
        color(colors[layer])
        at(hx[i], hy[i])
        print(chars[layer], end="")

def scroller(text: str, offset: int, row: int, shade: int):
    """Scrolling text: a 39-character window into the looping text, one character further each frame."""
    window: str = ""
    for i in range(39):
        window = window + text[(offset + i) % len(text)]
    color(shade)
    at(0, row)
    print(window, end="")

def backdrop(frame: int):
    """The drawn background: tiny stars made of points, a crescent moon and an outline of mountains made of lines. cls() clears the drawing, so it is drawn again every frame."""
    color(GREY)
    # Stars made of points: multiplying with a remainder works out where they go (a demoscene trick instead of a list); every frame they move one point to the left.
    for i in range(40):
        plot((i * 97 - frame) % 320, i * 53 % 128 + 4)
    # A crescent moon: a yellow circle with a black one over it, shifted a little to the side.
    color(YELLOW)
    circle(272, 36, 18, True)
    color(BLACK)
    circle(281, 30, 16, True)
    # The mountain outline: lines between peaks 40 points apart, moving slower than the stars (parallax).
    peaks: list[int] = [160, 136, 150, 124, 146, 132, 156, 140]
    offset: int = frame // 2
    color(PURPLE)
    for i in range(9):
        x: int = i * 40 - offset % 40
        j: int = (i + offset // 40) % len(peaks)
        line(x, peaks[j], x + 40, peaks[(j + 1) % len(peaks)])

def intro(chords: list[list[str]]):
    """Scene 1: title, colour bars and scrolling text."""
    colors: list[int] = [BLUE, LIGHT_BLUE, CYAN, WHITE, CYAN, LIGHT_BLUE, BLUE, PURPLE]
    title: str = "TOKBIT  DEMO"
    text: str = "*** TOKBIT DEMO *** NIGHT FLIGHT *** GRAPHICS AND SOUND FROM A FLOWCHART *** GREETINGS TO EVERYONE WHO CODES *** "
    # The scene loop: one pass = one frame; the note at the end decides how long the frame lasts.
    for s in range(96):
        cls()
        # Colour bars made of characters: the colours shift by one row every frame.
        for r in range(6):
            color(colors[(r + s) % len(colors)])
            at(0, r + 2)
            print("=" * 40, end="")
            at(0, 17 - r)
            print("=" * 40, end="")
        at(14, 10)
        # Colour cycling: each letter of the title has its own colour and the colours rotate.
        for i in range(len(title)):
            color(colors[(i + s) % len(colors)])
            print(title[i], end="")
        scroller(text, s, 22, YELLOW)
        note(frame_note(chords, s, 0), 140)

def starfield(chords: list[list[str]], hx: list[int], hy: list[int]):
    """Scene 2: starry sky with parallax."""
    text: str = "*** STARS IN THREE LAYERS: NEAR ONES FLY FASTER THAN FAR ONES *** "
    for s in range(96):
        cls()
        backdrop(s)
        stars(hx, hy, s)
        scroller(text, s, 23, LIGHT_BLUE)
        note(frame_note(chords, s, 1), 150)

def flyby(chords: list[list[str]], hx: list[int], hy: list[int], wave: list[int], shape: list[str]):
    """Scene 3: a rocket with a custom shape flies through the stars along a wave."""
    sprite_shape(0, shape)
    sprite_color(0, LIGHT_GREY)
    for s in range(128):
        cls()
        backdrop(s)
        stars(hx, hy, s)
        # The rocket flies right and up and down along the wave.
        sprite_at(0, s * 3 - 30, 84 + wave[s * 2 % 64])
        if s % 4 < 2:
            sprite_color(0, YELLOW)
        else:
            sprite_color(0, ORANGE)
        note(frame_note(chords, s, 1), 150)
    sprite_hide(0)

def ufo_scene(chords: list[list[str]], hx: list[int], hy: list[int], wave: list[int]):
    """Scene 4: a UFO formation and the moon."""
    colors: list[int] = [GREEN, LIGHT_GREEN, CYAN, YELLOW, PURPLE]
    for k in range(5):
        sprite(k + 1, "alien")
    for s in range(128):
        cls()
        backdrop(s)
        stars(hx, hy, s)
        # The UFO formation on a wave, each a bit further in phase; colours cycle.
        for k in range(5):
            sprite_at(k + 1, 330 - s * 3 + k * 36, 60 + wave[(s * 3 + k * 10) % 64])
            sprite_color(k + 1, colors[(s // 2 + k) % len(colors)])
        note(frame_note(chords, s, 0), 150)
    for k in range(5):
        sprite_hide(k + 1)

def explosion(cx: int, cy: int, r: int, shade: int, ch: str):
    """A ring of stars with radius r around the centre; doubled horizontally because characters are narrow."""
    color(shade)
    for k in range(8):
        x: int = cx + round(2 * r * cos(radians(k * 45)))
        y: int = cy + round(r * sin(radians(k * 45)))
        if 0 <= x <= 39 and 0 <= y <= 23:
            at(x, y)
            print(ch, end="")

def finale(hx: list[int], hy: list[int]):
    """Scene 5: fireworks, the caption and a fanfare."""
    colors: list[int] = [RED, YELLOW, LIGHT_GREEN, CYAN, PURPLE, WHITE, ORANGE]
    # Fireworks: fourteen bursts at random places, the rings expand and the sound falls.
    for v in range(14):
        cx: int = randint(8, 31)
        cy: int = randint(4, 15)
        shade: int = choice(colors)
        for r in range(8):
            cls()
            backdrop(v * 8 + r)
            stars(hx, hy, r)
            explosion(cx, cy, r, shade, "*")
            if r > 0:
                explosion(cx, cy, r - 1, shade, ".")
            beep(900 - r * 90, 60)
            sleep(40)
    cls()
    over: str = "T H E   E N D"
    fanfare: list[str] = ["C4", "E4", "G4", "C5", "G4", "C5"]
    lengths: list[int] = [150, 150, 150, 400, 150, 900]
    # The final caption and a fanfare.
    for i in range(len(fanfare)):
        color(colors[i % len(colors)])
        at(20 - len(over) // 2, 11)
        print(over, end="")
        note(fanfare[i], lengths[i])
    color(WHITE)

background(BLACK)
border(BLACK)
cls()
# The rocket's shape: a 16 × 16 grid, open the block and redraw it.
rocket: list[str] = ["................", "................", "...##...........", "...###..........", "....###.........", ".#...#######....", "..############..", "...#######..###.", "...#######..###.", "..############..", ".#...#######....", "....###.........", "...###..........", "...##...........", "................", "................"]
# The chords: A minor, F major, C major, G major.
chords: list[list[str]] = [["A3", "C4", "E4"], ["F3", "A3", "C4"], ["C4", "E4", "G4"], ["G3", "B3", "D4"]]
wave: list[int] = wave_table()
# Stars: columns and rows.
hx: list[int] = []
hy: list[int] = []
for i in range(24):
    hx.append(randint(0, 39))
    hy.append(randint(0, 21))
intro(chords)
starfield(chords, hx, hy)
flyby(chords, hx, hy, wave, rocket)
ufo_scene(chords, hx, hy, wave)
finale(hx, hy)

All examples