Jasne! Poniżej znajdziesz prostą grę w węża napisaną w HTML, CSS i JavaScript. Możesz skopiować cały kod do pliku .html i otworzyć w przeglądarce, aby zagrać.
html Copy code
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Gra Wąż</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background: #222;
margin: 0;
font-family: Arial, sans-serif;
color: #eee;
}
canvas {
background: #000;
display: block;
margin: 0 auto;
border: 2px solid #0f0;
}
#score {
position: absolute;
top: 20px;
font-size: 24px;
font-weight: bold;
color: #0f0;
}
</style>
</head>
<body>
<div id="score">Wynik: 0</div>
<canvas id="game" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
const box = 20; // rozmiar jednego pola
let snake = [];
snake[0] = { x: 9 * box, y: 10 * box };
let food = {
x: Math.floor(Math.random() * 20) * box,
y: Math.floor(Math.random() * 20) * box
};
let score = 0;
let d;
document.addEventListener('keydown', direction);
function direction(event) {
if(event.key === 'ArrowLeft' && d !== 'RIGHT') {
d = 'LEFT';
} else if(event.key === 'ArrowUp' && d !== 'DOWN') {
d = 'UP';
} else if(event.key === 'ArrowRight' && d !== 'LEFT') {
d = 'RIGHT';
} else if(event.key === 'ArrowDown' && d !== 'UP') {
d = 'DOWN';
}
}
function collision(head, array) {
for(let i = 0; i < array.length; i++) {
if(head.x === array[i].x && head.y === array[i].y) {
return true;
}
}
return false;
}
function draw() {
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, canvas.width, canvas.height);
for(let i = 0; i < snake.length; i++) {
ctx.fillStyle = (i === 0) ? '#0f0' : '#0a0';
ctx.fillRect(snake[i].x, snake[i].y, box, box);
ctx.strokeStyle = '#003300';
ctx.strokeRect(snake[i].x, snake[i].y, box, box);
}
ctx.fillStyle = '#f00';
ctx.fillRect(food.x, food.y, box, box);
// Pozycja głowy węża
let snakeX = snake[0].x;
let snakeY = snake[0].y;
// Ruch węża
if(d === 'LEFT') snakeX -= box;
if(d === 'UP') snakeY -= box;
if(d === 'RIGHT') snakeX += box;
if(d === 'DOWN') snakeY += box;
// Jeśli wąż zjadł jedzenie
if(snakeX === food.x && snakeY === food.y) {
score++;
document.getElementById('score').innerText = 'Wynik: ' + score;
food = {
x: Math.floor(Math.random() * 20) * box,
y: Math.floor(Math.random() * 20) * box
};
// Nie usuwamy ogona, więc wąż rośnie
} else {
// Usuwamy ogon
snake.pop();
}
// Nowa głowa
let newHead = {
x: snakeX,
y: snakeY
};
// Sprawdzenie kolizji z ciałem
if(snakeX < 0 || snakeX >= canvas.width || snakeY < 0 || snakeY >= canvas.height || collision(newHead, snake)) {
clearInterval(game);
alert('Koniec gry! Twój wynik: ' + score);
location.reload();
}
snake.unshift(newHead);
}
let game = setInterval(draw, 100);
</script>
</body>
</html>