Как сделать игру полноценную змейка на javascript

от admin

Создание игры «Змейка» на чистом JavaScript и HTML5

Змейка — классическая игра, которую мы знаем еще с давних времен. Мы представляем вам статью, в ходе которой мы создадим полноценную игру «Змейка» на чистом JavaScript и HTML5.

Для создания веб игр на языке JavaScript используется технология Canvas , которая позволяет выполнять JavaScript код в HTML5 документе. Вы можете более детально ознакомиться с этой технологией посмотрев видео ниже:

HTML страница может содержать классическую разметку, в которую необходимо вписать canvas для отображения игры внутри него. Пример кода:

Внутри этого файла мы подключаем скрипт «game.js«, который будет описывать весь функционал нашей игры.

JavaScript файл

Внутри JavaScript файла добавьте выборку канваса, а также укажите контекст игры.

Добавление изображений и аудио

Далее необходимо загрузить все основные изображения, которые будут использоваться в игре. Для этого используйте класс Image . Ниже вы можете скачать все необходимые картинки к игре.

Код добавления изображений и аудио в игру:

Рисование объектов

Чтобы нарисовать объекты, а также добавить функционал к игре необходимо прописать функцию, которая будет постоянно вызываться. Такую функцию вы можете назвать как вам будет угодно. Чтобы функция работала постоянно, вы можете запустите её выполнение через setInterval() .

Весь код игры стоит помещать в этот метод, ведь в нем он будет постоянно обрабатываться и игра будет выглядеть живой и анимированной.

Чтобы отследить нажатие игрока на какую-либо клавишу, необходимо использовать отслеживание событий — addEventListener . К примеру, чтобы отследить нажатие на любую клавишу на клавиатуре надо прописать следующий код:

Видео урок

Это были лишь небольшие азы перед созданием самой игры. Предлагаем вам ознакомиться с большим видео уроком, в ходе которого вы создадите 2D игру «Змейка» на чистом JavaScript'е.

Полезные ссылки из видео:

  • Текстовый редактор Atom.io ;
  • Подбор иконок IconFinder ;
  • Хостинг компания Reg.ru .

Весь JS код игры

Ниже вы можете посмотреть на полностью весь код JavaScript файла, который был создан в ходе видео урока выше:

Більше цікавих новин

Разбираемся в топовых IT-терминах: просто о сложномРазбираемся в топовых IT-терминах: просто о сложном
Лучшие примеры страниц ошибок 404Лучшие примеры страниц ошибок 404
Принцип работы сканера отпечатка пальцаПринцип работы сканера отпечатка пальца
Плохой код обходится компаниям в $85 млрд. в годПлохой код обходится компаниям в $85 млрд. в год

Name already in use

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Змейка классическая на JS + canvas

  • Счет игры зависит от длины змейки
  • Если длина змейки стала нулевой или змейка укусила себя — игра проиграна
  • Яблоки яблочно-зеленого цвета хорошие, яблочно-красного цвета — плохие
  • При поедании хорошего яблока увеличивается длина змейки и скорость её движения
  • При поедании плохого яблока длина змейки уменьшается

About

Змейка классическая на JS + canvas

Resources

Stars

Watchers

Forks

Releases

Packages 0

Languages

Footer

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Пишем игру змейка с помощью JavaScript + Canvas

Доброго времени суток, друзья. Сейчас я постараюсь вам показать как можно написать игру Змейка. Конечно, не самым быстрым способом и не самым маленьким в плане количества строк кода, но по-моему самым понятным для начинающих разработчиков, как я. Статья написана для людей, желающих чуть-чуть познакомиться с элементом canvas и его простыми методами для работы с 2D графикой.
image
Напишем змейку в «старом» виде, без особо красивой графики — в виде кубиков. Но это только упростит понимание разработки. Ну что же, поехали!

Подготовка

Пожалуй, стоит вообще начать с подготовки к созданию игры и написанию кода. Мы будем использовать простой редактор Sublime Text. Впрочем, это не важно. Все делаем в одном документе, чтобы было быстрее.

Первым делом, напишем сам код для встраивания canvas в документ. Напомню, что canvas поддерживается только в HTML5.

Подготовка завершена, теперь мы можем приступать к созданию самой игры.

Начинаем

Для начала, я хотел бы вам вообще объяснить как будет работать змейка, так будет гораздо понятнее. Наша змейка — это массив. Массив элементов, элементы — это ее части, на которые она делиться. Это всего лишь квадратики, которые имеют координаты X и Y. Как вы знаете, X — горизонталь, Y — вертикаль. В обычном виде мы представляем себе координатную плоскость вот так:

image

Она абсолютно правильная, в этом нет сомнения, но на мониторе компьютера (в частности, canvas) она выглядит по-другому, вот так:

image

Это нужно знать, если вы вдруг в первый раз столкнулись с canvas. Я, когда столкнулся с этим, сначала вообще не понял где точка (0,0), благо я быстро разобрался. Надеюсь и у вас проблем не возникло.

Вернемся к элементам змейки, ее частям. Представим, что каждый элемент имеет свои координаты, но одинаковую высоту и одинаковую ширину. Это квадратики, не более. А теперь представим, что мы вот нарисовали змейку, все квадратики, они идут друг за другом, одинаковые такие. И тут мы решили, что нам нужно подвинуть змейку вправо. Как бы вы поступили?

Некоторые люди ответили бы, что нам нужно первый элемент подвинуть вправо, затем второй, затем третий и так далее. Но для меня этот вариант не является правильным, так как в случае, если вдруг змейка огромная, а компьютер слабый, мы можем заметить, что змейка иногда разрывается, что вообще не должно быть. Да и вообще, данный способ требует слишком много команд, когда можно обойтись гораздо меньшим количеством, не потеряв качество. А теперь мой способ: Мы берем последний элемент змейки, и ставим его в начало, изменяя его координаты так, чтобы он был после головы. Теперь этот элемент — голова. Всего-то! И да, эффект движения будет присутствовать, а на компьютере вообще не будет заметно, как мы спрятали хвост, а потом его поставили в начало. именно так мы и будем поступать во время создания движения змейки.

Вот тут точно начинаем

Сначала нам нужно объявить некоторые переменные, которые мы в дальнейшем будем использовать.

И так, вообще, нужно чуть-чуть пояснить зачем нам нужно в функции возвращения случайного числа, умножать и делить на переменную s, которая хранит в себе ни что иное, как ширину, по совместительству и высоту элементов змейки. На самом деле, это нужно, чтобы не было смещений во время движения, так как у нас ширина элемента — 30, то если мы хотим двигать ее без разрывов, то все координаты должны делиться на 30 без остатка. Именно поэтому я делю на число, округляю, а потом умножаю. Таким образом, число возвращается таким, что его можно разделить без остатка на 30.

Вы могли бы возразить, сказав, что ты мог бы просто холсту сделать ширину и высоту, кратную 30. Но на самом деле, это не лучший вариант. Так как я лично привык использовать всю ширину экрана. И в случае, если ширина = 320, то мне пришлось бы аж целых 20 пикселей забирать у пользователя, что могло бы доставить дискомфорт. Именно поэтому в нашей змейки все координаты объектов делятся на 30, чтобы не было никаких неожиданных моментов. Было бы даже правильнее вынести это как отдельную функцию, так как она достаточно часто используется в коде. Но к этому выводу я пришел поздно. (Но возможно это даже не нужно).

Теперь сделаем так, чтобы картинка имела четкое качество отображения. По ходу статьи, я буду дописывать код, в некоторых местах возвращаться к началу, так что при себе имейте полную картину кода.

Если что, то переменные innerWidth и innerHeight хранятся в глобальном пространстве имен.
Поэтому к ним можно обратиться именно так. Правда, я не знаю правильно ли так делать.

Ну что же, теперь начинаем писать код змейки.

Чтобы было движение, нам нужна анимация, мы будем использовать функцию setInterval, вторым параметром которой будет число 60. Можно чуть больше, 75 на пример, но мне нравится 60. Функция всего на всего каждые 60 мс. рисует змейку «заново». Дальнейшее написание кода — это только этот интервал.

Покажу вообще простую отрисовку нашей змейки, пока что без движения.

Чтобы проверить, что наша змейка не сталкивается сама с собой, нам нужно сделать некоторую проверку для каждого элемента, кроме последнего. Мы будем проверять, не равны ли координаты последнего элемента (головы) змейки любым из… То есть проще говоря: не произошло ли столкновение. Эта строчка кода была единой строкой, но вам сделал ее понятной. Напоминаю, что все это добавляется в функцию интервала.

А теперь, вы наверное заметили, что во время того, как мы изменяем координаты, мы вечно что-то «сохраняем», сначала поделив, а потом округлив и умножив на число s. Это все тот же самый способ выравнивания змейки относительно яблока. Движение в данном случае строгое, простое, поэтому и есть змейка яблоко может строго по определенным правилам, которые задан в самом начале интервала. И если бы координаты головы змейки хоть на 1px сместились бы, то яблоко нельзя было бы съесть. И да, это простой вариант, поэтому все так сильно ограничено.

Ну а нам же осталось что сделать? Правильно, удалить из массива хвост (первый элемент), добавить новый элемент в самый конец и отрисовать всю змейку. Сделаем это, добавив в конец интервала вот такие строчки кода.

В добавок к отрисовке змейки, я добавил код, который делает ощущение, что конец экрана — это его начало. И если змейка выходит за границы, то она потом выходит из начала, на погибая.
Вы можете заменить обнуление координат, на пример, на сбрасывание игры, если у вас все очень жестко. Но мне нравится больше так. Ну а теперь, осталось только по нажатию кнопок изменять направление змейки. Делает за считанные секунды. Нужно лишь написать этот код сразу после setInterval. Примерно так:

Тут мы сделали так, что если змейка двигается вправо, то она не может изменить направление налево. Это логично, на самом деле.

Вот и все, друзья. Моя первая статья, написанная новичком для новичков. Надеюсь, все было понятно и кому-то это пригодилось. Змейку можно усовершенствовать, добавив на пример, счетчик очков, рекорды, дополнительные фишки, но это все уже дополнения, которые вы можете сделать сами. На этом все, всем удачи!

How to Build a Snake Game In JavaScript

Fakorede Damilola

Fakorede Damilola

How to Build a Snake Game In JavaScript

In this article I am going to show you how to build a snake game with JavaScript.

A snake game is a simple game where a snake moves around a box trying to eat an apple. Once it successfully eats the apple, the length of the snake increases and the movement becomes faster.

Then the game is over when the snake runs into itself or any of the four walls of the box.

Alright, let’s start with the HTML and CSS (the skeleton for our game).

The HTML above is pretty basic.

  • We have a div of class scoreDisplay that will display our scores.
  • There’s a div of class grid that will house the game (this is going to be a 10 by 10 grid)
  • The class button basically contains a button for users playing the game on a phone (we will automate it with the keyboard for desktop user).
  • And the popup class will hold our replay button.
Читать:
Как установить windows рядом с linux

Now let’s add some styling with CSS.

In the CSS, the grid which is the gameboard has a set dimension and a display of flex . This allows the contents (div) of this grid to line up in a horizontal manner as if they were inline elements instead of the normal block display which they possess.

The flex wrap property simply moves the divs to the next line, preventing them from going past the set dimension of their parent element (grid).

We will be dynamically creating the game board contents from JS but we can give a width and height here (with the .grid div). I included the comments here to help you actually see the divs, so as time goes on we will uncomment the code.

The snake and Apple classes are to show us where the snake and bonus is on the game, while the popup class is a fixed div that houses the replay div.

At this point, you should have something like this:

Screenshot--1710-

Structure with HTML and CSS

Now we’re ready for the JavaScript.

JavaScript

The first thing we need to do is define our variables:

The variable width is exactly what it is (the width of the grid, that is 10). Other variables will make more sense as we go on – but believe it or not our snake is actually an array called currentSnake .

Now let’s start with the functions:

There is an eventListener on the document object called DomContentLoaded and this event is fired off immediately once the HTML content is loaded on our screen.

Once this happens, we set an eventListener on the document to watch for clicks on the keyboard (more on this later). After that, we want to create the gameBoard , start the game, and watch out for clicks on our replay button.

The createBoard function

Like I said earlier, this is a 10 by 10 grid, meaning we are going to need 100 divs. So from above, we close the div popup and we loop to 100 every time we create a new div and append it to the grid (gameboard).

This will immediately add some of the styling we created from above (the .grid div). You can uncomment the CSS styles and you will see the divs created (uncomment them back).

The startGame function

The startGame function first gets all the divs (since we are creating the divs at runtime, we can not get them at the top of the code).

Next we select a spot for our apple. We will do that below in the randomApple function. The direction refers to where the snake is headed – 1 for right, -1 for left, and so on.

intervalTime sets the time it takes for the snake to move around, while currentSnake defines where exactly on the grid the snake will be (note that the snake is basically a couple of divs given a particular type of color).

To display our snake on the screen, we will loop over currentSnake with forEach . With each value we get, we will use it with squares. Remember that we accessed the grid divs with querySelectorAll , and we can then access them like an array, that is using numbers. In our case, these are the values of currentSnake .

After this, we simply append a setInterval call (with function move Outcome and a time of intervalTime , which we set above) to the variable interval . This is so that we can easily call clearInterval on that variable.

The moveOutcome runs every 1000ms (1s) and basically defines what happens when you move the snake.

The moveOutcome function

So like the startGame function above, we first get all the grid divs, and then we check if the checkForHits function returns true.

If it does, this means we have hit something and then it displays the replay button and it clears the interval. If it returns false, this means we did not hit anything and we move the snake with the moveSnake function.

So basically, every 1sec the game either comes to an end if checkForHits is true or we move the snake a step forward if checkForHits is false. I will talk about the moveSnake function first.

The moveSnake function

The moveSnake function receives an argument called squares so that we don’t have to get the .grid div again in this function.

The first thing we need to do is remove the last element of the currentSnake array via pop (this is the tail and the first element is always the head). Basically the snake moves a step forward leaving the previous position it was in. After this we simply add a new value to the beginning of the array with unShift .

Let’s assume that our snake just started moving and is facing to the right (that is, direction = 1). That direction will be added to the currentSnake ‘s head and the sum will be pushed as the new snakeHead .

For example, if the snake was in position [2,1,0], we remove the last element leaving it at position [2,1]. Then we take the head which is 2 and add the direction which is 1 and make this value the new value [3,2,1] which moves our snake a step forward to the right after one second.

If we want to move the snake downwards, the direction will be set to the width (which is 10) and added to the first element (that is 12 and pushed) [12,2,1].

After that we simply check if the snake has eaten an apple and display the new snakehead on the DOM.

The checkForHits function

The checkForHits function has an if statement. Depending on the condition defined, it could either return true (meaning we hit something) or false.

The first condition is if currentSnake [0] (the head of the snake) + width (10) is equal to the total area of the width (that is, width*width = 100) and the direction is equal to the width.

So basically let’s assume that the snake’s head is at position 97 which is the last layer of our grid. If you were to add 10 to 97 (= 107), that is greater than the whole grid which is 100. If the direction of the snake is still headed downwards, then the snake has hit the bottom border.

If the snake was at 97 , 97+10 =107, but the player was able to change the direction to, say, 1 (like, they pressed the left key), then it would not hit anything.

Or (||) if the remainder when the head of the snake divided by the width = width-1 (for example, 9) and the direction is 1. Every last div on the right hand side has a value of 9, 19, 29 and so on. So basically it will always remain 9 when you divide by 10.

If the head of our snake is at position 39 and the direction is still 1 (that is, the snake is still moving to the wall), then it has hit something (the right wall).

Every other condition is pretty much the exact opposite of the two above. The final condition allows that if the snake head is headed to a place that already contains a class snake, that simply means the snake is biting itself.

So. if any of the conditions above are true, the snake has hit something and true will be returned (else false). And if that’s the case, the game is over. But if it is false, move the snake a step forward with moveSnake .

The eatApple function

The eatApple function is called from the moveSnake function every time the snake moves a step.

It receives two argument squares, .grid div and tail (basically the value that was popped up from the snake in moveOutcome ). It then checks if the next position our snake moves to contains an apple.

If it does, it simply adds that tail we popped up back to the array. This is because every time our snake eats an apple we want to increase the length of the snake by one value – and what better way than to add the tail that was popped off when it moved?

Then we simply select a new position for our apple with randomApple (see below). After that we add a value of one to our score and display it to the user, clear the timeInterval (so that we can increase the speed of the snake, that is the time each movement happens) and then we simply set the interval back.

The randomApple function

randomApple simply picks a spot to place our apple by using a do while loop. First it picks a random position with Math.random() in the do loop and checks if the spot it picked already contains a snake class.

This means that the condition in the do statement will keep on running until it finds a spot that does not contain a snake (keep doing this while this is true). Once it finds a spot it simply gives that spot a class of apple.

Set up controls

Now we need to set up our controls. We will start with keyboard users.

Remember from above we set an eventListener for keyup . This function fires off immediately after your hand presses and. leaves a key on a keyboard.

Now each button on the keyboard has a value called keycode (numbers) which we have access to and let us know which number was clicked. Basically we will be watching for the arrow keys with their respective keycodes. With that we make changes to the direction, for example -1, 10 and so on.

Alright, I hope you understand how we are able to move the snake now.

Next, this set of buttons is for mobile devices and we are basically doing the same thing:

The final thing we need to do is create the replay div which will popup when the snake hits something. The button helps us reset the game.

The replay function

From above, we basically clear the grid (gameboard) and run the previous functions.

Congrats — you made it to the end! Here’s the final result:

Screenshot--1709-

Final game

I hope you were able to code along and you enjoyed it.

In this tutorial, we learned how to create our own snake game with JavaScript. Some other important concepts we covered include push, pop, setInterval, clearInterval and eventListener.

Похожие статьи