🐍 HTML + JSでヘビゲームを作ろう:ステップバイステップで、ミーム付き!
あなたは今までに、自分のゲームを作ることを夢見たことがありますか?あの古典的なゲームはどうでしょうか? ヘビ?😎今日は、ブラウザで実際のレトロゲームをステップバイステップで作成します。ライブラリもフレームワークも使わず、HTML、CSS、JavaScriptだけで作ります。
⚠️ネタバレ注意:あなたはヘビを放つだけでなく、 どのように機能するか.
もし、これが難しいと思われる場合は、 落ち着いて、落ち着いてください、すべてをミームと例で説明します。さあ始めましょう!🚀

✨ プロジェクトのデモ | 📂 GitHubでソースコードをダウンロードする
🤖アプリで コディック HTML、CSS、JavaScript、その他多くのコースを学び、ウェブ開発の旅を始めましょう! 🌱
📦 ステップ1:HTML — ゲームの基礎を作成する
HTMLはスケルトンです。その中に以下を配置します。
canvasは、スネークと食べ物を描くキャンバスです。divゲームの開始と終了のボタン。スコアカウンター。
<canvas id="game" width="320" height="320"></canvas>🎨ステップ2:CSS — 退屈なスタイル
スタイルの魔法を少し:
黒い背景
フレームと丸みを帯びたエッジのあるキャンバス
モバイルデバイスへの適応(タッチアクション)
ボタン、タイトル、開始画面、終了画面もスタイルが決められており、ゲームを楽しく見ることができます。
🧠 ステップ3:JavaScriptはすべてのスネークの脳🧬
それでは、ゲームのコード全体を詳しく見ていきましょう。
1. 要素の初期化:
const canvas = document.getElementById("game");
const ctx = canvas.getContext("2d");canvas — キャンバス要素にアクセスします。ctxは、私たちが描画するものです。
また、セルのサイズ、スネークの方向、スコア、速度、ゲームの状態などの変数も宣言します。
const scale = 20;
const rows = canvas.height / scale;
const columns = canvas.width / scale;
let direction = { x: 1, y: 0 };
let nextDirection = { x: 1, y: 0 };
let speed = 250;
let score = 0;2. Snakeクラス—ヘビ自身:
class Snake {
constructor() {
this.body = [
{ x: 5, y: 5 },
{ x: 4, y: 5 },
];
}
update() {
const head = { ...this.body[0] };
head.x += direction.x;
head.y += direction.y;
this.body.unshift(head);
if (head.x === fruit.x && head.y === fruit.y) {
score++;
if (speed > 80) speed -= 5;
placeFruit();
} else {
this.body.pop();
}
}
draw() {
this.body.forEach((segment, i) => {
ctx.fillStyle = i === 0 ? "#58a6ff" : "#3fb950";
ctx.beginPath();
ctx.roundRect(
segment.x * scale + 2,
segment.y * scale + 2,
scale - 4,
scale - 4,
6
);
ctx.fill();
});
}
checkCollision() {
const [head, ...body] = this.body;
return (
head.x < 0 ||
head.x >= columns ||
head.y < 0 ||
head.y >= rows ||
body.some((s) => s.x === head.x && s.y === head.y)
);
}
}説明:
update()— ヘビを動かし、果物を食べたかどうかを確認します。draw()— 各セグメントを描画します。checkCollision()—境界またはそれ自体との衝突をチェックします。
3. 食品(果物):
function placeFruit() {
fruit = {
x: Math.floor(Math.random() * columns),
y: Math.floor(Math.random() * rows),
};
if (snake.body.some((s) => s.x === fruit.x && s.y === fruit.y)) {
placeFruit();
}
}食べ物はランダムに配置されます。食べ物がヘビの上に落ちた場合は、再生します。
4. ゲームサイクル:
function gameLoop(time = 0) {
if (!playing) return;
const delta = time - lastTime;
if (delta > speed) {
direction = nextDirection;
ctx.clearRect(0, 0, canvas.width, canvas.height);
snake.update();
if (snake.checkCollision()) {
endGame();
return;
}
drawFruit();
snake.draw();
lastTime = time;
}
requestAnimationFrame(gameLoop);
}各「フレーム」:
キャンバスをクリアする
ヘビを動かす
死亡を確認します
食べ物とヘビを描く
5. 管理:
キーボード:
window.addEventListener("keydown", (e) => {
if (e.key === "ArrowUp" && direction.y !== 1) nextDirection = { x: 0, y: -1 };
if (e.key === "ArrowDown" && direction.y !== -1) nextDirection = { x: 0, y: 1 };
if (e.key === "ArrowLeft" && direction.x !== 1) nextDirection = { x: -1, y: 0 };
if (e.key === "ArrowRight" && direction.x !== -1) nextDirection = { x: 1, y: 0 };
});スワイプ:
canvas.addEventListener("touchstart", (e) => { ... });
canvas.addEventListener("touchend", (e) => { ... });💀 ゲームオーバー:
function endGame() {
playing = false;
canvas.style.display = "none";
scoreDisplay.style.display = "none";
gameOverScreen.style.display = "flex";
finalScore.textContent = `You scored ${score} points`;
}✅結論:あなたはヘビマスターになりました🐍
あなたは単にコードを書いただけでなく、ゲームのロジックがどのように機能するかを理解しました。これは大きな一歩です!
もっと詳しく知りたいですか? コディック — たくさんの練習問題、わかりやすい説明、楽しい課題が満載です。
