Created
September 9, 2018 19:23
-
-
Save eamonnmcevoy/8f0228ddf5a79eddb85f87bd3314f82d 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
class Snake { | |
constructor(position, direction) { | |
this.parts = [position]; | |
this.direction = direction; | |
this.newDirection = null; | |
} | |
update() { | |
const updates = []; | |
if (this.newDirection) { | |
this.direction = this.newDirection; | |
this.newDirection = null; | |
} | |
const next = this.updatePosition() | |
... | |
} | |
updatePosition() { | |
const next = Object.assign({}, this.parts[0]); | |
switch(this.direction) { | |
case 'up': | |
next.y--; | |
break; | |
case 'down': | |
next.y++; | |
break; | |
case 'right': | |
next.x++; | |
break; | |
case 'left': | |
next.x--; | |
break; | |
} | |
return next; | |
} | |
} | |
class Game { | |
... | |
keydownHandler (event) { | |
if (this.snake.newDirection) return; | |
switch (event.keyCode) { | |
case 37: //left | |
this.snake.newDirection = this.snake.direction !== 'right' ? 'left' : 'right'; | |
break; | |
case 38: //up | |
this.snake.newDirection = this.snake.direction !== 'down' ? 'up' : 'down'; | |
break; | |
case 39: //right | |
this.snake.newDirection = this.snake.direction !== 'left' ? 'right' : 'left'; | |
break; | |
case 40: //down | |
this.snake.newDirection = this.snake.direction !== 'up' ? 'down' : 'up'; | |
break; | |
} | |
} | |
} | |
... | |
const snake = new Snake({x:10, y:10}, 'right'); | |
document.addEventListener('keydown', game.keydownHandler.bind(game)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment