Folder structure

This commit is contained in:
zenoamaro committed 2019-06-30 13:01:53 +02:00
1 parent 946059650f
commit 2ed630a9cd
13 files changed
+2 -2

No files matched your search

+14
View File
@@ -0,0 +1,14 @@
import {PLAYER_MAX_ENERGY, PLAYER_INITIAL_POWER, PLAYER_ENERGY_POWER_MULTIPLIER} from './constants.js';
import {randomInt} from './math.js';
export const AI_TYPES = {
moron: {
decide() {
return {
a: randomInt(0, 180),
p: randomInt(PLAYER_INITIAL_POWER, PLAYER_MAX_ENERGY*PLAYER_ENERGY_POWER_MULTIPLIER)}
}
},
};
+107
View File
@@ -0,0 +1,107 @@
export const W = 640;
export const H = 400;
export const Z = 2;
export const SKY_COLORS = [
{from:[42, 78, 108], to:[0, 0, 0]},
{from:[82, 120, 187], to:[201, 218, 236]},
{from:[94, 171, 184], to:[225, 172, 139]},
{from:[49, 76, 148], to:[242, 171, 85]},
{from:[51, 89, 135], to:[163, 198, 220]},
{from:[105, 95, 108], to:[223, 183, 110]},
];
export const MAX_PLAYERS = 6;
export const PLAYER_COLORS = [
['tomato', 'darkred'],
['royalblue', 'darkblue'],
['greenyellow', 'green'],
['gold', 'peru'],
['hotpink', 'mediumvioletred'],
['blueviolet', 'indigo'],
];
export const PLAYER_STARTING_WEAPONS = [
{type: 'babyMissile', ammo:Infinity},
{type: 'missile', ammo:5},
{type: 'babyNuke', ammo:3},
{type: 'nuke', ammo:1},
{type: 'smallDirt', ammo:5},
{type: 'dirt', ammo:3},
{type: 'largeDirt', ammo:1},
{type: 'smallDigBomb', ammo:5},
{type: 'digBomb', ammo:3},
{type: 'largeDigBomb', ammo:1},
{type: 'tracer', ammo:Infinity},
]
export const WEAPON_TYPES = [
{id:'tracer', name:'Tracer', explosion:{type:'tracer'}},
{id:'babyMissile', name:'Baby Missile', explosion:{type:'blast', r:5}},
{id:'missile', name:'Missile', explosion:{type:'blast', r:20}},
{id:'babyNuke', name:'Baby Nuke', explosion:{type:'blast', r:50}},
{id:'nuke', name:'Nuke', explosion:{type:'blast', r:100}},
{id:'smallDirt', name:'Small Dirt', explosion:{type:'dirt', r:25}},
{id:'dirt', name:'Dirt', explosion:{type:'dirt', r:50}},
{id:'largeDirt', name:'Ton of Dirt', explosion:{type:'dirt', r:75}},
{id:'smallDigBomb', name:'Small Dig Bomb', explosion:{type:'digBomb', r:25}},
{id:'digBomb', name:'Dig Bomb', explosion:{type:'digBomb', r:50}},
{id:'largeDigBomb', name:'Large Dig Bomb', explosion:{type:'digBomb', r:75}},
];
export const DEATH_SPECS = [
{type: 'blast', r: 15},
{type: 'blast', r: 30},
{type: 'blast', r: 60},
{type: 'dirt', r: 25},
{type: 'dirt', r: 50},
{type: 'dirt', r: 75},
{type: 'digBomb', r: 25},
{type: 'digBomb', r: 50},
{type: 'digBomb', r: 75},
{type: 'dirtCone', r: 50},
{type: 'dirtCone', r: 100},
{type: 'dirtCone', r: 150},
];
export const MAX_WIND = 25;
export const DEFAULT_KEYPRESS_DELAY = 150;
export const PLAYER_MAX_ENERGY = 100;
export const PLAYER_ENERGY_POWER_MULTIPLIER = 10;
export const PLAYER_INITIAL_POWER = 300;
export const PLAYER_FALL_DAMAGE_HEIGHT = 50;
export const PLAYER_FALL_DAMAGE_FACTOR = 3;
export const PLAYER_EXPLOSION_PARTICLE_POWER = 500;
export const PLAYER_TANK_BOUNDING_RADIUS = 3;
export const PLAYER_ANGLE_INCREMENT = 1;
export const PLAYER_ANGLE_FAST_INCREMENT = 3;
export const PLAYER_POWER_INCREMENT = 1;
export const PLAYER_POWER_FAST_INCREMENT = 10;
export const PLAYER_ANGLE_TICK_SOUND_INTERVAL = 2;
export const PLAYER_POWER_TICK_SOUND_INTERVAL = 2;
export const PROJECTILE_POWER_REDUCTION_FACTOR = 10;
export const PROJECTILE_WIND_REDUCTION_FACTOR = 10;
export const PROJECTILE_ITERATIONS_PER_FRAME = 30;
export const PROJECTILE_ITERATION_PROGRESS = 0.01;
export const PROJECTILE_MIN_SOUND_FREQUENCY = 220;
export const PROJECTILE_MAX_SOUND_FREQUENCY = 2200;
export const TRAJECTORY_FADE_SPEED = 0.6;
export const TRAJECTORY_FLOAT_SPEED = 0.01;
export const PARTICLE_AMOUNT = 30;
export const PARTICLE_MIN_POWER_FACTOR = 0.4;
export const PARTICLE_MAX_POWER_FACTOR = 1;
export const PARTICLE_MIN_LIFETIME = 5;
export const PARTICLE_TIME_FACTOR = 13;
export const PARTICLE_POWER_REDUCTION_FACTOR = 15;
export const PARTICLE_WIND_REDUCTION_FACTOR = 3;
export const PARTICLE_FADE_AMOUNT = 1;
export const MAX_EXPLOSION_SHAKE_FACTOR = 60;
export const EXPLOSION_SHAKE_REDUCTION_FACTOR = 7;
export const FONT_WIDTH = 3;
export const FONT_HEIGHT = 5;
+135
View File
@@ -0,0 +1,135 @@
import {splitWords} from './utils.js';
import {parable} from './math.js';
import {FONT_HEIGHT, FONT_WIDTH} from './constants.js';
export function createCanvas(width, height) {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = width; canvas.height = height
return ctx;
}
export function loadImage(src) {
return new Promise((resolve, reject) => {
const img = document.createElement('img');
img.onload = (e) => resolve(img);
// @ts-ignore
img.onerror = (e) => reject(e.error);
img.src = src;
});
}
export function clipCanvas(ctx, fn) {
ctx.globalCompositeOperation = 'destination-out';
fn(ctx);
ctx.globalCompositeOperation = 'source-over';
}
export function plot(ctx, x, y, color) {
x = Math.round(x); y = Math.round(y);
ctx.fillStyle = color;
ctx.fillRect(x, y, 1, 1);
}
export function drawLine(ctx, x1, y1, x2, y2, color, plotFn=plot) {
x1 = Math.round(x1); y1 = Math.round(y1);
x2 = Math.round(x2); y2 = Math.round(y2);
const steep = Math.abs(y2 - y1) > Math.abs(x2 - x1);
if (steep) [x1, y1, x2, y2] = [y1, x1, y2, x2];
if (x1 > x2) [x1, y1, x2, y2] = [x2, y2, x1, y1];
const dX = (x2 - x1);
const dY = Math.abs(y2 - y1);
const ystep = (y1 < y2 ? 1 : -1);
let err = (dX / 2);
let y = y1;
for (let x = x1; x <= x2; ++x) {
if (steep) plotFn(ctx, y, x, color); else plotFn(ctx, x, y, color);
err = err - dY; if (err < 0) { y += ystep; err += dX }
}
}
export function drawLineVirtual(x1, y1, x2, y2, color) {
const points = [];
drawLine(null, x1, y1, x2, y2, color, (ctx, x, y, c) => points.push({x, y, c}));
return points;
}
export function drawRect(ctx, x, y, w, h, color) {
x = Math.round(x); y = Math.round(y);
w = Math.round(w); h = Math.round(h);
ctx.fillStyle = color;
ctx.fillRect(x, y, w, h);
}
export function strokeRect(ctx, x, y, w, h, color) {
if (w === 1 || h === 1) return drawRect(x, y, w, h, color);
x = Math.round(x); y = Math.round(y);
w = Math.round(w); h = Math.round(h);
ctx.lineWidth = 1;
ctx.strokeStyle = color;
ctx.strokeRect(x+0.5, y+0.5, w-1, h-1);
}
export function drawCircle(ctx, x, y, r, color) {
x = Math.round(x);
y = Math.round(y);
r = Math.round(r);
for (let cy = -r; cy <= r; cy++) {
const w = Math.round(Math.sqrt(r*r - cy*cy));
drawRect(ctx, x-w, y+cy, w*2, 1, color);
}
}
/** @param align {CanvasTextAlign} */
/** @param baseline {CanvasTextBaseline} */
export function drawText(ctx, text, x, y, color, align='left', baseline='top') {
x = Math.round(x); y = Math.round(y);
ctx.font = '5px text';
ctx.textBaseline = 'top';
ctx.textAlign = 'left';
ctx.fillStyle = color;
ctx.strokeStyle = 'black';
const length = (text.length * FONT_WIDTH) + (text.length -1);
const left = (
align === 'right' ? x - length :
align === 'center' ? x - Math.round(length /2) :
x
);
const top = (
baseline === 'bottom' ? y - FONT_HEIGHT :
baseline === 'middle' ? y - Math.round(FONT_HEIGHT /2) :
y
);
for (let i=0; i<text.length; i++) {
ctx.strokeText(text[i], left + i*FONT_WIDTH + i, top);
ctx.fillText(text[i], left + i*FONT_WIDTH + i, top);
}
}
export function drawParagraph(ctx, text, x, y, w, h, color) {
x = Math.round(x); y = Math.round(y);
w = Math.round(w); h = Math.round(h);
let tx = 0; let ty = 0;
// FIXME: Handle unbreakable words longer than width
const words = splitWords(text);
for (let word of words) {
const wordLength = word.length * 4;
if (word === '\n') { tx = 0; ty += 6; continue }
else if (tx + wordLength > w) { tx = 0; ty += 6 }
if (ty+6 > h) return;
for (let char of word) {
drawText(ctx, char, x+tx, y+ty, color);
tx += 4;
}
}
}
export function loop(fn) {
(function looped() {
fn();
requestAnimationFrame(looped);
})();
}
+19
View File
@@ -0,0 +1,19 @@
import {DEFAULT_KEYPRESS_DELAY} from './constants.js';
const input = {};
let lastKeypressTime = 0;
document.addEventListener('keydown', (e) => {input[e.key] = true; e.preventDefault()});
document.addEventListener('keyup', (e) => {input[e.key] = false; e.preventDefault()});
export function key(key) {
return input[key]
}
export function afterKeyDelay(amount=DEFAULT_KEYPRESS_DELAY) {
const now = Date.now();
if (now - lastKeypressTime >= amount) {
lastKeypressTime = now;
return true;
}
}
+449
View File
@@ -0,0 +1,449 @@
import {H, PROJECTILE_MAX_SOUND_FREQUENCY, MAX_WIND, PROJECTILE_MIN_SOUND_FREQUENCY, PLAYER_COLORS, PLAYER_INITIAL_POWER, PROJECTILE_POWER_REDUCTION_FACTOR, W, Z, PROJECTILE_ITERATIONS_PER_FRAME, PROJECTILE_ITERATION_PROGRESS, PLAYER_MAX_ENERGY, PLAYER_ENERGY_POWER_MULTIPLIER, PLAYER_FALL_DAMAGE_FACTOR, PLAYER_FALL_DAMAGE_HEIGHT, PARTICLE_AMOUNT, PROJECTILE_WIND_REDUCTION_FACTOR, PARTICLE_POWER_REDUCTION_FACTOR, PARTICLE_WIND_REDUCTION_FACTOR, PARTICLE_MIN_POWER_FACTOR, PARTICLE_MAX_POWER_FACTOR, PARTICLE_MIN_LIFETIME, PARTICLE_TIME_FACTOR, PLAYER_EXPLOSION_PARTICLE_POWER, EXPLOSION_SHAKE_REDUCTION_FACTOR, MAX_EXPLOSION_SHAKE_FACTOR, TRAJECTORY_FADE_SPEED, PARTICLE_FADE_AMOUNT, TRAJECTORY_FLOAT_SPEED, PLAYER_TANK_BOUNDING_RADIUS, PLAYER_STARTING_WEAPONS, WEAPON_TYPES, DEATH_SPECS, PLAYER_ANGLE_INCREMENT, PLAYER_POWER_FAST_INCREMENT, PLAYER_POWER_INCREMENT, PLAYER_ANGLE_TICK_SOUND_INTERVAL, PLAYER_POWER_TICK_SOUND_INTERVAL, PLAYER_ANGLE_FAST_INCREMENT} from './constants.js';
import {createCanvas, drawLine, drawRect, drawText, loop, plot, drawLineVirtual} from './gfx.js';
import {key, afterKeyDelay} from './input.js';
import {clamp, deg2rad, parable, randomInt, vec, wrap, random, within} from './math.js';
import {createSky} from './sky.js';
import {audio, createOsc, playTickSound} from './sound.js';
import {collapseTerrain, createTerrain, isTerrain, landHeight, closestLand, clipTerrain} from './terrain.js';
import {EXPLOSION_TYPES} from './weapons.js';
import {sample} from './utils.js';
import {AI_TYPES} from './ai.js';
let state = 'start-game';
const players = [];
let currentPlayer = 0;
let projectile = null;
let explosion = null;
let wind = 0;
let particles = [];
let screenShake = 0;
let trajectories = [];
let idle = false;
// Init layers
const sky = createSky(W, H);
const traces = createCanvas(W, H);
const terrain = createTerrain(W, H);
const foreground = createCanvas(W, H);
for (let c of [sky, traces, terrain, foreground]) {
c.canvas.style.width = `${W * Z}px`;
c.canvas.style.height = `${H * Z}px`;
document.body.appendChild(c.canvas);
}
// Init players
let i=0;
for (let [color, borderColor] of PLAYER_COLORS) {
const x = 50 + (W-100) / 5 * i;
const y = landHeight(terrain, x) + 1;
const a = x > W/2 ? 45 : 180-45;
players.push({
x, y, a,
c: color, cb: borderColor,
p: PLAYER_INITIAL_POWER,
weapons: [...PLAYER_STARTING_WEAPONS],
currentWeapon: 0,
energy: PLAYER_MAX_ENERGY,
ai: i !== 0 ? 'moron' : undefined,
fallHeight: 0,
dead: false,
});
clipTerrain(terrain, (ctx) => drawRect(ctx, x-4, 0, 8, y, ctx.color));
i++;
}
function update() {
idle = false;
updateParticles();
if (state === 'start-game') {
wind = randomInt(-MAX_WIND, +MAX_WIND);
state = 'start-turn';
}
else if (state === 'start-turn') {
state = 'aim';
}
else if (state === 'aim') {
const player = players[currentPlayer];
const {x, y, a, p, energy} = player;
const maxPower = energy * PLAYER_ENERGY_POWER_MULTIPLIER;
const isPrecise = key('Alt');
const isFast = key('Shift');
const isReverse = key('Shift');
let shoot;
if (player.ai) {
let ai = AI_TYPES[player.ai];
const plan = ai.decide();
const a = player.a = wrap(0, plan.a, 180);
const p = player.p = clamp(0, plan.p, maxPower);
shoot = {a, p};
}
else if (key('ArrowLeft')) {
if (isPrecise && !afterKeyDelay()) return;
let incr = isFast ? PLAYER_ANGLE_FAST_INCREMENT : PLAYER_ANGLE_INCREMENT;
player.a = wrap(0, a -incr, 180);
if (isPrecise || isFast || a % PLAYER_ANGLE_TICK_SOUND_INTERVAL === 0) playTickSound();
} else if (key('ArrowRight')) {
if (isPrecise && !afterKeyDelay()) return;
let incr = isFast ? PLAYER_ANGLE_FAST_INCREMENT : PLAYER_ANGLE_INCREMENT;
player.a = wrap(0, a +incr, 180);
if (isPrecise || isFast || a % PLAYER_ANGLE_TICK_SOUND_INTERVAL === 0) playTickSound();
} else if (key('ArrowUp')) {
if (isPrecise && !afterKeyDelay()) return;
let incr = isFast ? PLAYER_POWER_FAST_INCREMENT : PLAYER_POWER_INCREMENT;
player.p = clamp(0, p +incr, maxPower);
if (p < maxPower && (isPrecise || isFast || p % PLAYER_POWER_TICK_SOUND_INTERVAL === 0)) playTickSound();
} else if (key('ArrowDown')) {
if (isPrecise && !afterKeyDelay()) return;
let incr = isFast ? PLAYER_POWER_FAST_INCREMENT : PLAYER_POWER_INCREMENT;
player.p = clamp(0, p -incr, maxPower);
if (p > 0 && (isPrecise || isFast || p % PLAYER_POWER_TICK_SOUND_INTERVAL === 0)) playTickSound();
} else if (key('Tab')) {
if (!afterKeyDelay()) return;
const dir = isReverse ? -1 : 1;
player.currentWeapon = wrap(0, player.currentWeapon+dir, player.weapons.length);
playTickSound();
} else if (key(' ')) {
if (!afterKeyDelay()) return;
shoot = {a, p};
} else {
idle = true;
}
if (shoot) {
const {a, p} = shoot;
const [px, py] = vec(x, y-3, a+180, 5);
const weaponType = player.weapons[player.currentWeapon];
weaponType.ammo -= 1;
projectile = {
osc: createOsc(),
player: player,
weaponTypeId: weaponType.type,
ox:px, oy:py, a, p,
x:px, y:py, t: 0,
c: player.c
};
projectile.osc.start();
state = 'shoot';
}
}
else if (state === 'shoot') {
const prevProjectile = {...projectile};
for (let i=0; i<PROJECTILE_ITERATIONS_PER_FRAME; i++) {
const {weaponTypeId, ox, oy, a, p, t} = projectile;
const weapon = WEAPON_TYPES.find(x => x.id === weaponTypeId);
const [x, y] = parable(
t, ox, oy, deg2rad(180+a),
p / PROJECTILE_POWER_REDUCTION_FACTOR,
wind / PROJECTILE_WIND_REDUCTION_FACTOR,
);
const f = (
(1 - (1 / H * y)) *
(PROJECTILE_MAX_SOUND_FREQUENCY - PROJECTILE_MIN_SOUND_FREQUENCY) +
PROJECTILE_MIN_SOUND_FREQUENCY
);
projectile.t += PROJECTILE_ITERATION_PROGRESS;
projectile.x = x;
projectile.y = y;
projectile.osc.frequency.setValueAtTime(f, audio.currentTime);
if (
projectile.y > H ||
isTank(projectile.x, projectile.y) ||
isTerrain(terrain, projectile.x, projectile.y)
) {
projectile.osc.stop();
const explosionSpec = weapon.explosion;
const explosionType = EXPLOSION_TYPES[explosionSpec.type];
explosion = explosionType.create(explosionSpec, projectile.x, projectile.y);
// @ts-ignore: canvas color hack
createParticles(projectile.x, projectile.y, projectile.p, terrain.color);
state = 'explosion';
break;
}
}
fadeTrajectories(TRAJECTORY_FADE_SPEED);
let trajectory = drawLineVirtual(
prevProjectile.x, prevProjectile.y,
projectile.x, projectile.y,
projectile.c,
)
trajectory = trajectory
.slice(0, trajectory.length-1) // Cut last pixel to prevent overlap
.map(x => ({...x, a:255})); // Add alpha to all lines
trajectories = [
...trajectories,
...trajectory,
];
}
else if (state === 'explosion') {
const explosionType = EXPLOSION_TYPES[explosion.type];
screenShake = (
clamp(0, explosion.r, MAX_EXPLOSION_SHAKE_FACTOR) /
EXPLOSION_SHAKE_REDUCTION_FACTOR
);
if (!explosionType.update(explosion)) {
screenShake = 0;
explosionType.clip(explosion, terrain);
explosionType.stop(explosion);
for (let player of players) if (!player.dead) {
player.energy -= explosionType.damage(explosion, player) || 0;
}
explosion = null;
state = 'land-collapse';
}
}
else if (state === 'land-collapse') {
collapseTerrain(terrain);
state = 'land-players';
}
else if (state === 'land-players') {
let stable = true;
for (let player of players) {
if (player.dead) continue;
const y = closestLand(terrain, player.x, player.y);
if (player.y !== y) {
stable = false;
player.y++;
if (player.fallHeight++ >= PLAYER_FALL_DAMAGE_HEIGHT) {
player.energy -= PLAYER_FALL_DAMAGE_FACTOR;
}
}
}
if (stable) state = 'destroy-players';
}
else if (state === 'destroy-players') {
const dyingPlayer = players.find(x => x.energy<=0 && !x.dead);
if (!dyingPlayer) {state = 'end-turn'; return}
const {x, y, c} = dyingPlayer;
const explosionSpec = sample(DEATH_SPECS);
const explosionType = EXPLOSION_TYPES[explosionSpec.type];
explosion = explosionType.create(explosionSpec, x, y);
createParticles(x, y, PLAYER_EXPLOSION_PARTICLE_POWER, c);
dyingPlayer.dead = true;
state = 'explosion';
}
else if (state === 'end-turn') {
const player = players[currentPlayer];
const weaponType = player.weapons[player.currentWeapon];
if (weaponType.ammo <= 0) {
player.weapons = player.weapons.filter(x => x !== weaponType);
}
player.currentWeapon = wrap(0, player.currentWeapon, player.weapons.length);
player.fallHeight = 0;
let nextPlayer;
for (let p=0; p<players.length; p++) {
const i = wrap(0, currentPlayer+p+1, players.length);
if (!players[i].dead) {nextPlayer = i; break}
}
if (nextPlayer == null) return state = 'game-over';
else if (nextPlayer === currentPlayer) return state = 'player-win';
else currentPlayer = nextPlayer;
projectile = null;
state = 'start-turn';
}
else if (state === 'player-win') {
idle = true;
}
else if (state === 'game-over') {
idle = true;
}
else {
throw new Error(`Invalid state, ${state}`);
}
}
function createParticles(x, y, p, c) {
for (let i = 0; i < PARTICLE_AMOUNT; i++) {
particles.push({
t: 0,
ox: x, x: x,
oy: y, y: y,
a: randomInt(0, 359),
p: p * random(PARTICLE_MIN_POWER_FACTOR, PARTICLE_MAX_POWER_FACTOR),
// @ts-ignore: canvas color hack
c, alpha: 255,
});
}
}
function updateParticles() {
for (let i=particles.length-1; i>=0; i--) {
const particle = particles[i];
if (
particle.y > H ||
particle.alpha <= 0 ||
particle.t > PARTICLE_MIN_LIFETIME && isTerrain(terrain, particle.x, particle.y)
) {
particles.splice(i, 1);
continue;
}
const {ox, oy, t, a, p} = particle;
const [tx, ty] = parable(
t / PARTICLE_TIME_FACTOR,
ox, oy, deg2rad(180+a),
p / PARTICLE_POWER_REDUCTION_FACTOR,
wind / PARTICLE_WIND_REDUCTION_FACTOR,
);
particle.t++;
particle.x = tx;
particle.y = ty;
particle.alpha -= PARTICLE_FADE_AMOUNT;
}
}
function isTank(x, y) {
for (let player of players) {
if (within(x, y, player.x, player.y, PLAYER_TANK_BOUNDING_RADIUS)) {
return true;
}
}
}
function draw() {
if (idle && particles.length===0) return;
foreground.clearRect(0, 0, W, H);
drawTrajectories();
drawPlayers();
drawProjectile();
drawExplosions();
drawParticles();
drawStatus();
drawScreenShake();
}
function drawPlayers() {
for (let player of players) {
const {x, y, a, c, cb, dead} = player;
if (dead) continue;
const [px, py] = vec(x, y-3, a+180, 3);
drawLine(foreground, x-1, y-3, px-1, py, cb);
drawLine(foreground, x+1, y-3, px+1, py, cb);
drawLine(foreground, x, y-4, px, py-1, cb);
drawRect(foreground, x-4, y-3, 8, 1, cb);
drawRect(foreground, x-5, y-2, 10, 2, cb);
drawRect(foreground, x-4, y-0, 8, 1, cb);
drawRect(foreground, x-3, y+1, 6, 1, cb);
drawLine(foreground, x, y-3, px, py, c);
drawRect(foreground, x-4, y-2, 8, 2, c);
drawRect(foreground, x-3, y-0, 6, 1, c);
}
}
function drawTrajectories() {
traces.clearRect(0, 0, W, H);
for (let {x, y, c, a} of trajectories) {
traces.globalAlpha = a / 255;
plot(traces, x, y, c);
}
traces.globalAlpha = 1;
}
function drawProjectile() {
if (!projectile) return;
plot(foreground, clamp(0, projectile.x, W-1), clamp(0, projectile.y, H-1), 'white');
}
function fadeTrajectories(amount) {
for (let i=trajectories.length-1; i>=0; i--) {
const trajectory = trajectories[i];
trajectory.a -= amount;
trajectory.y -= TRAJECTORY_FLOAT_SPEED;
if (
trajectory.a <= 0 || trajectory.y <= 0 ||
isTerrain(terrain, trajectory.x, trajectory.y)
) {
trajectories.splice(i, 1);
}
}
}
function drawExplosions() {
if (!explosion) return;
const explosionType = EXPLOSION_TYPES[explosion.type];
explosionType.draw(explosion, foreground, terrain);
}
function drawParticles() {
for (let particle of particles) {
foreground.globalAlpha = clamp(0, particle.alpha / 255, 255);
plot(foreground, particle.x, particle.y, particle.c);
}
foreground.globalAlpha = 1;
}
function drawScreenShake() {
const x = randomInt(-screenShake, screenShake);
const y = randomInt(-screenShake, screenShake);
for (let c of [sky, terrain, traces, foreground]) {
c.canvas.style.transform = `translate(${x}px, ${y}px)`;
}
}
function drawStatus() {
if (state === 'player-win') {
const player = players[currentPlayer];
drawText(foreground, `Player ${currentPlayer+1} wins!`, 8, 8, player.c, 'left');
return;
}
else if (state === 'game-over') {
drawText(foreground, `EVERYBODY IS DEAD`, 8, 8, 'white', 'left');
return;
}
const player = players[currentPlayer];
const {currentWeapon} = player;
const weaponType = player.weapons[currentWeapon];
const weapon = WEAPON_TYPES.find(x => x.id === weaponType.type);
drawText(foreground, `NRG:${player.energy} AIM:${player.a} PWR:${player.p} ${clamp(0, weaponType.ammo, 99)} ${weapon.name}`, 8, 8, player.c, 'left');
drawText(foreground, `WIND: ${wind<=0?'<':''}${Math.abs(wind)}${wind>=0?'>':''}`, W-8, 8, 'white', 'right');
}
loop(() => {
update();
draw();
});
+55
View File
@@ -0,0 +1,55 @@
export function index2coords(width, i) {
i = Math.round(i);
width = Math.round(width);
return [i % width, i / width];
}
export function coords2index(width, x, y) {
x = Math.round(x);
y = Math.round(y);
width = Math.round(width);
return y * width + x;
}
export function gradient(from, to, i) {
return from + (to-from) * i;
}
export function random(min, max) {
return min + Math.random() * (max-min);
}
export function randomInt(min, max) {
return Math.round(random(min, max));
}
export function clamp(min, x, max) {
return Math.max(min, Math.min(x, max));
}
export function wrap(min, x, max) {
return ((x-min + max-min) % (max-min)) + min;
}
export function cycle(x, d) {
return Math.floor(x / d);
}
export function within(x, y, tx, ty, r) {
return Math.abs(x-tx) < r && Math.abs(y-ty) < r;
}
export function parable(t, x, y, a, v, w=0, g=9.8) {
const fx = x + t*v * Math.cos(a) - 0.5 * -w * t*t;
const fy = y + t*v * Math.sin(a) - 0.5 * -g * t*t;
return [fx, fy];
}
export function vec(x, y, a, l) {
a = a * Math.PI / 180;
return [x+Math.cos(a)*l, y+Math.sin(a)*l];
}
export function deg2rad(a) { return a * Math.PI/180 }
export function rad2deg(a) { return a * 180/Math.PI }
+23
View File
@@ -0,0 +1,23 @@
import {createCanvas, drawRect, clipCanvas, plot} from './gfx.js';
import {randomInt, gradient} from './math.js';
import {SKY_COLORS} from './constants.js';
import {sample} from './utils.js';
export function createSky(width, height) {
const ctx = createCanvas(width, height);
generateSky(ctx);
return ctx;
}
export function generateSky(ctx) {
const {width, height} = ctx.canvas;
const {from, to} = sample(SKY_COLORS);
for (let y=0; y<height; y++) {
const f = y / height;
const r = gradient(from[0], to[0], f);
const g = gradient(from[1], to[1], f);
const b = gradient(from[2], to[2], f);
drawRect(ctx, 0, y, width, 1, `rgb(${r},${g},${b})`);
}
}
+29
View File
@@ -0,0 +1,29 @@
// @ts-ignore
export const audio = new (window.AudioContext || window.webkitAudioContext)();
export const gain = audio.createGain(audio);
gain.gain.setValueAtTime(0.05, audio.currentTime);
gain.connect(audio.destination);
export function createOsc() {
const osc = audio.createOscillator();
osc.type = 'triangle';
osc.connect(gain);
return osc;
}
export function playTickSound() {
const osc = createOsc();
osc.frequency.setValueAtTime(440, audio.currentTime);
osc.frequency.setValueAtTime(0, audio.currentTime + 0.005);
osc.start();
osc.stop(audio.currentTime + 0.005);
}
function clickInit() {
const osc = createOsc();
osc.start();
osc.stop();
document.removeEventListener('keydown', clickInit);
}
document.addEventListener('keydown', clickInit);
+100
View File
@@ -0,0 +1,100 @@
import {createCanvas, drawRect, clipCanvas, drawCircle} from './gfx.js';
import {coords2index, random, randomInt, clamp} from './math.js';
import {sample} from './utils.js';
let cachedImageData;
function cacheImageData(ctx) {
const {width, height} = ctx.canvas;
cachedImageData = ctx.getImageData(0, 0, width, height);
}
export function createTerrain(width, height) {
const terrain = createCanvas(width, height);
const generateTerrain = sample(Object.values(TERRAIN_TYPES));
generateTerrain(terrain);
return terrain;
}
const TERRAIN_TYPES = {
mountain(ctx) {
ctx.color = sample(['palegreen', 'white']); // FIXME
const {width, height} = ctx.canvas;
const stepCount = 8;
const stepSize = width / stepCount;
let cy = random(.3, .7) * height;
let dy = 0;
for (let x=0; x<width; x++) {
if (x % stepSize === 0) dy = ((random(.3, .7) * height) - cy) / stepSize;
if (x % (stepSize/16) === 0) dy = dy - random(-1, 1);
const ty = clamp(0, cy+dy, height-1);
const wy = clamp(70, ty, height-70-1);
cy = wy + (ty-wy) * 0.5;
drawRect(ctx, x, cy, 1, height-cy, ctx.color);
}
cacheImageData(ctx);
},
sand(ctx) {
ctx.color = 'wheat';
const {width, height} = ctx.canvas;
const stepCount = 16;
const stepSize = width / stepCount;
for (let s=0; s<=stepCount; s++) {
drawCircle(ctx, s*stepSize, height, randomInt(stepSize, stepSize*2), ctx.color);
if (s % 3 === 0) drawCircle(ctx, s*stepSize, 0, randomInt(0, stepSize*4), ctx.color);
}
cacheImageData(ctx);
collapseTerrain(ctx);
}
};
export function collapseTerrain(ctx, ) {
const {width, height} = ctx.canvas;
const imageData = ctx.getImageData(0, 0, width, height);
for (let x=0; x<width; x++) {
let land = 0;
for (let y=0; y<height; y++) {
const index = y*width*4 + x*4 +3;
if (imageData.data[index] > 0) land++;
}
ctx.clearRect(0+x, 0, 1, height);
drawRect(ctx, 0+x, height-land, 1, land, ctx.color);
}
cacheImageData(ctx);
}
export function isTerrain(ctx, x, y) {
const index = coords2index(ctx.canvas.width, x, y) * 4;
return cachedImageData.data[index+3] > 0;
}
export function closestLand(ctx, x, y) {
const {width, height} = ctx.canvas;
for (let i=y; i<height; i++) {
const index = coords2index(width, x, i) * 4;
if (cachedImageData.data[index+3] !== 0) return i;
}
return height-1;
}
export function landHeight(ctx, x) {
const {width, height} = ctx.canvas;
for (let i=height-1; i>=0; i--) {
const index = coords2index(width, x, i) * 4;
if (cachedImageData.data[index+3] === 0) return i;
}
}
export function clipTerrain(ctx, fn) {
clipCanvas(ctx, fn);
cacheImageData(ctx);
}
+23
View File
@@ -0,0 +1,23 @@
import {randomInt} from './math.js';
export function sample(arr) {
return arr[randomInt(0, arr.length-1)];
}
export function nextId() {
// @ts-ignore
const id = nextId.id || 0;
// @ts-ignore
nextId.id = id + 1;
return id;
}
export function splitWords(text) {
let words = [''];
for (let char of text) {
if ([' ', '\n'].includes(char)) words.push(char, '');
else words[words.length-1] += char;
}
if (words[words.length-1] === '') words = words.slice(0, words.length-1);
return words;
}
+163
View File
@@ -0,0 +1,163 @@
import {drawCircle, plot} from './gfx.js';
import {clipTerrain} from './terrain.js';
import {within, cycle, random, randomInt} from './math.js';
import {createOsc, audio} from './sound.js';
import {PLAYER_TANK_BOUNDING_RADIUS} from './constants.js';
export function drawExplosion(ctx, x, y, r) {
const color = 255 - (16 * (r % 16));
drawCircle(ctx, x, y, r, `rgb(${color}, 0, 0)`);
}
export function drawDirt(ctx, x, y, r, c) {
drawCircle(ctx, x, y, r, c);
}
export const EXPLOSION_TYPES = {
tracer: {
create(spec, x, y) {
return {type:'tracer'};
},
update(explosion) {},
draw(explosion, foreground) {},
stop(explosion) {},
clip(explosion, terrain) {},
damage(explosion, player) {}
},
blast: {
create(spec, x, y) {
const {r} = spec;
const osc = createOsc();
osc.start();
return {type:'blast', x, y, r, cr:0, osc};
},
update(explosion) {
return ++explosion.cr < explosion.r;
},
draw(explosion, foreground) {
const {x, y, cr, osc} = explosion;
const f = cycle(explosion.cr, 6) % 2 === 0 ? 220 : 440;
osc.frequency.setValueAtTime(f, audio.currentTime);
drawExplosion(foreground, x, y, cr);
},
stop(explosion) {
const {osc} = explosion;
osc.stop();
},
clip(explosion, terrain) {
const {x, y, cr} = explosion;
clipTerrain(terrain, (ctx) => drawExplosion(ctx, x, y, cr));
},
damage(explosion, player) {
if (within(explosion.x, explosion.y, player.x, player.y, explosion.r)) {
return 100;
} else if (
within(explosion.x, explosion.y, player.x-PLAYER_TANK_BOUNDING_RADIUS, player.y, explosion.r) ||
within(explosion.x, explosion.y, player.x+PLAYER_TANK_BOUNDING_RADIUS, player.y, explosion.r)
) {
return 50;
}
}
},
dirt: {
create(spec, x, y) {
const {r} = spec;
const osc = createOsc();
osc.start();
return {type:'dirt', x, y, r, cr:0, osc};
},
stop(explosion) {
const {osc} = explosion;
osc.stop();
},
update(explosion) {
return ++explosion.cr < explosion.r;
},
draw(explosion, foreground, terrain) {
const {x, y, cr, osc} = explosion;
const f = explosion.cr % 2 === 0 ? 220 + explosion.cr : 0;
osc.frequency.setValueAtTime(f, audio.currentTime);
osc.frequency.setValueAtTime(0, audio.currentTime+0.1);
drawDirt(foreground, x, y, cr, terrain.color);
},
clip(explosion, terrain) {
const {x, y, cr} = explosion;
drawDirt(terrain, x, y, cr);
},
damage(explosion, player) {}
},
digBomb: {
create(spec, x, y) {
const {r} = spec;
const osc = createOsc();
osc.start();
return {type:'digBomb', x, y, r, cr:0, osc};
},
stop(explosion) {
const {osc} = explosion;
osc.stop();
},
update(explosion) {
return ++explosion.cr < explosion.r;
},
draw(explosion, foreground, terrain) {
const {x, y, cr, osc} = explosion;
const f = explosion.cr % 2 === 0 ? 440 - explosion.cr : 0;
osc.frequency.setValueAtTime(f, audio.currentTime);
osc.frequency.setValueAtTime(0, audio.currentTime+0.1);
drawDirt(foreground, x, y, cr, 'brown');
},
clip(explosion, terrain) {
const {x, y, cr} = explosion;
clipTerrain(terrain, (ctx) => drawDirt(ctx, x, y, cr));
},
damage(explosion, player) {}
},
dirtCone: {
create(spec, x, y) {
const {r} = spec;
const pattern = [];
const osc = createOsc();
osc.start();
return {type:'dirtCone', x, y, r, cr:0, osc, pattern};
},
stop(explosion) {
const {osc} = explosion;
osc.stop();
},
update(explosion) {
return ++explosion.cr < explosion.r;
},
draw(explosion, foreground, terrain) {
const {x, y, cr, osc, pattern} = explosion;
let row = [];
for (let cx=0; cx<=1+cr*2; cx++) {
row.push(randomInt(0, 3) === 0);
}
pattern.push(row);
for (let cy=0; cy<pattern.length; cy++) {
const row = pattern[cy];
for (let cx=0; cx<row.length; cx++) {
if (row[cx]) plot(foreground, x-cy+cx, y-cy, terrain.color);
}
}
const f = explosion.cr % 2 === 0 ? 220 + explosion.cr : 0;
osc.frequency.setValueAtTime(f, audio.currentTime);
osc.frequency.setValueAtTime(0, audio.currentTime+0.1);
},
clip(explosion, terrain) {
const {x, y, pattern} = explosion;
for (let cy=0; cy<pattern.length; cy++) {
const row = pattern[cy];
for (let cx=0; cx<row.length; cx++) {
if (row[cx]) plot(terrain, x-cy+cx, y-cy, terrain.color);
}
}
},
damage(explosion, player) {}
},
}