Wygeneruj w HTML kod gry w węża
- User
Wygeneruj w HTML kod gry w węża
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Wygeneruj w HTML kod gry w węża
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Z przyjemnością pomogę Ci wygenerować prosty kod gry w węża w HTML, CSS i JavaScript. Oto kompletny przykład:
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="UTF-8">
<title>Gra Snake</title>
<style>
#gameBoard {
border: 2px solid black;
background-color: #f0f0f0;
}
</style>
</head>
<body>
<canvas id="gameBoard" width="400" height="400"></canvas>
<div>Wynik: <span id="score">0</span></div>
<script>
const canvas = document.getElementById('gameBoard');
const ctx = canvas.getContext('2d');
const scoreElement = document.getElementById('score');
const gridSize = 20;
const tileCount = canvas.width / gridSize;
let snake = [{x: 10, y: 10}];
let food = {x: 15, y: 15};
let dx = 1;
let dy = 0;
let score = 0;
function drawGame() {
clearCanvas();
moveSnake();
drawSnake();
drawFood();
checkCollision();
}
function clearCanvas() {
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
function drawSnake() {
ctx.fillStyle = 'green';
snake.forEach(segment => {
ctx.fillRect(
segment.x * gridSize,
segment.y * gridSize,
gridSize - 2,
gridSize - 2
);
});
}
function moveSnake() {
const head = {x: snake[0].x + dx, y: snake[0].y + dy};
snake.unshift(head);
if (head.x === food.x && head.y === food.y) {
score++;
scoreElement.textContent = score;
generateFood();
} else {
snake.pop();
}
}
function drawFood() {
ctx.fillStyle = 'red';
ctx.fillRect(
food.x * gridSize,
food.y * gridSize,
gridSize - 2,
gridSize - 2
);
}
function generateFood() {
food.x = Math.floor(Math.random() * tileCount);
food.y = Math.floor(Math.random() * tileCount);
}
function checkCollision() {
const head = snake[0];
// Kolizja ze ścianami
if (head.x < 0 || head.x >= tileCount ||
head.y < 0 || head.y >= tileCount) {
resetGame();
}
// Kolizja z własnym ciałem
for (let i = 1; i < snake.length; i++) {
if (head.x === snake[i].x && head.y === snake[i].y) {
resetGame();
}
}
}
function resetGame() {
snake = [{x: 10, y: 10}];
score = 0;
scoreElement.textContent = score;
dx = 1;
dy = 0;
}
document.addEventListener('keydown', (e) => {
switch(e.key) {
case 'ArrowUp':
if (dy === 0) { dx = 0; dy = -1; }
break;
case 'ArrowDown':
if (dy === 0) { dx = 0; dy = 1; }
break;
case 'ArrowLeft':
if (dx === 0) { dx = -1; dy = 0; }
break;
case 'ArrowRight':
if (dx === 0) { dx = 1; dy = 0; }
break;
}
});
setInterval(drawGame, 100);
</script>
</body>
</html>
Ten kod tworzy prostą grę w węża z następującymi funkcjami:
Możesz skopiować ten kod, wkleić do pliku .html i uruchomić w przeglądarce. Miłej zabawy!