Створити браузерну гру
- User
Створити браузерну гру
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Створити браузерну гру
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Створення браузерної гри — чудовий спосіб навчитися основ веб-програмування та розробки ігор. Нижче я наведу приклад простої гри, створеної на HTML, CSS і JavaScript. Це буде гра "Впіймай котика", де потрібно клікати по котику, щоб отримувати очки.
catch-cat-game/
│
├── index.html - сторінка гри
├── style.css - оформлення
└── script.js - логіка гри
index.html<!DOCTYPE html>
<html lang="uk">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Впіймай котика!</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>🐱 Впіймай котика! 🐱</h1>
<p>Очки: <span id="score">0</span></p>
<div id="game-area">
<img id="cat" src="https://placekitten.com/100/100" alt="Котик" />
</div>
<script src="script.js"></script>
</body>
</html>
style.cssbody {
font-family: sans-serif;
text-align: center;
background-color: #fefae0;
margin: 0;
padding: 0;
}
#game-area {
position: relative;
width: 80%;
height: 60vh;
margin: 0 auto;
border: 2px solid #9e2a2b;
overflow: hidden;
background-color: #fff;
}
#cat {
position: absolute;
width: 100px;
height: auto;
cursor: pointer;
transition: transform 0.2s ease;
}
script.jsconst cat = document.getElementById("cat");
const gameArea = document.getElementById("game-area");
const scoreDisplay = document.getElementById("score");
let score = 0;
// Функція для переміщення котика
function moveCat() {
const areaWidth = gameArea.clientWidth;
const areaHeight = gameArea.clientHeight;
const catWidth = cat.clientWidth;
const catHeight = cat.clientHeight;
const x = Math.random() * (areaWidth - catWidth);
const y = Math.random() * (areaHeight - catHeight);
cat.style.left = `${x}px`;
cat.style.top = `${y}px`;
// Додатковий ефект: зменшується і повертається
cat.style.transform = "scale(0.9)";
setTimeout(() => {
cat.style.transform = "scale(1)";
}, 100);
}
// Обробник кліку по котику
cat.addEventListener("click", () => {
score++;
scoreDisplay.textContent = score;
moveCat();
});
// Початкове переміщення
moveCat();
// Переміщення котика кожні 1500 мс
setInterval(moveCat, 1500);
index.html, style.css, script.js у цю папку.index.html у браузері.Якщо хочеш, я можу допомогти створити більш складну гру, наприклад платформер або стрілялку, використовуючи Canvas або фреймворки типу Phaser.js.
Хочеш? 😊
Хочу
Супер! 😄 Тоді пропоную створити простий платформер за допомогою HTML5 Canvas та JavaScript. Це буде міні-гра, де гравець може рухатися, стрибати по платформах і збирати предмети.
cat-platformer/
│
├── index.html - сторінка гри
├── style.css - оформлення
└── game.js - логіка гри
index.html<!DOCTYPE html>
<html lang="uk">
<head>
<meta charset="UTF-8" />
<title>Котик на платформах</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>🐱 Котик на платформах</h1>
<p>Риба зібрана: <span id="score">0</span></p>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script src="game.js"></script>
</body>
</html>
style.cssbody {
text-align: center;
background-color: #f4f1de;
margin: 0;
padding: 0;
font-family: sans-serif;
}
#gameCanvas {
border: 3px solid #9e2a2b;
display: block;
margin: 0 auto;
background-color: #d4edec;
}
game.jsconst canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
const keys = {};
document.addEventListener("keydown", (e) => keys[e.code] = true);
document.addEventListener("keyup", (e) => keys[e.code] = false);
// Гравець
const player = {
x: 50,
y: 500,
width: 40,
height: 40,
color: "#e0bb17",
vx: 0,
vy: 0,
speed: 3,
jumpPower: -10,
onGround: false
};
// Платформи
const platforms = [
{ x: 0, y: 580, width: 800, height: 20 }, // підлога
{ x: 100, y: 500, width: 150, height: 10 },
{ x: 300, y: 420, width: 150, height: 10 },
{ x: 500, y: 340, width: 150, height: 10 },
];
// Риба
const fish = {
x: 600,
y: 300,
size: 20,
collected: false
};
let score = 0;
function update() {
// Рух гравця
player.vx = 0;
if (keys["ArrowLeft"] || keys["KeyA"]) player.vx = -player.speed;
if (keys["ArrowRight"] || keys["KeyD"]) player.vx = player.speed;
// Стрибок
if ((keys["ArrowUp"] || keys["Space"] || keys["KeyW"]) && player.onGround) {
player.vy = player.jumpPower;
player.onGround = false;
}
// Фізика
player.vy += 0.5; // гравітація
player.x += player.vx;
player.y += player.vy;
// Колізія з платформами
player.onGround = false;
for (const plat of platforms) {
if (
player.x < plat.x + plat.width &&
player.x + player.width > plat.x &&
player.y + player.height < plat.y + player.vy + 10 &&
player.y + player.height + player.vy >= plat.y
) {
player.vy = 0;
player.y = plat.y - player.height;
player.onGround = true;
}
}
// Колізія з рибою
if (!fish.collected &&
player.x < fish.x + fish.size &&
player.x + player.width > fish.x &&
player.y < fish.y + fish.size &&
player.y + player.height > fish.y) {
fish.collected = true;
score++;
document.getElementById("score").textContent = score;
}
// Не вилітати за межі екрана
if (player.y > canvas.height) {
player.x = 50;
player.y = 500;
player.vy = 0;
}
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Малюємо гравця
ctx.fillStyle = player.color;
ctx.fillRect(player.x, player.y, player.width, player.height);
// Малюємо платформи
ctx.fillStyle = "#457b9d";
for (const plat of platforms) {
ctx.fillRect(plat.x, plat.y, plat.width, plat.height);
}
// Малюємо рибу
if (!fish.collected) {
ctx.fillStyle = "#f77f00";
ctx.beginPath();
ctx.arc(fish.x + fish.size / 2, fish.y + fish.size / 2, fish.size / 2, 0, Math.PI * 2);
ctx.fill();
}
}
function gameLoop() {
update();
draw();
requestAnimationFrame(gameLoop);
}
gameLoop();
cat-platformer.index.html, style.css і game.js.index.html у браузері.Хочеш, я додам ще функціонал? Наприклад, музику, меню або рівні?
Або можемо перейти до більш серйозного фреймворка типу Phaser.js для професійної розробки ігор.
Напиши, що хочеш побачити далі! 😊