-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
5 changed files
with
214 additions
and
95 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,106 @@ | ||
import { updateScore, showGameOverScreen, resetUI } from './ui.js'; | ||
|
||
let canvas = document.getElementById("gameCanvas"); | ||
let ctx = canvas.getContext("2d"); | ||
|
||
let Snake = [{ x: 0, y: 0 }]; | ||
let Food = { | ||
x: Math.floor(Math.random() * 29) * 10, | ||
y: Math.floor(Math.random() * 29) * 10, | ||
}; | ||
|
||
let speedX = 10; | ||
let speedY = 0; | ||
let interval = 100; | ||
let move; | ||
let score = 0; // Счет игры | ||
|
||
// Функция для создания новой еды в случайном месте | ||
function createNewFood() { | ||
Food.x = Math.floor(Math.random() * 29) * 10; | ||
Food.y = Math.floor(Math.random() * 29) * 10; | ||
} | ||
|
||
// Функция завершения игры | ||
function endGame() { | ||
clearInterval(move); | ||
showGameOverScreen(score); // Показываем всплывающее окно с финальным счетом | ||
} | ||
|
||
// Проверка на столкновение змейки с собой | ||
function checkSelfCollision() { | ||
for (let i = 1; i < Snake.length; i++) { | ||
if (Snake[0].x === Snake[i].x && Snake[0].y === Snake[i].y) { | ||
return true; | ||
} | ||
} | ||
return false; | ||
} | ||
|
||
// Перемещение змейки | ||
function movingSnake() { | ||
ctx.clearRect(0, 0, canvas.width, canvas.height); | ||
|
||
for (let i = Snake.length - 1; i > 0; i--) { | ||
Snake[i] = { ...Snake[i - 1] }; | ||
} | ||
Snake[0].x += speedX; | ||
Snake[0].y += speedY; | ||
|
||
// Проверка столкновения с границами | ||
if (Snake[0].x < 0 || Snake[0].x >= canvas.width || Snake[0].y < 0 || Snake[0].y >= canvas.height) { | ||
endGame(); | ||
return; | ||
} | ||
|
||
// Проверка столкновения с собой | ||
if (checkSelfCollision()) { | ||
endGame(); | ||
return; | ||
} | ||
|
||
// Проверка на поедание еды | ||
if (Snake[0].x === Food.x && Snake[0].y === Food.y) { | ||
Snake.push({ ...Snake[Snake.length - 1] }); // Увеличиваем длину змейки | ||
createNewFood(); // Создаем новую еду | ||
score++; // Увеличиваем счет | ||
updateScore(score); // Обновляем счет на экране | ||
} | ||
|
||
// Отрисовка еды и змейки | ||
ctx.fillStyle = 'red'; | ||
ctx.fillRect(Food.x, Food.y, 10, 10); | ||
|
||
ctx.fillStyle = 'lime'; | ||
Snake.forEach(segment => { | ||
ctx.fillRect(segment.x, segment.y, 10, 10); | ||
}); | ||
} | ||
|
||
// Старт игры | ||
export function startGame() { | ||
resetUI(); // Сбрасываем интерфейс перед началом игры | ||
Snake = [{ x: 0, y: 0 }]; | ||
speedX = 10; | ||
speedY = 0; | ||
score = 0; | ||
createNewFood(); | ||
|
||
move = setInterval(movingSnake, interval); | ||
|
||
document.addEventListener('keydown', function (event) { | ||
if (event.key === "ArrowRight" && speedX === 0) { | ||
speedX = 10; | ||
speedY = 0; | ||
} else if (event.key === "ArrowLeft" && speedX === 0) { | ||
speedX = -10; | ||
speedY = 0; | ||
} else if (event.key === "ArrowDown" && speedY === 0) { | ||
speedX = 0; | ||
speedY = 10; | ||
} else if (event.key === "ArrowUp" && speedY === 0) { | ||
speedX = 0; | ||
speedY = -10; | ||
} | ||
}); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,18 +1,31 @@ | ||
<!DOCTYPE html> | ||
<html lang="en"> | ||
<head> | ||
<meta charset="UTF-8"> | ||
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | ||
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | ||
<title>Snake</title> | ||
<link rel="stylesheet" href="style.css"> | ||
</head> | ||
<body> | ||
<head> | ||
<meta charset="UTF-8" /> | ||
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> | ||
<title>Snake Game</title> | ||
<link rel="stylesheet" href="style.css" /> | ||
</head> | ||
<body> | ||
<h1 style="color: white">Snake Game</h1> | ||
<div id="menu"> | ||
<button id="startButton">Start Game</button> | ||
</div> | ||
|
||
<canvas id="canvaArea" height="300" width="300"> | ||
<!-- Счетчик очков --> | ||
<div id="score">Score: 0</div> | ||
|
||
</canvas> | ||
</body> | ||
<script src="index.js"></script> | ||
<canvas id="gameCanvas" width="300" height="300"></canvas> | ||
|
||
</html> | ||
<!-- Всплывающее окно при окончании игры --> | ||
<div id="gameOverScreen" class="overlay"> | ||
<div class="overlay-content"> | ||
<h2>Game Over</h2> | ||
<p id="finalScore"></p> | ||
<button id="restartButton">Restart Game</button> | ||
</div> | ||
</div> | ||
|
||
<script type="module" src="index.js"></script> | ||
</body> | ||
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,72 +1,11 @@ | ||
var canvas = document.getElementById("canvaArea") | ||
var ctx = canvas.getContext("2d") | ||
|
||
//Create two objects | ||
var Snake = [] | ||
Snake[0] = { | ||
x: 0, | ||
y: 0 | ||
} | ||
|
||
var Food = [] | ||
Food[0] = { | ||
x: Math.floor(Math.random()*23+1) * 10, | ||
y: Math.floor(Math.random()*32+3) * 10 | ||
} | ||
|
||
//Draw them | ||
ctx.fillRect(Snake[0].x,Snake[0].y,10,10) | ||
ctx.fillRect(Food[0].x,Food[0].y,10,10) | ||
|
||
var speedX = 10 | ||
var speedY = 0 | ||
|
||
ctx.fillRect(Snake[0].x,Snake[0].y,10,10) | ||
|
||
movingSnake = () => { | ||
ctx.clearRect(Snake[0].x,Snake[0].y,10,10) | ||
Snake[0].x += speedX | ||
Snake[0].y += speedY | ||
if(Snake[0].x < 0 || Snake[0].x > 291 || Snake[0].y < 0 || Snake[0].y > 291){ | ||
ctx.fillRect(Snake[0].x-speedX,Snake[0].y-speedY,10,10) | ||
clearInterval(move) | ||
console.log('game over') | ||
} else { | ||
move | ||
} | ||
ctx.fillRect(Snake[0].x,Snake[0].y,10,10) | ||
} | ||
|
||
|
||
var interval = 100 | ||
var move = setInterval(movingSnake,interval) | ||
|
||
document.addEventListener('keydown', function(event) { | ||
if(event.key == "ArrowRight") { | ||
speedX = 10 | ||
speedY = 0 | ||
} | ||
}) | ||
|
||
document.addEventListener('keydown', function(event) { | ||
if(event.key == "ArrowLeft") { | ||
speedX = -10 | ||
speedY = 0 | ||
} | ||
}) | ||
|
||
document.addEventListener('keydown', function(event) { | ||
if(event.key == "ArrowDown") { | ||
speedX = 0 | ||
speedY = 10 | ||
} | ||
}) | ||
|
||
document.addEventListener('keydown', function(event) { | ||
if(event.key == "ArrowUp") { | ||
speedX = 0 | ||
speedY = -10 | ||
} | ||
}) | ||
import { startGame } from './game.js'; | ||
import { hideMenu } from './ui.js'; | ||
|
||
// Запуск игры по нажатию на кнопку | ||
document.getElementById('startButton').addEventListener('click', () => { | ||
hideMenu(); // Скрываем меню | ||
startGame(); // Стартуем игру | ||
}); | ||
|
||
// Перезапуск игры по нажатию на кнопку Restart | ||
document.getElementById('restartButton').addEventListener('click', startGame); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,15 +1,47 @@ | ||
#gameArea{ | ||
width: 200px; | ||
height: 200px; | ||
border: solid 2px; | ||
padding: 0%; | ||
body { | ||
margin: 0; | ||
display: flex; | ||
flex-direction: column; | ||
align-items: center; | ||
background-color: #333; | ||
} | ||
#snake{ | ||
width: 20px; | ||
height: 20px; | ||
border: solid 2px; | ||
|
||
#menu { | ||
text-align: center; | ||
color: white; | ||
} | ||
|
||
#score { | ||
color: white; | ||
font-size: 20px; | ||
margin-bottom: 10px; | ||
} | ||
|
||
#gameCanvas { | ||
background-color: black; | ||
} | ||
|
||
#canvaArea{ | ||
border: solid 2px; | ||
} | ||
.overlay { | ||
position: absolute; | ||
top: 0; | ||
left: 0; | ||
width: 100%; | ||
height: 100%; | ||
background-color: rgba(0, 0, 0, 0.8); | ||
display: flex; | ||
justify-content: center; | ||
align-items: center; | ||
display: none; | ||
} | ||
|
||
.overlay-content { | ||
text-align: center; | ||
color: white; | ||
} | ||
|
||
button { | ||
padding: 10px 20px; | ||
font-size: 16px; | ||
margin-top: 20px; | ||
cursor: pointer; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
export function showMenu() { | ||
document.getElementById('menu').style.display = 'block'; | ||
} | ||
|
||
export function hideMenu() { | ||
document.getElementById('menu').style.display = 'none'; | ||
} | ||
|
||
let scoreDisplay = document.getElementById("score"); | ||
let gameOverScreen = document.getElementById("gameOverScreen"); | ||
let finalScoreDisplay = document.getElementById("finalScore"); | ||
let restartButton = document.getElementById("restartButton"); | ||
|
||
// Обновление и отображение текущего счета | ||
export function updateScore(score) { | ||
scoreDisplay.innerText = `Score: ${score}`; | ||
} | ||
|
||
// Показ окна Game Over и итогового счета | ||
export function showGameOverScreen(finalScore) { | ||
finalScoreDisplay.innerText = `Your final score: ${finalScore}`; | ||
gameOverScreen.style.display = 'flex'; // Показываем всплывающее окно | ||
} | ||
|
||
// Сброс интерфейса (очистка счета и скрытие окон) | ||
export function resetUI() { | ||
gameOverScreen.style.display = 'none'; // Скрываем Game Over экран | ||
scoreDisplay.innerText = `Score: 0`; // Сбрасываем счет | ||
} |