Snake Game

Snake

by habla

HTML

<canvas id="tutorial" width="150" height="150"></canvas>

<!--
Mini Book

4 chapters, 4 "pages" of 500 words per chapter. Total 8000 words/ 16 pages.

Ch 1. Introduction to HTML Canvas

This will give a quick introduction, and then we set up an array to represent the sake and a render function that will draw the current snake.

Ch 2. Making the snake move

Here we will store some state about which way it is moving, then change that based on key presses. We will set a timer to update the snake position every second.

Ch 3. Collision Detection

We now need to check if the snake has hit itself or the wall (which we will add). If it has then the player is shown game over and gets another turn.

Ch 4. Food

We now want to add food at random places, and make it so the snake grows when it has some food. We can also use this to keep a score.

Then

Create a landing page for the snake game (which includes the game so you can play it). Add your email and download. We can then submit that landing page, and then link to it with a banner from other pages on SJS.

-->

JavaScript

var canvas = document.getElementById('tutorial');
var ctx = canvas.getContext('2d');

snake = [[0,1],[1,1],[2,1]];

setInterval(function() {
var head = snake[snake.length - 1];
var newhead = [head[0]+1, head[1]];
snake.push(newhead);
snake.shift();
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (part of snake) {
  ctx.fillStyle = 'rgb(200, 0, 0)';
  ctx.fillRect(part[0]*10, part[1]*10, 10, 10);
}
}, 1000);