File size: 11,540 Bytes
ef987bb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Flappy Bird</title>
<style>
body{font-family:sans-serif;background:#4ec0ca;color:#fff;text-align:center;margin:0}
h1{margin:12px 0 4px}
#hud{font-size:22px;margin:6px}
canvas{background:#70c5ce;border:4px solid #543847;display:block;margin:10px auto;border-radius:6px}
button{font-size:16px;padding:6px 12px;margin:6px}
p{margin:6px}
</style>
</head>
<body>
<h1>Flappy Bird</h1>
<div id="hud">Score: <span data-testid="score">0</span> · <span data-testid="status">ready</span></div>
<canvas id="game" data-testid="canvas" width="288" height="400"></canvas>
<div>
<button data-testid="flap">Flap</button>
<button data-testid="new-game">New Game</button>
<p>Press Space / click / tap to flap</p>
</div>
<script>
(function(){
// ===========================================================================
// COORDINATE CONVENTION: the origin (0,0) is the TOP-LEFT corner of the play
// field. y grows DOWNWARD (larger y = lower on screen). x grows to the RIGHT.
// A flap therefore sets a NEGATIVE vy (moving up). The bird's x is fixed; the
// world (pipes) scrolls left toward the bird.
//
// A pipe is solid for y < gapY (top column) and y > gapY + gapH (bottom
// column); the gap is the open interval (gapY, gapY+gapH). Passing through
// that gap is safe.
//
// DETERMINISM: physics advances ONLY via step(dtMs) using a fixed integration
// scheme keyed off dt; there is no coupling to wall-clock. The visible
// requestAnimationFrame loop calls step(16) but grading calls step() directly.
// ===========================================================================
// Small deterministic PRNG (mulberry32) so pipe gaps are reproducible.
function makeRng(seed){
let s = (seed >>> 0) || 1;
return function(){
s |= 0; s = (s + 0x6D2B79F5) | 0;
let t = Math.imul(s ^ (s >>> 15), 1 | s);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const DEFAULTS = {
gravity: 0.5, // vy units added per 16ms of dt
flapImpulse: 7, // magnitude of upward velocity set on flap (vy = -7)
pipeSpeed: 2, // x units pipes move left per 16ms of dt
gapH: 120, // gap height (px)
pipeInterval: 180, // horizontal spacing between consecutive pipes (px)
width: 288,
height: 400,
pipeWidth:52,
birdX: 60, // fixed x of the bird
birdR: 12 // bird radius for collision (treated as a box ~ point)
};
const G = {
cfg: null,
bird: { y: 0, vy: 0 },
pipes: [],
score: 0,
status: 'ready',
width: DEFAULTS.width,
height: DEFAULTS.height,
rng: makeRng(1),
_nextPipeX: 0, // x at which the next pipe will be spawned
_seedCounter: 0,
// ---- init -------------------------------------------------------------
// config (all optional, sensible defaults):
// seed, gravity, flapImpulse, pipeSpeed, gapH, pipeInterval, width, height
// PLACEMENT HOOKS (for deterministic verification):
// birdY : set the bird's initial y (default height/2)
// birdVy : set the bird's initial vy (default 0)
// pipes : an explicit array of pipe objects to use verbatim, e.g.
// [{x, gapY, gapH, passed}]. When provided, NO automatic
// pipe generation happens (fully deterministic placement).
// autoPipes : boolean (default true unless `pipes` was provided) — when
// false, no pipes are generated automatically.
init(cfg){
cfg = cfg || {};
const c = Object.assign({}, DEFAULTS, cfg);
this.cfg = c;
this.width = c.width;
this.height = c.height;
const canvas = document.querySelector('[data-testid="canvas"]');
if (canvas) { canvas.width = c.width; canvas.height = c.height; }
this.rng = makeRng(cfg.seed != null ? cfg.seed : 1);
this.score = 0;
// PLACEMENT HOOK: `status:'playing'` starts the sim already in play, so a
// verifier can step() without first calling flap() (which would perturb
// vy). Any other value (or omitted) yields the normal 'ready' start.
this.status = (cfg.status === 'playing') ? 'playing' : 'ready';
this.bird = {
y: cfg.birdY != null ? cfg.birdY : c.height / 2,
vy: cfg.birdVy != null ? cfg.birdVy : 0
};
if (Array.isArray(cfg.pipes)){
// Explicit, verbatim pipe placement (deterministic test hook).
this.pipes = cfg.pipes.map(p => ({
x: p.x,
gapY: p.gapY,
gapH: p.gapH != null ? p.gapH : c.gapH,
passed: !!p.passed
}));
this._autoPipes = cfg.autoPipes === true; // default false when explicit
this._nextPipeX = this.width + c.pipeInterval;
} else {
this.pipes = [];
this._autoPipes = cfg.autoPipes !== false; // default true
this._nextPipeX = this.width; // first pipe enters at the right edge
if (this._autoPipes){
// Pre-generate a few upcoming pipes so getState() always has one.
this._spawnPipe();
this._spawnPipe();
this._spawnPipe();
}
}
render();
return this.getState();
},
getState(){
return {
bird: { y: this.bird.y, vy: this.bird.vy },
pipes: this.pipes.map(p => ({ x: p.x, gapY: p.gapY, gapH: p.gapH, passed: p.passed })),
score: this.score,
status: this.status,
width: this.width,
height: this.height
};
},
flap(){
if (this.status === 'over') return this.getState();
if (this.status === 'ready') this.status = 'playing';
this.bird.vy = -this.cfg.flapImpulse; // negative vy = upward (y grows down)
render();
return this.getState();
},
// ---- step -------------------------------------------------------------
// Advance the simulation by a FIXED dt (ms). Semi-implicit Euler scaled so
// that dt=16 applies exactly one unit of each per-frame constant.
step(dtMs){
if (this.status === 'over') return this.getState();
if (this.status === 'ready') return this.getState(); // not playing yet
const c = this.cfg;
const k = dtMs / 16;
// Integrate vertical motion (semi-implicit Euler).
this.bird.vy += c.gravity * k;
this.bird.y += this.bird.vy * k;
// Move pipes left.
const dx = c.pipeSpeed * k;
for (const p of this.pipes) p.x -= dx;
// A collision in this same step is not a safe passage and earns no score.
this._checkCollision();
if (this.status === 'over') { render(); return this.getState(); }
// Score: a pipe is "passed" once its RIGHT edge moves left of the bird's x.
// Increment EXACTLY ONCE per pipe (guarded by the passed flag).
const birdX = c.birdX;
const pipeW = this._pipeW();
for (const p of this.pipes){
if (!p.passed && (p.x + pipeW) < birdX){
p.passed = true;
this.score += 1;
}
}
// Recycle off-screen pipes and (optionally) spawn new ones to keep the
// field populated. Recycling never affects already-counted scores.
this.pipes = this.pipes.filter(p => (p.x + pipeW) > -1);
if (this._autoPipes){
while (this.pipes.length < 4) this._spawnPipe();
}
render();
return this.getState();
},
// ---- internals --------------------------------------------------------
_pipeW(){ return this.cfg.pipeWidth; },
_spawnPipe(){
const c = this.cfg;
const w = this._pipeW();
const margin = 30; // keep the gap fully on-screen
const maxTop = c.height - c.gapH - margin;
const gapY = margin + Math.floor(this.rng() * Math.max(1, (maxTop - margin)));
const x = (this.pipes.length === 0)
? this._nextPipeX
: (this.pipes[this.pipes.length - 1].x + c.pipeInterval);
// Ensure spacing from the configured cursor for the very first pipe.
this.pipes.push({ x: Math.max(x, this._nextPipeX === this.width ? this.width : x), gapY: gapY, gapH: c.gapH, passed: false });
},
_checkCollision(){
const c = this.cfg;
const y = this.bird.y;
const r = c.birdR;
// Ground / ceiling.
if (y >= this.height){ this.bird.y = this.height; this.status = 'over'; return; }
if (y <= 0){ this.bird.y = 0; this.status = 'over'; return; }
// Pipe columns. The bird occupies x-range [birdX-r, birdX+r].
const bx0 = c.birdX - r, bx1 = c.birdX + r;
const pipeW = this._pipeW();
for (const p of this.pipes){
const px0 = p.x, px1 = p.x + pipeW;
const overlapX = bx1 > px0 && bx0 < px1;
if (!overlapX) continue;
// Horizontally overlapping a pipe column: safe ONLY inside the gap.
const topClear = (y - r) > p.gapY; // above the top edge of gap
const botClear = (y + r) < (p.gapY + p.gapH); // below the bottom edge
const insideGap = topClear && botClear;
if (!insideGap){ this.status = 'over'; return; }
}
}
};
// ---- visible rendering (human view only; not used for grading) ----------
function render(){
const canvas = document.getElementById('game');
if (!canvas) return;
const ctx = canvas.getContext('2d');
if (!ctx) return;
const W = canvas.width, H = canvas.height;
ctx.clearRect(0, 0, W, H);
// sky
ctx.fillStyle = '#70c5ce'; ctx.fillRect(0, 0, W, H);
// pipes
const pipeW = G._pipeW();
ctx.fillStyle = '#5ea417';
for (const p of G.pipes){
ctx.fillRect(p.x, 0, pipeW, p.gapY);
ctx.fillRect(p.x, p.gapY + p.gapH, pipeW, H - (p.gapY + p.gapH));
}
// ground line
ctx.fillStyle = '#ded895'; ctx.fillRect(0, H - 4, W, 4);
// bird
const bx = G.cfg ? G.cfg.birdX : DEFAULTS.birdX;
const br = G.cfg ? G.cfg.birdR : DEFAULTS.birdR;
ctx.fillStyle = '#ffce00';
ctx.beginPath();
ctx.arc(bx, G.bird.y, br, 0, Math.PI * 2);
ctx.fill();
ctx.strokeStyle = '#543847'; ctx.stroke();
// HUD
const s = document.querySelector('[data-testid="score"]');
const st = document.querySelector('[data-testid="status"]');
if (s) s.textContent = G.score;
if (st) st.textContent = G.status;
}
// ---- input + visible animation loop -------------------------------------
document.addEventListener('keydown', e => {
if (e.code === 'Space' || e.key === ' '){ e.preventDefault(); G.flap(); }
});
document.addEventListener('click', e => {
if (e.target && e.target.matches('[data-testid="new-game"]')){ manual = false; G.init({}); return; }
if (e.target && e.target.matches('[data-testid="flap"]')){ G.flap(); return; }
if (e.target && e.target.id === 'game'){ G.flap(); }
});
let manual = false;
function loop(ts){
// The visible loop uses a fixed step so the on-screen game also stays
// deterministic regardless of frame timing; grading never relies on this.
if (!manual && G.status === 'playing') G.step(16);
requestAnimationFrame(loop);
}
window.__game = {
init(cfg){ manual = true; return G.init(cfg); },
getState(){ manual = true; return G.getState(); },
flap(){ manual = true; return G.flap(); },
step(dtMs){ manual = true; return G.step(dtMs); }
};
G.init({});
requestAnimationFrame(loop);
})();
</script>
</body>
</html>
|