Created
September 9, 2018 18:54
-
-
Save eamonnmcevoy/b164576d20f3a12083d4807dbcbd01b9 to your computer and use it in GitHub Desktop.
This file contains 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
<html> | |
<head> | |
</head> | |
<body> | |
<canvas id="game"></canvas> | |
<br> | |
<span id="gameover"></span> | |
<script src="./index.js"></script> | |
</body> | |
</html> |
This file contains 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
class Snake { | |
... | |
update() { | |
const updates = []; | |
const next = Object.assign({}, snake.parts[0]); | |
next.x++; | |
const previousTailPosition = Object.assign({}, this.parts[this.parts.length - 1]); | |
this.parts[this.parts.length - 1] = next; | |
updates.push({ point: this.head, state: 'on' }); | |
updates.push({ point: previousTailPosition, state: 'off' }); | |
return updates; | |
} | |
... | |
get isAlive() { | |
const collidesWithSelf = this.parts.filter(_ => this.collision(_, this.head)).length > 1; | |
const collidesWithEdge = this.head.x < 0 || | |
this.head.x >= height || | |
this.head.y < 0 || | |
this.head.y >= width; | |
return (!collidesWithEdge && !collidesWithSelf); | |
} | |
collision(a, b) { | |
return (a.x === b.x && a.y === b.y); | |
} | |
} | |
class Game { | |
async run() { | |
while (true) { | |
... | |
const updates = this.snake.update(); | |
if (!this.snake.isAlive) | |
break; | |
... | |
} | |
document.getElementById("gameover").innerHTML = `You crashed!`; | |
} | |
} | |
... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment