Skip to content

Instantly share code, notes, and snippets.

@eamonnmcevoy
Created September 9, 2018 18:54
Show Gist options
  • Save eamonnmcevoy/b164576d20f3a12083d4807dbcbd01b9 to your computer and use it in GitHub Desktop.
Save eamonnmcevoy/b164576d20f3a12083d4807dbcbd01b9 to your computer and use it in GitHub Desktop.
<html>
<head>
</head>
<body>
<canvas id="game"></canvas>
<br>
<span id="gameover"></span>
<script src="./index.js"></script>
</body>
</html>
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