Tinggal Coppy Paste
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title>Game Snake</title>
<style>
body {
background-color: #111;
display: flex;
flex-direction: column;
align-items: center;
color: white;
font-family: sans-serif;
}
canvas {
background-color: #222;
border: 2px solid #0f0;
margin-top: 20px;
}
h1 {
margin-top: 20px;
color: #0f0;
}
</style>
</head>
<body>
<h1>🐍 Game Snake</h1>
<canvas id="game" width="400" height="400"></canvas>
<p>Gunakan tombol panah untuk bermain (di HP: geser layar)</p>
<script>
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
const gridSize = 20;
const tileCount = canvas.width / gridSize;
let snake = [{ x: 10, y: 10 }];
let food = { x: 15, y: 15 };
let dx = 0;
let dy = 0;
let score = 0;
function gameLoop() {
requestAnimationFrame(gameLoop);
if (++frame % 6 !== 0) return; // Slow down game speed
// Move snake
const head = { x: snake[0].x + dx, y: snake[0].y + dy };
// Game over if hit wall or itself
if (
head.x < 0 || head.x >= tileCount ||
head.y < 0 || head.y >= tileCount ||
snake.some(seg => seg.x === head.x && seg.y === head.y)
) {
alert("Game Over! Skor: " + score);
snake = [{ x: 10, y: 10 }];
dx = dy = 0;
score = 0;
return;
}
snake.unshift(head);
// Makan makanan
if (head.x === food.x && head.y === food.y) {
score++;
food = {
x: Math.floor(Math.random() * tileCount),
y: Math.floor(Math.random() * tileCount)
};
} else {
snake.pop();
}
// Gambar background
ctx.fillStyle = '#111';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Gambar snake
ctx.fillStyle = '#0f0';
snake.forEach(seg => {
ctx.fillRect(seg.x * gridSize, seg.y * gridSize, gridSize - 2, gridSize - 2);
});
// Gambar food
ctx.fillStyle = 'red';
ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize - 2, gridSize - 2);
}
// Keyboard control
document.addEventListener('keydown', e => {
if (e.key === 'ArrowUp' && dy === 0) {
dx = 0; dy = -1;
} else if (e.key === 'ArrowDown' && dy === 0) {
dx = 0; dy = 1;
} else if (e.key === 'ArrowLeft' && dx === 0) {
dx = -1; dy = 0;
} else if (e.key === 'ArrowRight' && dx === 0) {
dx = 1; dy = 0;
}
});
// Swipe control (untuk HP)
let startX, startY;
canvas.addEventListener('touchstart', e => {
const t = e.touches[0];
startX = t.clientX;
startY = t.clientY;
});
canvas.addEventListener('touchmove', e => {
const t = e.touches[0];
const dxTouch = t.clientX - startX;
const dyTouch = t.clientY - startY;
if (Math.abs(dxTouch) > Math.abs(dyTouch)) {
if (dxTouch > 0 && dx === 0) {
dx = 1; dy = 0;
} else if (dxTouch < 0 && dx === 0) {
dx = -1; dy = 0;
}
} else {
if (dyTouch > 0 && dy === 0) {
dx = 0; dy = 1;
} else if (dyTouch < 0 && dy === 0) {
dx = 0; dy = -1;
}
}
startX = t.clientX;
startY = t.clientY;
});
let frame = 0;
requestAnimationFrame(gameLoop);
</script>
</body>
</html>
Komentar
Posting Komentar