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

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

Запись от 8Observer8 размещена 06.02.2019 в 21:49
Показов 1551 Комментарии 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
Комментарии
 
Новые блоги и статьи
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
Ломающие изменения в C#.NStar Alpha
Etyuhibosecyu 20.11.2025
Уже можно не только тестировать, но и пользоваться C#. NStar - писать оконные приложения, содержащие надписи, кнопки, текстовые поля и даже изображения, например, моя игра "Три в ряд" написана на этом. . .
Мысли в слух
kumehtar 18.11.2025
Кстати, совсем недавно имел разговор на тему медитаций с людьми. И обнаружил, что они вообще не понимают что такое медитация и зачем она нужна. Самые базовые вещи. Для них это - когда просто люди. . .
Создание Single Page Application на фреймах
krapotkin 16.11.2025
Статья исключительно для начинающих. Подходы оригинальностью не блещут. В век Веб все очень привыкли к дизайну Single-Page-Application . Быстренько разберем подход "на фреймах". Мы делаем одну. . .
Фото: Daniel Greenwood
kumehtar 13.11.2025
Расскажи мне о Мире, бродяга
kumehtar 12.11.2025
— Расскажи мне о Мире, бродяга, Ты же видел моря и метели. Как сменялись короны и стяги, Как эпохи стрелою летели. - Этот мир — это крылья и горы, Снег и пламя, любовь и тревоги, И бескрайние. . .
PowerShell Snippets
iNNOKENTIY21 11.11.2025
Модуль PowerShell 5. 1+ : Snippets. psm1 У меня модуль расположен в пользовательской папке модулей, по умолчанию: \Documents\WindowsPowerShell\Modules\Snippets\ А в самом низу файла-профиля. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru