Skip to content

Instantly share code, notes, and snippets.

@twfarland
Last active August 25, 2016 17:45
Show Gist options
  • Save twfarland/f5d214f29c19da402058c446f1ce517c to your computer and use it in GitHub Desktop.
Save twfarland/f5d214f29c19da402058c446f1ce517c to your computer and use it in GitHub Desktop.
snake game
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Snake</title>
</head>
<style>
.board {
width: 300px;
height: 300px;
}
.cell {
float: left;
width: 15px;
height: 15px;
background: #ebebeb;
}
.apple {
background: #ff0000;
}
.snake {
background: #00cc00;
}
</style>
<body>
<div id="snake"></div>
<script>
(function () {
var size = 20
var score
var snake
var dir
var apple
var dead
// utils
function addPos (posA, posB) {
return [
(posA[0] + posB[0] + size) % size,
(posA[1] + posB[1] + size) % size
]
}
function equalPos (posA, posB) {
return posA[0] === posB[0] && posA[1] === posB[1]
}
function containsPos (posArray, posA) {
for (var i = 0; i < posArray.length; i++) {
if (equalPos(posA, posArray[i])) { return true }
}
}
function randomPos () {
return [
Math.floor(Math.random() * size),
Math.floor(Math.random() * size)
]
}
// updaters
function turnLeft () {
dir = [-dir[1], dir[0]]
}
function turnRight () {
dir = [dir[1], -dir[0]]
}
function restart () {
score = 0
snake = [[0,5],[0,4],[0,3],[0,2],[0,1],[0,0]]
dir = [0,1]
apple = randomPos()
dead = false
}
function tick () {
var nextHead = addPos(snake[0], dir)
if (containsPos(snake, nextHead)) {
dead = true
} else if (equalPos(apple, nextHead)) {
score++
snake.unshift(nextHead)
apple = randomPos()
} else {
snake.splice(-1, 1)
snake.unshift(nextHead)
}
}
function view () {
var res = 'Score: ' + score + '<div class="board">'
var x
var y
var square = ''
for (x = 0; x < size; x++) {
for (y = 0; y < size; y++) {
square = equalPos(apple, [x, y]) ? ' apple' : containsPos(snake, [x, y]) ? ' snake' : ''
res += '<div class="cell' + square + '"></div>'
}
}
return res + '</div>' + (dead ? 'Press (r) to restart' : '')
}
document.addEventListener('keydown', function (evt) {
switch (evt.keyCode) {
case 37: return turnLeft()
case 39: return turnRight()
case 82: return restart()
default: return
}
})
setInterval(function () {
tick()
document.body.innerHTML = view()
}, 100)
restart()
})()
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment