Skip to content

Instantly share code, notes, and snippets.

@abzeede
Last active December 5, 2018 13:42
Show Gist options
  • Select an option

  • Save abzeede/89588e8b58bbce5c9fcb085bcd6589af to your computer and use it in GitHub Desktop.

Select an option

Save abzeede/89588e8b58bbce5c9fcb085bcd6589af to your computer and use it in GitHub Desktop.
<html>
<body>
<canvas id="board"></canvas>
</body>
<script>
const board = document.getElementById("board")
const boardSize = 300 // game space size
const gridSize = 10 // size for snake body, apple
const totalAxCell = boardSize / gridSize
const boardCtx = init(board, boardSize) // get canvas context
let snakeSize = 5 // initial size of snake
let snakePosX = snakePosY = 0 // initial snake position
let xSpeed = 1 // snake movement direction in x
let ySpeed = 0 // snake movement direction in y
let snakeBody = []
function init(canvasDom, boardSize) {
if (canvasDom.getContext) { // is support canvas context api
canvasDom.width = canvasDom.height = boardSize // set canvas size
return canvasDom.getContext('2d')
}
}
function renderGameSpace() {
boardCtx.fillStyle = "black"
boardCtx.fillRect(0, 0, board.width, board.height) // fillRect(x, y, width, height)
}
function renderSnake() {
boardCtx.fillStyle = "green"
for (let i = 0; i < snakeBody.length; i++ ) {
boardCtx.fillRect(snakeBody[i].x * gridSize, snakeBody[i].y * gridSize, gridSize - 1, gridSize - 1) // fillRect(snakePositionX, snakePositionY, snakeWidth, snakeHeight)
}
snakeBody.push({ x: snakePosX, y: snakePosY }) // save last position of snake
if (snakeBody.length > snakeSize) { // if snake body is over max snake size then cut the over tail off
snakeBody.shift()
}
}
function renderApple() {
boardCtx.fillStyle = "red"
boardCtx.fillRect(5 * gridSize, 5 * gridSize, gridSize, gridSize)
}
function game() {
// move the snake
snakePosX += xSpeed
snakePosY += ySpeed
// clear canvas
boardCtx.clearRect(0, 0, board.width, board.height)
// when the snake hit border then warp it to the other side
if (snakePosX < 0) {
snakePosX = totalAxCell - 1
} else if (snakePosX > totalAxCell - 1) {
snakePosX = 0
} else if (snakePosY < 0) {
snakePosY = totalCell - 1
} else if (snakePosY > totalAxCell - 1) {
snakePosY = 0
}
renderGameSpace() // draw game space
renderSnake() // draw snake
renderApple() // draw apple
}
window.onload = function(e) {
if (typeof boardCtx !== 'undefined') {
setInterval(game, 50)
} else {
// this browser doesn't support canvas API
}
}
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment