Форум программистов, компьютерный форум, киберфорум
8Observer8
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  

How to write a prototype of the Snake Game using JavaScript/ES5, HTML5 Canvas API

Запись от 8Observer8 размещена 06.02.2019 в 21:49
Показов 1653 Комментарии 0
Метки canvas, html, javascript

Blog content

Let's make a very simple classic snake game. For example, if we have a snake head with 10x10 pixels then we will move our snake by a step with 10 pixels using timer.

Create a "index.html" file with a canvas element and set the size for the canvas element:

PHP/HTML
1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE html>
 
<head>
    <title>Snake</title>
</head>
 
<body>
    <canvas width="200" height="200" id="gameCanvas">
        Your browser does not support HTML5 Canvas. Please shift to a newer browser.
    </canvas>
</body>
 
</html>
We need to get a canvas context from the canvas element. The canvas context is an object that have methods for working with graphics.

Lets' create a script element inside of "index.html" file, get the canvas element, get the canvas context and set a clear color to black:

Playground

PHP/HTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE html>
 
<head>
    <title>Snake</title>
</head>
 
<body>
    <canvas width="200" height="200" id="gameCanvas">
        Your browser does not support HTML5 Canvas. Please shift to a newer browser.
    </canvas>
 
    <script>
        var canvas, ctx;
 
        canvas = document.getElementById("gameCanvas");
        ctx = canvas.getContext("2d");
 
        // Clear the canvas element
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        // Set a clear color
        ctx.fillStyle = "black";
        // Fill the canvas element with the clear color
        ctx.beginPath();
        ctx.rect(0, 0, canvas.width, canvas.height);
        ctx.fill();
    </script>
</body>
 
</html>
Write a function for drawing a rectangle and call this function for test:

Playground

PHP/HTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<!DOCTYPE html>
 
<head>
    <title>Snake</title>
</head>
 
<body>
    <canvas width="200" height="200" id="gameCanvas">
        Your browser does not support HTML5 Canvas. Please shift to a newer browser.
    </canvas>
 
    <script>
        var canvas, ctx;
 
        canvas = document.getElementById("gameCanvas");
        ctx = canvas.getContext("2d");
 
        // Clear the canvas element
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        // Set a clear color
        ctx.fillStyle = "black";
        // Fill the canvas element with the clear color
        ctx.beginPath();
        ctx.rect(0, 0, canvas.width, canvas.height);
        ctx.fill();
 
        // Call a drawRectangle() function
        drawRectangle(0, 20, "green", 20);
 
        function drawRectangle(x, y, color, size)
        {
            ctx.beginPath();
            ctx.rect(x, y, size, size);
            ctx.fillStyle = color;
            ctx.fill();
        }
    </script>
</body>
 
</html>
Each game must have a game loop that will be called by timer. I created the GameLoop method that just prints "Hello, World!" to the debug console every 500 ms:

JavaScript
1
2
3
4
5
setInterval(gameLoop, 500)
function gameLoop()
{
    console.log("Hello, World!");
}
For a while our GameLoop will have only two called methods Update() and Draw(). The Update() method will have updates for snake cell coordinates and etc. The Draw() method will have only draw methods for game entities.

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function gameLoop()
{
    update();
    draw();
}
 
function update()
{
    console.log("update");
}
 
function draw()
{
    drawSnake();
    drawFood();
}
 
function drawSnake()
{
    console.log("draw snake");
}
 
function drawFood()
{
    console.log("draw food");
}
List data structure is ideal for keeping snake cells coordinates:

JavaScript
1
2
// Snake list of (x, y) positions
var snake = [{ x: 10, y: 10 }];
Create a function for clearing the canvas:
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function draw()
{
    clearCanvas("black")
    drawSnake();
    drawFood();
}
 
function clearCanvas(color)
{
    // Clear the canvas element
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    // Set a clear color
    ctx.fillStyle = color;
    // Fill the canvas element with the clear color
    ctx.beginPath();
    ctx.rect(0, 0, canvas.width, canvas.height);
    ctx.fill();
}
Draw the snake:

JavaScript
1
2
3
4
5
6
7
function drawSnake()
{
    snake.forEach(cell =>
    {
        drawRectangle(cell.x, cell.y, "green");
    });
}
Playground

For moving the snake we need to create the "snakeDir" variable:

JavaScript
1
2
// Snake movement direction
var snakeDir = { x: 10, y: 0 };
The snake moving is very simple. Please, read comments:

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
function update()
{
    // Calc a new position of the head
    var newHeadPosition = {
        x: snake[0].x + snakeDir.x,
        y: snake[0].y + snakeDir.y
    }
 
    // Insert new position in the beginning of the snake list
    snake.unshift(newHeadPosition);
 
    // Remove the last element
    snake.pop();
}
Playground

I will explain eating food later. But you can read comments in the code.

Note. I got ideas from this tutorial: Python Snake Game

This is a result: Playground

PHP/HTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
<!DOCTYPE html>
 
<head>
    <title>Snake</title>
</head>
 
<body>
    <canvas width="200" height="200" id="gameCanvas">
        Your browser does not support HTML5 Canvas. Please shift to a newer browser.
    </canvas>
 
    <p>Click on this window to activate keyboard handlers to control the snake by WASD and arrow keys.</p>
 
    <script>
        // Canvas element and context
        var canvas, ctx;
        // Snake list of (x, y) positions
        var snake = [{ x: 10, y: 10 }];
        // Snake movement direction
        var snakeDir = { x: 10, y: 0 };
        // Snake step
        var cellSize = 10;
 
        // Food
        var food = { x: 0, y: 0 };
 
        canvas = document.getElementById("gameCanvas");
        ctx = canvas.getContext("2d");
 
        // Field size
        var fieldWidth = canvas.width;
        var fieldHeight = canvas.height;
 
        // Generate an initial random position for the food
        generateFood();
 
        // Set a key handler
        document.onkeydown = (event) =>
        {
            switch (event.keyCode)
            {
                case 38:    // Up
                case 87:    // W
                    snakeDir.x = 0;
                    snakeDir.y = -cellSize;
                    break;
                case 37:    // Left
                case 65:    // A
                    snakeDir.x = -cellSize;
                    snakeDir.y = 0;
                    break;
                case 39:    // Right
                case 68:    // D
                    snakeDir.x = cellSize;
                    snakeDir.y = 0;
                    break;
                case 40:    // Down
                case 83:    // S
                    snakeDir.x = 0;
                    snakeDir.y = cellSize;
                    break;
            }
        };
 
        // Run Game Loop
        setInterval(gameLoop, 200)
        function gameLoop()
        {
            update();
            draw();
        }
 
        function update()
        {
            // Calc a new position of the head
            var newHeadPosition = {
                x: snake[0].x + snakeDir.x,
                y: snake[0].y + snakeDir.y
            }
 
            // Insert new position in the beginning of the snake list
            snake.unshift(newHeadPosition);
 
            // Remove the last element
            snake.pop();
 
            // Check a collision with the snake and the food
            if (snake[0].x === food.x &&
                snake[0].y === food.y)
            {
                snake.push({ x: food.x, y: food.y });
 
                // Generate a new food position
                generateFood();
            }
        }
 
        function draw()
        {
            clearCanvas("black")
            drawSnake();
            drawFood();
        }
 
        function clearCanvas(color)
        {
            // Clear the canvas element
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            // Set a clear color
            ctx.fillStyle = color;
            // Fill the canvas element with the clear color
            ctx.beginPath();
            ctx.rect(0, 0, canvas.width, canvas.height);
            ctx.fill();
        }
 
        function drawSnake()
        {
            snake.forEach(cell =>
            {
                drawRectangle(cell.x, cell.y, "green", cellSize);
            });
        }
 
        function drawFood()
        {
            drawRectangle(food.x, food.y, "orange", cellSize);
        }
 
        function drawRectangle(x, y, color, size)
        {
            ctx.beginPath();
            ctx.rect(x, y, size, size);
            ctx.fillStyle = color;
            ctx.fill();
        }
 
        function generateFood()
        {
            food.x = 10 * getRandomInt(0, fieldWidth / 10  - 1);
            food.y = 10 * getRandomInt(0, fieldHeight / 10  - 1);
        }
 
        // Returns a random integer between min (inclusive) and max (inclusive)
        function getRandomInt(min, max)
        {
            min = Math.ceil(min);
            max = Math.floor(max);
            return Math.floor(Math.random() * (max - min + 1)) + min;
        }
    </script>
</body>
 
</html>
Метки canvas, html, javascript
Размещено в Без категории
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
Всего комментариев 0
Комментарии
 
Новые блоги и статьи
Debian 13: Установка Lazarus QT5
ВитГо 09.05.2026
Эта инструкция моя компиляция инструкций volvo https:/ / www. cyberforum. ru/ blogs/ 203668/ 10753. html и его же старой инструкции по установке Lazarus с gtk2. . .
Нейросеть на алгоритме "эстафета хвоста" как перспектива.
Hrethgir 06.05.2026
На десерт, когда запущу сервер. Статья тут https:/ / habr. com/ ru/ articles/ 1030914/ . Автор я сам, нейросеть только помогает в вопросах которые мне не известны - не знаю людей которые знали-бы. . .
Асинхронный приём данных из COM-порта
Argus19 01.05.2026
Асинхронный приём данных из COM-порта Купил на aliexpress термопринтер QR701. Он оказался странным. Поключил к Arduino Nano. Был очень удивлён. Наотрез отказывается печатать русские буквы. Чтобы. . .
попытка написать игровой сервер на C++
pyirrlicht 29.04.2026
попытка написать игровой сервер на плюсах с открытым бесконечным миром. возможно получится прикрутить интерпретатор питон для кастомизации игровой логики. что есть на текущий момент:. . .
Контроль уникальности выбранного документа-основания при изменении реквизита
Maks 28.04.2026
Алгоритм из решения ниже разработан на примере нетипового документа "ЗаявкаНаРемонтСпецтехники", разработанного в КА2. Задача: уведомлять пользователя, если указанная заявка (документ-основание). . .
Благородство как наказание
Maks 24.04.2026
У хорошего человека отношения с женщинами всегда складываются трудно. А я человек хороший. Заявляю без тени смущения, потому что гордиться тут нечем. От хорошего человека ждут соответствующего. . .
Валидация и контроль данных табличной части документа перед записью
Maks 22.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа, разработанного в КА2. Задача: контроль и валидация данных табличной части документа перед записью с учетом регламента компании. . .
Отчёт о затраченных материалах за определенный период с макетом печатной формы
Maks 21.04.2026
Отчёт из решения ниже размещён в конфигурации КА2. Задача: разработка отчёта по затраченным материалам за определённый период, с возможностью вывода печатной формы отчёта с шапкой и подвалом. В. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru