Найти тему
Kentafuriks

[JS] Как сделать игру змейку

Оглавление

Необходимо:

1) Нужно любой текстовый редактор, но я буду пользоваться Visual Studio Code (Вот ссылка на него https://code.visualstudio.com/, он абсолютно бесплатный, мало весит и очень много плюшек. Могу сделать гайд если надо)
2)Время
3)Желание:3

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

В папке необходимо создать 3 документа:


index.html - это наш сайт, точнее индекс нашего веб-сайта.

style.css - необходим для оформление нашей игры.

app.js - сама логика игры написанной на JavaScripte.


Вот код для Index.html

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<link rel="stylesheet" href="style.css">

<title>Snake</title>

</head>

<body>

<div class="container" onclick='document.getElementById("txt").focus();'>

<div id="menu">

<div class="menu-item">

<span id="menu-text">Press ENTER to start the game</span>

</div>

</div>

<div id="map" style="display: none;">

</div>

</div>

<input style="opacity:0;width:0;height:0" id="txt" type="text">

<script src="app.js"></script>

</body>

</html>

Код для style.css:

* {

margin: 0;

padding: 0;

}

html,

body {

height: 100%;

}

body {

background: #333;

color: #fff;

height: 100%;

display: flex;

justify-content: center;

align-items: center;

}

.container {

max-width: 90vmin;

max-height: 90vmin;

width: 100%;

border: 5px solid #666666;

margin: auto;

overflow: hidden;

}

#menu,

#map {

position: relative;

width: 100%;

height: 100%;

padding-bottom: 100%;

}

#menu {

background: #000000;

}

.menu-item {

position: absolute;

top: 0;

left: 0;

bottom: 0;

right: 0;

display: flex;

justify-content: center;

align-items: center;

}

#menu-text {

font-family: Arial, Helvetica, sans-serif;

font-size: 20px;

text-align: center;

line-height: 40px;

}

.pixel {

width: 10%;

padding-bottom: 10%;

float: left;

}

.snake-body {

z-index: 5;

position: relative;

background: #00ff00;

box-shadow: 0 0 7px #00ff00, 0 0 20px #00ff00;

}

.food {

background: #ff0000;

box-shadow: 0 0 10px #ff0000, 0 0 40px #ff0000, 0 0 80px #ff0000;

}

Код для app.js:

var snakeBody, food, direction, allowedToMove, isPlaying;

var map;

var speed = 2;

var play;

function initializeVariables() {

snakeBody = [[0, 0]];

food = 0;

direction = "Right";

allowedToMove = false;

isPlaying = false;

}

// Создание игрового поля и инициализация переменных

function initializeGameState(mapElementId) {

map = document.getElementById(mapElementId);

initializeVariables();

// Создание пикселей для игрового поля

for (var i = 0; i < 100; i++) {

var pixel = document.createElement("div");

pixel.setAttribute("class", "pixel");

map.appendChild(pixel);

}

// Генерация тела змеи и еды

map.children[0].classList.add("snake-body");

generateFood();

}

function generateFood() {

// To prevent generating food over the snake

while (map.children[food].classList.contains("snake-body")) {

food = Math.floor(Math.random() * 100);

}

// Размещение еды на карте

map.children[food].classList.add("food");

}

function startGame() {

if (!isPlaying) {

allowedToMove = true;

play = setInterval(updatePosition, 500 / speed);

document.getElementById("menu").style.display = "none";

document.getElementById("map").style.display = "block";

isPlaying = true;

}

}

function pauseGame() {

if (isPlaying) {

allowedToMove = false;

clearInterval(play);

document.getElementById("menu-text").innerText =

"PAUSED\nPress ENTER to resume";

document.getElementById("menu").style.display = "block";

document.getElementById("map").style.display = "none";

isPlaying = false;

}

}

function gameOver() {

clearInterval(play);

document.getElementById("menu-text").innerText =

"Game Over\nYour Score: " +

(snakeBody.length - 1) +

"\nPress ENTER to restart";

document.getElementById("menu").style.display = "";

document.getElementById("map").style.display = "none";

map.innerText = ""; // Clearing the map

initializeGameState(map.id); // Re-generating the map

}

function updatePosition() {

var newPosR, newPosC;

var head = snakeBody[snakeBody.length - 1];

switch (direction) {

case "Up":

newPosR = head[0] - 1;

newPosC = head[1];

break;

case "Down":

newPosR = head[0] + 1;

newPosC = head[1];

break;

case "Left":

newPosR = head[0];

newPosC = head[1] - 1;

break;

case "Right":

newPosR = head[0];

newPosC = head[1] + 1;

break;

default:

break;

}

// Проверка, не ударилась ли змея о стену

if (newPosR < 0 || newPosR > 9 || newPosC < 0 || newPosC > 9) {

gameOver();

} else {

snakeBody.push([newPosR, newPosC]);

updateScreen();

allowedToMove = true;

}

}

function updateScreen() {

var tailArray = snakeBody.shift();

var tail = parseInt(tailArray[0] + "" + tailArray[1]);

var headArray = snakeBody[snakeBody.length - 1];

var head = parseInt(headArray[0] + "" + headArray[1]);

// Проверяем, не укусила ли змея свое тело

if (map.children[head].classList.contains("snake-body")) {

gameOver();

} else {

// Добавляет новый головной блок

map.children[head].classList.add("snake-body");

// Удаляет хвостовой блок

map.children[tail].classList.remove("snake-body");

// Если змея ест еду

if (head == food) {

map.children[food].classList.remove("food");

snakeBody.unshift(tailArray);

// Проверка, достигла ли змея своего максимального размера

snakeBody.length == 100 && gameOver();

generateFood();

}

}

}

// Управление

document.onkeydown = keyPress;

function keyPress(e) {

e.preventDefault();

e = e || window.event;

// Пауза

e.keyCode == 27 && pauseGame();

// Передвижение

e.keyCode == 13 && startGame();

let up = 38;

let down = 40;

let left = 37;

let right = 39;

if (allowedToMove) {

allowedToMove = false;

switch (e.keyCode) {

case left:

direction != "Right" && (direction = "Left");

break;

case up:

direction != "Down" && (direction = "Up");

break;

case right:

direction != "Left" && (direction = "Right");

break;

case down:

direction != "Up" && (direction = "Down");

break;

default:

allowedToMove = true;

break;

}

}

}

initializeGameState("map");

=============================

После чего необходимо сохранить все файлы и запустить index.html в любом браузере.
Результат: