pathological-web/main.js
KaKi87 83ab4fc040 Port Pathological to a web app
Browser port of the pygame puzzle game by John-Paul Gignac and Joe Wreschnig
(GPL v2), built from the SourceForge CVS snapshot. Includes all 50 levels,
the original graphics, sound effects and XM soundtracks (played through
chiptune3/libopenmpt).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-04 00:44:59 +01:00

2004 lines
71 KiB
JavaScript

// Pathological, ported to the web.
// Original game by John-Paul Gignac (2003) and Joe Wreschnig (2004), GPL v2.
// This file follows the structure of the original pathological.py closely, so
// that marble physics, scoring and level behavior match the pygame version.
import { ChiptuneJsPlayer } from './vendor/chiptune3.js';
// ---------------------------------------------------------------- constants
const
WHEEL_STEPS = 9,
FRAMES_PER_SEC = 100,
FRAME_MS = 1000 / FRAMES_PER_SEC,
TIMER_WIDTH = 36,
TIMER_MARGIN = 4,
INFO_HEIGHT = 20,
INITIAL_LIVES = 3,
EXTRA_LIFE_FREQUENCY = 5000,
MAX_SPARE_LIVES = 10,
INTRO_MUSIC_VOLUME = 0.6,
INGAME_MUSIC_VOLUME = 0.9,
SOUND_EFFECTS_VOLUME = 0.6,
DEFAULT_COLORS = [2, 3, 4, 6],
DEFAULT_STOPLIGHT = [6, 4, 3],
DEFAULT_LAUNCH_TIMER = 6,
DEFAULT_BOARD_TIMER = 30,
MARBLE_SPEED = 2,
TRIGGER_TIME = 30,
REPLICATOR_DELAY = 35,
HORIZ_TILES = 8,
VERT_TILES = 6,
MARBLE_SIZE = 28,
TILE_SIZE = 92,
WHEEL_MARGIN = 4,
LIFE_MARBLE_SIZE = 16,
SCREEN_WIDTH = 36 + TILE_SIZE * HORIZ_TILES + MARBLE_SIZE,
SCREEN_HEIGHT = 20 + TILE_SIZE * VERT_TILES + MARBLE_SIZE,
HALF_MARBLE = MARBLE_SIZE / 2,
HALF_TILE = TILE_SIZE / 2,
DIRS = [[0, -1], [1, 0], [0, 1], [-1, 0]],
BOARD_WIDTH = HORIZ_TILES * TILE_SIZE,
BOARD_HEIGHT = VERT_TILES * TILE_SIZE,
LAUNCH_TIMER_POS = [0, INFO_HEIGHT],
BOARD_POS = [TIMER_WIDTH, INFO_HEIGHT + MARBLE_SIZE],
TIMER_HEIGHT = BOARD_HEIGHT + MARBLE_SIZE,
NUM_HIGHSCORES = 10,
MODIFIER_KEYS = ['Shift', 'Alt', 'Control', 'Meta', 'CapsLock'],
DIR_OF = { '^': 0, '>': 1, 'v': 2, '<': 3 };
// Pixel offsets of the four holes in a wheel, for each of the rotation steps.
const HOLECENTERS = Array.from({ length: WHEEL_STEPS }, (_, i) => {
const
radius = (TILE_SIZE - MARBLE_SIZE) / 2 - WHEEL_MARGIN,
theta = Math.PI * i / (2 * WHEEL_STEPS),
c = Math.floor(0.5 + Math.cos(theta) * radius),
s = Math.floor(0.5 + Math.sin(theta) * radius);
return [
[HALF_TILE + s, HALF_TILE - c],
[HALF_TILE + c, HALF_TILE + s],
[HALF_TILE - s, HALF_TILE + c],
[HALF_TILE - c, HALF_TILE - s]
];
});
const
floorDiv = (a, b) => Math.floor(a / b),
mod = (a, b) => (a % b + b) % b,
randomChoice = list => list[Math.floor(Math.random() * list.length)],
// pygame's default font is scaled by 0.6875 to reach the requested pixel height.
fontFor = size => `bold ${Math.round(size * 0.6875)}px "Helvetica Neue", Arial, Helvetica, sans-serif`;
// ------------------------------------------------------------------- state
const
params = new URLSearchParams(location.search),
canvas = document.getElementById('screen'),
ctx = canvas.getContext('2d'),
nameInput = document.getElementById('name-input'),
images = {},
settings = {
sound: params.get('q') !== '1',
music: params.get('q') !== '1',
colorblind: params.get('cb') === '1'
};
let levelData = [];
// localStorage can be missing or throw (private windows), so every access is
// wrapped in a promise and failures are ignored.
const
storageGet = key => Promise
.allSettled([Promise.resolve().then(() => localStorage.getItem(key))])
.then(([{ value }]) => value ?? null),
storageSet = (key, value) => void Promise
.resolve()
.then(() => localStorage.setItem(key, value))
.catch(() => {});
// ------------------------------------------------------------------- assets
const loadRawImage = url => new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = () => reject(new Error(`Cannot load image: ${url}`));
img.src = url;
});
// Mirrors the original load_image(): optional scaling, plus a color key.
// colorkey: 'corner' uses the top-left pixel, an [r, g, b] array uses that
// color, and null disables keying.
const makeSprite = (img, colorkey, size) => {
const
w = size ? size[0] : img.width,
h = size ? size[1] : img.height,
c = document.createElement('canvas'),
g = c.getContext('2d', { willReadFrequently: true });
c.width = w;
c.height = h;
g.imageSmoothingEnabled = false;
g.drawImage(img, 0, 0, w, h);
if(colorkey !== null){
const
data = g.getImageData(0, 0, w, h),
px = data.data,
key = colorkey === 'corner' ? [px[0], px[1], px[2]] : colorkey;
for(let i = 0; i < px.length; i += 4)
if(px[i + 3] === 0 || (px[i] === key[0] && px[i + 1] === key[1] && px[i + 2] === key[2]))
px[i + 3] = 0;
g.putImageData(data, 0, 0);
}
return c;
};
const loadImages = async () => {
const
names = [],
raw = {};
for(let i = 0; i < 9; i++)
names.push(`marble-${i}.png`, `marble-${i}-cb.png`);
for(let i = 0; i < 16; i++)
names.push(`path-${i}.png`, `tunnel-${i}.png`);
for(let i = 0; i < 8; i++)
names.push(`painter-${i}.png`, `painter-${i}-cb.png`, `filter-${i}.png`, `filter-${i}-cb.png`);
for(let i = 0; i < 4; i++)
names.push(`director-${i}.png`);
for(let i = 0; i < 4; i++)
for(let j = 0; j < 4; j++)
if(i !== j)
names.push(`switch-${i}${j}.png`);
names.push(...[
'tile', 'wheel', 'wheel-dark', 'blank-wheel', 'blank-wheel-dark', 'moving-hole',
'moving-hole-dark', 'buffer', 'buffer-top', 'shredder', 'replicator', 'teleporter-h',
'teleporter-v', 'trigger', 'stoplight', 'life-marble', 'launcher', 'launcher-v',
'launcher-corner', 'entrance', 'intro'
].map(n => `${n}.png`), 'backdrop.jpg');
await Promise.all(names.map(async n => {
raw[n] = await loadRawImage(`graphics/${n}`);
}));
const
T = [TILE_SIZE, TILE_SIZE],
M = [MARBLE_SIZE, MARBLE_SIZE],
sprite = (n, key = 'corner', size) => makeSprite(raw[n], key, size),
range = n => Array.from({ length: n }, (_, i) => i);
// Indexed [colorblind ? 1 : 0][color]
images.marble = [range(9).map(i => sprite(`marble-${i}.png`, 'corner', M)), range(9).map(i => sprite(`marble-${i}-cb.png`, 'corner', M))];
images.painter = [range(8).map(i => sprite(`painter-${i}.png`, 'corner', T)), range(8).map(i => sprite(`painter-${i}-cb.png`, 'corner', T))];
images.filter = [range(8).map(i => sprite(`filter-${i}.png`, 'corner', T)), range(8).map(i => sprite(`filter-${i}-cb.png`, 'corner', T))];
const baseTile = sprite('tile.png', [206, 53, 53], T);
images.plainTiles = range(16).map(i => {
const
tile = document.createElement('canvas'),
g = tile.getContext('2d');
tile.width = tile.height = TILE_SIZE;
g.drawImage(baseTile, 0, 0);
g.drawImage(sprite(`path-${i}.png`, 'corner', T), 0, 0);
return tile;
});
images.tunnels = range(16).map(i => sprite(`tunnel-${i}.png`, 'corner', T));
images.wheel = [sprite('wheel.png', 'corner', T), sprite('wheel-dark.png', 'corner', T)];
images.blankWheel = [sprite('blank-wheel.png', 'corner', T), sprite('blank-wheel-dark.png', 'corner', T)];
images.movingHole = [sprite('moving-hole.png', 'corner', M), sprite('moving-hole-dark.png', 'corner', M)];
images.bufferBottom = sprite('buffer.png', 'corner', T);
images.bufferTop = sprite('buffer-top.png', 'corner', T);
images.director = range(4).map(i => sprite(`director-${i}.png`, 'corner', T));
images.shredder = sprite('shredder.png', 'corner', T);
images.switches = range(4).map(i => range(4).map(j => i === j ? null : sprite(`switch-${i}${j}.png`, 'corner', T)));
images.replicator = sprite('replicator.png', 'corner', T);
images.teleporterH = sprite('teleporter-h.png', 'corner', T);
images.teleporterV = sprite('teleporter-v.png', 'corner', T);
images.trigger = sprite('trigger.png', 'corner', T);
images.stoplight = sprite('stoplight.png', 'corner', T);
images.lifeMarble = sprite('life-marble.png', 'corner', [LIFE_MARBLE_SIZE, LIFE_MARBLE_SIZE]);
images.launcherBackground = sprite('launcher.png', null, [BOARD_WIDTH, MARBLE_SIZE]);
images.launcherV = sprite('launcher-v.png', null, [MARBLE_SIZE, BOARD_HEIGHT + MARBLE_SIZE]);
images.launcherCorner = sprite('launcher-corner.png', [255, 0, 0], [(TILE_SIZE - MARBLE_SIZE) / 2 + MARBLE_SIZE, MARBLE_SIZE]);
images.launcherEntrance = sprite('entrance.png', 'corner', [TILE_SIZE, MARBLE_SIZE]);
images.intro = sprite('intro.png', null, [SCREEN_WIDTH, SCREEN_HEIGHT]);
images.backdrop = sprite('backdrop.jpg', null, [BOARD_WIDTH, BOARD_HEIGHT]);
};
const marbleImage = color => images.marble[settings.colorblind ? 1 : 0][color];
// ------------------------------------------------------------------- audio
// Sound name -> [file, volume]
const SOUND_FILES = {
filter_admit: ['filter_admit.wav', 0.8],
wheel_turn: ['wheel_turn.wav', 0.8],
wheel_completed: ['wheel_completed.wav', 0.7],
change_color: ['change_color.wav', 0.8],
direct_marble: ['direct_marble.wav', 0.6],
ping: ['ping.wav', 0.8],
trigger_setup: ['trigger_setup.wav', 1],
teleport: ['teleport.wav', 0.6],
marble_release: ['marble_release.wav', 0.5],
levelfinish: ['levelfinish.wav', 0.6],
die: ['die.wav', 1],
incorrect: ['incorrect.wav', 0.15],
switch: ['switch.wav', 1],
shredder: ['shredder.wav', 1],
replicator: ['replicator.wav', 1],
extra_life: ['extra_life.wav', 1],
menu_scroll: ['menu_scroll.wav', 0.8],
menu_select: ['switch.wav', 1]
};
const audio = {
ctx: null,
buffers: {},
player: null,
playerReady: false,
moduleCache: {},
currentSong: null,
pendingSong: null,
songVolume: 1,
songLoaded: false,
init: () => {
const AudioCtx = window.AudioContext || window.webkitAudioContext;
if(!AudioCtx)
return;
audio.ctx = new AudioCtx();
Object.entries(SOUND_FILES).forEach(([name, [file]]) => void fetch(`sounds/${file}`)
.then(r => r.arrayBuffer())
.then(data => new Promise((resolve, reject) => audio.ctx.decodeAudioData(data, resolve, reject)))
.then(buf => {
audio.buffers[name] = buf;
})
.catch(() => {}));
audio.player = new ChiptuneJsPlayer({ context: audio.ctx, repeatCount: -1 });
audio.player.gain.connect(audio.ctx.destination);
audio.player.onInitialized(() => {
audio.playerReady = true;
if(audio.pendingSong)
void audio.startMusic(audio.pendingSong, audio.songVolume);
});
},
resume: () => {
if(audio.ctx && audio.ctx.state === 'suspended')
void audio.ctx.resume();
},
play: name => {
if(!settings.sound || !audio.ctx || !audio.buffers[name])
return;
const
src = audio.ctx.createBufferSource(),
gain = audio.ctx.createGain();
src.buffer = audio.buffers[name];
gain.gain.value = SOUND_FILES[name][1] * SOUND_EFFECTS_VOLUME;
src.connect(gain).connect(audio.ctx.destination);
src.start();
},
startMusic: async (name, volume) => {
audio.songVolume = volume;
if(audio.player)
audio.player.setVol(volume);
if(!settings.music || !audio.playerReady){
audio.pendingSong = name;
return;
}
audio.pendingSong = null;
if(audio.currentSong === name && audio.songLoaded){
audio.player.unpause();
return;
}
audio.currentSong = name;
audio.songLoaded = false;
audio.moduleCache[name] ??= fetch(`music/${name}`).then(r => r.arrayBuffer());
const [{ value: data }] = await Promise.allSettled([audio.moduleCache[name]]);
if(!data){
audio.currentSong = null;
return;
}
if(audio.currentSong !== name)
return;
if(!settings.music){
audio.pendingSong = name;
return;
}
audio.player.play(data.slice(0));
audio.player.unpause();
audio.songLoaded = true;
},
toggleMusic: () => {
settings.music = !settings.music;
if(settings.music){
if(audio.pendingSong)
void audio.startMusic(audio.pendingSong, audio.songVolume);
else if(audio.player && audio.songLoaded)
audio.player.unpause();
}
else if(audio.player && audio.songLoaded)
audio.player.pause();
}
};
const
playSound = name => audio.play(name),
toggleSound = () => void (settings.sound = !settings.sound),
toggleColorblind = () => {
settings.colorblind = !settings.colorblind;
storageSet('pathological.colorblind', settings.colorblind ? '1' : '0');
},
toggleFullscreen = () => document.fullscreenElement
? void document.exitFullscreen()
: void document.documentElement.requestFullscreen?.();
// ------------------------------------------------------------ game objects
const makeMarble = (color, x, y, direction) => ({ color, x, y, direction });
const
updateMarble = (board, marble) => {
marble.x += MARBLE_SPEED * DIRS[marble.direction][0];
marble.y += MARBLE_SPEED * DIRS[marble.direction][1];
board.affectMarble(marble);
},
drawMarble = (g, marble) => g.drawImage(marbleImage(marble.color), marble.x - HALF_MARBLE, marble.y - HALF_MARBLE);
// Behavior shared by every tile type, which subtypes call like a super method.
const
centerX = tile => tile.left + HALF_TILE,
centerY = tile => tile.top + HALF_TILE,
isCenter = (rx, ry) => rx === HALF_TILE && ry === HALF_TILE,
baseDrawBack = (tile, g) => g.drawImage(images.plainTiles[tile.paths], tile.left, tile.top),
drawTunnel = (tile, g) => g.drawImage(images.tunnels[tile.paths], tile.left, tile.top),
baseAffect = (tile, marble, rx, ry) => {
if(!isCenter(rx, ry) || tile.paths & (1 << marble.direction))
return;
// Figure out the new direction
const t = tile.paths - (1 << (marble.direction ^ 2));
marble.direction = t === 1 ? 0
: t === 2 ? 1
: t === 4 ? 2
: t === 8 ? 3
: marble.direction ^ 2;
};
const makeTile = (kind, paths = 0) => {
const tile = {
kind,
paths,
left: -HALF_TILE,
top: -HALF_TILE,
drawBack: g => baseDrawBack(tile, g),
update: () => {},
drawFore: () => {},
click: () => {},
affectMarble: (board, marble, rx, ry) => baseAffect(tile, marble, rx, ry)
};
return tile;
};
const makeWheel = paths => {
const wheel = makeTile('wheel', paths);
Object.assign(wheel, {
spinpos: 0,
completed: 0,
marbles: [-3, -3, -3, -3],
drawBack: g => {
baseDrawBack(wheel, g);
const step = mod(wheel.spinpos, WHEEL_STEPS);
if(wheel.spinpos){
g.drawImage(images.blankWheel[wheel.completed], wheel.left, wheel.top);
for(let i = 0; i < 4; i++){
const h = HOLECENTERS[step][i];
g.drawImage(images.movingHole[wheel.completed], h[0] - HALF_MARBLE + wheel.left, h[1] - HALF_MARBLE + wheel.top);
}
}
else
g.drawImage(images.wheel[wheel.completed], wheel.left, wheel.top);
for(let i = 0; i < 4; i++)
if(wheel.marbles[i] >= 0){
const h = HOLECENTERS[step][i];
g.drawImage(marbleImage(wheel.marbles[i]), h[0] - HALF_MARBLE + wheel.left, h[1] - HALF_MARBLE + wheel.top);
}
},
update: () => {
if(wheel.spinpos > 0)
wheel.spinpos -= 1;
else if(wheel.spinpos < 0){
wheel.spinpos += 1;
if(wheel.spinpos === 0){
// Reposition the marbles
const m = wheel.marbles;
m.unshift(m.pop());
}
}
},
// button: 0 is left, 2 is right
click: (board, posx, posy, tileX, tileY, button, shift) => {
// Ignore all clicks while rotating
if(wheel.spinpos)
return;
if(button === 2){
// Make sure that no marbles are currently entering
if(wheel.marbles.some(m => m === -1 || m === -2))
return;
wheel.spinpos = WHEEL_STEPS - 1;
playSound('wheel_turn');
if(shift)
// Spin the wheel backwards
wheel.spinpos = -wheel.spinpos;
else
wheel.marbles.push(wheel.marbles.shift());
return;
}
// Determine which hole is being clicked
for(let i = 0; i < 4; i++){
if(wheel.marbles[i] < 0)
continue;
const
h = HOLECENTERS[0][i],
l = h[0] - HALF_MARBLE,
t = h[1] - HALF_MARBLE;
if(posx < l || posx >= l + MARBLE_SIZE || posy < t || posy >= t + MARBLE_SIZE)
continue;
const neighbor = board.tiles[mod(tileY + DIRS[i][1], VERT_TILES)][mod(tileX + DIRS[i][0], HORIZ_TILES)];
if(
// Marbles may not go off the top of the board
(tileY === 0 && i === 0)
// No way out here
|| (wheel.paths & (1 << i)) === 0
// The neighbor wheel is turning or already has a marble in that hole
|| (neighbor.kind === 'wheel' && (neighbor.spinpos || neighbor.marbles[i ^ 2] !== -3))
)
playSound('incorrect');
else if(neighbor.kind !== 'wheel' && board.marbles.length >= board.liveMarblesLimit)
playSound('incorrect');
else {
if(neighbor.kind === 'wheel')
neighbor.marbles[i ^ 2] = -2;
board.marbles.push(makeMarble(wheel.marbles[i], h[0] + wheel.left, h[1] + wheel.top, i));
wheel.marbles[i] = -3;
playSound('marble_release');
}
break;
}
},
affectMarble: (board, marble, rx, ry) => {
// Watch for marbles entering
if(
rx + HALF_MARBLE === WHEEL_MARGIN
|| rx - HALF_MARBLE === TILE_SIZE - WHEEL_MARGIN
|| ry + HALF_MARBLE === WHEEL_MARGIN
|| ry - HALF_MARBLE === TILE_SIZE - WHEEL_MARGIN
)
if(wheel.spinpos || wheel.marbles[marble.direction ^ 2] >= -1){
// Reject the marble
marble.direction ^= 2;
playSound('ping');
}
else
wheel.marbles[marble.direction ^ 2] = -1;
if(HOLECENTERS[0].some(h => rx === h[0] && ry === h[1])){
// Accept the marble
board.removeMarble(marble);
wheel.marbles[marble.direction ^ 2] = marble.color;
}
},
complete: board => {
wheel.marbles.fill(-3);
board.game.increaseScore(wheel.completed ? 10 : 50);
wheel.completed = 1;
playSound('wheel_completed');
},
maybeComplete: board => {
if(wheel.spinpos)
return 0;
// Is there a trigger?
if(board.trigger?.marbles){
if(wheel.marbles.some((m, i) => m !== board.trigger.marbles[i] && m !== 8))
return 0;
wheel.complete(board);
board.trigger.complete(board);
return 1;
}
// Do we have four the same color?
let color = 8;
for(let c of wheel.marbles){
if(c < 0)
return 0;
if(color === 8)
color = c;
else if(c === 8)
c = color;
else if(c !== color)
return 0;
}
// Is there a stoplight?
const light = board.stoplight;
if(light && light.current < 3){
if(color !== 8 && color !== light.marbles[light.current])
return 0;
light.complete(board);
}
wheel.complete(board);
return 1;
}
});
return wheel;
};
const makeBuffer = (paths, color = -1) => {
const buffer = makeTile('buffer', paths);
Object.assign(buffer, {
marble: color,
entering: null,
drawBack: g => {
baseDrawBack(buffer, g);
if(buffer.marble >= 0)
g.drawImage(marbleImage(buffer.marble), centerX(buffer) - HALF_MARBLE, centerY(buffer) - HALF_MARBLE);
else
g.drawImage(images.bufferBottom, buffer.left, buffer.top);
},
drawFore: g => {
drawTunnel(buffer, g);
g.drawImage(images.bufferTop, buffer.left, buffer.top);
},
affectMarble: (board, marble, rx, ry) => {
// Watch for marbles entering
if(
(rx + MARBLE_SIZE === HALF_TILE && marble.direction === 1)
|| (rx - MARBLE_SIZE === HALF_TILE && marble.direction === 3)
|| (ry + MARBLE_SIZE === HALF_TILE && marble.direction === 2)
|| (ry - MARBLE_SIZE === HALF_TILE && marble.direction === 0)
){
if(buffer.entering){
// Bump the marble that is currently entering
const bumped = buffer.entering;
bumped.x = centerX(buffer);
bumped.y = centerY(buffer);
bumped.direction = marble.direction;
playSound('ping');
baseAffect(buffer, bumped, HALF_TILE, HALF_TILE);
}
else if(buffer.marble >= 0){
// Bump the marble that is currently caught
const bumped = makeMarble(buffer.marble, centerX(buffer), centerY(buffer), marble.direction);
board.marbles.push(bumped);
playSound('ping');
baseAffect(buffer, bumped, HALF_TILE, HALF_TILE);
buffer.marble = -1;
}
// Remember which marble is on its way in
buffer.entering = marble;
}
else if(isCenter(rx, ry)){
// Catch this marble
buffer.marble = marble.color;
board.removeMarble(marble);
buffer.entering = null;
}
}
});
return buffer;
};
const makePainter = (paths, color) => {
const painter = makeTile('painter', paths);
Object.assign(painter, {
color,
drawFore: g => {
drawTunnel(painter, g);
g.drawImage(images.painter[settings.colorblind ? 1 : 0][color], painter.left, painter.top);
},
affectMarble: (board, marble, rx, ry) => {
baseAffect(painter, marble, rx, ry);
if(isCenter(rx, ry) && marble.color !== color){
marble.color = color;
playSound('change_color');
}
}
});
return painter;
};
const makeFilter = (paths, color) => {
const filter = makeTile('filter', paths);
Object.assign(filter, {
color,
drawFore: g => {
drawTunnel(filter, g);
g.drawImage(images.filter[settings.colorblind ? 1 : 0][color], filter.left, filter.top);
},
affectMarble: (board, marble, rx, ry) => {
if(!isCenter(rx, ry))
return;
// If the color is wrong, bounce the marble
if(marble.color !== color && marble.color !== 8){
marble.direction ^= 2;
playSound('ping');
}
else {
baseAffect(filter, marble, rx, ry);
playSound('filter_admit');
}
}
});
return filter;
};
const makeDirector = (paths, direction) => {
const director = makeTile('director', paths);
Object.assign(director, {
direction,
drawFore: g => {
drawTunnel(director, g);
g.drawImage(images.director[direction], director.left, director.top);
},
affectMarble: (board, marble, rx, ry) => {
if(!isCenter(rx, ry))
return;
marble.direction = direction;
playSound('direct_marble');
}
});
return director;
};
const makeShredder = paths => {
const shredder = makeTile('shredder', paths);
Object.assign(shredder, {
drawFore: g => {
drawTunnel(shredder, g);
g.drawImage(images.shredder, shredder.left, shredder.top);
},
affectMarble: (board, marble, rx, ry) => {
if(!isCenter(rx, ry))
return;
board.removeMarble(marble);
playSound('shredder');
}
});
return shredder;
};
const makeSwitch = (paths, dir1, dir2) => {
const sw = makeTile('switch', paths);
Object.assign(sw, {
curdir: dir1,
otherdir: dir2,
drawFore: g => {
drawTunnel(sw, g);
g.drawImage(images.switches[sw.curdir][sw.otherdir], sw.left, sw.top);
},
affectMarble: (board, marble, rx, ry) => {
if(!isCenter(rx, ry))
return;
marble.direction = sw.curdir;
[sw.curdir, sw.otherdir] = [sw.otherdir, sw.curdir];
playSound('switch');
}
});
return sw;
};
const makeReplicator = (paths, count) => {
const replicator = makeTile('replicator', paths);
Object.assign(replicator, {
pending: [],
drawFore: g => {
drawTunnel(replicator, g);
g.drawImage(images.replicator, replicator.left, replicator.top);
},
update: board => {
for(const p of replicator.pending.slice()){
p[3] -= 1;
if(p[3] !== 0)
continue;
p[3] = REPLICATOR_DELAY;
// Make sure that the active marble limit isn't exceeded
if(board.marbles.length >= board.liveMarblesLimit){
replicator.pending = [];
return;
}
board.marbles.push(makeMarble(p[0], centerX(replicator), centerY(replicator), p[1]));
playSound('replicator');
p[2] -= 1;
if(p[2] <= 0)
replicator.pending.splice(replicator.pending.indexOf(p), 1);
}
},
affectMarble: (board, marble, rx, ry) => {
baseAffect(replicator, marble, rx, ry);
if(!isCenter(rx, ry))
return;
replicator.pending.push([marble.color, marble.direction, count - 1, REPLICATOR_DELAY]);
playSound('replicator');
}
});
return replicator;
};
const makeTeleporter = (paths, other = null) => {
const teleporter = makeTile('teleporter', paths);
Object.assign(teleporter, {
image: paths & 5 ? images.teleporterV : images.teleporterH,
other: null,
drawFore: g => {
drawTunnel(teleporter, g);
g.drawImage(teleporter.image, teleporter.left, teleporter.top);
},
affectMarble: (board, marble, rx, ry) => {
if(!isCenter(rx, ry) || !teleporter.other)
return;
marble.x = centerX(teleporter.other);
marble.y = centerY(teleporter.other);
playSound('teleport');
}
});
if(other){
teleporter.other = other;
other.other = teleporter;
}
return teleporter;
};
const makeTrigger = colors => {
const trigger = makeTile('trigger', 0);
const setup = list => {
trigger.countdown = 0;
trigger.marbles = Array.from({ length: 4 }, () => randomChoice(list));
};
Object.assign(trigger, {
marbles: null,
countdown: 0,
update: board => {
if(trigger.countdown > 0){
trigger.countdown -= 1;
if(trigger.countdown === 0){
setup(board.colors);
playSound('trigger_setup');
}
}
},
drawBack: g => {
baseDrawBack(trigger, g);
g.drawImage(images.trigger, trigger.left, trigger.top);
if(trigger.marbles)
for(let i = 0; i < 4; i++)
g.drawImage(marbleImage(trigger.marbles[i]),
HOLECENTERS[0][i][0] + trigger.left - HALF_MARBLE,
HOLECENTERS[0][i][1] + trigger.top - HALF_MARBLE);
},
complete: board => {
trigger.marbles = null;
trigger.countdown = TRIGGER_TIME * FRAMES_PER_SEC;
board.game.increaseScore(50);
}
});
setup(colors);
return trigger;
};
const makeStoplight = colors => {
const light = makeTile('stoplight', 0);
Object.assign(light, {
marbles: colors.slice(),
current: 0,
drawBack: g => {
baseDrawBack(light, g);
g.drawImage(images.stoplight, light.left, light.top);
for(let i = light.current; i < 3; i++)
g.drawImage(marbleImage(light.marbles[i]),
centerX(light) - HALF_MARBLE,
light.top + Math.round(TILE_SIZE / 30) + Math.floor(TILE_SIZE / 3.1) * i);
},
complete: board => {
const i = light.marbles.findIndex(m => m >= 0);
if(i >= 0)
light.marbles[i] = -1;
light.current += 1;
board.game.increaseScore(20);
}
});
return light;
};
// ------------------------------------------------------------------ levels
// Parses the all-boards file the same way the original loader walks it: level
// parameters precede a top border row ('+'), then up to six '|' rows follow.
const parseLevels = text => {
const levels = [];
let
cur = { params: {}, rows: [] },
inside = false;
for(const line of text.split('\n'))
if(line[0] === '+'){
if(inside){
levels.push(cur);
cur = { params: {}, rows: [] };
}
inside = !inside;
}
else if(line[0] === '|'){
if(inside && cur.rows.length < VERT_TILES)
cur.rows.push(line);
}
else {
const m = /^(name|author|launchtimer|boardtimer|maxmarbles|colors|stoplight|backdrop)=(.*)$/.exec(line.replace(/\r$/, ''));
if(m)
cur.params[m[1]] = m[2];
}
return levels;
};
const charValue = ch => ch === undefined || ch === ' ' ? 0
: ch >= 'a' ? ch.charCodeAt(0) - 97 + 10
: ch >= '0' && ch <= '9' ? Number(ch)
: 0;
// Builds the tile for one 3-character cell of a level row.
const makeTileFromCell = (type, pathsInt, color, colorInt, colors, stoplight, teleporters) => {
if(type === 'O')
return makeWheel(pathsInt);
if(type === '%')
return makeTrigger(colors);
if(type === '!')
return makeStoplight(stoplight);
if(type === '&')
return makePainter(pathsInt, colorInt);
if(type === '#')
return makeFilter(pathsInt, colorInt);
if(type === '@')
return color === ' ' ? makeBuffer(pathsInt) : makeBuffer(pathsInt, colorInt);
if(type === 'X')
return makeShredder(pathsInt);
if(type === '*')
return makeReplicator(pathsInt, colorInt);
if(type in DIR_OF)
return color in DIR_OF && color !== type
? makeSwitch(pathsInt, DIR_OF[type], DIR_OF[color])
: makeDirector(pathsInt, DIR_OF[type]);
if(type === '='){
if(color in teleporters)
return makeTeleporter(pathsInt, teleporters[color]);
teleporters[color] = makeTeleporter(pathsInt);
return teleporters[color];
}
return makeTile('plain', pathsInt);
};
// ------------------------------------------------------------------- board
const makeBoard = game => {
const board = {
game,
pos: BOARD_POS,
marbles: [],
trigger: null,
stoplight: null,
launchQueue: [],
boardComplete: 0,
paused: false,
name: 'Unnamed',
liveMarblesLimit: 10,
launchTimeout: -1,
boardTimeout: -1,
colors: DEFAULT_COLORS,
tiles: Array.from({ length: VERT_TILES }, () => new Array(HORIZ_TILES)),
launchTimer: 0,
launchTimeoutStart: 0,
boardTimeoutStart: 0,
setLaunchTimer: passes => {
board.launchTimer = passes;
board.launchTimeoutStart = Math.floor((MARBLE_SIZE + (HORIZ_TILES * TILE_SIZE - MARBLE_SIZE) * passes) / MARBLE_SPEED);
},
setBoardTimer: seconds => {
board.boardTimeoutStart = seconds * FRAMES_PER_SEC;
board.boardTimeout = board.boardTimeoutStart;
},
setTile: (x, y, tile) => {
board.tiles[y][x] = tile;
tile.left = board.pos[0] + TILE_SIZE * x;
tile.top = board.pos[1] + TILE_SIZE * y;
if(tile.kind === 'trigger')
board.trigger = tile;
if(tile.kind === 'stoplight')
board.stoplight = tile;
},
removeMarble: marble => {
const i = board.marbles.indexOf(marble);
if(i >= 0)
board.marbles.splice(i, 1);
},
launchMarble: () => {
board.launchQueue.push(randomChoice(board.colors));
board.marbles.unshift(makeMarble(board.launchQueue.shift(),
board.pos[0] + TILE_SIZE * HORIZ_TILES + HALF_MARBLE, board.pos[1] - HALF_MARBLE, 3));
board.launchTimeout = board.launchTimeoutStart;
},
affectMarble: marble => {
const
cx = marble.x - board.pos[0],
cy = marble.y - board.pos[1];
// Bounce marbles off of the top
if(cy === HALF_MARBLE){
marble.direction = 2;
return;
}
let effX, effY;
if(cy < 0){
if(cx === HALF_MARBLE){
marble.direction = 1;
return;
}
if(cx === TILE_SIZE * HORIZ_TILES - HALF_MARBLE && marble.direction === 1){
marble.direction = 3;
return;
}
// The special case of new marbles at the top
effX = cx;
effY = cy + MARBLE_SIZE;
}
else {
effX = cx + HALF_MARBLE * DIRS[marble.direction][0];
effY = cy + HALF_MARBLE * DIRS[marble.direction][1];
}
const
tileX = floorDiv(effX, TILE_SIZE),
tileY = floorDiv(effY, TILE_SIZE),
rx = cx - tileX * TILE_SIZE,
ry = cy - tileY * TILE_SIZE;
if(tileX >= HORIZ_TILES || tileX < 0 || tileY < 0 || tileY >= VERT_TILES)
return;
const tile = board.tiles[tileY][tileX];
if(cy >= 0 || marble.direction === 2){
tile.affectMarble(board, marble, rx, ry);
return;
}
// The special case of new marbles at the top
if(rx !== HALF_TILE || !(tile.paths & 1))
return;
if(tile.kind === 'wheel'){
if(tile.spinpos || tile.marbles[0] !== -3)
return;
tile.marbles[0] = -2;
marble.direction = 2;
board.launchMarble();
}
else if(board.marbles.length < board.liveMarblesLimit){
marble.direction = 2;
board.launchMarble();
}
},
click: (x, y, button, shift) => {
const
tileX = floorDiv(x - board.pos[0], TILE_SIZE),
tileY = floorDiv(y - board.pos[1], TILE_SIZE);
if(tileX >= 0 && tileX < HORIZ_TILES && tileY >= 0 && tileY < VERT_TILES)
board.tiles[tileY][tileX].click(board,
x - board.pos[0] - tileX * TILE_SIZE,
y - board.pos[1] - tileY * TILE_SIZE,
tileX, tileY, button, shift);
},
update: () => {
for(const marble of board.marbles.slice())
updateMarble(board, marble);
board.tiles.flat().forEach(tile => tile.update(board));
// Complete any wheels, if appropriate
const wheels = board.tiles.flat().filter(tile => tile.kind === 'wheel');
while(wheels.map(wheel => wheel.maybeComplete(board)).includes(1));
// Check if the board is complete
board.boardComplete = wheels.every(wheel => wheel.completed) ? 1 : 0;
if(board.launchTimeout > 0){
board.launchTimeout -= 1;
if(board.launchTimeout === 0)
board.boardComplete = -1;
}
if(board.boardTimeout > 0){
board.boardTimeout -= 1;
if(board.boardTimeout === 0)
board.boardComplete = -2;
}
},
draw: g => {
// Backdrop, info bar color and launcher
g.fillStyle = 'rgb(200, 200, 200)';
g.fillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
g.drawImage(images.backdrop, board.pos[0], board.pos[1]);
g.drawImage(images.launcherBackground, board.pos[0], board.pos[1] - MARBLE_SIZE);
g.drawImage(images.launcherV, board.pos[0] + BOARD_WIDTH, board.pos[1]);
board.tiles[0].forEach((tile, i) => {
if(tile.paths & 1)
g.drawImage(images.launcherEntrance, board.pos[0] + TILE_SIZE * i, board.pos[1] - MARBLE_SIZE);
});
g.drawImage(images.launcherCorner,
board.pos[0] + BOARD_WIDTH - (TILE_SIZE - MARBLE_SIZE) / 2, board.pos[1] - MARBLE_SIZE);
board.drawInfo(g);
board.tiles.flat().forEach(tile => tile.drawBack(g));
board.launchQueue.forEach((color, i) =>
g.drawImage(marbleImage(color), board.pos[0] + BOARD_WIDTH, board.pos[1] + i * MARBLE_SIZE - MARBLE_SIZE));
board.marbles.forEach(marble => drawMarble(g, marble));
board.tiles.flat().forEach(tile => tile.drawFore(g));
},
drawInfo: g => {
// Launch timer
const height = board.launchTimeout >= 0 && board.launchTimeoutStart > 0
? Math.floor(TIMER_HEIGHT * board.launchTimeout / board.launchTimeoutStart)
: TIMER_HEIGHT;
g.fillStyle = '#000';
g.fillRect(LAUNCH_TIMER_POS[0], LAUNCH_TIMER_POS[1], TIMER_WIDTH, TIMER_HEIGHT);
g.fillStyle = 'rgb(0, 40, 255)';
g.fillRect(LAUNCH_TIMER_POS[0] + TIMER_MARGIN, LAUNCH_TIMER_POS[1] + TIMER_HEIGHT - height,
TIMER_WIDTH - TIMER_MARGIN * 2, height);
g.font = fontFor(TIMER_WIDTH - 2 * TIMER_MARGIN);
g.fillStyle = '#fff';
g.textAlign = 'center';
g.textBaseline = 'alphabetic';
g.fillText(String(board.launchTimer), LAUNCH_TIMER_POS[0] + TIMER_WIDTH / 2 + 1,
LAUNCH_TIMER_POS[1] + TIMER_HEIGHT - TIMER_MARGIN - 4);
g.textAlign = 'left';
g.textBaseline = 'top';
// Info bar
g.font = fontFor(INFO_HEIGHT);
g.fillStyle = '#000';
g.fillText(board.boardName, 8, 2);
g.fillText(`Score: ${String(game.score).padStart(8, '0')}`, board.scorePos, 2);
const remaining = Math.floor((board.boardTimeout + FRAMES_PER_SEC - 1) / FRAMES_PER_SEC);
g.fillText(`${Math.floor(remaining / 60)}:${String(remaining % 60).padStart(2, '0')}`, board.boardTimerPos, 2);
// Lives
for(let i = 0; i < game.lives - 1; i++)
g.drawImage(images.lifeMarble,
board.boardTimerPos - 32 - (LIFE_MARBLE_SIZE + 4) * i - LIFE_MARBLE_SIZE,
INFO_HEIGHT / 2 - LIFE_MARBLE_SIZE / 2);
// Live marble count
g.font = fontFor(MARBLE_SIZE);
g.fillStyle = 'rgb(40, 40, 40)';
g.textBaseline = 'middle';
g.fillText(`${Math.min(board.marbles.length, board.liveMarblesLimit)}/${board.liveMarblesLimit}`,
board.pos[0] + 8, board.pos[1] - HALF_MARBLE + 1);
g.textBaseline = 'top';
}
};
board.setLaunchTimer(DEFAULT_LAUNCH_TIMER);
board.setBoardTimer(DEFAULT_BOARD_TIMER);
// Levels past the last one are picked pseudo-randomly, but repeatably.
const index = game.level < game.numLevels ? game.level : game.randomLevelIndex(game.level);
const { params: p, rows } = levelData[index];
if(p.name !== undefined)
board.name = p.name;
if(p.maxmarbles !== undefined)
board.liveMarblesLimit = parseInt(p.maxmarbles, 10);
if(p.launchtimer !== undefined)
board.setLaunchTimer(parseInt(p.launchtimer, 10));
if(p.colors !== undefined)
// Crazy marbles (8) are one-third as common as the others
board.colors = [...p.colors].flatMap(c => c >= '0' && c <= '7' ? [+c, +c, +c] : c === '8' ? [8] : []);
const stoplight = p.stoplight === undefined ? DEFAULT_STOPLIGHT
: [...p.stoplight].filter(c => c >= '0' && c <= '7').map(Number);
const teleporters = {};
let numWheels = 0;
for(let j = 0; j < VERT_TILES; j++)
for(let i = 0; i < HORIZ_TILES; i++){
const line = rows[j] ?? '';
if(line.length < (i + 1) * 4){
board.setTile(i, j, makeTile('plain'));
continue;
}
const
type = line[i * 4 + 1],
color = line[i * 4 + 3],
tile = makeTileFromCell(type, charValue(line[i * 4 + 2]), color, charValue(color), board.colors, stoplight, teleporters);
if(tile.kind === 'wheel')
numWheels++;
board.setTile(i, j, tile);
// Digits mark initial marble locations
if(type >= '0' && type <= '8')
board.marbles.push(makeMarble(+type, centerX(tile), centerY(tile), color in DIR_OF ? DIR_OF[color] : 3));
}
board.setBoardTimer(p.boardtimer === undefined ? DEFAULT_BOARD_TIMER * numWheels : parseInt(p.boardtimer, 10));
// Fill up the launch queue
for(let i = 0; i < Math.floor(BOARD_HEIGHT / MARBLE_SIZE) + 2; i++)
board.launchQueue.push(randomChoice(board.colors));
board.boardName = `${game.level + 1} - ${board.name}${game.level >= game.numLevels ? ' (Random)' : ''}`;
ctx.font = fontFor(INFO_HEIGHT);
board.scorePos = SCREEN_WIDTH - 8 - ctx.measureText('Score: 00000000').width;
board.boardTimerPos = board.scorePos - 16 - ctx.measureText('00:00').width;
return board;
};
// -------------------------------------------------------------- high scores
const highscores = {
scores: [],
currentScore: -1,
// Fills the list from storage, padding it with empty entries.
load: async () => {
const
raw = await storageGet('pathological.highscores'),
[{ value: parsed }] = await Promise.allSettled([Promise.resolve().then(() => JSON.parse(raw || '[]'))]);
highscores.scores = (Array.isArray(parsed) ? parsed : [])
.filter(s => Array.isArray(s) && s.length === 4)
.slice(0, NUM_HIGHSCORES)
.map(s => [Number(s[0]) || 0, String(s[1]), Number(s[2]) || 1, String(s[3])]);
while(highscores.scores.length < NUM_HIGHSCORES)
highscores.scores.push([0, 'all-boards', 1, '']);
},
qualifies: score => score >= highscores.scores[highscores.scores.length - 1][0],
add: (score, circuit, level, name) => {
const i = highscores.scores.findIndex(s => score >= s[0]);
if(i < 0)
return -1;
highscores.scores.splice(i, 0, [score, circuit, level, name]);
highscores.scores.length = NUM_HIGHSCORES;
storageSet('pathological.highscores', JSON.stringify(highscores.scores));
highscores.currentScore = i;
return i;
}
};
// ------------------------------------------------------------------- popup
const drawPopup = (g, text, minSize) => {
const lines = text.split('\n');
if(lines[lines.length - 1] === '')
lines.pop();
g.font = fontFor(24);
g.textBaseline = 'top';
g.textAlign = 'left';
const
spacing = 28,
maxWidth = Math.max(...lines.map(l => g.measureText(l).width)),
w = Math.max(Math.ceil(maxWidth) + 40, minSize?.[0] ?? 0),
h = Math.max(19 + spacing * (lines.length - 1) + 40, minSize?.[1] ?? 0),
x = Math.round((SCREEN_WIDTH - w) / 2),
y = Math.round((SCREEN_HEIGHT - h) / 2) - 40;
g.fillStyle = '#000';
g.fillRect(x, y, w, h);
g.fillStyle = 'rgb(250, 250, 250)';
g.fillRect(x + 1, y + 1, w - 2, h - 2);
g.fillStyle = '#000';
g.textAlign = 'center';
lines.forEach((l, i) => g.fillText(l, x + w / 2, y + 20 + i * spacing));
g.textAlign = 'left';
};
// ---------------------------------------------------------------------- md5
const
MD5_SHIFTS = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21],
MD5_K = Array.from({ length: 64 }, (_, i) => Math.floor(Math.abs(Math.sin(i + 1)) * 2 ** 32) >>> 0);
// Returns the 16 digest bytes of the UTF-8 encoding of `text`.
const md5Bytes = text => {
const
bytes = [...new TextEncoder().encode(text), 0x80],
bitLength = (bytes.length - 1) * 8;
while(bytes.length % 64 !== 56)
bytes.push(0);
for(let i = 0; i < 8; i++)
bytes.push(i < 4 ? (bitLength >>> (8 * i)) & 255 : 0);
let [a0, b0, c0, d0] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476];
for(let off = 0; off < bytes.length; off += 64){
const m = Array.from({ length: 16 }, (_, i) =>
(bytes[off + 4 * i] | (bytes[off + 4 * i + 1] << 8) | (bytes[off + 4 * i + 2] << 16) | (bytes[off + 4 * i + 3] << 24)) >>> 0);
let [a, b, c, d] = [a0, b0, c0, d0];
for(let i = 0; i < 64; i++){
const round = i >> 4;
let f, g;
if(round === 0){
f = (b & c) | (~b & d);
g = i;
}
else if(round === 1){
f = (d & b) | (~d & c);
g = (5 * i + 1) % 16;
}
else if(round === 2){
f = b ^ c ^ d;
g = (3 * i + 5) % 16;
}
else {
f = c ^ (b | ~d);
g = (7 * i) % 16;
}
f = (f + a + MD5_K[i] + m[g]) >>> 0;
a = d;
d = c;
c = b;
const shift = MD5_SHIFTS[round * 4 + i % 4];
b = (b + ((f << shift) | (f >>> (32 - shift)))) >>> 0;
}
a0 = (a0 + a) >>> 0;
b0 = (b0 + b) >>> 0;
c0 = (c0 + c) >>> 0;
d0 = (d0 + d) >>> 0;
}
return [a0, b0, c0, d0].flatMap(w => [w & 255, (w >>> 8) & 255, (w >>> 16) & 255, (w >>> 24) & 255]);
};
// -------------------------------------------------------------------- game
const makeGame = level => {
const game = {
numLevels: levelData.length,
level,
score: 0,
lives: INITIAL_LIVES,
gameStart: Date.now(),
board: null,
phase: 'play', // 'play', 'dialog' or 'name'
dialog: null,
popupText: null,
popupMin: null,
result: null, // set when the game ends: 'menu', 'gameover' or 'highscore'
// The original hashes the game start time and level with MD5, which makes
// the random level choice consistent and backtrackable within a game.
randomLevelIndex: lvl => {
const [a, b, c, d] = md5Bytes(`${game.gameStart}/${lvl}`);
return ((a + (b << 8) + (c << 16) + (d << 24)) & 32767) % game.numLevels;
},
increaseScore: amount => {
game.score += amount;
// Award any extra lives that are due
const extra = Math.min(
Math.floor(amount / EXTRA_LIFE_FREQUENCY) + (game.score % EXTRA_LIFE_FREQUENCY < amount % EXTRA_LIFE_FREQUENCY ? 1 : 0),
MAX_SPARE_LIVES + 1 - game.lives
);
if(extra > 0){
game.lives += extra;
playSound('extra_life');
}
},
startBoard: () => {
game.board = makeBoard(game);
game.phase = 'play';
game.popupText = null;
// First render, then launch the first marble
game.board.update();
game.board.launchMarble();
},
resetProgress: () => {
game.score = 0;
game.lives = INITIAL_LIVES;
},
// Events are {type: 'key', key, shift} or {type: 'mouse', x, y, button, shift}
handleEvent: ev => {
if(game.phase === 'play')
game.playEvent(ev);
else if(game.phase === 'dialog')
game.dialogEvent(ev);
},
step: () => {
if(game.phase !== 'play' || game.board.paused)
return;
game.board.update();
if(game.board.boardComplete)
game.endBoard(game.board.boardComplete);
},
playEvent: ev => {
const { board } = game;
if(ev.type === 'mouse'){
if(board.paused){
board.paused = false;
game.popupText = null;
}
else
board.click(ev.x, ev.y, ev.button, ev.shift);
return;
}
if(ev.key === 'Escape')
game.endBoard(-3);
else if(ev.key === 'n')
game.endBoard(2);
else if(ev.key === 'b')
game.endBoard(3);
else if([' ', 'p', 'Pause'].includes(ev.key)){
board.paused = !board.paused;
game.popupText = board.paused ? 'Game Paused' : null;
}
else if(ev.key === 'F2')
toggleFullscreen();
else if(ev.key === 'F3')
audio.toggleMusic();
else if(ev.key === 'F4')
toggleSound();
else if(ev.key === 'F5')
toggleColorblind();
},
// rc: 1 completed, 2 skip forward, 3 skip back, -1 launch timer, -2 board timer, -3 aborted
endBoard: rc => {
if(rc === 2){
game.level += 1;
game.startBoard();
return;
}
if(rc === 3){
if(game.level > 0)
game.level -= 1;
game.resetProgress();
game.startBoard();
return;
}
playSound(rc > 0 ? 'levelfinish' : 'die');
if(rc > 0){
game.completeBoard();
return;
}
const message = rc === -3 ? 'Level Aborted.'
: rc === -2 ? 'The board timer has expired.'
: 'The launch timer has expired.';
game.lives -= 1;
if(game.lives > 0)
game.openDialog(`${message}\nClick to try again.`, rc !== -3, false, () => {});
else if(highscores.qualifies(game.score)){
game.phase = 'name';
game.popupText = 'Congratulations!\nYou have a highscore!\nPlease enter your name:';
game.popupMin = [300, 180];
app.beginNameEntry(name => {
highscores.add(game.score, 'all-boards', game.level + 1, name);
game.result = 'highscore';
});
}
else
game.openDialog(`${message}\nGame Over.\nClick to continue\n`, rc !== -3, false, code => {
if(code === 1)
game.result = 'gameover';
else
game.resetProgress();
});
},
completeBoard: () => {
const
{ board } = game,
wheels = board.tiles.flat().filter(tile => tile.kind === 'wheel'),
totalHoles = wheels.length * 4,
emptyHoles = wheels.flatMap(wheel => wheel.marbles).filter(m => m < 0).length,
// Time remaining bonus
timeRemaining = Math.floor(100 * board.boardTimeout / Math.max(1, board.boardTimeoutStart)),
timeBonus = 5 * timeRemaining,
// Empty holes bonus
emptyPct = totalHoles ? Math.floor((100 * emptyHoles + Math.floor(totalHoles / 2)) / totalHoles) : 0,
holesBonus = 2 * emptyPct;
game.increaseScore(timeBonus + holesBonus);
game.openDialog(
'Level Complete!\n'
+ `Bonus for ${timeRemaining}% time remaining: ${timeBonus}\n`
+ `Bonus for ${emptyPct}% holes empty: ${holesBonus}\n`
+ '\nClick to continue.',
true, true, () => void (game.level += 1));
},
// The dialog callback receives -1 for Escape, 0 for b/n, 1 for any other event.
openDialog: (message, pause, complete, after) => {
game.phase = 'dialog';
game.popupText = message;
game.popupMin = null;
game.dialog = { complete, after, ignoreUntil: pause ? performance.now() + 1000 : 0 };
},
dialogEvent: ev => {
const d = game.dialog;
// The original sleeps for a second here and discards input.
if(performance.now() < d.ignoreUntil)
return;
let code = 1;
if(ev.type === 'key'){
if(ev.key === 'F2')
return toggleFullscreen();
if(ev.key === 'F3')
return audio.toggleMusic();
if(ev.key === 'F4')
return toggleSound();
if(ev.key === 'F5')
return toggleColorblind();
if(MODIFIER_KEYS.includes(ev.key))
return;
if(ev.key === 'Escape')
code = -1;
else if(ev.key === 'b'){
if(game.level > 0)
game.level -= 1;
game.resetProgress();
code = 0;
}
else if(ev.key === 'n'){
if(!d.complete)
game.level += 1;
code = 0;
}
}
game.dialog = null;
game.popupText = null;
if(code === -1){
game.result = 'menu';
return;
}
d.after(code);
if(!game.result)
game.startBoard();
},
draw: g => {
game.board.draw(g);
if(game.popupText)
drawPopup(g, game.popupText, game.popupMin);
}
};
highscores.currentScore = -1;
void audio.startMusic('background.xm', INGAME_MUSIC_VOLUME);
game.startBoard();
return game;
};
// ------------------------------------------------------------------- intro
const
MENU = ['Start Game', 'High Scores', 'Fullscreen:', 'Music:', 'Sound Effects:', 'Quit Game'],
MENU_WIDTH = 240,
MENU_POS = [(SCREEN_WIDTH - MENU_WIDTH) / 2, Math.floor(SCREEN_HEIGHT / 4.13)],
MENU_FONT_HEIGHT = 32,
MENU_OPTION_LEFT = 200,
SCROLLER_RECT = [10, SCREEN_HEIGHT - 50, SCREEN_WIDTH - 20, 28],
SCROLLER_TEXT = [
'Copyright (C) 2003 John-Paul Gignac.',
'Soundtrack by Matthias Le Bidan.',
'Board designs contributed by Mike Brenneman and Kim Gignac.',
'Web port of the original pygame game, see the README for details.',
'Logo by Carrie Bloomfield.',
'Other graphics based on artwork by Mike Brenneman.',
'Project motivated by Paul Prescod.',
'Thanks to all my friends who helped make this project a success!',
'This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License. See the LICENSE file for details.'
].join(' '),
HS_FONT_HEIGHT = 24,
HS_WIDTH = 320,
HS_POS = [(SCREEN_WIDTH - HS_WIDTH) / 2, Math.floor(SCREEN_HEIGHT / 5.26)],
HS_MARGIN = 8,
HS_SCORE_WIDTH = 70,
HS_LEVEL_WIDTH = 24;
const makeIntro = () => {
const intro = {
page: 0, // 0 is the menu, 1 the high scores
cursor: 0,
scrollerPos: -SCROLLER_RECT[2],
scrollerClock: 0,
scrollerWidth: 0,
startLevel: 1,
begin: showHighscores => {
intro.page = showHighscores ? 1 : 0;
intro.scrollerPos = -SCROLLER_RECT[2];
void audio.startMusic('intro.xm', INTRO_MUSIC_VOLUME);
},
// The original loop ran about 45 times a second, 2 pixels per iteration.
step: dtMs => {
intro.scrollerClock += dtMs;
while(intro.scrollerClock >= 22){
intro.scrollerClock -= 22;
intro.scrollerPos += 2;
if(intro.scrollerWidth > 0 && intro.scrollerPos >= intro.scrollerWidth)
intro.scrollerPos = -SCROLLER_RECT[2];
}
},
toMainMenu: () => {
playSound('menu_select');
intro.page = 0;
},
// Returns 'start', 'quit' or null.
select: i => {
if(i === 0)
return 'start';
if(i === 5)
return 'quit';
if(i === 4)
toggleSound();
playSound('menu_select');
if(i === 1)
intro.page = 1;
else if(i === 2)
toggleFullscreen();
else if(i === 3)
audio.toggleMusic();
return null;
},
handleEvent: ev => {
if(ev.type === 'mouse'){
if(intro.page === 1){
intro.toMainMenu();
return null;
}
const i = Math.floor((ev.y - MENU_POS[1]) / MENU_FONT_HEIGHT);
if(ev.x < MENU_POS[0] || ev.x >= MENU_POS[0] + MENU_WIDTH || ev.y < MENU_POS[1] || i >= MENU.length)
return null;
intro.cursor = i;
return intro.select(i);
}
const k = ev.key;
if(k === 'F2' || k === 'F3'){
playSound('menu_select');
if(k === 'F2')
toggleFullscreen();
else
audio.toggleMusic();
return null;
}
if(k === 'F4'){
toggleSound();
playSound('menu_select');
return null;
}
if(k === 'F5'){
toggleColorblind();
return null;
}
if(MODIFIER_KEYS.includes(k))
return null;
if(intro.page === 1){
intro.toMainMenu();
return null;
}
if(k === 'Escape')
return 'quit';
if(k === 'ArrowDown' || k === 'ArrowUp'){
intro.cursor = mod(intro.cursor + (k === 'ArrowDown' ? 1 : -1), MENU.length);
playSound('menu_scroll');
}
else if(k === ' ' || k === 'Enter')
return intro.select(intro.cursor);
else if(k === 'ArrowLeft' && intro.cursor === 0)
intro.startLevel = Math.max(1, intro.startLevel - 1);
else if(k === 'ArrowRight' && intro.cursor === 0 && intro.startLevel < Math.max(...highscores.scores.map(s => s[2])))
intro.startLevel += 1;
return null;
},
draw: g => {
g.drawImage(images.intro, 0, 0);
g.textBaseline = 'top';
g.textAlign = 'left';
if(intro.page === 1)
intro.drawHighscores(g);
else
intro.drawMenu(g);
// Scroller
g.save();
g.beginPath();
g.rect(...SCROLLER_RECT);
g.clip();
g.font = fontFor(28);
intro.scrollerWidth = g.measureText(SCROLLER_TEXT).width;
g.fillStyle = 'rgb(60, 60, 60)';
g.fillText(SCROLLER_TEXT, SCROLLER_RECT[0] - intro.scrollerPos, SCROLLER_RECT[1] + 3);
g.restore();
},
drawMenu: g => {
g.fillStyle = 'rgb(60, 60, 60)';
g.fillRect(MENU_POS[0] - 2, MENU_POS[1] + intro.cursor * MENU_FONT_HEIGHT, MENU_WIDTH + 4, MENU_FONT_HEIGHT - 2);
g.font = fontFor(MENU_FONT_HEIGHT);
g.fillStyle = '#fff';
MENU.forEach((label, i) => g.fillText(label, MENU_POS[0], MENU_POS[1] + i * MENU_FONT_HEIGHT + 4));
g.textAlign = 'right';
g.fillText(`(Lvl. ${intro.startLevel})`, MENU_POS[0] + MENU_OPTION_LEFT + 40, MENU_POS[1] + 4);
g.textAlign = 'left';
[!!document.fullscreenElement, settings.music, settings.sound].forEach((on, i) =>
g.fillText(on ? 'On' : 'Off', MENU_POS[0] + MENU_OPTION_LEFT, MENU_POS[1] + MENU_FONT_HEIGHT * (i + 2) + 4));
},
drawHighscores: g => {
g.font = fontFor(HS_FONT_HEIGHT);
const
w = s => g.measureText(s).width,
scoreRight = HS_WIDTH,
scoreLeft = scoreRight - w('Score'),
levelRight = scoreRight - HS_SCORE_WIDTH - HS_MARGIN,
levelLeft = levelRight - w('Level'),
nameRight = levelRight - HS_LEVEL_WIDTH - HS_MARGIN,
numberWidth = w('10.'),
nameLeft = numberWidth + 5,
nameWidth = nameRight - nameLeft,
[x, top] = HS_POS;
g.fillStyle = '#000';
g.fillText('Name', x + nameLeft, top);
g.fillText('Level', x + levelLeft, top);
g.fillText('Score', x + scoreLeft, top);
highscores.scores.forEach(([score, , level, name], j) => {
const
y = top + HS_FONT_HEIGHT * (j + 1),
current = j === highscores.currentScore;
g.fillStyle = current ? 'rgb(240, 50, 50)' : 'rgb(210, 210, 210)';
g.textAlign = 'right';
g.fillText(`${j + 1}.`, x + numberWidth, y);
g.fillStyle = current ? 'rgb(240, 50, 50)' : 'rgb(240, 240, 240)';
g.fillText(String(level), x + levelRight, y);
g.fillText(String(score), x + scoreRight, y);
g.textAlign = 'left';
g.save();
g.beginPath();
g.rect(x + nameLeft, y - 2, nameWidth, HS_FONT_HEIGHT);
g.clip();
g.fillText(name, x + nameLeft, y);
g.restore();
});
}
};
return intro;
};
// --------------------------------------------------------------------- app
const positionNameInput = () => {
const scale = canvas.clientWidth / SCREEN_WIDTH;
// Matches get_name(): a 250 px wide box at (275, 310), one font-height tall
Object.assign(nameInput.style, {
left: `${275 * scale}px`,
top: `${310 * scale}px`,
width: `${250 * scale}px`,
height: `${22 * scale}px`,
fontSize: `${16 * scale}px`
});
};
const app = {
mode: 'intro', // 'intro', 'game' or 'quit'
intro: null,
game: null,
events: [],
nameCallback: null,
push: ev => void app.events.push(ev),
beginNameEntry: callback => {
app.nameCallback = callback;
nameInput.hidden = false;
nameInput.value = '';
positionNameInput();
nameInput.focus();
},
finishNameEntry: () => {
if(!app.nameCallback)
return;
const callback = app.nameCallback;
app.nameCallback = null;
nameInput.hidden = true;
canvas.focus();
callback(nameInput.value.trim());
},
step: dtMs => {
const events = app.events.splice(0);
if(app.mode === 'intro'){
app.intro.step(dtMs);
for(const ev of events){
const rc = app.intro.handleEvent(ev);
if(rc === 'start'){
app.game = makeGame(app.intro.startLevel - 1);
app.mode = 'game';
break;
}
if(rc === 'quit'){
// Browsers only honor this for windows a script opened; otherwise the goodbye screen shows.
window.close();
app.mode = 'quit';
break;
}
}
}
else if(app.mode === 'game'){
for(const ev of events){
app.game.handleEvent(ev);
if(app.game.result)
break;
}
app.game.step();
if(app.game.result){
const { result } = app.game;
app.mode = 'intro';
app.nameCallback = null;
nameInput.hidden = true;
app.intro.begin(['highscore', 'gameover'].includes(result));
app.game = null;
}
}
else if(events.some(ev => ev.type === 'mouse' || !ev.key.startsWith('F'))){
app.mode = 'intro';
app.intro.begin(false);
}
},
draw: () => {
ctx.imageSmoothingEnabled = true;
if(app.mode === 'game')
app.game.draw(ctx);
else {
app.intro.draw(ctx);
if(app.mode === 'quit')
drawPopup(ctx, 'Thanks for playing Pathological!\nClick to return to the menu.');
}
}
};
// ------------------------------------------------------------------- input
const
HANDLED_KEYS = ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', ' ', 'Enter', 'Escape', 'F2', 'F3', 'F4', 'F5', 'Pause'],
canvasPoint = e => {
const r = canvas.getBoundingClientRect();
return [
Math.floor((e.clientX - r.left) * SCREEN_WIDTH / r.width),
Math.floor((e.clientY - r.top) * SCREEN_HEIGHT / r.height)
];
};
const installInput = () => {
window.addEventListener('keydown', e => {
audio.resume();
if(e.target === nameInput){
if(['Enter', 'Escape'].includes(e.key)){
e.preventDefault();
app.finishNameEntry();
}
return;
}
if(e.ctrlKey || e.metaKey || e.altKey)
return;
if(HANDLED_KEYS.includes(e.key))
e.preventDefault();
if(e.repeat && !['ArrowLeft', 'ArrowRight'].includes(e.key))
return;
app.push({ type: 'key', key: e.key.length === 1 ? e.key.toLowerCase() : e.key, shift: e.shiftKey });
});
// Mouse and touch. A long press on a touch screen acts as a right click.
let press = null;
canvas.addEventListener('contextmenu', e => e.preventDefault());
canvas.addEventListener('pointerdown', e => {
audio.resume();
canvas.focus();
const
[x, y] = canvasPoint(e),
shift = e.shiftKey || !!e.getModifierState?.('CapsLock');
if(e.pointerType === 'touch'){
press = { x, y, shift, id: e.pointerId, fired: false };
press.timer = setTimeout(() => {
press.fired = true;
app.push({ type: 'mouse', x, y, button: 2, shift });
}, 450);
return;
}
e.preventDefault();
// Middle click and Ctrl + click stand in for a right click, as on trackpads.
const right = e.button === 2 || e.button === 1 || (e.button === 0 && e.ctrlKey);
app.push({ type: 'mouse', x, y, button: right ? 2 : 0, shift });
});
const endPress = e => {
if(!press || e.pointerId !== press.id)
return;
clearTimeout(press.timer);
if(!press.fired && e.type === 'pointerup')
app.push({ type: 'mouse', x: press.x, y: press.y, button: 0, shift: press.shift });
press = null;
};
canvas.addEventListener('pointerup', endPress);
canvas.addEventListener('pointercancel', endPress);
nameInput.addEventListener('blur', () => void setTimeout(() => {
if(app.nameCallback)
nameInput.focus();
}, 0));
// Toolbar
document.querySelectorAll('#toolbar button').forEach(btn => btn.addEventListener('click', () => {
audio.resume();
app.push({ type: 'key', key: btn.dataset.key, shift: false });
btn.blur();
canvas.focus();
}));
document.addEventListener('fullscreenchange', () => {
document.body.classList.toggle('fullscreen', !!document.fullscreenElement);
resize();
});
};
const updateToolbar = () => Object.entries({
'btn-sound': settings.sound,
'btn-music': settings.music,
'btn-cb': settings.colorblind,
'btn-fs': !!document.fullscreenElement
}).forEach(([id, on]) => document.getElementById(id).setAttribute('aria-pressed', String(on)));
const resize = () => {
const
w = Math.max(SCREEN_WIDTH, Math.round(canvas.clientWidth * (window.devicePixelRatio || 1))),
h = Math.round(w * SCREEN_HEIGHT / SCREEN_WIDTH);
if(canvas.width !== w || canvas.height !== h){
canvas.width = w;
canvas.height = h;
}
positionNameInput();
};
// -------------------------------------------------------------------- main
const main = async () => {
const
loading = document.getElementById('loading'),
[{ value: storedCb }] = await Promise.allSettled([storageGet('pathological.colorblind')]);
if(storedCb === '1')
settings.colorblind = true;
audio.init();
const [loaded] = await Promise.allSettled([
Promise.all([loadImages(), fetch('circuits/all-boards').then(r => r.text()), highscores.load()])
]);
if(loaded.reason){
loading.textContent = String(loaded.reason.message || loaded.reason);
return;
}
levelData = parseLevels(loaded.value[1]);
loading.hidden = true;
installInput();
window.addEventListener('resize', resize);
new ResizeObserver(resize).observe(canvas);
resize();
app.intro = makeIntro();
app.intro.begin(false);
let
last = performance.now(),
acc = 0;
const frame = now => {
acc += Math.min(now - last, 250);
last = now;
for(; acc >= FRAME_MS; acc -= FRAME_MS)
app.step(FRAME_MS);
ctx.setTransform(canvas.width / SCREEN_WIDTH, 0, 0, canvas.height / SCREEN_HEIGHT, 0, 0);
app.draw();
updateToolbar();
requestAnimationFrame(frame);
};
requestAnimationFrame(frame);
window.pathological = { app, audio, settings, highscores, levelData, makeGame, md5Bytes };
};
void main();