#!/usr/bin/env bash # ============================================================================= # MARTIANS v1 (commented edition) # A tiny terminal arcade game: zeros fall from the sky, you catch them with a # carriage at the bottom. Catch = +10 points. Miss = lose a life (3 lives). # # The founder's first game, built with Grok as an engineering partner # (code, troubleshooting, math). Built by the Starbound crew with Grok. # # This edition keeps the original rules and adds: # - a constants block, so look and speed are easy to tweak # - a clean game loop: INPUT -> UPDATE -> RENDER -> WAIT # - a steady frame rate (keys no longer speed the game up) # - a frame around the field, an inverted flash on a miss, # a GAME OVER screen with r (restart) / q (quit) # - a terminal-size check and a clean exit that always restores the cursor # # Needs only bash (4+; 5+ for the steady frame rate) and the standard # `tput`, `stty` and `sleep` tools. No network, no files written. # # Run: bash martians_v1_commented.sh # Keys: a / d or arrow keys = move, q = quit, r = restart (on GAME OVER) # ============================================================================= # ----------------------------------------------------------------------------- # 1. CONSTANTS (change these to tune the game) # ----------------------------------------------------------------------------- FIELD_W=40 # playfield width in characters (original: width=40) FIELD_H=16 # playfield height in rows (original: height=16) CARRIAGE="=====" # what the carriage looks like (original: =====) ZERO="0" # what falls from the sky (video shows a "0") START_LIVES=3 # lives at the start (original: lives=3) POINTS=10 # points per catch (original: score += 10) SPAWN_ONE_IN=12 # new zero on ~1 frame in 12 (session: RANDOM % 12 == 0) MAX_ZEROS=1 # zeros on screen at once (video: one; session: count < 5) FRAME_SEC=0.07 # length of one frame in seconds FALL_EVERY=3 # zeros move down every 3rd frame (session: tick % 3) # fall time = FIELD_H * FALL_EVERY * FRAME_SEC # = 16 * 3 * 0.07 s = about 3.4 s (video: 3-4 s) FLASH_FRAMES=3 # how many frames the screen stays inverted after a miss CARRIAGE_W=${#CARRIAGE} # carriage width, from its text FRAME_US=$(( 10#${FRAME_SEC/./} * 10000 )) # 0.07 -> 70000 microseconds # (assumes exactly two decimals in FRAME_SEC) # Screen layout (rows/columns are 0-based, like `tput cup row col`): # row 0 : Score (left) and Lives (right) # row 1 : top of the frame +----+ # rows 2..FIELD_H+1 : the sky where zeros fall # row FIELD_H+2 : the carriage # row FIELD_H+3 : bottom of the frame TOP=2 # first sky row on screen CARRIAGE_ROW=$(( TOP + FIELD_H )) # the row the carriage lives on NEED_COLS=$(( FIELD_W + 2 )) # field + left and right border NEED_ROWS=$(( FIELD_H + 4 )) # HUD + border + sky + carriage + border # Escape codes for the inverted flash (same as `tput rev` / `tput sgr0`). REV=$(tput rev 2>/dev/null || printf '\033[7m') NORM=$(tput sgr0 2>/dev/null || printf '\033[0m') # ----------------------------------------------------------------------------- # 2. TERMINAL SETUP AND CLEAN EXIT # ----------------------------------------------------------------------------- cleanup() { # Runs on every exit path (q, Ctrl+C, errors): put the terminal back. printf '%s' "$NORM" tput cnorm 2>/dev/null # show the cursor again stty echo 2>/dev/null # typed keys are visible again tput cup "$(( NEED_ROWS ))" 0 2>/dev/null printf '\n' } trap cleanup EXIT trap 'exit 130' INT TERM # Ctrl+C -> exit -> cleanup runs via EXIT trap check_terminal_size() { local cols rows cols=$(tput cols 2>/dev/null || echo 80) rows=$(tput lines 2>/dev/null || echo 24) if (( cols < NEED_COLS || rows < NEED_ROWS )); then echo "Terminal too small: need ${NEED_COLS}x${NEED_ROWS}, have ${cols}x${rows}." echo "Make the window bigger and run again." trap - EXIT exit 1 fi } # ----------------------------------------------------------------------------- # 3. GAME STATE # ----------------------------------------------------------------------------- new_game() { score=0 lives=$START_LIVES carriage=$(( (FIELD_W - CARRIAGE_W) / 2 )) # start in the middle zero_x=() # x position (column) of each falling zero zero_y=() # y position (row inside the sky) of each zero tick=0 # frame counter: used for "move every Nth frame" flash=0 # frames left of the inverted flash } # ----------------------------------------------------------------------------- # 4. INPUT: read at most one key per frame, never block for long # ----------------------------------------------------------------------------- # Sets $key to: left, right, quit, restart, or "" (nothing pressed). read_key() { local k rest key="" # -s: don't echo, -n1: one character, -t: give up after one frame. if IFS= read -rsn1 -t "$FRAME_SEC" k; then if [[ $k == $'\033' ]]; then # Arrow keys arrive as three characters: ESC [ C (right) / ESC [ D (left). # (The very first version read only one character, so an arrow key # leaked its last letter into the game. The founder kept that quirk as a # "feature of the first game"; this edition reads the whole sequence.) IFS= read -rsn2 -t 0.01 rest case $rest in '[D') key=left ;; '[C') key=right ;; esac else case $k in a|A) key=left ;; d|D) key=right ;; q|Q) key=quit ;; r|R) key=restart ;; esac fi fi } # ----------------------------------------------------------------------------- # 5. UPDATE: move things and apply the rules (no drawing here) # ----------------------------------------------------------------------------- update() { # 5.1 Move the carriage, clamped to the field (no wrap-around). case $key in left) (( carriage > 0 )) && (( carriage-- )) ;; right) (( carriage < FIELD_W - CARRIAGE_W )) && (( carriage++ )) ;; esac # 5.2 Sometimes drop a new zero on the top row. # RANDOM is 0..32767; "RANDOM % 12 == 0" is true about 1 time in 12. if (( RANDOM % SPAWN_ONE_IN == 0 && ${#zero_x[@]} < MAX_ZEROS )); then zero_x+=( $(( RANDOM % (FIELD_W - 1) )) ) zero_y+=( 0 ) fi # 5.3 Zeros fall only every FALL_EVERY-th frame, so the carriage stays quick # while zeros fall slowly (the fix from the build session: tick % 3). if (( tick % FALL_EVERY == 0 )); then local i kept_x=() kept_y=() for i in "${!zero_x[@]}"; do local x=${zero_x[i]} y=$(( zero_y[i] + 1 )) if (( y >= FIELD_H )); then # Landed. Caught if it is over the carriage: carriage <= x < carriage + width if (( x >= carriage && x < carriage + CARRIAGE_W )); then (( score += POINTS )) else (( lives-- )) flash=$FLASH_FRAMES # start the inverted flash fi # A landed zero is not kept (this replaces unset + re-pack of the arrays). else kept_x+=( "$x" ); kept_y+=( "$y" ) fi done zero_x=( "${kept_x[@]}" ); zero_y=( "${kept_y[@]}" ) fi (( tick++ )) } # ----------------------------------------------------------------------------- # 6. RENDER: build the whole frame in one string, then print it once # (printing once per frame avoids the flicker of `clear` + many prints) # ----------------------------------------------------------------------------- render() { local on="" row col line i buf AT (( flash > 0 )) && { on=$REV; (( flash-- )); } # HUD: Score on the left, Lives on the right. local left="Score: $score" right="Lives: $lives" printf -v line '%s%*s' "$left" $(( NEED_COLS - ${#left} )) "$right" at 0 0; buf="$AT$on$line$NORM" # Frame top. printf -v line '+%*s+' "$FIELD_W" ''; line=${line// /-} at 1 0; buf+="$AT$on$line$NORM" # Sky rows: start with spaces, then drop each zero into its column. for (( row = 0; row < FIELD_H; row++ )); do printf -v line '%*s' "$FIELD_W" '' for i in "${!zero_y[@]}"; do if (( zero_y[i] == row )); then col=${zero_x[i]} line="${line:0:col}$ZERO${line:col+1}" fi done at $(( TOP + row )) 0; buf+="$AT$on|${line}|$NORM" done # Carriage row. printf -v line '%*s%s%*s' "$carriage" '' "$CARRIAGE" $(( FIELD_W - carriage - CARRIAGE_W )) '' at "$CARRIAGE_ROW" 0; buf+="$AT$on|${line}|$NORM" # Frame bottom. printf -v line '+%*s+' "$FIELD_W" ''; line=${line// /-} at $(( CARRIAGE_ROW + 1 )) 0; buf+="$AT$on$line$NORM" printf '%s' "$buf" } # Cursor-move escape code (same as `tput cup row col`, but without starting a # new process for every row, which would be too slow at ~14 frames a second). at() { printf -v AT '\033[%d;%dH' $(( $1 + 1 )) $(( $2 + 1 )); } # Centred text on a given screen row. center() { local row=$1 text=$2 tput cup "$row" $(( (NEED_COLS - ${#text}) / 2 )) printf '%s' "$text" } # ----------------------------------------------------------------------------- # 7. GAME OVER: show the score and wait for r or q # ----------------------------------------------------------------------------- game_over() { render center $(( TOP + FIELD_H / 2 - 2 )) " GAME OVER " center $(( TOP + FIELD_H / 2 )) " Score: $score " center $(( TOP + FIELD_H / 2 + 2 )) " Press 'r' to restart or 'q' to quit " local k while IFS= read -rsn1 k; do case $k in r|R) return 0 ;; # play again q|Q) return 1 ;; # leave the game esac done return 1 # input closed: leave } # ----------------------------------------------------------------------------- # 8. MAIN: the game loop INPUT -> UPDATE -> RENDER -> WAIT # ----------------------------------------------------------------------------- main() { check_terminal_size stty -echo 2>/dev/null tput civis 2>/dev/null clear local start now spent while true; do new_game while (( lives > 0 )); do start=${EPOCHREALTIME/./} # microseconds (bash 5+; empty on bash 4) read_key # INPUT (waits up to one frame) [[ $key == quit ]] && exit 0 update # UPDATE render # RENDER # WAIT: a key press ends `read` early; sleep the rest of the frame so # the game runs at the same speed whether or not keys are pressed. if [[ -n $start ]]; then now=${EPOCHREALTIME/./} spent=$(( now - start )) if (( spent < FRAME_US )); then sleep "0.$(printf '%06d' $(( FRAME_US - spent )))" fi fi done game_over || exit 0 clear done } main "$@"