Skip to content

Instantly share code, notes, and snippets.

@ioxua
Created June 4, 2018 23:34
Show Gist options
  • Save ioxua/6710b37076594ae72699e83434ed8e7a to your computer and use it in GitHub Desktop.
Save ioxua/6710b37076594ae72699e83434ed8e7a to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<style>
.game { width: 800; height: 600; margin: 0 auto; }
</style>
</head>
<body>
<div class="game">
<canvas tabindex='1' id="gCanvas" width="800" height="600"></canvas>
</div>
<script>
const COLORS = {
black: "#393c42", mustard: "#f4df42", teal: "#42f4ee"
}
const coinFactory = {
randomPlacement() {
let instance = {
x: 0, y: 0, w: 0, h: 0, s: 0,
color: COLORS.mustard,
draw: function(where){
where.fillStyle = this.color
where.fillRect(this.x, this.y, this.w, this.h)
},
hear: function(event){ return }
}
const size = randomNumberBetween(4, 8)
instance.w = instance.h = size
instance.x = randomNumberBetween(0 + instance.w, 800 - instance.w)
instance.y = randomNumberBetween(0 + instance.h, 800 - instance.h)
return instance
}
}
const character = {
x: 400, y: 300, w: 40, h: 40, s: 5,
color: COLORS.teal,
draw: function(where) {
where.fillStyle = this.color
where.fillRect(this.x, this.y, this.w, this.h)
},
hear: function(event) {
if(event.key == "w") this.y -= this.s;
else if(event.key == "a") this.x -= this.s;
else if(event.key == "s") this.y += this.s;
else if(event.key == "d") this.x += this.s;
}
}
const clone = Object.assign({}, character)
const ACTORS = [character]
for(let i = 0; i < 40; i++) {
ACTORS.push(coinFactory.randomPlacement())
}
const canvas = document.getElementById("gCanvas")
const ctx = canvas.getContext("2d")
canvas.onkeydown = canvas.onkeyup = canvas.onkeypress = handleKeyPress
window.requestAnimationFrame(gameLoop)
function gameLoop() {
clearCanvas()
ACTORS.forEach(actor => {
actor.draw(ctx)
})
window.requestAnimationFrame(gameLoop)
}
function handleKeyPress(e) {
ACTORS.forEach(each => {
each.hear(e)
})
}
function clearCanvas() {
ctx.fillStyle = COLORS.black
ctx.fillRect(0, 0, 800, 600)
}
function randomNumberBetween(a, b) {
return Math.floor((Math.random() * b) + a);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment