const canvas = document.getElementById("game") const context = canvas.getContext('2d'); class Snake { constructor(x, y) { this.x = x this.y = y } } const tileCount = 20 const tileSize = canvas.clientWidth / tileCount - 2 let headX = 10 let headY = 10 let appleX = 3 let appleY = 3 let xVelocity = 0 let yVelocity = 0 let tailLength = 2 let score = 0 const snakeParts = [] function clearScreen() { context.fillStyle = "black" context.fillRect(0, 0, canvas.clientWidth, canvas.clientHeight) } function drawGame() { changeSnakePosition() if(isGameOver()) { return } clearScreen() drawSnake() drawApple() collisionDetection() drawScore() setTimeout(drawGame, 1000 / 7) } function drawSnake() { context.fillStyle = "green" for(let i = 0; i < snakeParts.length; i++) { let partOfSnake = snakeParts[i] context.fillRect(partOfSnake.x * tileCount, partOfSnake.y * tileCount, tileSize, tileSize) } snakeParts.push(new Snake(headX, headY)) if(snakeParts.length > tailLength) { snakeParts.shift() } context.fillStyle = "orange" context.fillRect(headX * tileCount, headY * tileCount, tileSize, tileSize) } function drawScore() { context.fillStyle = "white" context.font = "16px arial" context.fillText("Score " + score, canvas.clientWidth - 60, 20) } // drawSnake() function changeSnakePosition() { headX += xVelocity headY += yVelocity } function drawApple() { context.fillStyle = "red" context.fillRect(appleX * tileCount, appleY * tileCount, tileSize, tileSize) } function collisionDetection() { if(appleX === headX && appleY === headY) { appleX = Math.floor(Math.random() * tileCount) appleY = Math.floor(Math.random() * tileCount) tailLength++ score++ } } function isGameOver() { let over = false if(xVelocity === 0 && yVelocity === 0) { return false } if(headX < 0) { over = true } else if(headX === tileCount) { over = true } else if(headY < 0) { over = true } else if(headY === tileCount) { over = true } for(let i = 0; i < snakeParts.length; i++) { let partOfSnake = snakeParts[i] if(headX === partOfSnake.x && headY === partOfSnake.y) { over = true break } } if(over == true) { context.fillStyle = "white" context.font = "50px arial" context.fillText("GAME OVER!", canvas.clientWidth / 7, canvas.clientHeight / 2) } return over } document.addEventListener('keydown', keyPressed) function keyPressed() { if(event.keyCode === 38) { // W if(yVelocity === 1) { return } xVelocity = 0 yVelocity = -1 } if(event.keyCode === 40) { // if(yVelocity === -1) { return } xVelocity = 0 yVelocity = 1 } if(event.keyCode === 37) { // A if(xVelocity === 1) { return } xVelocity = -1 yVelocity = 0 } if(event.keyCode === 39) { // D if(xVelocity === -1) { return } xVelocity = 1 yVelocity = 0 } } drawGame()