كود لعبة الأفعى — Snake Engine
by ChromeFlame24460 lines11.7 KB
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>كود لعبة الأفعى — Snake Engine</title>
<style>
:root {
--bg: #090d16;
--panel: #111827;
--panel-2: #192234;
--text: #e5edf8;
--muted: #94a3b8;
--accent: #22c55e;
--food: #ef4444;
--grid: rgba(148, 163, 184, 0.07);
--border: rgba(148, 163, 184, 0.16);
--radius: 14px;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
background: radial-gradient(circle at top, #132038 0%, var(--bg) 70%);
color: var(--text);
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
padding: 20px;
}
.container {
width: 100%;
max-width: 560px;
background: var(--panel);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 18px;
box-shadow: 0 16px 40px rgba(0, 0, 0, 0.45);
display: grid;
gap: 14px;
}
.top-bar {
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 10px;
}
h1 {
font-size: 1.2rem;
}
.metrics {
display: flex;
gap: 10px;
}
.metric {
background: var(--panel-2);
border: 1px solid var(--border);
padding: 6px 12px;
border-radius: 10px;
font-size: 0.9rem;
}
.metric strong {
color: var(--accent);
}
.canvas-wrap {
position: relative;
width: 100%;
aspect-ratio: 1 / 1;
border-radius: 12px;
overflow: hidden;
border: 1px solid var(--border);
background: #070b12;
}
canvas {
width: 100%;
height: 100%;
display: block;
}
.controls {
display: flex;
flex-wrap: wrap;
gap: 8px;
justify-content: space-between;
align-items: center;
}
.btn-group {
display: flex;
gap: 8px;
flex-wrap: wrap;
}
button, select {
font-family: inherit;
font-size: 0.9rem;
padding: 8px 14px;
border-radius: 10px;
border: 1px solid var(--border);
background: var(--panel-2);
color: var(--text);
cursor: pointer;
}
button.primary {
background: var(--accent);
color: #05160c;
border: none;
font-weight: 700;
}
.dpad {
display: grid;
grid-template-columns: repeat(3, 52px);
grid-template-rows: repeat(2, 44px);
gap: 6px;
justify-content: center;
margin-top: 4px;
}
.dpad button {
padding: 0;
font-size: 1rem;
font-weight: bold;
}
.dpad .empty {
visibility: hidden;
}
.hint {
text-align: center;
color: var(--muted);
font-size: 0.82rem;
}
</style>
</head>
<body>
<main class="container">
<div class="top-bar">
<h1>محرك لعبة الأفعى</h1>
<div class="metrics">
<div class="metric">النقاط: <strong id="scoreEl">0</strong></div>
<div class="metric">الأعلى: <strong id="highScoreEl">0</strong></div>
</div>
</div>
<div class="canvas-wrap">
<canvas id="gameCanvas" width="480" height="480"></canvas>
</div>
<div class="controls">
<div class="btn-group">
<button class="primary" id="startBtn">بدء / إعادة</button>
<button id="pauseBtn">إيقاف مؤقت</button>
</div>
<select id="speedSelect" aria-label="السرعة">
<option value="150">سرعة هادئة</option>
<option value="105" selected>سرعة متوسطة</option>
<option value="70">سرعة عالية</option>
</select>
</div>
<div class="dpad">
<span class="empty"></span>
<button data-dir="UP">▲</button>
<span class="empty"></span>
<button data-dir="LEFT">◀</button>
<button data-dir="DOWN">▼</button>
<button data-dir="RIGHT">▶</button>
</div>
<p class="hint" id="statusHint">استخدم الأسهم أو WASD للتحرك — Space للإيقاف المؤقت</p>
</main>
<script>
const DIRS = {
UP: { x: 0, y: -1, opposite: "DOWN" },
DOWN: { x: 0, y: 1, opposite: "UP" },
LEFT: { x: -1, y: 0, opposite: "RIGHT" },
RIGHT: { x: 1, y: 0, opposite: "LEFT" }
};
class SnakeGame {
constructor(gridSize = 20) {
this.gridSize = gridSize;
this.highScore = Number(localStorage.getItem("snake_high_score") || 0);
this.reset();
}
reset() {
const mid = Math.floor(this.gridSize / 2);
this.snake = [
{ x: mid, y: mid },
{ x: mid - 1, y: mid },
{ x: mid - 2, y: mid }
];
this.direction = "RIGHT";
this.inputQueue = [];
this.score = 0;
this.state = "READY"; // READY | RUNNING | PAUSED | GAME_OVER
this.food = this.spawnFood();
}
start() {
this.reset();
this.state = "RUNNING";
}
togglePause() {
if (this.state === "RUNNING") {
this.state = "PAUSED";
} else if (this.state === "PAUSED") {
this.state = "RUNNING";
}
}
queueDirection(nextDir) {
if (!DIRS[nextDir]) return;
const lastScheduled = this.inputQueue.length
? this.inputQueue[this.inputQueue.length - 1]
: this.direction;
if (nextDir === lastScheduled || DIRS[nextDir].opposite === lastScheduled) {
return;
}
if (this.inputQueue.length < 2) {
this.inputQueue.push(nextDir);
}
}
spawnFood() {
const occupied = new Set(this.snake.map((seg) => `${seg.x},${seg.y}`));
const freeCells = [];
for (let y = 0; y < this.gridSize; y++) {
for (let x = 0; x < this.gridSize; x++) {
if (!occupied.has(`${x},${y}`)) {
freeCells.push({ x, y });
}
}
}
if (freeCells.length === 0) return null;
const idx = Math.floor(Math.random() * freeCells.length);
return freeCells[idx];
}
step() {
if (this.state !== "RUNNING") return;
if (this.inputQueue.length > 0) {
this.direction = this.inputQueue.shift();
}
const vec = DIRS[this.direction];
const head = this.snake[0];
const nextHead = { x: head.x + vec.x, y: head.y + vec.y };
// اصطدام بالجدران
if (
nextHead.x < 0 ||
nextHead.x >= this.gridSize ||
nextHead.y < 0 ||
nextHead.y >= this.gridSize
) {
this.state = "GAME_OVER";
return;
}
const willEat =
this.food && nextHead.x === this.food.x && nextHead.y === this.food.y;
// إذا لن تأكل، الذيل سيتحرك للأمام لذا لا يُعد تصادماً إلا إذا لم يكن سيتحرك
const bodyToCheck = willEat ? this.snake : this.snake.slice(0, -1);
const hitSelf = bodyToCheck.some(
(seg) => seg.x === nextHead.x && seg.y === nextHead.y
);
if (hitSelf) {
this.state = "GAME_OVER";
return;
}
this.snake.unshift(nextHead);
if (willEat) {
this.score += 10;
if (this.score > this.highScore) {
this.highScore = this.score;
localStorage.setItem("snake_high_score", String(this.highScore));
}
this.food = this.spawnFood();
if (!this.food) {
this.state = "GAME_OVER";
}
} else {
this.snake.pop();
}
}
}
// طبقة العرض والتحكم
const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");
const scoreEl = document.getElementById("scoreEl");
const highScoreEl = document.getElementById("highScoreEl");
const statusHint = document.getElementById("statusHint");
const startBtn = document.getElementById("startBtn");
const pauseBtn = document.getElementById("pauseBtn");
const speedSelect = document.getElementById("speedSelect");
const game = new SnakeGame(20);
let tickMs = Number(speedSelect.value);
let lastTime = 0;
let accumulator = 0;
function draw() {
const size = canvas.width;
const cell = size / game.gridSize;
ctx.clearRect(0, 0, size, size);
// رسم الشبكة
ctx.strokeStyle = "rgba(148, 163, 184, 0.07)";
ctx.lineWidth = 1;
for (let i = 0; i <= game.gridSize; i++) {
const pos = i * cell;
ctx.beginPath();
ctx.moveTo(pos, 0);
ctx.lineTo(pos, size);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(0, pos);
ctx.lineTo(size, pos);
ctx.stroke();
}
// رسم الطعام
if (game.food) {
ctx.fillStyle = "#ef4444";
ctx.beginPath();
ctx.arc(
(game.food.x + 0.5) * cell,
(game.food.y + 0.5) * cell,
cell * 0.38,
0,
Math.PI * 2
);
ctx.fill();
}
// رسم الأفعى
game.snake.forEach((seg, idx) => {
ctx.fillStyle = idx === 0 ? "#4ade80" : "#22c55e";
const pad = idx === 0 ? 1.5 : 2.5;
ctx.beginPath();
ctx.roundRect(
seg.x * cell + pad,
seg.y * cell + pad,
cell - pad * 2,
cell - pad * 2,
6
);
ctx.fill();
});
// تحديث الإحصائيات والحالة
scoreEl.textContent = game.score;
highScoreEl.textContent = game.highScore;
if (game.state === "READY") {
statusHint.textContent = "اضغط «بدء / إعادة» أو أي سهم للانطلاق";
} else if (game.state === "PAUSED") {
statusHint.textContent = "اللعبة متوقفة مؤقتاً — اضغط Space للاستئناف";
} else if (game.state === "GAME_OVER") {
statusHint.textContent = `انتهت الجولة! مجموع النقاط: ${game.score} — اضغط «بدء / إعادة»`;
} else {
statusHint.textContent = "جاري اللعب... الأسهم أو WASD للتحكم";
}
}
function loop(timestamp) {
if (!lastTime) lastTime = timestamp;
const delta = timestamp - lastTime;
lastTime = timestamp;
accumulator += delta;
while (accumulator >= tickMs) {
game.step();
accumulator -= tickMs;
}
draw();
requestAnimationFrame(loop);
}
const keyMap = {
ArrowUp: "UP",
KeyW: "UP",
ArrowDown: "DOWN",
KeyS: "DOWN",
ArrowLeft: "LEFT",
KeyA: "LEFT",
ArrowRight: "RIGHT",
KeyD: "RIGHT"
};
window.addEventListener("keydown", (e) => {
if (keyMap[e.code]) {
e.preventDefault();
if (game.state === "READY") {
game.start();
}
game.queueDirection(keyMap[e.code]);
} else if (e.code === "Space") {
e.preventDefault();
game.togglePause();
}
});
document.querySelectorAll(".dpad button[data-dir]").forEach((btn) => {
btn.addEventListener("click", () => {
if (game.state === "READY") game.start();
game.queueDirection(btn.dataset.dir);
});
});
startBtn.addEventListener("click", () => {
game.start();
accumulator = 0;
});
pauseBtn.addEventListener("click", () => {
game.togglePause();
});
speedSelect.addEventListener("change", () => {
tickMs = Number(speedSelect.value);
});
draw();
requestAnimationFrame(loop);
</script>
</body>
</html>Game Source: كود لعبة الأفعى — Snake Engine
Creator: ChromeFlame24
Libraries: none
Complexity: complex (460 lines, 11.7 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: snake-engine-chromeflame24" to link back to the original. Then publish at arcadelab.ai/publish.