Created
October 30, 2018 01:33
-
-
Save ichub/8a8539ee64e09df38dd81c090cb430b9 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
<canvas id="my-canvas" width="500" height="500"></canvas> | |
<style> | |
canvas { | |
border: 1px solid black; | |
} | |
</style> | |
<script> | |
let mycanvas = document.getElementById('my-canvas') | |
let ctx = mycanvas.getContext('2d') | |
let snake = [{ | |
x: 0, | |
y: 0 | |
}] | |
let food = { | |
x: 10, | |
y: 10 | |
} | |
let vx = 0 | |
let vy = 1 | |
let desiredSnakeLength = 3 | |
let haveYouLost = false | |
function getHeadOfSnake() { | |
return snake[snake.length - 1] | |
} | |
function eatFood() { | |
// we need to check if we are on the same spot as a food | |
// if we are, eat the food, | |
// increase length of snake | |
// randomize the position of the food | |
const head = getHeadOfSnake() | |
if (head.x == food.x && head.y == food.y) { | |
desiredSnakeLength++ | |
food.x = Math.floor(Math.random() * 500 / 10) | |
food.y = Math.floor(Math.random() * 500 / 10) | |
} | |
} | |
function moveSnake() { | |
const currentHead = getHeadOfSnake() | |
const newHead = { | |
x: (currentHead.x + vx + 500 / 10) % (500 / 10), | |
y: (currentHead.y + vy + 500 / 10) % (500 / 10) | |
} | |
snake.push(newHead) | |
if (snake.length > desiredSnakeLength) { | |
removeTail() | |
} | |
} | |
function removeTail() { | |
snake.shift() | |
} | |
function isSnakeIntersectingWithSelf() { | |
const head = getHeadOfSnake() | |
for (let i = 0; i < snake.length - 1; i++) { | |
if (head.x == snake[i].x && head.y == snake[i].y) { | |
alert('your score was: ' + desiredSnakeLength) | |
return true | |
} | |
} | |
return false | |
} | |
function drawSnake() { | |
for (let i = 0; i < snake.length; i++) { | |
ctx.fillRect(snake[i].x * 10, snake[i].y * 10, 10, 10) | |
} | |
} | |
function drawFood() { | |
ctx.fillRect(food.x * 10, food.y * 10, 10, 10) | |
} | |
function draw() { | |
drawSnake() | |
drawFood() | |
} | |
function clear() { | |
ctx.clearRect(0, 0, 500, 500) | |
} | |
function update() { | |
moveSnake() | |
eatFood() | |
if (isSnakeIntersectingWithSelf()) { | |
haveYouLost = true | |
} | |
} | |
function frame() { | |
if (!haveYouLost) { | |
clear() | |
update() | |
draw() | |
} | |
} | |
function onKeyPress(e) { | |
console.log(e.keyCode) | |
if (e.keyCode == 37) { // left | |
vx = -1 | |
vy = 0 | |
} else if (e.keyCode == 38) { // up | |
vx = 0 | |
vy = -1 | |
} else if (e.keyCode == 39) { // right | |
vx = 1 | |
vy = 0 | |
} else if (e.keyCode == 40) { // down | |
vx = 0 | |
vy = 1 | |
} | |
} | |
document.addEventListener('keydown', onKeyPress) | |
setInterval(frame, 100) | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment