Gra Wąż w HTML i JavaScript
Oto kompletny kod gry Wąż (Snake) napisany w HTML i JavaScript:
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Gra Wąż</title>
<style>
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
font-family: Arial, sans-serif;
}
h1 {
color: #333;
margin-bottom: 10px;
}
#game-container {
position: relative;
}
#game-board {
border: 2px solid #333;
background-color: #fff;
}
#score {
margin-top: 20px;
font-size: 24px;
font-weight: bold;
}
#game-over {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: rgba(0, 0, 0, 0.8);
color: white;
padding: 20px;
border-radius: 10px;
text-align: center;
display: none;
}
#restart-btn {
margin-top: 15px;
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
}
#restart-btn:hover {
background-color: #45a049;
}
.controls {
margin-top: 20px;
text-align: center;
}
.controls p {
margin: 5px 0;
font-size: 16px;
}
</style>
</head>
<body>
<h1>Gra Wąż</h1>
<div id="game-container">
<canvas id="game-board" width="400" height="400"></canvas>
<div id="game-over">
<h2>Koniec gry!</h2>
<p id="final-score">Twój wynik: 0</p>
<button id="restart-btn">Zagraj ponownie</button>
</div>
</div>
<div id="score">Wynik: 0</div>
<div class="controls">
<p>Sterowanie: strzałki na klawiaturze</p>
</div>
<script>
// Ustawienia gry
const canvas = document.getElementById('game-board');
const ctx = canvas.getContext('2d');
const scoreElement = document.getElementById('score');
const gameOverElement = document.getElementById('game-over');
const finalScoreElement = document.getElementById('final-score');
const restartBtn = document.getElementById('restart-btn');
const boxSize = 20;
const rows = canvas.height / boxSize;
const cols = canvas.width / boxSize;
let snake = [];
let direction = null;
let food = null;
let score = 0;
let gameSpeed = 100; // ms
let gameInterval = null;
// Inicjalizacja gry
function initGame() {
// Resetowanie węża
snake = [
{x: 5 * boxSize, y: 10 * boxSize},
{x: 4 * boxSize, y: 10 * boxSize},
{x: 3 * boxSize, y: 10 * boxSize}
];
// Resetowanie kierunku
direction = null;
// Resetowanie wyniku
score = 0;
scoreElement.textContent = `Wynik: ${score}`;
// Generowanie jedzenia
generateFood();
// Ukrywanie ekranu końca gry
gameOverElement.style.display = 'none';
// Rozpoczęcie gry
if (gameInterval) clearInterval(gameInterval);
gameInterval = setInterval(gameLoop, gameSpeed);
}
// Generowanie jedzenia
function generateFood() {
const foodX = Math.floor(Math.random() * cols) * boxSize;
const foodY = Math.floor(Math.random() * rows) * boxSize;
// Sprawdzenie, czy jedzenie nie pojawia się na wężu
for (let segment of snake) {
if (segment.x === foodX && segment.y === foodY) {
return generateFood();
}
}
food = {x: foodX, y: foodY};
}
// Główna pętla gry
function gameLoop() {
// Rysowanie planszy
ctx.fillStyle = '#fff';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Rysowanie węża
for (let i = 0; i < snake.length; i++) {
ctx.fillStyle = i === 0 ? '#4CAF50' : '#8BC34A';
ctx.fillRect(snake[i].x, snake[i].y, boxSize, boxSize);
ctx.strokeStyle = '#fff';
ctx.strokeRect(snake[i].x, snake[i].y, boxSize, boxSize);
}
// Rysowanie jedzenia
ctx.fillStyle = '#F44336';
ctx.fillRect(food.x, food.y, boxSize, boxSize);
// Aktualizacja pozycji węża
const head = {x: snake[0].x, y: snake[0].y};
if (direction === 'UP') {
head.y -= boxSize;
} else if (direction === 'DOWN') {
head.y += boxSize;
} else if (direction === 'LEFT') {
head.x -= boxSize;
} else if (direction === 'RIGHT') {
head.x += boxSize;
}
// Sprawdzenie kolizji ze ścianami
if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height) {
gameOver();
return;
}
// Sprawdzenie kolizji z własnym ciałem
for (let i = 1; i < snake.length; i++) {
if (head.x === snake[i].x && head.y === snake[i].y) {
gameOver();
return;
}
}
// Dodanie nowej głowy
snake.unshift(head);
// Sprawdzenie, czy wąż zjadł jedzenie
if (head.x === food.x && head.y === food.y) {
score++;
scoreElement.textContent = `Wynik: ${score}`;
// Zwiększenie prędkości co 5 punktów
if (score % 5 === 0 && gameSpeed > 50) {
gameSpeed -= 5;
clearInterval(gameInterval);
gameInterval = setInterval(gameLoop, gameSpeed);
}
generateFood();
} else {
// Usunięcie ogona, jeśli nie zjedzono jedzenia
snake.pop();
}
}
// Obsługa końca gry
function gameOver() {
clearInterval(gameInterval);
finalScoreElement.textContent = `Twój wynik: ${score}`;
gameOverElement.style.display = 'block';
}
// Obsługa przycisku restart
restartBtn.addEventListener('click', initGame);
// Obsługa klawiszy
document.addEventListener('keydown', function(event) {
// Zapobieganie zmianie kierunku na przeciwny
switch(event.key) {
case 'ArrowUp':
if (direction !== 'DOWN') direction = 'UP';
break;
case 'ArrowDown':
if (direction !== 'UP') direction = 'DOWN';
break;
case 'ArrowLeft':
if (direction !== 'RIGHT') direction = 'LEFT';
break;
case 'ArrowRight':
if (direction !== 'LEFT') direction = 'RIGHT';
break;
}
});
// Rozpoczęcie gry
initGame();
</script>
</body>
</html>
Jak działa ta gra:
-
Plansza gry: Gra odbywa się na kwadratowej planszy o rozmiarze 400x400 pikseli.
-
Wąż: Składa się z segmentów, z których pierwszy (głowa) jest zielony, a reszta jaśniejsza.
-
Jedzenie: Czerwone kwadraty, które pojawiają się losowo na planszy.
-
Sterowanie: Strzałkami na klawiaturze (góra, dół, lewo, prawo).
-
Mechanika gry:
- Wąż porusza się w wybranym kierunku
- Gdy zje jedzenie, rośnie i zwiększa się wynik
- Gra kończy się, gdy wąż uderzy w ścianę lub w siebie
- Co 5 punktów gra przyspiesza
-
Ekran końca gry: Po zakończeniu gry wyświetla się komunikat z końcowym wynikiem i przyciskiem do restartu.
Możesz skopiować ten kod do pliku HTML i otworzyć go w przeglądarce, aby zagrać w Węża.