Game Perang Sederhana
by ShadowNinja40151 lines3.3 KB
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Game Perang Sederhana</title>
<style>
body {
margin: 0;
overflow: hidden;
background: #222;
}
canvas {
display: block;
margin: auto;
background: linear-gradient(#87ceeb, #4caf50);
}
#info {
position: absolute;
top: 10px;
left: 10px;
color: white;
font-family: Arial;
font-size: 20px;
}
</style>
</head>
<body>
<div id="info">Skor: <span id="score">0</span></div>
<canvas id="game" width="800" height="500"></canvas>
<script>
const canvas = document.getElementById("game");
const ctx = canvas.getContext("2d");
let score = 0;
const player = {
x: 380,
y: 430,
width: 40,
height: 40,
speed: 6
};
const bullets = [];
const enemies = [];
const keys = {};
document.addEventListener("keydown", e => keys[e.key] = true);
document.addEventListener("keyup", e => keys[e.key] = false);
document.addEventListener("keydown", e => {
if (e.code === "Space") {
bullets.push({
x: player.x + player.width / 2 - 2,
y: player.y,
width: 4,
height: 10
});
}
});
function spawnEnemy() {
enemies.push({
x: Math.random() * 760,
y: -40,
width: 40,
height: 40,
speed: 2 + Math.random() * 2
});
}
setInterval(spawnEnemy, 1000);
function update() {
if (keys["ArrowLeft"]) player.x -= player.speed;
if (keys["ArrowRight"]) player.x += player.speed;
player.x = Math.max(0, Math.min(canvas.width - player.width, player.x));
bullets.forEach((b, i) => {
b.y -= 8;
if (b.y < 0) bullets.splice(i, 1);
});
enemies.forEach((e, ei) => {
e.y += e.speed;
if (e.y > canvas.height) {
enemies.splice(ei, 1);
}
bullets.forEach((b, bi) => {
if (
b.x < e.x + e.width &&
b.x + b.width > e.x &&
b.y < e.y + e.height &&
b.y + b.height > e.y
) {
enemies.splice(ei, 1);
bullets.splice(bi, 1);
score += 10;
document.getElementById("score").textContent = score;
}
});
if (
player.x < e.x + e.width &&
player.x + player.width > e.x &&
player.y < e.y + e.height &&
player.y + player.height > e.y
) {
alert("Game Over! Skor: " + score);
location.reload();
}
});
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Pemain
ctx.fillStyle = "blue";
ctx.fillRect(player.x, player.y, player.width, player.height);
// Peluru
ctx.fillStyle = "yellow";
bullets.forEach(b => {
ctx.fillRect(b.x, b.y, b.width, b.height);
});
// Musuh
ctx.fillStyle = "red";
enemies.forEach(e => {
ctx.fillRect(e.x, e.y, e.width, e.height);
});
}
function gameLoop() {
update();
draw();
requestAnimationFrame(gameLoop);
}
gameLoop();
</script>
</body>
</html>Game Source: Game Perang Sederhana
Creator: ShadowNinja40
Libraries: none
Complexity: moderate (151 lines, 3.3 KB)
The full source code is displayed above on this page.
Remix Instructions
To remix this game, copy the source code above and modify it. Add a ARCADELAB header at the top with "remix_of: game-perang-sederhana-shadowninja40" to link back to the original. Then publish at arcadelab.ai/publish.