Created
October 10, 2016 03:04
-
-
Save coopy/4d5a9944d6e4657ef8fe2f97919c3d71 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
const WIDTH = 800 | |
const HEIGHT = 600 | |
const SIXTY_FPS_DELAY = 1000 / 60 | |
function createContext () { | |
const canvas = document.getElementById('canvas') | |
canvas.width = WIDTH | |
canvas.height = HEIGHT | |
return canvas.getContext('2d') | |
} | |
function generateGame() { | |
const {floor, random} = Math | |
const config = { | |
numBlocks: 1500, | |
blockStartV: 55, | |
blockAverageWidth: 2, | |
blockSizeVariance: 15 | |
} | |
const game = { | |
blocks: [], | |
constants: { | |
edgeDrag: .75 | |
} | |
} | |
let blockWidth | |
for(let i = 0; i < config.numBlocks; i++) { | |
blockWidth = floor(random() * config.blockSizeVariance * config.blockAverageWidth) | |
game.blocks.push({ | |
x: floor(random() * WIDTH), | |
y: floor(random() * HEIGHT), | |
w: blockWidth, | |
h: blockWidth, | |
color: '#'+Math.random().toString(16).substr(-6), | |
vx: random() * config.blockStartV, | |
vy: random() * config.blockStartV | |
}) | |
} | |
return game | |
} | |
function clear (ctx) { | |
ctx.fillStyle = '#000' | |
ctx.fillRect(0, 0, WIDTH, HEIGHT) | |
} | |
function calcForces(game) { | |
game.blocks.forEach((block) => { | |
// Edge detection (bounce) | |
if (block.x <= 0 || block.x + block.w > WIDTH) { | |
// Reverse direction and penalize some vx | |
block.vx *= (-1 * game.constants.edgeDrag) | |
} | |
if (block.y <= 0 || block.y + block.h > HEIGHT) { | |
block.vy *= (-1 * game.constants.edgeDrag) | |
} | |
}) | |
return game | |
} | |
function move(game) { | |
game.blocks.forEach((block) => { | |
block.x += block.vx | |
block.y += block.vy | |
}) | |
return game | |
} | |
function draw(ctx, game) { | |
game.blocks.forEach((block) => { | |
ctx.fillStyle = block.color | |
ctx.fillRect(block.x, block.y, block.w, block.h) | |
}) | |
return game | |
} | |
function loop (ctx, game) { | |
clear(ctx) | |
calcForces(game) | |
move(game) | |
draw(ctx, game) | |
} | |
function start() { | |
const ctx = createContext() | |
let game = generateGame() | |
let stop = true | |
clear(ctx) | |
document.addEventListener('keyup', (ev) => { | |
if (ev.which === 27) { | |
stop = !stop | |
} | |
}, false); | |
window.setInterval(() => { | |
if (!stop) loop(ctx, game) | |
}, SIXTY_FPS_DELAY) | |
} | |
window.addEventListener('DOMContentLoaded', start) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment