#!/usr/bin/env python3
"""
Yanky Doodle's Shooting Gallery - a colonial fair amusement, Anno 1776
theyankydoodle.com
One file, pure Pygame, no pictures or sound files needed.
Run: python yanky_shooting_gallery.py (or: py yanky_shooting_gallery.py)
"""
# ======================= EASY SETTINGS (edit me) ===========================
# Where the online scoreboard lives. Change this if the website moves.
API_BASE = 'https://theyankydoodle.com/gallery/api'
# ===========================================================================
import os
import sys
import math
import json
import time
import queue
import random
import asyncio
import pygame
# Running inside a web browser (pygbag / WebAssembly)?
IS_WEB = sys.platform == 'emscripten'
if IS_WEB:
import platform as _platform # pygbag's bridge to the browser
WINDOW = _platform.window
else:
WINDOW = None
import threading
import webbrowser
import urllib.request
import urllib.error
# A tester can point the game at another server without editing the file.
API_BASE = os.environ.get('YANKY_API_BASE', API_BASE).rstrip('/')
SITE_BASE = API_BASE[:-4] if API_BASE.endswith('/api') else API_BASE
if IS_WEB:
# In the browser the game lives at .../gallery/play/, next to the API.
try:
SITE_BASE = str(WINDOW.eval("new URL('../', document.baseURI || location.href).href")).rstrip('/')
except Exception:
SITE_BASE = '..'
API_BASE = SITE_BASE + '/api'
REGISTER_URL = SITE_BASE + '/register.php'
LEADERBOARD_URL = SITE_BASE + '/leaderboard.php'
CLICK_GUARD = 0.3 # seconds after a screen change during which menu clicks are ignored
def web_log(msg, error=False):
"""Browser only: write a line to the developer console (so problems are never silent)."""
if not IS_WEB:
return
try:
if error:
WINDOW.console.error('YANKY ' + msg)
else:
WINDOW.console.log('YANKY ' + msg)
except Exception:
pass
def test_env(name, default=''):
"""Self-test settings: environment variables on a PC, localStorage['yanky_selftest'] in a browser."""
if IS_WEB:
try:
cfg = json.loads(str(WINDOW.eval("localStorage.getItem('yanky_selftest') || '{}'")))
return str(cfg.get(name, default))
except Exception:
return default
return os.environ.get(name, default)
CLIENT_VERSION = '1.0'
NET_FAIL = "Couldn't reach scoreboard."
# --------------------------------------------------------------------------
# Game rules
# --------------------------------------------------------------------------
W, H = 960, 600
FPS = 60
GAME_SECONDS = 90
START_LIVES = 3
ESCAPE_PENALTY = 5 # points lost when a good target gets away
POINTS = {'squirrel': 30, 'deer': 20, 'bear': 50}
SHOTS_TO_DROP = {'squirrel': 1, 'deer': 2, 'bear': 3} # balls needed to knock each one down
# Streak bonuses, counted on knock-downs in a row (a miss or a bonnet hit breaks them).
# Point bonuses are multiples of 5 and stay inside the scoreboard's 30-points-per-hit check.
DEER_STREAK_BONUS = 60 # three deer in a row
SBD_STREAK_BONUS = 80 # squirrel, then bear, then deer, in a row
# Screen layout
VALANCE_BOTTOM = 92
RAIL1_Y = 212
RAIL2_Y = 322
FENCE_TOP = 396
COUNTER_Y = 516
PLAY_LEFT, PLAY_RIGHT = 86, 874
# Palette: navy, brick red, cream, gold, wood browns, parchment
NAVY = (30, 44, 78); NAVY_D = (18, 27, 50)
BRICK = (158, 52, 38); BRICK_D = (108, 34, 26)
CREAM = (240, 228, 196); WHITE = (250, 246, 234)
PARCH = (236, 220, 178); PARCH_D = (208, 184, 134); PARCH_DD = (176, 150, 102)
GOLD = (200, 154, 56); GOLD_L = (234, 198, 108); GOLD_D = (150, 110, 36)
WOOD = (132, 88, 50); WOOD_L = (172, 122, 74); WOOD_D = (86, 56, 32); WOOD_DD = (60, 38, 22)
INK = (38, 26, 18)
INDIGO = (46, 60, 112); MADDER = (172, 62, 48)
GREEN = (110, 118, 70); GREEN_D = (80, 88, 52)
EARTH = (192, 158, 106); EARTH_D = (160, 126, 80)
SKIN = (234, 198, 162); SKIN_D = (196, 150, 112)
RUST = (172, 94, 50); RUST_L = (200, 124, 70)
TAN = (186, 132, 78); TAN_D = (150, 102, 60)
BEAR_C = (96, 62, 40); BEAR_D = (72, 46, 30); BEAR_L = (156, 112, 72)
BASKET = (190, 150, 80)
IRON = (74, 72, 70)
STRAW = (222, 186, 110)
CHARACTERS = [
dict(key='boy', name='Master Tom', title='The Boy', weapon='Wooden popgun',
reload=1.2, sight=15,
lines=['Wooden popgun', 'Reload: 1.2 s (fastest)', 'Sight: small ring']),
dict(key='girl', name='Miss Patience', title='The Girl', weapon='Wooden popgun',
reload=1.4, sight=19,
lines=['Wooden popgun', 'Reload: 1.4 s', 'Sight: medium ring']),
dict(key='yankee', name='Mr. Yankee', title='The Grown-up Yankee', weapon='Brass spyglass',
reload=1.8, sight=27,
lines=['Brass spyglass piece', 'Reload: 1.8 s (slowest)', 'Sight: big ring']),
]
# --------------------------------------------------------------------------
# Small helpers
# --------------------------------------------------------------------------
_FONTS = {}
def font(size, bold=False):
key = (size, bold)
if key not in _FONTS:
f = None
try:
if IS_WEB:
raise RuntimeError('no system fonts in the browser')
f = pygame.font.SysFont('georgia,bookantiqua,palatinolinotype,timesnewroman,dejavuserif',
size, bold=bold)
except Exception:
f = None
if f is None:
f = pygame.font.Font(None, int(size * 1.3))
f.set_bold(bold)
_FONTS[key] = f
return _FONTS[key]
def text(surf, s, size, color, pos, anchor='center', bold=False, shadow=None, alpha=255):
img = font(size, bold).render(str(s), True, color)
r = img.get_rect(**{anchor: (int(pos[0]), int(pos[1]))})
if shadow:
sh = font(size, bold).render(str(s), True, shadow)
if alpha < 255:
sh.set_alpha(alpha)
surf.blit(sh, r.move(2, 2))
if alpha < 255:
img.set_alpha(alpha)
surf.blit(img, r)
return r
def text_wrap(surf, s, size, color, center_x, y, max_w, bold=False, line_h=None):
words, lines, cur = str(s).split(), [], ''
for wd in words:
trial = (cur + ' ' + wd).strip()
if font(size, bold).size(trial)[0] <= max_w or not cur:
cur = trial
else:
lines.append(cur)
cur = wd
if cur:
lines.append(cur)
line_h = line_h or int(size * 1.3)
for i, ln in enumerate(lines):
text(surf, ln, size, color, (center_x, y + i * line_h), bold=bold)
return len(lines)
def hatch(surf, rect, color, spacing=6, width=1, slope=1.0):
r = pygame.Rect(rect)
old = surf.get_clip()
surf.set_clip(r.clip(old) if old else r)
for i in range(-r.h * 2, r.w + r.h, spacing):
pygame.draw.line(surf, color, (r.x + i, r.bottom), (r.x + i + int(r.h * slope), r.y), width)
surf.set_clip(old)
def wood_rect(surf, rect, base, rng, vertical=False, outline=INK, knots=True, ow=2):
"""A rough-hewn plank with grain lines."""
r = pygame.Rect(rect)
pygame.draw.rect(surf, base, r)
dark = tuple(max(0, c - 28) for c in base)
light = tuple(min(255, c + 18) for c in base)
length = r.h if vertical else r.w
across = r.w if vertical else r.h
n = max(2, across // 6)
for k in range(n):
off = int((k + 0.5) * across / n) + rng.randint(-1, 1)
amp = rng.uniform(0.5, 2.0)
freq = rng.uniform(0.02, 0.06)
ph = rng.uniform(0, 6.28)
pts = []
for t in range(0, length + 1, 6):
d = off + amp * math.sin(t * freq + ph)
pts.append((r.x + d, r.y + t) if vertical else (r.x + t, r.y + d))
if len(pts) > 1:
pygame.draw.lines(surf, dark if k % 2 == 0 else light, False, pts, 1)
if knots and length > 60 and rng.random() < 0.7:
t = rng.randint(15, length - 15)
c = (r.x + across // 2, r.y + t) if vertical else (r.x + t, r.y + across // 2)
kr = pygame.Rect(0, 0, max(4, across // 3), max(3, across // 5)) if not vertical else \
pygame.Rect(0, 0, max(3, across // 5), max(4, across // 3))
kr.center = c
pygame.draw.ellipse(surf, dark, kr)
pygame.draw.ellipse(surf, WOOD_DD, kr, 1)
if outline:
pygame.draw.rect(surf, outline, r, ow)
class Pen:
"""Draws shapes in 'unit' coordinates, scaled and moved, with ink outlines."""
def __init__(self, surf, x, y, s=1.0, flip=False):
self.surf, self.x, self.y, self.s, self.flip = surf, x, y, s, flip
def p(self, dx, dy):
return (round(self.x + (-dx if self.flip else dx) * self.s), round(self.y + dy * self.s))
def w(self, ow):
return 0 if ow == 0 else max(1, round(ow * self.s))
def poly(self, col, pts, ow=2, oc=INK):
P = [self.p(*q) for q in pts]
pygame.draw.polygon(self.surf, col, P)
if ow:
pygame.draw.polygon(self.surf, oc, P, self.w(ow))
def rect(self, col, x0, y0, x1, y1, ow=2, oc=INK):
self.poly(col, [(x0, y0), (x1, y0), (x1, y1), (x0, y1)], ow, oc)
def ell(self, col, cx, cy, rx, ry, ow=2, oc=INK):
r = pygame.Rect(0, 0, max(2, round(2 * rx * self.s)), max(2, round(2 * ry * self.s)))
r.center = self.p(cx, cy)
pygame.draw.ellipse(self.surf, col, r)
if ow:
pygame.draw.ellipse(self.surf, oc, r, self.w(ow))
def circ(self, col, cx, cy, r, ow=2, oc=INK):
self.ell(col, cx, cy, r, r, ow, oc)
def line(self, col, a, b, width=2):
pygame.draw.line(self.surf, col, self.p(*a), self.p(*b), self.w(width))
def lines(self, col, pts, width=2):
pygame.draw.lines(self.surf, col, False, [self.p(*q) for q in pts], self.w(width))
def arc(self, col, cx, cy, rx, ry, a0, a1, width=2):
r = pygame.Rect(0, 0, max(2, round(2 * rx * self.s)), max(2, round(2 * ry * self.s)))
r.center = self.p(cx, cy)
if self.flip:
a0, a1 = math.pi - a1, math.pi - a0
pygame.draw.arc(self.surf, col, r, a0, a1, self.w(width))
# --------------------------------------------------------------------------
# Characters (drawn with primitives). (x, y) = point between the feet.
# --------------------------------------------------------------------------
def draw_popgun(pen, hx, hy, angle=0.0):
# a wooden tube with a cork on a string and a plunger handle
ca, sa = math.cos(angle), math.sin(angle)
def r(dx, dy):
return (hx + dx * ca - dy * sa, hy + dx * sa + dy * ca)
pen.poly(WOOD_L, [r(-14, -4), r(34, -4), r(34, 4), r(-14, 4)], 2)
pen.poly(WOOD_D, [r(-22, -2), r(-14, -2), r(-14, 2), r(-22, 2)], 1)
pen.poly(WOOD, [r(-25, -5), r(-21, -5), r(-21, 5), r(-25, 5)], 1)
pen.ell(STRAW, *r(37, 0), 3.5, 3.5, 1)
pen.lines(INK, [r(37, 3), r(30, 10), r(20, 6)], 1)
for k in (0, 12, 24):
pen.line(WOOD_D, r(k, -4), r(k, 4), 1)
def draw_boy(surf, x, y, s=1.0, arm=0.0):
pen = Pen(surf, x, y, s)
pen.ell(INK, -9, -4, 8, 4, 0); pen.ell(INK, 9, -4, 8, 4, 0)
pen.rect(CREAM, -12, -34, -3, -5, 2); pen.rect(CREAM, 3, -34, 12, -5, 2)
pen.rect(WOOD, -14, -54, 14, -32, 2)
pen.line(GOLD, (-12, -36), (-4, -36), 2); pen.line(GOLD, (4, -36), (12, -36), 2)
pen.rect(WHITE, -16, -84, 16, -52, 2) # shirt
pen.poly(BRICK, [(-14, -82), (-3, -82), (-3, -52), (-14, -52)], 2) # waistcoat halves
pen.poly(BRICK, [(3, -82), (14, -82), (14, -52), (3, -52)], 2)
for by in (-76, -68, -60):
pen.circ(GOLD, 0, by, 1.6, 1)
pen.rect(WHITE, -24, -82, -15, -58, 2) # left arm
pen.circ(SKIN, -19, -56, 4, 1)
draw_popgun(pen, 20, -66 + arm, -0.08)
pen.poly(WHITE, [(12, -82), (22, -78), (26, -66), (18, -64), (13, -72)], 2) # gun arm
pen.circ(SKIN, 23, -65 + arm, 4.5, 1)
pen.rect(SKIN, -4, -90, 4, -83, 1)
pen.circ(SKIN, 0, -101, 13, 2)
pen.poly(WOOD_D, [(-14, -104), (-10, -114), (0, -117), (10, -114), (14, -104), (8, -108), (-8, -108)], 1)
pen.ell(NAVY, 0, -113, 14, 6, 2) # wool cap
pen.circ(BRICK, 0, -120, 3.5, 1) # pompom
pen.circ(INK, -5, -101, 1.4, 0); pen.circ(INK, 5, -101, 1.4, 0)
pen.arc(INK, 0, -96, 5, 3, math.pi + 0.3, 2 * math.pi - 0.3, 1)
pen.circ((228, 150, 130), -8, -97, 2, 0); pen.circ((228, 150, 130), 8, -97, 2, 0)
def draw_girl(surf, x, y, s=1.0, arm=0.0):
pen = Pen(surf, x, y, s)
pen.ell(INK, -7, -3, 6, 3, 0); pen.ell(INK, 7, -3, 6, 3, 0)
pen.poly(MADDER, [(-12, -84), (12, -84), (24, -6), (-24, -6)], 2) # dress
pen.poly(CREAM, [(-9, -60), (9, -60), (13, -14), (-13, -14)], 1) # apron
pen.poly(WHITE, [(-14, -84), (14, -84), (8, -70), (0, -66), (-8, -70)], 2) # kerchief
pen.rect(MADDER, -22, -82, -13, -58, 2)
pen.circ(SKIN, -18, -56, 4, 1)
draw_popgun(pen, 20, -66 + arm, -0.08)
pen.poly(MADDER, [(10, -82), (22, -78), (26, -66), (18, -64), (12, -72)], 2)
pen.circ(SKIN, 23, -65 + arm, 4.5, 1)
pen.circ(STRAW, 0, -101, 17, 2) # straw bonnet brim
pen.arc(GOLD_D, 0, -101, 14, 14, 0.4, math.pi - 0.4, 1) # straw weave
pen.arc(GOLD_D, 0, -101, 11, 11, 0.5, math.pi - 0.5, 1)
pen.circ(SKIN, 0, -99, 12, 2)
pen.ell(WOOD, 0, -108, 11, 4, 0) # hair fringe
pen.circ(INK, -4, -99, 1.4, 0); pen.circ(INK, 4, -99, 1.4, 0)
pen.arc(INK, 0, -94, 4, 3, math.pi + 0.3, 2 * math.pi - 0.3, 1)
pen.circ((228, 150, 130), -7, -95, 2, 0); pen.circ((228, 150, 130), 7, -95, 2, 0)
pen.lines(BRICK, [(-13, -92), (-6, -84), (0, -86)], 2) # bonnet ribbon
pen.lines(BRICK, [(13, -92), (6, -84), (0, -86)], 2)
def draw_yankee(surf, x, y, s=1.0, arm=0.0, glass=True):
pen = Pen(surf, x, y, s)
pen.ell(INK, -10, -4, 10, 4, 0); pen.ell(INK, 11, -4, 10, 4, 0)
pen.rect(GOLD, -13, -8, -7, -4, 0); pen.rect(GOLD, 8, -8, 14, -4, 0)
pen.rect(CREAM, -12, -62, -4, -6, 2); pen.rect(CREAM, 4, -62, 12, -6, 2) # stockings
pen.poly(CREAM, [(-14, -96), (14, -96), (14, -60), (-14, -60)], 2) # breeches
# long navy coat with tails
pen.poly(NAVY, [(-19, -150), (-6, -150), (-8, -96), (-26, -54), (-30, -60), (-22, -100)], 2)
pen.poly(NAVY, [(19, -150), (6, -150), (8, -96), (26, -54), (30, -60), (22, -100)], 2)
pen.poly(CREAM, [(-6, -148), (6, -148), (6, -104), (-6, -104)], 1) # waistcoat
pen.poly(BRICK, [(-7, -150), (-2, -150), (-6, -110), (-10, -112)], 1) # red facings
pen.poly(BRICK, [(7, -150), (2, -150), (6, -110), (10, -112)], 1)
for by in (-140, -130, -120):
pen.circ(GOLD, -12, by, 1.8, 1); pen.circ(GOLD, 12, by, 1.8, 1)
pen.poly(NAVY, [(-19, -148), (-27, -140), (-27, -104), (-20, -104)], 2) # left arm
pen.rect(BRICK, -28, -110, -19, -102, 1)
pen.circ(SKIN, -23, -98, 4, 1)
pen.rect(SKIN, -4, -158, 4, -150, 1)
pen.poly(WHITE, [(-6, -154), (6, -154), (3, -144), (-3, -144)], 1) # cravat
pen.ell(SKIN, 0, -170, 9, 13, 2) # long lean face
pen.poly(SKIN, [(7, -172), (12, -166), (7, -164)], 1) # nose
pen.circ(INK, 3, -173, 1.3, 0); pen.circ(INK, -4, -173, 1.3, 0)
pen.lines(INK, [(-3, -162), (2, -162), (6, -164)], 1) # wry half-smile
pen.ell(CREAM, -9, -166, 3, 6, 1) # powdered hair at side
pen.lines(INK, [(-9, -160), (-14, -150)], 2) # queue ribbon
# tricorne: three-cornered hat
pen.poly(NAVY_D, [(-24, -180), (24, -180), (16, -186), (0, -198), (-16, -186)], 2)
pen.poly(NAVY, [(-24, -180), (-14, -192), (0, -186), (14, -192), (24, -180), (0, -184)], 2)
pen.lines(GOLD, [(-23, -181), (0, -185), (23, -181)], 2)
pen.lines(WHITE, [(10, -190), (18, -200), (26, -204), (30, -202)], 3) # one white feather
pen.lines(PARCH_D, [(14, -194), (20, -200)], 1)
# right arm and brass spyglass held to the eye
if glass:
pen.poly(NAVY, [(19, -148), (26, -142), (24, -172 + arm), (16, -170 + arm), (16, -146)], 2)
pen.rect(BRICK, 16, -168 + arm, 25, -162 + arm, 1)
pen.poly(GOLD, [(4, -176), (22, -180), (23, -170), (5, -170)], 2)
pen.poly(GOLD_L, [(22, -181), (40, -184), (40, -173), (22, -170)], 2)
pen.poly(GOLD, [(40, -185), (56, -187), (56, -173), (40, -172)], 2)
pen.line(GOLD_D, (31, -182), (31, -171), 2)
pen.ell(WHITE, 56, -180, 2, 7, 1)
pen.circ(SKIN, 22, -168 + arm, 4.5, 1)
else:
pen.poly(NAVY, [(19, -148), (27, -140), (27, -104), (20, -104)], 2)
pen.rect(BRICK, 19, -110, 28, -102, 1)
pen.circ(SKIN, 23, -98, 4, 1)
def draw_character(surf, key, x, y, s=1.0, arm=0.0):
{'boy': draw_boy, 'girl': draw_girl, 'yankee': draw_yankee}[key](surf, x, y, s, arm)
# --------------------------------------------------------------------------
# Target cut-outs (painted wooden carnival figures)
# --------------------------------------------------------------------------
def _cutout(w, h, painter, rim=INK, rim_w=3):
pad = 6
surf = pygame.Surface((w + pad * 2, h + pad * 2), pygame.SRCALPHA)
painter(Pen(surf, pad, pad, 1.0), surf)
m = pygame.mask.from_surface(surf)
pts = m.outline(2)
if len(pts) > 2:
pygame.draw.lines(surf, rim, True, pts, rim_w)
return surf
def paint_squirrel(pen, surf):
pen.rect(WOOD_D, 24, 52, 42, 60, 2)
pen.ell(RUST, 14, 26, 12, 20)
pen.ell(RUST_L, 16, 9, 10, 8)
for k in range(4):
pen.line(BRICK_D, (8 + k * 3, 14 + k * 6), (18 + k * 2, 18 + k * 6), 1)
pen.ell(RUST_L, 30, 50, 10, 4)
pen.ell(RUST, 33, 38, 15, 13)
pen.ell(CREAM, 40, 41, 6, 9, 1)
pen.ell(RUST, 45, 43, 4, 3, 1)
pen.circ(RUST, 47, 24, 10)
pen.poly(RUST, [(42, 17), (45, 6), (50, 15)], 2)
pen.circ(INK, 51, 21, 2.2, 0)
pen.circ(WHITE, 51.6, 20.4, 0.7, 0)
pen.circ(INK, 57, 26, 1.6, 0)
pen.lines(INK, [(57, 26), (63, 24)], 1)
def paint_deer(pen, surf):
pen.rect(WOOD_D, 20, 96, 84, 104, 2)
for lx in (26, 36, 66, 76):
pen.rect(TAN_D, lx, 60, lx + 6, 96, 2)
pen.rect(INK, lx, 93, lx + 6, 96, 0)
pen.ell(TAN, 52, 56, 30, 15)
pen.ell(CREAM, 52, 64, 18, 5, 1)
pen.ell(WHITE, 22, 48, 5, 6, 1)
for sx, sy in ((40, 50), (50, 47), (60, 50), (45, 56)):
pen.circ(CREAM, sx, sy, 2, 0)
pen.poly(TAN, [(70, 48), (77, 24), (87, 26), (83, 54)])
pen.ell(TAN, 88, 26, 10, 7)
pen.ell(TAN, 96, 30, 6, 5)
pen.circ(INK, 101, 30, 2, 0)
pen.poly(TAN, [(81, 20), (72, 12), (84, 17)])
pen.circ(INK, 89, 24, 1.8, 0)
for a, b in (((85, 19), (80, 4)), ((82, 12), (74, 8)), ((80, 6), (86, 1)),
((90, 19), (95, 4)), ((94, 10), (101, 6))):
pen.line(WOOD_D, a, b, 3)
def paint_bear(pen, surf):
pen.rect(WOOD_D, 28, 112, 130, 120, 2)
for lx in (30, 54, 96, 116):
pen.rect(BEAR_D, lx, 70, lx + 17, 112, 2)
for c in range(3):
pen.line(CREAM, (lx + 4 + c * 4, 108), (lx + 4 + c * 4, 112), 1)
pen.ell(BEAR_C, 80, 64, 56, 32)
hatch(surf, pygame.Rect(46, 40, 60, 24), BEAR_D, 5)
pen.ell(BEAR_C, 80, 64, 56, 32, 2)
pen.ell(BEAR_L, 80, 80, 30, 9, 0)
pen.circ(BEAR_C, 116, 32, 7); pen.circ(BEAR_L, 116, 32, 3.5, 0)
pen.circ(BEAR_C, 138, 32, 7); pen.circ(BEAR_L, 138, 32, 3.5, 0)
pen.circ(BEAR_C, 128, 52, 22)
pen.ell(BEAR_L, 144, 60, 11, 9)
pen.ell(INK, 152, 56, 4, 3, 0)
pen.circ(INK, 132, 45, 2.4, 0)
pen.circ(WHITE, 132.8, 44.2, 0.8, 0)
pen.arc(INK, 144, 64, 6, 4, math.pi + 0.4, 2 * math.pi - 0.2, 1)
def paint_woman(pen, surf):
pen.rect(WOOD_D, 18, 106, 48, 114, 2)
pen.ell(INK, 26, 104, 5, 3, 0); pen.ell(INK, 38, 104, 5, 3, 0)
pen.poly(NAVY, [(20, 58), (44, 58), (54, 103), (10, 103)])
pen.poly(CREAM, [(25, 60), (39, 60), (42, 96), (22, 96)], 1)
pen.rect(NAVY, 21, 40, 43, 60)
pen.rect(NAVY, 13, 42, 21, 66)
pen.circ(SKIN, 17, 68, 3.5, 1)
pen.rect(NAVY, 43, 42, 50, 62)
pen.poly(WHITE, [(15, 40), (49, 40), (41, 54), (32, 57), (23, 54)])
pen.arc(WOOD_D, 54, 66, 9, 10, 0.1, math.pi - 0.1, 2)
pen.circ(BRICK, 49, 64, 3.5, 1); pen.circ(BRICK, 56, 63, 3.5, 1); pen.circ(GOLD, 53, 61, 3, 1)
pen.ell(BASKET, 53, 71, 11, 7)
for k in range(-8, 9, 4):
pen.line(GOLD_D, (53 + k, 65), (53 + k, 77), 1)
pen.line(GOLD_D, (43, 71), (63, 71), 1)
pen.circ(SKIN, 47, 63, 3.5, 1)
pen.circ(WHITE, 32, 23, 16) # pilgrim bonnet
pen.arc(PARCH_D, 32, 23, 13, 13, 0.3, math.pi - 0.3, 1)
pen.circ(SKIN, 32, 27, 10, 1)
pen.ell(WOOD, 32, 19, 8, 3, 0)
pen.circ(INK, 28, 27, 1.4, 0); pen.circ(INK, 36, 27, 1.4, 0)
pen.circ((230, 150, 136), 26, 31, 2, 0); pen.circ((230, 150, 136), 38, 31, 2, 0)
pen.arc(INK, 32, 31, 3, 2, math.pi + 0.3, 2 * math.pi - 0.3, 1)
pen.lines(WHITE, [(20, 32), (28, 40)], 2); pen.lines(WHITE, [(44, 32), (36, 40)], 2)
SPRITE_SPECS = {
'squirrel': (66, 60, paint_squirrel, INK, 3),
'deer': (104, 104, paint_deer, INK, 3),
'bear': (158, 120, paint_bear, INK, 3),
'woman': (66, 114, paint_woman, BRICK, 5),
}
SPRITES = {}
def build_sprites():
for kind, (w, h, painter, rim, rw) in SPRITE_SPECS.items():
right = _cutout(w, h, painter, rim, rw)
left = pygame.transform.flip(right, True, False)
SPRITES[kind] = {
1: (right, pygame.mask.from_surface(right)),
-1: (left, pygame.mask.from_surface(left)),
}
# --------------------------------------------------------------------------
# Background and foreground (rendered once)
# --------------------------------------------------------------------------
def draw_tent(s, rng, x, base, w, h, col):
roof_h = h * 0.45
body = pygame.Rect(x, int(base - h + roof_h), w, int(h - roof_h))
stripe = max(8, w // 7)
for i, sx in enumerate(range(body.x, body.right, stripe)):
pygame.draw.rect(s, col if i % 2 == 0 else CREAM, (sx, body.y, min(stripe, body.right - sx), body.h))
pygame.draw.rect(s, INK, body, 2)
door = [(x + w // 2 - w // 8, base), (x + w // 2, body.y + 8), (x + w // 2 + w // 8, base)]
pygame.draw.polygon(s, WOOD_DD, door)
pygame.draw.polygon(s, INK, door, 2)
peak = (x + w // 2, base - h)
roof = [(x - 6, body.y), peak, (x + w + 6, body.y)]
pygame.draw.polygon(s, col, roof)
for k in range(1, 6):
t = k / 6
pygame.draw.line(s, tuple(max(0, c - 30) for c in col), peak, (x - 6 + (w + 12) * t, body.y), 1)
pygame.draw.polygon(s, INK, roof, 2)
for i in range(0, w + 12, 12): # scalloped edge
pygame.draw.arc(s, INK, (x - 6 + i, body.y - 4, 12, 9), math.pi, 2 * math.pi, 2)
pygame.draw.line(s, WOOD_D, peak, (peak[0], peak[1] - 22), 3)
flag = [(peak[0], peak[1] - 22), (peak[0] + 16, peak[1] - 17), (peak[0], peak[1] - 12)]
pygame.draw.polygon(s, BRICK if col == INDIGO else NAVY, flag)
pygame.draw.polygon(s, INK, flag, 1)
def draw_stall(s, rng, x, base, w, h, awning_col):
for px in (x, x + w - 8):
wood_rect(s, (px, base - h, 8, h), WOOD, rng, vertical=True)
wood_rect(s, (x - 4, base - 34, w + 8, 12), WOOD_L, rng) # counter plank
wood_rect(s, (x, base - 22, w, 22), WOOD, rng)
aw = pygame.Rect(x - 8, base - h - 6, w + 16, 22)
stripe = 12
for i, sx in enumerate(range(aw.x, aw.right, stripe)):
pygame.draw.rect(s, awning_col if i % 2 == 0 else CREAM, (sx, aw.y, min(stripe, aw.right - sx), aw.h))
pygame.draw.rect(s, INK, aw, 2)
for sx in range(aw.x, aw.right - 4, stripe):
pygame.draw.arc(s, INK, (sx, aw.bottom - 6, stripe, 12), math.pi, 2 * math.pi, 2)
# goods hanging on strings under the awning: loaves, cheese, a little doll
for k, gx in enumerate(range(x + 14, x + w - 8, 22)):
drop = 16 + (k % 2) * 10
gy = aw.bottom + drop
pygame.draw.line(s, INK, (gx, aw.bottom), (gx, gy), 1)
kind = k % 3
if kind == 0:
pygame.draw.ellipse(s, GOLD, (gx - 7, gy, 14, 9)); pygame.draw.ellipse(s, INK, (gx - 7, gy, 14, 9), 1)
elif kind == 1:
pygame.draw.circle(s, STRAW, (gx, gy + 5), 6); pygame.draw.circle(s, INK, (gx, gy + 5), 6, 1)
else:
pygame.draw.circle(s, SKIN, (gx, gy + 3), 3)
pygame.draw.polygon(s, BRICK, [(gx - 5, gy + 14), (gx, gy + 5), (gx + 5, gy + 14)])
bx = x + w + 6 # a barrel
pygame.draw.ellipse(s, WOOD, (bx, base - 24, 18, 24)); pygame.draw.ellipse(s, INK, (bx, base - 24, 18, 24), 2)
pygame.draw.line(s, IRON, (bx + 1, base - 17), (bx + 17, base - 17), 2)
pygame.draw.line(s, IRON, (bx + 1, base - 7), (bx + 17, base - 7), 2)
def draw_prize(s, kind, x, y):
"""A prize hanging from a string; (x, y) is the peg."""
pygame.draw.line(s, INK, (x, y), (x, y + 18), 1)
pygame.draw.circle(s, WOOD_DD, (x, y), 3)
y += 18
pen = Pen(s, x, y, 1.0)
if kind == 'soldier': # painted tin soldier
pen.rect(IRON, -6, 34, 6, 38, 1)
pen.rect(CREAM, -4, 22, -1, 34, 1); pen.rect(CREAM, 1, 22, 4, 34, 1)
pen.rect(NAVY, -5, 8, 5, 23, 1)
pen.line(WHITE, (-5, 9), (5, 20), 1); pen.line(WHITE, (5, 9), (-5, 20), 1)
pen.line(IRON, (7, 2), (7, 30), 2)
pen.circ(SKIN, 0, 5, 3.5, 1)
pen.poly(INK, [(-6, 2), (6, 2), (0, -4)], 0)
elif kind == 'doll': # rag doll
pen.poly(BRICK, [(-4, 10), (4, 10), (10, 32), (-10, 32)], 1)
pen.line(CREAM, (-4, 12), (-11, 20), 3); pen.line(CREAM, (4, 12), (11, 20), 3)
pen.circ(CREAM, 0, 5, 6, 1)
pen.lines(GOLD_D, [(-6, 2), (-9, 10)], 2); pen.lines(GOLD_D, [(6, 2), (9, 10)], 2)
pen.circ(INK, -2, 5, 1.2, 0); pen.circ(INK, 2, 5, 1.2, 0)
pen.line(BRICK, (-2, 8), (2, 8), 1)
elif kind == 'horse': # carved wooden horse
pen.ell(WOOD_L, 0, 12, 12, 6)
pen.poly(WOOD_L, [(8, 8), (15, -2), (20, 0), (13, 12)])
pen.ell(WOOD_L, 18, -1, 5, 3)
for lx in (-9, -4, 5, 9):
pen.line(WOOD_D, (lx, 16), (lx, 26), 2)
pen.lines(WOOD_DD, [(-12, 10), (-17, 18)], 2)
pen.lines(WOOD_DD, [(10, 2), (14, -4)], 2)
elif kind == 'rooster': # carved wooden rooster
pen.ell(WOOD_L, 0, 12, 9, 7)
pen.poly(WOOD, [(-8, 8), (-15, 0), (-11, 12)])
pen.circ(WOOD_L, 6, 3, 4)
pen.poly(BRICK, [(5, -1), (7, -5), (9, -1)], 0)
pen.poly(GOLD, [(10, 3), (14, 4), (10, 5)], 0)
pen.line(WOOD_D, (-2, 18), (-2, 25), 2); pen.line(WOOD_D, (3, 18), (3, 25), 2)
pen.rect(WOOD_D, -7, 25, 8, 28, 1)
def make_background():
rng = random.Random(1776)
s = pygame.Surface((W, H)).convert()
for y in range(H): # parchment sky
t = y / H
c = (int(PARCH[0] - 10 * t), int(PARCH[1] - 18 * t), int(PARCH[2] - 30 * t))
pygame.draw.line(s, c, (0, y), (W, y))
for _ in range(1400):
s.set_at((rng.randrange(W), rng.randrange(260)), PARCH_D)
for _ in range(7): # cracks in the parchment
x, y = rng.randrange(100, 860), rng.randrange(95, 200)
pts = [(x, y)]
for _ in range(rng.randint(5, 9)):
x += rng.randint(4, 14); y += rng.randint(-5, 5)
pts.append((x, y))
pygame.draw.lines(s, PARCH_DD, False, pts, 1)
for cx, cy in ((230, 128), (560, 112), (770, 140)): # woodcut clouds
for dx, r in ((-26, 14), (0, 20), (24, 15), (44, 10)):
pygame.draw.circle(s, WHITE, (cx + dx, cy), r)
for dx, r in ((-26, 14), (0, 20), (24, 15), (44, 10)):
pygame.draw.arc(s, PARCH_DD, (cx + dx - r, cy - r, 2 * r, 2 * r), 0.2, math.pi - 0.2, 1)
pygame.draw.line(s, PARCH_DD, (cx - 40, cy + 6), (cx + 56, cy + 6), 1)
hill = [] # rolling hills
for x in range(0, W + 40, 40):
hill.append((x, 214 + int(10 * math.sin(x * 0.012)) + int(6 * math.sin(x * 0.031))))
pygame.draw.polygon(s, GREEN, hill + [(W, 262), (0, 262)])
hatch(s, pygame.Rect(0, 196, W, 66), GREEN_D, 7)
s.set_clip(None)
pygame.draw.lines(s, INK, False, hill, 2)
sx, sy = 640, 202 # distant meeting-house steeple
pygame.draw.rect(s, WHITE, (sx, sy, 22, 22)); pygame.draw.rect(s, INK, (sx, sy, 22, 22), 1)
pygame.draw.polygon(s, WHITE, [(sx + 6, sy), (sx + 11, sy - 28), (sx + 16, sy)])
pygame.draw.polygon(s, INK, [(sx + 6, sy), (sx + 11, sy - 28), (sx + 16, sy)], 1)
pygame.draw.polygon(s, BRICK, [(sx - 2, sy), (sx + 11, sy - 8), (sx + 24, sy)])
pygame.draw.polygon(s, INK, [(sx - 2, sy), (sx + 11, sy - 8), (sx + 24, sy)], 1)
for tx in (120, 180, 400, 700, 830, 880):
ty = 214 + int(10 * math.sin(tx * 0.012)) + 4
pygame.draw.line(s, WOOD_D, (tx, ty), (tx, ty - 16), 3)
for dx, dy, r in ((0, -26, 13), (-9, -18, 9), (9, -18, 9)):
pygame.draw.circle(s, GREEN_D, (tx + dx, ty + dy), r)
pygame.draw.circle(s, INK, (tx + dx, ty + dy), r, 1)
pygame.draw.rect(s, EARTH, (0, 252, W, H - 252)) # trodden fairground earth
pygame.draw.line(s, INK, (0, 252), (W, 252), 1)
for _ in range(260):
x, y = rng.randrange(W), rng.randrange(256, FENCE_TOP + 30)
pygame.draw.line(s, EARTH_D, (x, y), (x + rng.randint(3, 9), y), 1)
for _ in range(40):
x, y = rng.randrange(W), rng.randrange(262, FENCE_TOP)
for k in (-3, 0, 3):
pygame.draw.line(s, GREEN_D, (x, y), (x + k, y - 6), 1)
draw_tent(s, rng, 110, 262, 120, 140, INDIGO) # tents and timber stalls
draw_stall(s, rng, 262, 262, 110, 96, MADDER)
draw_tent(s, rng, 424, 262, 130, 150, MADDER)
draw_stall(s, rng, 590, 262, 104, 92, INDIGO)
draw_tent(s, rng, 730, 262, 112, 134, INDIGO)
pygame.draw.rect(s, STRAW, (392, 244, 30, 20)); pygame.draw.rect(s, INK, (392, 244, 30, 20), 2)
hatch(s, pygame.Rect(392, 244, 30, 20), GOLD_D, 4)
for ry, ground in ((RAIL1_Y, 290), (RAIL2_Y, FENCE_TOP + 20)): # target rails on posts
for px in range(130, W, 180):
wood_rect(s, (px, ry + 10, 10, ground - ry - 10), WOOD, rng, vertical=True)
wood_rect(s, (0, ry, W, 13), WOOD_L, rng)
pygame.draw.line(s, WOOD_DD, (0, ry + 13), (W, ry + 13), 3)
return s
def make_fence_overlay():
rng = random.Random(1777)
s = pygame.Surface((W, H), pygame.SRCALPHA)
x = 0
while x < W:
pw = rng.randint(34, 50)
top = FENCE_TOP + rng.randint(-4, 6)
wood_rect(s, (x, top, pw, COUNTER_Y - top), rng.choice((WOOD, WOOD_L, (150, 104, 62))), rng, vertical=True)
pygame.draw.polygon(s, (0, 0, 0, 0), [(x, top - 1), (x + 7, top - 1), (x - 1, top + 7)])
pygame.draw.line(s, INK, (x + 7, top), (x, top + 7), 2)
x += pw
for ry in (FENCE_TOP + 22, FENCE_TOP + 88):
wood_rect(s, (0, ry, W, 12), WOOD_D, rng)
for nx in range(18, W, 44):
pygame.draw.circle(s, IRON, (nx, ry + 6), 2)
for px in (150, 305, 470, 640, 800): # paper targets pinned to the fence
paper = pygame.Surface((54, 62), pygame.SRCALPHA)
paper.fill(CREAM)
for k in range(3):
pygame.draw.line(paper, PARCH_D, (0, 8 + 22 * k), (54, 10 + 22 * k), 1)
for rr, col in ((22, INK), (18, CREAM), (14, BRICK), (9, CREAM), (4, INK)):
pygame.draw.circle(paper, col, (27, 31), rr)
for _ in range(rng.randint(1, 4)):
pygame.draw.circle(paper, INK, (27 + rng.randint(-16, 16), 31 + rng.randint(-18, 18)), 2)
pygame.draw.polygon(paper, PARCH_D, [(54, 50), (54, 62), (42, 62)])
pygame.draw.rect(paper, INK, paper.get_rect(), 1)
rot = pygame.transform.rotate(paper, rng.uniform(-7, 7))
rr = rot.get_rect(center=(px, FENCE_TOP + 62))
s.blit(rot, rr)
for tx in (rr.x + 10, rr.right - 10):
pygame.draw.circle(s, GOLD, (tx, rr.y + 8), 3); pygame.draw.circle(s, INK, (tx, rr.y + 8), 3, 1)
return s
def make_frame_overlay():
rng = random.Random(1778)
s = pygame.Surface((W, H), pygame.SRCALPHA)
for x0 in (0, PLAY_RIGHT): # rough-hewn side posts
wood_rect(s, (x0, 0, 86, COUNTER_Y), WOOD, rng, vertical=True, ow=3)
wood_rect(s, (x0 + 8, 0, 70, COUNTER_Y), WOOD_L, rng, vertical=True)
for ay in range(60, COUNTER_Y, 70): # adze marks
pygame.draw.arc(s, WOOD_D, (x0 + 18, ay, 40, 12), 0.3, math.pi - 0.3, 2)
hatch(s, pygame.Rect(x0 + (64 if x0 == 0 else 8), 0, 14, COUNTER_Y), WOOD_D, 5)
for py in (150, 300): # peg rails
wood_rect(s, (x0 + 4, py, 78, 10), WOOD_D, rng)
draw_prize(s, 'soldier', 22, 160); draw_prize(s, 'doll', 62, 160)
draw_prize(s, 'horse', 34, 310); draw_prize(s, 'soldier', 68, 310)
draw_prize(s, 'rooster', PLAY_RIGHT + 24, 160); draw_prize(s, 'soldier', PLAY_RIGHT + 62, 160)
draw_prize(s, 'doll', PLAY_RIGHT + 22, 310); draw_prize(s, 'horse', PLAY_RIGHT + 54, 310)
wood_rect(s, (0, 0, W, 36), WOOD, rng, ow=3) # header beam
wood_rect(s, (0, 30, W, 8), WOOD_D, rng)
stripe = 32 # striped valance with gold fringe
top, bot = 38, VALANCE_BOTTOM - 10
for i, sx in enumerate(range(0, W, stripe)):
col = (INDIGO, CREAM, MADDER, CREAM)[i % 4]
pygame.draw.rect(s, col, (sx, top, stripe, bot - top))
pygame.draw.ellipse(s, col, (sx, bot - 10, stripe, 20))
pygame.draw.arc(s, INK, (sx, bot - 10, stripe, 20), math.pi, 2 * math.pi, 2)
pygame.draw.line(s, INK, (sx, top), (sx, bot), 1)
for fx in range(sx + 4, sx + stripe, 6):
fy = bot + 6 + int(4 * (1 - abs((fx - sx - stripe / 2) / (stripe / 2))))
pygame.draw.line(s, GOLD, (fx, fy - 2), (fx, fy + 4), 2)
hatch(s, pygame.Rect(0, top, W, 10), (0, 0, 0, 70), 6)
pygame.draw.line(s, INK, (0, top), (W, top), 2)
return s
def make_counter():
rng = random.Random(1779)
s = pygame.Surface((W, H - COUNTER_Y)).convert()
for x in range(0, W, 160):
wood_rect(s, (x, 14, 160, H - COUNTER_Y - 14), WOOD, rng, ow=2)
wood_rect(s, (0, 0, W, 14), WOOD_L, rng, ow=2)
return s
# --------------------------------------------------------------------------
# Sound (only if numpy is available; never crashes)
# --------------------------------------------------------------------------
class Sounds:
def __init__(self):
self.ok = False
self.snd = {}
if IS_WEB:
return # no sound in the browser version
try:
import importlib
np = importlib.import_module('numpy') # optional; hidden from the web packer on purpose
if not pygame.mixer.get_init():
pygame.mixer.init(22050, -16, 1, 512)
freq, _fmt, ch = pygame.mixer.get_init()
rnd = np.random.default_rng(7)
def env(n, k):
return np.exp(-np.linspace(0, k, n))
def mk(sig):
a = (np.clip(sig, -1, 1) * 26000).astype(np.int16)
if ch > 1:
a = np.repeat(a[:, None], ch, axis=1)
return pygame.sndarray.make_sound(np.ascontiguousarray(a))
def t(sec):
return np.arange(int(freq * sec)) / freq
tt = t(0.45); n = len(tt)
self.snd['shot'] = mk(0.65 * rnd.uniform(-1, 1, n) * env(n, 9) + 0.5 * np.sin(2 * np.pi * 70 * tt) * env(n, 6))
tt = t(0.04)
self.snd['click'] = mk(0.6 * np.sin(2 * np.pi * 1800 * tt) * env(len(tt), 12))
tt = t(0.12)
sc = np.convolve(rnd.uniform(-1, 1, len(tt)), np.ones(6) / 6, mode='same')
self.snd['ram'] = mk(0.9 * sc * np.sin(np.linspace(0, np.pi, len(tt))))
self.snd['hit'] = mk(0.7 * np.sin(2 * np.pi * 620 * tt) * env(len(tt), 10)
+ 0.3 * rnd.uniform(-1, 1, len(tt)) * env(len(tt), 25))
tt = t(0.45)
self.snd['bad'] = mk(0.4 * np.sign(np.sin(2 * np.pi * (300 - 200 * tt) * tt)) * env(len(tt), 3))
tt = t(0.09)
self.snd['loaded'] = mk(0.5 * np.sin(2 * np.pi * 900 * tt) * env(len(tt), 8)
+ 0.4 * np.sin(2 * np.pi * 1350 * tt) * env(len(tt), 8))
self.ok = True
except Exception:
self.ok = False
def play(self, name):
if self.ok and name in self.snd:
try:
self.snd[name].play()
except Exception:
pass
# --------------------------------------------------------------------------
# Online scoreboard (standard library only; runs in background threads)
# --------------------------------------------------------------------------
class Net:
def __init__(self, base):
self.base = base
self.token = None
self.display_name = None
self.results = queue.Queue()
def post(self, tag, endpoint, payload):
payload = dict(payload)
if self.token:
payload['token'] = self.token
if IS_WEB:
self._web_post(tag, endpoint, payload)
return
threading.Thread(target=self._worker, args=(tag, endpoint, payload), daemon=True).start()
# ---- browser: use JavaScript fetch(); poll for the answer each frame (never blocks)
JS_HELPER = """
if (!window.yankyPost) {
window.yankyRes = {};
window.yankyPost = function (id, url, body) {
var ctl = (typeof AbortController !== 'undefined') ? new AbortController() : null;
var timer = setTimeout(function () { if (ctl) ctl.abort(); }, 12000);
fetch(url, {method: 'POST', headers: {'Content-Type': 'application/json'}, body: body,
credentials: 'same-origin', signal: ctl ? ctl.signal : undefined})
.then(function (r) { return r.text().then(function (t) {
clearTimeout(timer); window.yankyRes[id] = JSON.stringify({status: r.status, body: t}); }); })
.catch(function (e) { clearTimeout(timer); window.yankyRes[id] = JSON.stringify({status: 0, body: ''}); });
return 1;
};
window.yankyTake = function (id) {
var v = window.yankyRes[id];
if (v === undefined) return '';
delete window.yankyRes[id];
return v;
};
}
1;
"""
def _web_post(self, tag, endpoint, payload):
if not getattr(self, '_web_ready', False):
WINDOW.eval(self.JS_HELPER)
self._web_ready = True
self._web_pending = {}
self._web_n = 0
self._web_n += 1
rid = self._web_n
self._web_pending[rid] = tag
url = self.base + '/' + endpoint
WINDOW.eval('yankyPost(%d, %s, %s)' % (rid, json.dumps(url), json.dumps(json.dumps(payload))))
def web_poll(self):
if not IS_WEB or not getattr(self, '_web_ready', False):
return
for rid in list(self._web_pending):
try:
raw = str(WINDOW.eval('yankyTake(%d)' % rid) or '')
except Exception:
raw = ''
if not raw:
continue
tag = self._web_pending.pop(rid)
ok, data = False, NET_FAIL
try:
env = json.loads(raw)
status = int(env.get('status', 0))
body = json.loads(env.get('body') or 'null') if status else None
if isinstance(body, dict) and body.get('ok') and status == 200:
ok, data = True, body
elif isinstance(body, dict) and body.get('error'):
data = str(body['error'])
except Exception:
pass
self.results.put((tag, ok, data))
def _worker(self, tag, endpoint, payload):
try:
ok, data = self._post_sync(endpoint, payload)
except Exception:
ok, data = False, NET_FAIL
self.results.put((tag, ok, data))
def _post_sync(self, endpoint, payload):
url = self.base + '/' + endpoint
headers = {'Content-Type': 'application/json', 'Accept': 'application/json',
'User-Agent': 'YankyGallery/' + CLIENT_VERSION}
req = urllib.request.Request(url, data=json.dumps(payload).encode('utf-8'),
headers=headers, method='POST')
try:
with urllib.request.urlopen(req, timeout=10) as r:
data = json.loads(r.read(65536).decode('utf-8'))
except urllib.error.HTTPError as e:
msg = None
try:
d = json.loads(e.read(65536).decode('utf-8'))
msg = d.get('error') if isinstance(d, dict) else None
except Exception:
pass
return False, msg or NET_FAIL
except Exception:
return False, NET_FAIL
if isinstance(data, dict) and data.get('ok'):
return True, data
if isinstance(data, dict) and data.get('error'):
return False, str(data['error'])
return False, NET_FAIL
# --------------------------------------------------------------------------
# Targets
# --------------------------------------------------------------------------
class Target:
def __init__(self, kind, mode, speed_mult, rng):
self.kind = kind
self.good = kind != 'woman'
self.hp = SHOTS_TO_DROP.get(kind, 1)
self.mode = mode
self.dir = rng.choice((1, -1))
self.surf, self.mask = SPRITES[kind][self.dir]
self.w, self.h = self.surf.get_size()
self.dead = False
self.knock = -1.0 # >= 0 while falling over after a hit
self.flash = 0.0
self.escaped = False
self.t = 0.0
if mode == 'rail':
if kind == 'squirrel':
row = RAIL1_Y
elif kind in ('deer', 'bear'):
row = RAIL2_Y
else:
row = rng.choice((RAIL1_Y, RAIL2_Y))
self.base_y = row + 8
self.x = -self.w / 2 if self.dir == 1 else W + self.w / 2
base = {'squirrel': 250, 'deer': 150, 'bear': 78, 'woman': 130}[kind]
self.vx = self.dir * base * rng.uniform(0.85, 1.15) * speed_mult
elif mode == 'pop': # pops up from behind the fence
self.x = rng.uniform(PLAY_LEFT + 70, PLAY_RIGHT - 70)
self.hidden_y = FENCE_TOP + self.h + 4
self.up_y = FENCE_TOP + 16
self.base_y = self.hidden_y
self.rise = 0.35
self.stay = {'squirrel': 1.3, 'deer': 1.8, 'bear': 3.4, 'woman': 2.0}[kind] / speed_mult ** 0.5
else: # hang: lowered on a rope from the valance
self.x = rng.uniform(PLAY_LEFT + 70, PLAY_RIGHT - 70)
self.hidden_y = VALANCE_BOTTOM - 14
self.up_y = VALANCE_BOTTOM + self.h + rng.randint(10, 50)
self.base_y = self.hidden_y
self.rise = 0.4
self.stay = {'squirrel': 1.3, 'woman': 1.9}.get(kind, 1.6) / speed_mult ** 0.5
@property
def rect(self):
return pygame.Rect(int(self.x - self.w / 2), int(self.base_y - self.h), self.w, self.h)
def fully_visible(self):
if self.knock >= 0 or self.dead:
return False
r = self.rect
if self.mode == 'rail':
return r.left > PLAY_LEFT + 10 and r.right < PLAY_RIGHT - 10
return self.rise < self.t < self.rise + self.stay - 0.2
def update(self, dt):
self.t += dt
if self.flash > 0:
self.flash -= dt
if self.knock >= 0:
self.knock += dt
if self.knock > 0.35:
self.dead = True
return
if self.mode == 'rail':
self.x += self.vx * dt
if (self.dir == 1 and self.x - self.w / 2 > W) or (self.dir == -1 and self.x + self.w / 2 < 0):
self.dead = True; self.escaped = True
else:
a, b, c = self.rise, self.rise + self.stay, self.rise * 2 + self.stay
if self.t < a:
k = self.t / a
elif self.t < b:
k = 1.0
elif self.t < c:
k = 1.0 - (self.t - b) / self.rise
else:
k = 0.0; self.dead = True; self.escaped = True
k = 1 - (1 - k) ** 2
self.base_y = self.hidden_y + (self.up_y - self.hidden_y) * k
def draw(self, screen):
r = self.rect
if self.mode == 'hang':
pygame.draw.line(screen, INK, (int(self.x), 40), (int(self.x), r.y + 8), 2)
pygame.draw.circle(screen, IRON, (int(self.x), r.y + 8), 4, 2)
img = self.surf
if self.knock >= 0: # flips backward like a gallery target
k = max(0.02, 1 - self.knock / 0.35)
img = pygame.transform.scale(self.surf, (self.w, max(1, int(self.h * k))))
r = img.get_rect(midbottom=(int(self.x), r.bottom))
screen.blit(img, r)
if self.flash > 0:
m = self.mask.to_surface(setcolor=(255, 250, 220, 170), unsetcolor=(0, 0, 0, 0))
screen.blit(m, r)
def hit_test(self, pos, ring):
"""ring = (mask, radius) of the player's sight circle. Returns distance or None."""
if self.knock >= 0 or self.dead:
return None
mask, rad = ring
r = self.rect
if self.mask.overlap(mask, (int(pos[0] - rad - r.x), int(pos[1] - rad - r.y))) is None:
return None
return math.hypot(pos[0] - r.centerx, pos[1] - r.centery)
# --------------------------------------------------------------------------
# Buttons and panels
# --------------------------------------------------------------------------
def draw_button(screen, rect, label, hover=False, enabled=True, size=24, glow=False):
r = pygame.Rect(rect)
base = WOOD if enabled else (120, 100, 80)
pygame.draw.rect(screen, WOOD_DD, r.move(3, 4), border_radius=6)
pygame.draw.rect(screen, base, r, border_radius=6)
pygame.draw.rect(screen, WOOD_L if enabled else (140, 120, 100), r.inflate(-8, -8), border_radius=4)
for k in range(r.y + 10, r.bottom - 6, 7):
pygame.draw.line(screen, base, (r.x + 8, k), (r.right - 8, k), 1)
col = GOLD_L if (hover or glow) and enabled else INK
pygame.draw.rect(screen, col, r, 3 if (hover or glow) and enabled else 2, border_radius=6)
text(screen, label, size, CREAM if enabled else PARCH_D, r.center, bold=True, shadow=INK)
_PANEL_CACHE = {}
def parchment_panel(screen, rect, border=NAVY):
r = pygame.Rect(rect)
key = r.size
if key not in _PANEL_CACHE:
p = pygame.Surface(r.size)
p.fill(PARCH)
rng = random.Random(r.w * 7 + r.h)
for _ in range(r.w * r.h // 160):
p.set_at((rng.randrange(r.w), rng.randrange(r.h)), PARCH_D)
_PANEL_CACHE[key] = p
sh = pygame.Surface(r.size, pygame.SRCALPHA)
sh.fill((0, 0, 0, 90))
screen.blit(sh, r.move(6, 8))
screen.blit(_PANEL_CACHE[key], r)
pygame.draw.rect(screen, border, r, 4)
pygame.draw.rect(screen, BRICK, r.inflate(-12, -12), 1)
QUIPS_GREAT = ["Huzzah! King George would tax that aim if he could.",
"Sharp as a Boston lawyer, and twice as hard on squirrels.",
"Mr. Franklin would put that shooting in his almanac."]
QUIPS_GOOD = ["Fair shooting. Not Bunker Hill, but nobody's counting.",
"Respectable. The bear has written to Parliament about you.",
"A solid day at the fair. Go buy yourself a gingerbread."]
QUIPS_POOR = ["The squirrels have formed a Continental Congress in your honour.",
"More powder than sense, as the almanac says.",
"The deer send their regards. From very far away."]
QUIPS_BONNET = ["Goody Prudence and her basket are NOT the game, friend.",
"You've startled Goody Prudence. The town crier will hear of it.",
"Three bonnets knocked flat. The magistrate would like a word."]
# --------------------------------------------------------------------------
# The game
# --------------------------------------------------------------------------
class Game:
def __init__(self, screen, selftest=False):
self.screen = screen
self.clock = pygame.time.Clock()
self.rng = random.Random()
self.bg = make_background()
self.fence = make_fence_overlay()
self.frame = make_frame_overlay()
self.counter = make_counter()
self.dim = pygame.Surface((W, H), pygame.SRCALPHA)
self.sounds = Sounds()
self.net = Net(API_BASE)
self.state = 'title'
self.running = True
self.exit_code = 0
self.mouse = (W // 2, H // 2)
self.char_idx = 2
self.gen = 0
self.login_fields = ['', '']
self.login_focus = 0
self.login_msg = ''
self.login_busy = False
self._seen_textinput = False
self._kd_char, self._kd_time = '', 0.0
self.title_msg = ''
self.pending_shot = None
self.t_state = 0.0
self.frames = 0
self.error_text = ''
self.error_count = 0
self._last_tb = ''
self._quip_key = None
self._quip = ''
self.rings = {}
for c in CHARACTERS:
r = c['sight']
surf = pygame.Surface((2 * r + 1, 2 * r + 1), pygame.SRCALPHA)
pygame.draw.circle(surf, (255, 255, 255, 255), (r, r), r)
self.rings[c['key']] = (pygame.mask.from_surface(surf), r)
self.script = self.selftest_script() if selftest else None
self.reset_play()
@property
def char(self):
return CHARACTERS[self.char_idx]
def set_state(self, s):
if s == 'login':
try:
pygame.key.start_text_input()
except Exception:
pass
elif self.state == 'login':
try:
pygame.key.stop_text_input()
except Exception:
pass
self.state = s
self.t_state = 0.0
try:
pygame.mouse.set_visible(s != 'play')
except Exception:
pass
web_log('state -> ' + s)
def reset_play(self):
self.targets = []
self.effects = [] # smoke puffs, wood chips
self.floats = [] # floating score text
self.score = 0
self.lives = START_LIVES
self.time_left = float(GAME_SECONDS)
self.elapsed = 0.0
self.hits = 0
self.shots = 0
self.bad_hits = 0
self.escaped = 0
self.squirrel_run = 0 # streak bonuses: squirrels / deer knocked down in a row
self.deer_run = 0
self.kill_seq = [] # last knock-downs, for the squirrel-bear-deer bonus
self.bonuses = [] # names of bonuses earned this round
self.gun = 'loaded' # loaded / empty / reloading
self.reload_t = 0.0
self.reload_stroke = -1
self.spawn_t = 0.6
self.empty_flash = 0.0
self.red_flash = 0.0
self.recoil = 0.0
self.ended_by = ''
self.run_state = 'none' # none / pending / ready / failed
self.run_id = None
self.run_msg = ''
self.submit_state = 'none'
self.submit_msg = ''
def start_game(self):
self.reset_play()
self.gen += 1
self.set_state('play')
if self.net.token:
self.run_state = 'pending'
self.net.post(('start_run', self.gen), 'start_run.php',
{'character': self.char['key'], 'client_version': CLIENT_VERSION})
def end_game(self, why):
self.ended_by = why
self.set_state('over')
if not self.net.token:
self.submit_state = 'guest'
self.submit_msg = 'Guest game - log in to put scores on the board.'
else:
self.submit_state = 'waiting_run'
self.submit_msg = 'Sending your score to the scoreboard'
def send_score(self):
self.submit_state = 'sending'
self.net.post(('submit', self.gen), 'submit_score.php', {
'run_id': self.run_id, 'score': int(self.score), 'hits': self.hits, 'shots': self.shots,
'bad_hits': self.bad_hits, 'escaped': self.escaped,
'duration_s': round(self.elapsed, 2), 'ended_by': self.ended_by,
'character': self.char['key'], 'client_version': CLIENT_VERSION})
def poll_net(self):
self.net.web_poll()
while True:
try:
tag, ok, data = self.net.results.get_nowait()
except queue.Empty:
break
name = tag[0] if isinstance(tag, tuple) else tag
if name == 'login':
self.login_busy = False
if ok and data.get('token'):
self.net.token = data['token']
self.net.display_name = data.get('display_name') or self.login_fields[0]
self.login_fields[1] = ''
self.login_msg = ''
self.title_msg = 'Welcome, %s!' % self.net.display_name
if self.state == 'login':
self.set_state('select')
else:
self.login_msg = data if isinstance(data, str) else 'Login failed.'
elif name == 'start_run' and tag[1] == self.gen:
if ok and data.get('run_id'):
self.run_id = data['run_id']
self.run_state = 'ready'
else:
self.run_state = 'failed'
self.run_msg = data if isinstance(data, str) else NET_FAIL
elif name == 'submit' and tag[1] == self.gen:
if ok:
self.submit_state = 'done'
msg = data.get('message')
if not msg and data.get('rank'):
msg = 'Saved! Your rank this month: #%s' % data['rank']
self.submit_msg = msg or 'Saved!'
else:
self.submit_state = 'failed'
self.submit_msg = (data if isinstance(data, str) else NET_FAIL) + ' Score not saved.'
def update_over(self):
if self.state == 'over' and self.submit_state == 'waiting_run':
if self.run_state == 'ready':
self.send_score()
elif self.run_state == 'failed':
self.submit_state = 'failed'
self.submit_msg = (self.run_msg or NET_FAIL) + ' Score not saved.'
# ------------------------------------------------------------ layout
def title_buttons(self):
if self.net.token:
items = [('Play', 'play'), ('Log Out', 'logout'), ('Leaderboard (website)', 'board')]
else:
items = [('Log In', 'login'), ('Register (opens website)', 'register'),
('Play as Guest', 'guest'), ('Leaderboard (website)', 'board')]
return [(pygame.Rect(W // 2 - 170, 236 + i * 54, 340, 44), label, act)
for i, (label, act) in enumerate(items)]
def login_rects(self):
return {'user': pygame.Rect(W // 2 - 160, 250, 320, 40),
'pass': pygame.Rect(W // 2 - 160, 330, 320, 40),
'ok': pygame.Rect(W // 2 - 160, 400, 150, 46),
'back': pygame.Rect(W // 2 + 10, 400, 150, 46)}
def select_rects(self):
return [pygame.Rect(60 + i * 290, 146, 260, 356) for i in range(3)]
@property
def reload_btn(self):
return pygame.Rect(W - 182, COUNTER_Y + 16, 166, 56)
# ------------------------------------------------------------ input
def do_login(self):
u, p = self.login_fields[0].strip(), self.login_fields[1]
if not u or not p:
self.login_msg = 'Please fill in both boxes.'
return
if self.login_busy:
return
self.login_busy = True
self.login_msg = 'Knocking on the scoreboard door...'
self.net.post('login', 'login.php', {'username': u, 'password': p})
def open_url(self, url):
try:
if IS_WEB:
# new tab if the browser allows it, otherwise go there in this tab
WINDOW.eval('(function(u){var w=window.open(u,"_blank"); if(!w){location.href=u;} return 1;})(%s)' % json.dumps(url))
return
webbrowser.open(url)
except Exception:
pass
def handle(self, e):
if e.type == pygame.QUIT:
self.running = False
return
if e.type == pygame.MOUSEMOTION:
self.mouse = e.pos
st = self.state
if (e.type == pygame.MOUSEBUTTONDOWN and st in ('title', 'login', 'select')
and self.t_state < CLICK_GUARD):
return # second half of a double-click: ignore it
if e.type == pygame.KEYDOWN and e.key == pygame.K_ESCAPE:
self.error_text = ''
if st in ('title', 'over'):
if not IS_WEB: # a web page can't be "quit"
self.running = False
else:
if st == 'play':
self.gen += 1 # abandon this run; nothing is submitted
self.set_state('title')
return
if st == 'title':
if e.type == pygame.MOUSEBUTTONDOWN and e.button == 1:
for r, _label, act in self.title_buttons():
if r.collidepoint(e.pos):
self.title_action(act)
elif st == 'login':
rects = self.login_rects()
if e.type == pygame.MOUSEBUTTONDOWN and e.button == 1:
if rects['user'].collidepoint(e.pos):
self.login_focus = 0
elif rects['pass'].collidepoint(e.pos):
self.login_focus = 1
elif rects['ok'].collidepoint(e.pos):
self.do_login()
elif rects['back'].collidepoint(e.pos):
self.set_state('title')
elif e.type == pygame.TEXTINPUT:
first = not self._seen_textinput
self._seen_textinput = True
if first and e.text == self._kd_char and time.monotonic() - self._kd_time < 0.25:
return # this letter was already typed via KEYDOWN
add = ''.join(ch for ch in e.text if ch.isprintable())
self.login_fields[self.login_focus] = (self.login_fields[self.login_focus] + add)[:64]
elif e.type == pygame.KEYDOWN:
ch = getattr(e, 'unicode', '') or ''
if (not self._seen_textinput and len(ch) == 1 and ch.isprintable()
and e.key not in (pygame.K_TAB, pygame.K_RETURN, pygame.K_KP_ENTER, pygame.K_BACKSPACE)):
# some browsers only send KEYDOWN; use its letter until real text events show up
self._kd_char, self._kd_time = ch, time.monotonic()
self.login_fields[self.login_focus] = (self.login_fields[self.login_focus] + ch)[:64]
elif e.key == pygame.K_TAB:
self.login_focus = 1 - self.login_focus
elif e.key in (pygame.K_RETURN, pygame.K_KP_ENTER):
if self.login_focus == 0:
self.login_focus = 1
else:
self.do_login()
elif e.key == pygame.K_BACKSPACE:
self.login_fields[self.login_focus] = self.login_fields[self.login_focus][:-1]
elif st == 'select':
if e.type == pygame.MOUSEBUTTONDOWN and e.button == 1:
for i, r in enumerate(self.select_rects()):
if r.collidepoint(e.pos):
self.char_idx = i
self.start_game()
return
elif e.type == pygame.KEYDOWN and e.key in (pygame.K_1, pygame.K_2, pygame.K_3):
self.char_idx = e.key - pygame.K_1
self.start_game()
elif st == 'play':
if e.type == pygame.MOUSEBUTTONDOWN and e.button == 1:
if self.reload_btn.collidepoint(e.pos):
self.start_reload()
elif e.pos[1] < COUNTER_Y:
self.fire(e.pos)
elif e.type == pygame.KEYDOWN and e.key == pygame.K_r:
self.start_reload()
elif st == 'over':
if e.type == pygame.MOUSEBUTTONDOWN and e.button == 1 and self.t_state > 1.0:
self.start_game()
elif e.type == pygame.KEYDOWN:
if e.key == pygame.K_c:
self.set_state('select')
elif e.key == pygame.K_l:
self.open_url(LEADERBOARD_URL)
def title_action(self, act):
if act == 'login':
self.login_msg = ''
self.login_focus = 0 if not self.login_fields[0] else 1
self.set_state('login')
elif act == 'register':
self.open_url(REGISTER_URL)
self.title_msg = 'Opened the sign-up page in your web browser.'
elif act == 'board':
self.open_url(LEADERBOARD_URL)
self.title_msg = 'Opened the leaderboard in your web browser.'
elif act in ('guest', 'play'):
if act == 'guest':
self.net.token = None
self.set_state('select')
elif act == 'logout':
self.net.token = None
self.net.display_name = None
self.title_msg = 'Logged out. Scores will not be saved.'
# ------------------------------------------------------------ the musket
def start_reload(self):
if self.gun == 'empty':
self.gun = 'reloading'
self.reload_t = 0.0
self.reload_stroke = -1
elif self.gun == 'loaded':
self.add_float('Already loaded!', CREAM, self.reload_btn.centerx, COUNTER_Y - 12, size=20)
def fire(self, pos):
if self.gun != 'loaded': # one shot per load
self.sounds.play('click')
self.empty_flash = 0.8
return
self.gun = 'empty'
self.shots += 1
self.recoil = 0.25
self.sounds.play('shot')
for _ in range(7):
self.effects.append(dict(kind='smoke', x=pos[0] + self.rng.uniform(-8, 8), y=pos[1] + self.rng.uniform(-6, 6),
vx=self.rng.uniform(-20, 20), vy=self.rng.uniform(-40, -10),
r=self.rng.uniform(6, 12), t=0.0, life=self.rng.uniform(0.6, 1.0)))
self.effects.append(dict(kind='flash', x=pos[0], y=pos[1], t=0.0, life=0.12))
ring = self.rings[self.char['key']]
best, bd = None, 1e9
for tg in self.targets:
d = tg.hit_test(pos, ring)
if d is not None and d < bd:
best, bd = tg, d
if best is None:
self.add_float('miss', PARCH_DD, pos[0], pos[1] - 24, size=18)
self.break_streaks()
return
self.hits += 1
cx, cy = best.rect.center
for _ in range(8):
self.effects.append(dict(kind='chip', x=pos[0], y=pos[1], vx=self.rng.uniform(-120, 120),
vy=self.rng.uniform(-160, -40), t=0.0, life=0.6,
col=self.rng.choice((WOOD_L, WOOD, CREAM))))
if best.good:
best.hp -= 1
self.sounds.play('hit')
if best.hp > 0:
best.flash = 0.3
self.add_float('One more, quick!' if best.hp == 1 else 'Two more, quick!', GOLD_L, cx, cy - 50, size=22)
return
pts = POINTS[best.kind]
self.score += pts
best.knock = 0.0
self.add_float('+%d' % pts, GOLD_L, cx, cy - 40, size=34)
self.count_streaks(best.kind, cx, cy)
else:
best.knock = 0.0
self.break_streaks()
self.bad_hits += 1
self.lives -= 1
self.red_flash = 0.5
self.sounds.play('bad')
self.add_float('Pardon, madam! -1 life', BRICK, cx, cy - 50, size=26)
def break_streaks(self):
self.squirrel_run = 0
self.deer_run = 0
self.kill_seq = []
def count_streaks(self, kind, cx, cy):
"""A good target was just knocked down: check the three streak bonuses."""
x = min(max(cx, PLAY_LEFT + 150), PLAY_RIGHT - 150)
y = max(cy - 84, VALANCE_BOTTOM + 30)
self.squirrel_run = self.squirrel_run + 1 if kind == 'squirrel' else 0
self.deer_run = self.deer_run + 1 if kind == 'deer' else 0
self.kill_seq = (self.kill_seq + [kind])[-3:]
if self.squirrel_run >= 3: # three squirrels: the gun loads itself
self.squirrel_run = 0
self.bonuses.append('squirrel')
self.gun = 'loaded'
self.reload_t = 0.0
self.reload_stroke = -1
self.sounds.play('loaded')
self.add_float('SQUIRREL STREAK QUICK LOAD!', GOLD_L, x, y, size=26)
if self.deer_run >= 3:
self.deer_run = 0
self.bonuses.append('deer')
self.score += DEER_STREAK_BONUS
self.add_float('DEER STREAK +%d' % DEER_STREAK_BONUS, GOLD_L, x, y, size=26)
if self.kill_seq == ['squirrel', 'bear', 'deer']:
self.kill_seq = []
self.bonuses.append('sbd')
self.score += SBD_STREAK_BONUS
self.add_float('SQUIRREL-BEAR-DEER +%d' % SBD_STREAK_BONUS, GOLD_L, x, y - 30, size=28)
def add_float(self, s, col, x, y, size=28):
self.floats.append(dict(s=s, col=col, x=x, y=y, t=0.0, life=1.1, size=size))
# ------------------------------------------------------------ update
def spawn(self):
p = min(1.0, self.elapsed / GAME_SECONDS)
speed = 1.0 + 0.6 * p # difficulty ramps up over the 90 seconds
if self.rng.random() < 0.2 + 0.12 * p:
kind = 'woman'
else:
kind = self.rng.choices(('squirrel', 'deer', 'bear'), (0.42, 0.44, 0.14))[0]
if kind == 'bear' and any(t.kind == 'bear' for t in self.targets):
kind = 'deer' # at most one bear at a time
modes = {'squirrel': ('rail', 'rail', 'hang', 'pop'), 'deer': ('rail', 'rail', 'pop'),
'bear': ('rail', 'pop'), 'woman': ('rail', 'pop', 'hang')}[kind]
self.targets.append(Target(kind, self.rng.choice(modes), speed, self.rng))
def update(self, dt):
self.t_state += dt
if self.state != 'play':
return
self.elapsed += dt
self.time_left -= dt
self.empty_flash = max(0.0, self.empty_flash - dt)
self.red_flash = max(0.0, self.red_flash - dt)
self.recoil = max(0.0, self.recoil - dt)
if self.gun == 'reloading':
dur = self.char['reload']
self.reload_t += dt
stroke = int(self.reload_t / dur * 3)
if stroke != self.reload_stroke and stroke < 3:
self.reload_stroke = stroke
self.sounds.play('ram')
if self.reload_t >= dur:
self.gun = 'loaded'
self.sounds.play('loaded')
self.spawn_t -= dt
if self.spawn_t <= 0:
if len(self.targets) < 9:
self.spawn()
p = min(1.0, self.elapsed / GAME_SECONDS)
self.spawn_t = self.rng.uniform(0.9, 1.6) * (1.0 - 0.45 * p)
for tg in self.targets:
tg.update(dt)
if tg.dead and tg.escaped and tg.good:
self.escaped += 1
self.score = max(0, self.score - ESCAPE_PENALTY)
x = min(max(tg.x, PLAY_LEFT + 50), PLAY_RIGHT - 50)
y = min(tg.rect.centery, FENCE_TOP - 10)
self.add_float('-%d got away' % ESCAPE_PENALTY, BRICK, x, y, size=18)
self.targets = [t for t in self.targets if not t.dead]
for ef in self.effects:
ef['t'] += dt
if 'vx' in ef:
ef['x'] += ef['vx'] * dt
ef['y'] += ef['vy'] * dt
if ef['kind'] == 'chip':
ef['vy'] += 500 * dt
self.effects = [e for e in self.effects if e['t'] < e['life']]
for f in self.floats:
f['t'] += dt
f['y'] -= 40 * dt
self.floats = [f for f in self.floats if f['t'] < f['life']]
if self.lives <= 0:
self.end_game('lives')
elif self.time_left <= 0:
self.time_left = 0
self.end_game('time')
# ------------------------------------------------------------ drawing
def dim_screen(self, alpha):
self.dim.fill((20, 14, 8, alpha))
self.screen.blit(self.dim, (0, 0))
def draw_scene(self):
s = self.screen
s.blit(self.bg, (0, 0))
for mode in ('rail', 'hang', 'pop'):
for tg in self.targets:
if tg.mode == mode:
tg.draw(s)
s.blit(self.fence, (0, 0))
s.blit(self.frame, (0, 0))
s.blit(self.counter, (0, COUNTER_Y))
def draw_effects(self):
s = self.screen
for ef in self.effects:
k = ef['t'] / ef['life']
if ef['kind'] == 'smoke':
r = int(ef['r'] * (1 + 1.8 * k))
puff = pygame.Surface((2 * r + 2, 2 * r + 2), pygame.SRCALPHA)
pygame.draw.circle(puff, (246, 240, 226, int(210 * (1 - k))), (r + 1, r + 1), r)
pygame.draw.circle(puff, (170, 160, 140, int(150 * (1 - k))), (r + 1, r + 1), r, 1)
s.blit(puff, (ef['x'] - r, ef['y'] - r))
elif ef['kind'] == 'flash':
pygame.draw.circle(s, GOLD_L, (int(ef['x']), int(ef['y'])), int(10 + 30 * k), 3)
elif ef['kind'] == 'chip':
pygame.draw.rect(s, ef['col'], (int(ef['x']), int(ef['y']), 4, 3))
for f in self.floats:
a = int(255 * min(1.0, 2 * (1 - f['t'] / f['life'])))
text(s, f['s'], f['size'], f['col'], (f['x'], f['y']), bold=True, shadow=INK, alpha=a)
def draw_crosshair(self):
s = self.screen
x, y = self.mouse
if y >= COUNTER_Y: # plain pointer over the counter
pts = [(x, y), (x + 4, y + 16), (x + 8, y + 10), (x + 14, y + 10)]
pygame.draw.polygon(s, GOLD_L, pts)
pygame.draw.polygon(s, INK, pts, 2)
return
r = self.char['sight']
y += int(self.recoil * 24)
col = INK if self.gun == 'loaded' else BRICK
if self.gun == 'loaded':
pygame.draw.circle(s, GOLD_L, (x, y), r + 2, 2)
pygame.draw.circle(s, col, (x, y), r, 2)
else: # dashed ring = not loaded
for a in range(0, 360, 30):
a0 = math.radians(a)
pygame.draw.arc(s, col, (x - r, y - r, 2 * r, 2 * r), a0, a0 + 0.28, 2)
for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
pygame.draw.line(s, col, (x + dx * (r - 6), y + dy * (r - 6)), (x + dx * (r + 8), y + dy * (r + 8)), 2)
pygame.draw.circle(s, col, (x, y), 2)
if self.empty_flash > 0:
msg = 'EMPTY - RELOAD!' if self.gun == 'empty' else 'Still loading...'
text(s, msg, 24, BRICK, (x, y - r - 22), bold=True, shadow=CREAM)
def draw_reload_panel(self):
if self.gun != 'reloading':
return
s = self.screen
prog = min(1.0, self.reload_t / self.char['reload'])
panel = pygame.Rect(8, 262, 136, 250)
parchment_panel(s, panel, NAVY)
cx = panel.centerx - 10
muzzle = panel.y + 84
key = self.char['key']
stock = [(cx - 8, panel.bottom - 72), (cx + 8, panel.bottom - 72), (cx + 20, panel.bottom - 36), (cx - 16, panel.bottom - 36)]
pygame.draw.polygon(s, WOOD, stock)
pygame.draw.polygon(s, INK, stock, 2)
br = pygame.Rect(cx - 7, muzzle, 14, panel.bottom - 72 - muzzle)
pygame.draw.rect(s, GOLD if key == 'yankee' else WOOD_L, br)
hatch(s, br.inflate(-6, 0), GOLD_D if key == 'yankee' else WOOD_D, 6)
pygame.draw.rect(s, INK, br, 2)
pygame.draw.rect(s, INK, (cx - 9, muzzle - 3, 18, 5))
f = (prog * 3) % 1.0 # three strokes of the ramrod
depth = math.sin(math.pi * f)
rod_top = muzzle - 66 + int(52 * depth)
pygame.draw.line(s, WOOD_DD, (cx, rod_top), (cx, muzzle), 4)
pygame.draw.circle(s, IRON, (cx, rod_top), 4)
sleeve = {'boy': WHITE, 'girl': MADDER, 'yankee': NAVY}[key]
pygame.draw.rect(s, sleeve, (cx + 10, rod_top + 4, 44, 15))
pygame.draw.rect(s, INK, (cx + 10, rod_top + 4, 44, 15), 2)
if key == 'yankee':
pygame.draw.rect(s, BRICK, (cx + 10, rod_top + 4, 9, 15))
hand = pygame.Rect(0, 0, 20, 16)
hand.center = (cx + 4, rod_top + 11)
pygame.draw.ellipse(s, SKIN, hand)
pygame.draw.ellipse(s, INK, hand, 2)
if depth > 0.8:
for k in range(3):
pygame.draw.circle(s, PARCH_DD, (cx - 14 - k * 6, muzzle - 4 - k * 5), 2 + k)
text(s, 'RELOADING', 16, BRICK, (panel.centerx, panel.y + 18), bold=True)
text(s, 'Ramming...', 15, NAVY, (panel.centerx, panel.bottom - 30), bold=True)
bar = pygame.Rect(panel.x + 12, panel.bottom - 16, panel.w - 24, 7)
pygame.draw.rect(s, PARCH_D, bar)
pygame.draw.rect(s, BRICK, (bar.x, bar.y, int(bar.w * prog), bar.h))
pygame.draw.rect(s, INK, bar, 1)
def draw_hud(self):
s = self.screen
y0 = COUNTER_Y
port = pygame.Rect(8, y0 + 8, 80, 76) # chosen character, small
pygame.draw.rect(s, PARCH, port)
pygame.draw.rect(s, NAVY, port, 3)
clip = s.get_clip()
s.set_clip(port.inflate(-6, -6))
key = self.char['key']
arm = 3 * math.sin(self.reload_t * 16) if self.gun == 'reloading' else 0.0
if key == 'yankee':
draw_yankee(s, port.centerx - 8, port.bottom + 4, 0.39, arm)
else:
draw_character(s, key, port.centerx - 8, port.bottom - 2, 0.58, arm)
s.set_clip(clip)
text(s, 'SCORE', 15, CREAM, (104, y0 + 26), anchor='midleft', bold=True)
text(s, '%d' % self.score, 34, GOLD_L, (104, y0 + 58), anchor='midleft', bold=True, shadow=INK)
text(s, 'LIVES', 15, CREAM, (262, y0 + 26), anchor='midleft', bold=True)
for i in range(START_LIVES): # lives drawn as tricornes
hx, hy = 280 + i * 40, y0 + 64
col = NAVY if i < self.lives else (120, 104, 86)
pts = [(hx - 17, hy), (hx + 17, hy), (hx + 10, hy - 9), (hx, hy - 16), (hx - 10, hy - 9)]
pygame.draw.polygon(s, col, pts)
pygame.draw.polygon(s, INK, pts, 2)
if i < self.lives:
pygame.draw.line(s, GOLD, (hx - 15, hy - 2), (hx + 15, hy - 2), 2)
text(s, 'TIME', 15, CREAM, (418, y0 + 26), anchor='midleft', bold=True)
tl = max(0, int(math.ceil(self.time_left)))
text(s, '%d:%02d' % (tl // 60, tl % 60), 34, BRICK if tl <= 10 else GOLD_L, (418, y0 + 58),
anchor='midleft', bold=True, shadow=INK)
text(s, 'CHARGE', 15, CREAM, (548, y0 + 26), anchor='midleft', bold=True)
blink = (pygame.time.get_ticks() // 300) % 2 == 0
if self.gun == 'loaded':
pygame.draw.circle(s, IRON, (558, y0 + 58), 8)
pygame.draw.circle(s, INK, (558, y0 + 58), 8, 2)
text(s, 'LOADED', 24, GOLD_L, (572, y0 + 58), anchor='midleft', bold=True, shadow=INK)
elif self.gun == 'empty':
text(s, 'EMPTY', 24, BRICK if blink else CREAM, (548, y0 + 58), anchor='midleft', bold=True, shadow=INK)
else:
prog = min(1.0, self.reload_t / self.char['reload'])
bar = pygame.Rect(548, y0 + 48, 150, 20)
pygame.draw.rect(s, PARCH_D, bar)
pygame.draw.rect(s, GOLD, (bar.x, bar.y, int(bar.w * prog), bar.h))
pygame.draw.rect(s, INK, bar, 2)
draw_button(s, self.reload_btn, 'RELOAD (R)', hover=self.reload_btn.collidepoint(self.mouse),
enabled=self.gun == 'empty', size=21, glow=(self.gun == 'empty' and blink) or self.empty_flash > 0)
if self.red_flash > 0:
self.dim.fill((158, 52, 38, int(120 * self.red_flash / 0.5)))
s.blit(self.dim, (0, 0))
def draw_title(self):
s = self.screen
self.draw_scene()
self.dim_screen(90)
parchment_panel(s, (150, 64, 660, 480))
text(s, 'The Yankee Doodles Shooting Gallery', 36, BRICK, (W // 2, 124), bold=True, shadow=PARCH_D)
text(s, 'A Colonial Fair Amusement ~ Anno 1776', 19, INK, (W // 2, 184))
who = ('Logged in as %s - your scores go on the board.' % self.net.display_name) if self.net.token \
else 'Not logged in - guest scores are not saved.'
text(s, who, 17, NAVY, (W // 2, 212))
for r, label, act in self.title_buttons():
draw_button(s, r, label, hover=r.collidepoint(self.mouse), size=21)
ly = 462
legend = [('squirrel', '30', 0.6), ('deer', '20*', 0.5), ('bear', '50*', 0.4), ('woman', "DON'T!", 0.5)]
for i, (k, lab, sc) in enumerate(legend):
img = SPRITES[k][1][0]
img = pygame.transform.smoothscale(img, (int(img.get_width() * sc), int(img.get_height() * sc)))
x = 236 + i * 140
s.blit(img, img.get_rect(midbottom=(x - 22, ly + 46)))
text(s, lab, 21, BRICK if k == 'woman' else NAVY, (x + 22, ly + 24), anchor='midleft', bold=True)
text(s, '*deer take 2 shots, the bear 3 ~ hit Goody Prudence (red rim) and you lose a life',
14, INK, (W // 2, ly + 62))
if self.title_msg:
text(s, self.title_msg, 18, CREAM, (W // 2, 576), bold=True, shadow=INK)
def draw_login(self):
s = self.screen
self.draw_scene()
self.dim_screen(90)
parchment_panel(s, (230, 130, 500, 370))
text(s, 'Log In to the Scoreboard', 30, NAVY, (W // 2, 176), bold=True)
rects = self.login_rects()
for i, (key, label) in enumerate((('user', 'Username'), ('pass', 'Password'))):
r = rects[key]
text(s, label, 17, INK, (r.x, r.y - 14), anchor='midleft', bold=True)
pygame.draw.rect(s, WHITE, r)
pygame.draw.rect(s, BRICK if self.login_focus == i else INK, r, 3 if self.login_focus == i else 1)
val = self.login_fields[i] if i == 0 else '*' * len(self.login_fields[i])
caret = '|' if self.login_focus == i and (pygame.time.get_ticks() // 450) % 2 == 0 else ''
text(s, val[-26:] + caret, 21, INK, (r.x + 10, r.centery), anchor='midleft')
draw_button(s, rects['ok'], 'Log In', hover=rects['ok'].collidepoint(self.mouse), size=21)
draw_button(s, rects['back'], 'Back', hover=rects['back'].collidepoint(self.mouse), size=21)
text(s, self.login_msg or 'Tab switches boxes. Enter logs in. No account? Use Register.', 15,
BRICK if self.login_msg else INK, (W // 2, 474), bold=bool(self.login_msg))
def draw_select(self):
s = self.screen
self.draw_scene()
self.dim_screen(110)
text(s, 'Choose Your Marksman', 40, CREAM, (W // 2, 112), bold=True, shadow=INK)
for i, r in enumerate(self.select_rects()):
c = CHARACTERS[i]
hover = r.collidepoint(self.mouse)
parchment_panel(s, r, GOLD if hover else NAVY)
foot = (r.centerx - 8, r.y + 222)
pygame.draw.ellipse(s, PARCH_D, (foot[0] - 50, foot[1] - 8, 100, 16))
draw_character(s, c['key'], foot[0], foot[1], 1.0 if c['key'] == 'yankee' else 1.45)
text(s, '%d. %s' % (i + 1, c['name']), 23, NAVY, (r.centerx, r.y + 248), bold=True)
text(s, c['title'], 16, BRICK, (r.centerx, r.y + 272), bold=True)
for k, ln in enumerate(c['lines']):
text(s, ln, 15, INK, (r.centerx, r.y + 296 + k * 18))
who = ('Scores saved for %s' % self.net.display_name) if self.net.token else 'Guest game: score not saved'
text(s, 'Click a marksman (or press 1, 2, 3) ~ ' + who + ' ~ Esc = back', 17, CREAM,
(W // 2, 526), shadow=INK)
@property
def quip(self):
if self._quip_key != self.gen:
self._quip_key = self.gen
acc = (self.hits / self.shots) if self.shots else 0
if self.bad_hits >= START_LIVES:
pool = QUIPS_BONNET
elif self.score >= 500 and acc >= 0.6:
pool = QUIPS_GREAT
elif self.score >= 200:
pool = QUIPS_GOOD
else:
pool = QUIPS_POOR
self._quip = self.rng.choice(pool)
return self._quip
def draw_over(self):
s = self.screen
self.draw_scene()
self.dim_screen(120)
parchment_panel(s, (150, 50, 660, 490))
text(s, 'Out of lives!' if self.ended_by == 'lives' else "Time's up!", 24, BRICK, (W // 2, 86), bold=True)
text(s, 'Final Score', 26, NAVY, (W // 2, 120), bold=True)
text(s, str(self.score), 64, GOLD_D, (W // 2, 174), bold=True, shadow=PARCH_D)
acc = (100.0 * self.hits / self.shots) if self.shots else 0.0
text(s, 'Hits %d ~ Shots %d ~ Accuracy %d%% ~ Got away %d'
% (self.hits, self.shots, round(acc), self.escaped), 18, INK, (W // 2, 226))
text_wrap(s, self.quip, 18, NAVY, W // 2, 262, 600, bold=True)
draw_character(s, self.char['key'], 236, 512, 0.95 if self.char['key'] == 'yankee' else 1.25)
col = {'done': NAVY, 'failed': BRICK}.get(self.submit_state, INK)
msg = self.submit_msg
if self.submit_state in ('sending', 'waiting_run'):
msg += '.' * ((pygame.time.get_ticks() // 400) % 4)
cx = W // 2 + 76
text_wrap(s, msg, 18, col, cx, 318, 420, bold=True, line_h=22)
text(s, 'Leaderboard:', 15, INK, (cx, 368), bold=True)
text(s, LEADERBOARD_URL, 15, INK, (cx, 388))
text(s, '(press L to open it in your browser)', 14, INK, (cx, 408))
text(s, 'Click to play again', 22, BRICK, (cx, 450), bold=True)
text(s, 'C = change marksman' if IS_WEB else 'C = change marksman ~ Esc to quit', 16, INK, (cx, 480))
def draw(self):
st = self.state
if st == 'title':
self.draw_title()
elif st == 'login':
self.draw_login()
elif st == 'select':
self.draw_select()
elif st == 'play':
self.draw_scene()
self.draw_effects()
self.draw_reload_panel()
self.draw_hud()
self.draw_crosshair()
elif st == 'over':
self.draw_over()
# ------------------------------------------------------------ main loop
def export_status(self):
"""Browser only: publish a little status object (used by the automated browser test)."""
if not IS_WEB:
return
st = {'frame': self.frames, 'error': self.error_text, 'state': self.state, 'score': self.score, 'shots': self.shots, 'hits': self.hits,
'gun': self.gun, 'lives': self.lives, 'submit_state': self.submit_state,
'submit_msg': self.submit_msg, 'login_msg': self.login_msg,
'user': self.net.display_name or '', 'fields': [self.login_fields[0], len(self.login_fields[1])],
'shot': self.pending_shot or ''}
try:
WINDOW.eval('window.yankyStatus = %s; 1;' % json.dumps(json.dumps(st)))
except Exception:
pass
def frame_error(self):
"""Something broke inside one frame. Log it loudly, show it on the canvas, keep the loop alive."""
import traceback
tb = traceback.format_exc()
if tb != self._last_tb:
self._last_tb = tb
print(tb)
web_log('ERROR in state %s:\n%s' % (self.state, tb), error=True)
self.error_count += 1
self.error_text = tb.strip().splitlines()[-1][:110]
if self.error_count > 3 and self.state != 'title':
self.gen += 1 # abandon the round, go back to the title screen
self.set_state('title')
def draw_error(self):
s = self.screen
try:
pygame.draw.rect(s, BRICK, (40, H - 74, W - 80, 58))
pygame.draw.rect(s, CREAM, (40, H - 74, W - 80, 58), 2)
text(s, 'Oops - the game hit a snag. Press Esc for the title screen, or reload the page.', 17, CREAM,
(W // 2, H - 56), bold=True)
text(s, self.error_text, 14, CREAM, (W // 2, H - 32))
except Exception:
pass
async def run(self):
while self.running:
await asyncio.sleep(0) # hand control back to the browser every frame
if IS_WEB and self.pending_shot:
# test hook: hold still until the browser test has taken its screenshot
try:
if str(WINDOW.eval("window.yankyShotDone || ''")) == self.pending_shot:
self.pending_shot = None
self.clock.tick(FPS)
except Exception:
self.pending_shot = None
self.export_status()
continue
dt = min(0.05, self.clock.tick(FPS) / 1000.0)
if self.script is not None:
try:
next(self.script)
except StopIteration:
self.script = None
self.running = False
self.frames += 1
try:
for e in pygame.event.get():
self.handle(e)
self.poll_net()
self.update(dt)
self.update_over()
self.draw()
except Exception:
self.frame_error()
if self.error_text:
self.draw_error()
if self.pending_shot and IS_WEB:
pygame.display.flip()
self.export_status()
continue
if IS_WEB and (pygame.time.get_ticks() // 100) % 2 == 0:
self.export_status()
if self.pending_shot:
try:
pygame.image.save(self.screen, self.pending_shot)
print('saved screenshot', self.pending_shot)
except Exception as ex:
print('screenshot failed', ex)
self.pending_shot = None
pygame.display.flip()
return self.exit_code
# ------------------------------------------------------------ hidden self-test
def selftest_script(self):
"""Plays by itself: python yanky_shooting_gallery.py --selftest"""
outdir = test_env('YANKY_SHOT_DIR', os.path.dirname(os.path.abspath(__file__)))
user = test_env('YANKY_TEST_USER', '')
pw = test_env('YANKY_TEST_PASS', '')
expect = test_env('YANKY_TEST_EXPECT', '')
char_i = int(test_env('YANKY_TEST_CHAR', '2'))
good_goal = int(test_env('YANKY_TEST_GOOD', '6'))
prefix = test_env('YANKY_SHOT_PREFIX', 'shot_')
full_time = test_env('YANKY_TEST_MODE') == 'time' # play the whole 90 s, never hit a bonnet
t_start = time.monotonic()
def post(ev_type, **kw):
pygame.event.post(pygame.event.Event(ev_type, **kw))
def click(pos):
pos = (int(pos[0]), int(pos[1]))
post(pygame.MOUSEMOTION, pos=pos, rel=(0, 0), buttons=(0, 0, 0))
post(pygame.MOUSEBUTTONDOWN, pos=pos, button=1)
post(pygame.MOUSEBUTTONUP, pos=pos, button=1)
def wait(sec):
end = time.monotonic() + sec
while time.monotonic() < end:
yield
def wait_until(cond, sec):
end = time.monotonic() + sec
while time.monotonic() < end and not cond():
yield
return cond()
def shot(name):
self.pending_shot = os.path.join(outdir, prefix + name + '.png')
def fail(msg):
print('SELFTEST FAIL:', msg)
self.exit_code = 1
self.running = False
yield from wait(0.4)
shot('title'); yield
if user:
r = [b for b in self.title_buttons() if b[2] == 'login'][0][0]
click(r.center)
yield from wait(0.2)
for ch in user:
post(pygame.TEXTINPUT, text=ch)
post(pygame.KEYDOWN, key=pygame.K_TAB, mod=0, unicode='\t', scancode=0)
for ch in pw:
post(pygame.TEXTINPUT, text=ch)
yield from wait(0.3)
shot('login'); yield
post(pygame.KEYDOWN, key=pygame.K_RETURN, mod=0, unicode='\r', scancode=0)
ok = yield from wait_until(lambda: self.state == 'select', 12)
if not ok:
fail('login did not reach the select screen: %s' % self.login_msg)
return
print('login ok as', self.net.display_name)
else:
r = [b for b in self.title_buttons() if b[2] == 'guest'][0][0]
click(r.center)
yield from wait(0.2)
self.mouse = self.select_rects()[char_i].center
yield from wait(0.4)
shot('select'); yield
click(self.select_rects()[char_i].center)
yield from wait(0.2)
if self.state != 'play':
fail('did not start play')
return
phase = 'good'
tested_empty = False
took_play_shot = False
t_play = time.monotonic()
while self.state == 'play':
if time.monotonic() - t_play > 110:
fail('play never ended')
return
if phase == 'good' and not full_time and (self.hits >= good_goal or time.monotonic() - t_play > 30):
phase = 'bad'
if self.gun == 'loaded':
pool = [t for t in self.targets if t.fully_visible() and t.good == (phase == 'good')]
if pool:
tg = pool[0]
click(tg.rect.center)
yield
yield
continue
elif self.gun == 'empty':
if not tested_empty:
tested_empty = True
before = self.shots
click((W // 2, 250))
yield
yield
if self.shots != before:
fail('an empty gun fired')
return
print('empty-gun click correctly did nothing')
yield from wait(0.3)
click(self.reload_btn.center)
yield
post(pygame.MOUSEMOTION, pos=(W // 2 + 60, 280), rel=(0, 0), buttons=(0, 0, 0))
elif self.gun == 'reloading':
if (not took_play_shot and self.reload_t > 0.4 * self.char['reload']
and len(self.targets) >= 3 and self.score > 0):
took_play_shot = True
shot('play')
yield
print('game over by', self.ended_by, '| score', self.score, '| hits', self.hits, '| shots', self.shots,
'| bonnet hits', self.bad_hits, '| %.1fs' % self.elapsed)
yield from wait_until(lambda: self.submit_state in ('done', 'failed', 'guest'), 15)
yield from wait(1.2)
self.mouse = (W - 60, 570)
shot('over'); yield
yield
print('scoreboard:', self.submit_state, '-', self.submit_msg)
if expect == 'saved' and self.submit_state != 'done':
fail('expected the score to be saved')
return
if expect == 'failed' and self.submit_state != 'failed':
fail('expected a scoreboard failure message')
return
if not took_play_shot:
print('note: no reload screenshot taken')
print('SELFTEST OK in %.1fs' % (time.monotonic() - t_start))
self.running = False
WEB_PAGE_SETUP = """
(function () {
document.title = "Yanky Doodle's Shooting Gallery";
document.body.style.background = '#2b1b10';
try { if (window.config) window.config.gui_divider = 1; } catch (e) {}
try { if (window.infobox) window.infobox.style.display = 'none'; } catch (e) {}
if (!document.getElementById('yanky-back')) {
var a = document.createElement('a');
a.id = 'yanky-back'; a.href = '../'; a.textContent = '< Back to the gallery';
a.style.cssText = 'position:fixed;left:8px;top:6px;z-index:50;color:#f0e4c4;font:bold 13px Georgia,serif;' +
'text-decoration:none;background:rgba(30,44,78,.9);padding:4px 10px;border:1px solid #c89a38;border-radius:4px';
document.body.appendChild(a);
}
if (!window.yankyWatch) {
var last = -1, still = 0;
window.yankyWatch = setInterval(function () {
var f = -1;
try { f = JSON.parse(window.yankyStatus || '{}').frame; } catch (e) {}
if (document.hidden || window.yankyShotPending) { still = 0; return; }
if (f === last) { still += 1; } else { still = 0; last = f; var o = document.getElementById('yanky-stall'); if (o) o.remove(); }
if (still === 3 && !document.getElementById('yanky-stall')) {
console.error('YANKY: the game loop has stopped (frame ' + f + ').');
var d = document.createElement('div'); d.id = 'yanky-stall';
d.style.cssText = 'position:fixed;left:50%;top:40%;transform:translate(-50%,-50%);z-index:60;background:#f0e4c4;' +
'color:#2b1b10;border:3px solid #c89a38;border-radius:8px;padding:18px 24px;font:16px Georgia,serif;text-align:center';
d.innerHTML = 'The game stopped responding.
';
document.body.appendChild(d);
}
}, 1000);
}
var fit = function () { try { window_resize(); } catch (e) {} };
fit(); setTimeout(fit, 300); setTimeout(fit, 1200);
return 1;
})();
"""
async def main():
selftest = '--selftest' in sys.argv or os.environ.get('YANKY_SELFTEST') == '1'
if IS_WEB:
selftest = bool(test_env('YANKY_SELFTEST', ''))
else:
try:
pygame.mixer.pre_init(22050, -16, 1, 512)
except Exception:
pass
if IS_WEB:
os.environ['SDL_AUDIODRIVER'] = 'dummy'
pygame.init()
if IS_WEB:
try:
pygame.mixer.quit()
except Exception:
pass
screen = pygame.display.set_mode((W, H))
pygame.display.set_caption("Yanky Doodle's Shooting Gallery - Anno 1776 - theyankydoodle.com")
build_sprites()
if IS_WEB:
try:
WINDOW.eval(WEB_PAGE_SETUP)
except Exception:
pass
try:
game = Game(screen, selftest)
web_log('ready (%s)' % pygame.version.ver)
code = await game.run()
except Exception:
if IS_WEB:
import traceback
WINDOW.console.error('YANKY CRASH: ' + traceback.format_exc())
raise
if IS_WEB:
return
pygame.quit()
sys.exit(code)
if __name__ == '__main__':
asyncio.run(main())