貪食蛇遊戲 - 完整教學範例
兩種版本的提示詞、完整程式碼與五種客製化練習。
📝 提示詞範例(給學員使用)
版本 1:基礎版提示詞
請幫我建立一個網頁版貪食蛇遊戲:
遊戲規格:
- 遊戲區域:20x20 的格子
- 控制方式:鍵盤方向鍵(↑↓←→)
- 蛇的初始長度:3 格
- 移動速度:每 150 毫秒移動一格
遊戲規則:
1. 蛇自動持續移動
2. 吃到食物後身體變長 1 格,分數 +10
3. 撞到牆壁或自己的身體時遊戲結束
4. 食物隨機出現在空格上
視覺設計:
- 蛇的顏色:綠色 (#4CAF50)
- 食物顏色:紅色 (#F44336)
- 背景:淺灰色 (#F5F5F5)
- 格線:淡灰色邊框
介面元素:
- 遊戲標題
- 分數顯示
- 遊戲結束時顯示最終分數和重新開始按鈕
技術要求:
- 使用純 HTML + CSS + JavaScript
- 程式碼要有清楚的註解
- 確保在 Chrome/Firefox/Safari 都能執行版本 2:進階版提示詞(加入更多功能)
請幫我建立一個進階版網頁貪食蛇遊戲:
基礎功能:
- 遊戲區域:可調整大小(預設 20x20)
- 方向鍵控制,支援 WASD 按鍵
- 蛇初始長度:3 格
- 吃食物變長並得分
進階功能:
1. 難度選擇:
- 簡單(速度 250ms)
- 普通(速度 150ms)
- 困難(速度 100ms)
2. 計分系統:
- 顯示當前分數
- 顯示最高分(儲存在瀏覽器)
- 連續吃到食物有加成
3. 音效(可選):
- 吃到食物:嗶聲
- 遊戲結束:提示音
4. 暫停功能:
- 按空白鍵暫停/繼續
- 暫停時顯示提示
視覺設計:
- 現代化 UI 設計
- 使用漸層色和陰影效果
- 響應式設計(手機也能玩)
- 平滑的動畫過渡
技術要求:
- 純 HTML + CSS + JavaScript
- 程式碼有詳細註解
- 支援鍵盤操作
- localStorage 儲存最高分💻 完整程式碼(基礎版)
snake-game.html
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>貪食蛇遊戲</title>
<style>
/* ==================== 全局樣式 ==================== */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Arial', '微軟正黑體', sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
padding: 20px;
}
/* ==================== 遊戲容器 ==================== */
.game-container {
background: white;
border-radius: 20px;
padding: 30px;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
max-width: 600px;
width: 100%;
}
/* ==================== 標題區 ==================== */
h1 {
text-align: center;
color: #333;
margin-bottom: 20px;
font-size: 2.5em;
}
/* ==================== 資訊面板 ==================== */
.info-panel {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
padding: 15px;
background: #f8f9fa;
border-radius: 10px;
}
.score {
font-size: 1.5em;
font-weight: bold;
color: #4CAF50;
}
.controls-hint {
font-size: 0.9em;
color: #666;
}
/* ==================== 遊戲畫布 ==================== */
#gameCanvas {
border: 3px solid #333;
border-radius: 10px;
display: block;
margin: 0 auto;
background: #F5F5F5;
cursor: pointer;
}
/* ==================== 遊戲結束覆蓋層 ==================== */
.game-over {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.8);
justify-content: center;
align-items: center;
z-index: 1000;
}
.game-over.show {
display: flex;
}
.game-over-content {
background: white;
padding: 40px;
border-radius: 20px;
text-align: center;
max-width: 400px;
}
.game-over-content h2 {
color: #F44336;
margin-bottom: 20px;
font-size: 2em;
}
.game-over-content p {
font-size: 1.3em;
margin-bottom: 30px;
color: #666;
}
/* ==================== 按鈕樣式 ==================== */
.btn {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
padding: 15px 40px;
font-size: 1.1em;
border-radius: 50px;
cursor: pointer;
transition: transform 0.2s, box-shadow 0.2s;
font-weight: bold;
}
.btn:hover {
transform: translateY(-2px);
box-shadow: 0 10px 20px rgba(102, 126, 234, 0.4);
}
.btn:active {
transform: translateY(0);
}
/* ==================== 響應式設計 ==================== */
@media (max-width: 600px) {
h1 {
font-size: 2em;
}
.game-container {
padding: 20px;
}
#gameCanvas {
width: 100% !important;
height: auto !important;
}
}
</style>
</head>
<body>
<div class="game-container">
<h1>🐍 貪食蛇遊戲</h1>
<!-- 資訊面板 -->
<div class="info-panel">
<div class="score">分數:<span id="score">0</span></div>
<div class="controls-hint">使用 ↑↓←→ 控制</div>
</div>
<!-- 遊戲畫布 -->
<canvas id="gameCanvas" width="400" height="400"></canvas>
</div>
<!-- 遊戲結束畫面 -->
<div class="game-over" id="gameOver">
<div class="game-over-content">
<h2>遊戲結束!</h2>
<p>最終分數:<strong id="finalScore">0</strong></p>
<button class="btn" onclick="restartGame()">重新開始</button>
</div>
</div>
<script>
// ==================== 遊戲設定 ====================
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const scoreElement = document.getElementById('score');
const gameOverElement = document.getElementById('gameOver');
const finalScoreElement = document.getElementById('finalScore');
// 格子設定
const gridSize = 20; // 20x20 格子
const cellSize = canvas.width / gridSize; // 每格的大小
// 遊戲狀態
let snake = [
{ x: 10, y: 10 }, // 蛇頭
{ x: 9, y: 10 },
{ x: 8, y: 10 }
];
let direction = { x: 1, y: 0 }; // 初始向右移動
let nextDirection = { x: 1, y: 0 }; // 下一個方向(避免快速按鍵導致蛇撞到自己)
let food = { x: 15, y: 15 };
let score = 0;
let gameRunning = true;
let gameSpeed = 150; // 移動間隔(毫秒)
// ==================== 遊戲初始化 ====================
function init() {
// 生成隨機食物位置
generateFood();
// 開始遊戲循環
gameLoop();
}
// ==================== 生成食物 ====================
function generateFood() {
// 確保食物不會出現在蛇的身體上
do {
food = {
x: Math.floor(Math.random() * gridSize),
y: Math.floor(Math.random() * gridSize)
};
} while (snake.some(segment => segment.x === food.x && segment.y === food.y));
}
// ==================== 繪製遊戲畫面 ====================
function draw() {
// 清空畫布
ctx.fillStyle = '#F5F5F5';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 繪製格線(可選,讓遊戲看起來更清楚)
ctx.strokeStyle = '#E0E0E0';
ctx.lineWidth = 1;
for (let i = 0; i <= gridSize; i++) {
// 垂直線
ctx.beginPath();
ctx.moveTo(i * cellSize, 0);
ctx.lineTo(i * cellSize, canvas.height);
ctx.stroke();
// 水平線
ctx.beginPath();
ctx.moveTo(0, i * cellSize);
ctx.lineTo(canvas.width, i * cellSize);
ctx.stroke();
}
// 繪製蛇
snake.forEach((segment, index) => {
// 蛇頭顏色稍深
if (index === 0) {
ctx.fillStyle = '#2E7D32'; // 深綠色(蛇頭)
} else {
ctx.fillStyle = '#4CAF50'; // 淺綠色(蛇身)
}
ctx.fillRect(
segment.x * cellSize + 1,
segment.y * cellSize + 1,
cellSize - 2,
cellSize - 2
);
// 添加圓角效果(可選)
ctx.strokeStyle = '#2E7D32';
ctx.lineWidth = 2;
ctx.strokeRect(
segment.x * cellSize + 1,
segment.y * cellSize + 1,
cellSize - 2,
cellSize - 2
);
});
// 繪製食物
ctx.fillStyle = '#F44336'; // 紅色
ctx.beginPath();
ctx.arc(
food.x * cellSize + cellSize / 2,
food.y * cellSize + cellSize / 2,
cellSize / 2 - 2,
0,
Math.PI * 2
);
ctx.fill();
}
// ==================== 更新蛇的位置 ====================
function update() {
// 更新方向(避免連續按鍵導致蛇撞到自己)
direction = nextDirection;
// 計算新的蛇頭位置
const newHead = {
x: snake[0].x + direction.x,
y: snake[0].y + direction.y
};
// 檢查是否撞牆
if (newHead.x < 0 || newHead.x >= gridSize ||
newHead.y < 0 || newHead.y >= gridSize) {
gameOver();
return;
}
// 檢查是否撞到自己
if (snake.some(segment => segment.x === newHead.x && segment.y === newHead.y)) {
gameOver();
return;
}
// 將新的頭部加入蛇
snake.unshift(newHead);
// 檢查是否吃到食物
if (newHead.x === food.x && newHead.y === food.y) {
// 吃到食物,增加分數
score += 10;
scoreElement.textContent = score;
// 生成新的食物
generateFood();
} else {
// 沒吃到食物,移除尾巴(保持蛇的長度)
snake.pop();
}
}
// ==================== 遊戲循環 ====================
function gameLoop() {
if (!gameRunning) return;
update(); // 更新遊戲狀態
draw(); // 繪製畫面
// 設定下一次循環
setTimeout(gameLoop, gameSpeed);
}
// ==================== 遊戲結束 ====================
function gameOver() {
gameRunning = false;
finalScoreElement.textContent = score;
gameOverElement.classList.add('show');
}
// ==================== 重新開始遊戲 ====================
function restartGame() {
// 重置遊戲狀態
snake = [
{ x: 10, y: 10 },
{ x: 9, y: 10 },
{ x: 8, y: 10 }
];
direction = { x: 1, y: 0 };
nextDirection = { x: 1, y: 0 };
score = 0;
scoreElement.textContent = score;
gameRunning = true;
// 隱藏遊戲結束畫面
gameOverElement.classList.remove('show');
// 重新開始遊戲
generateFood();
gameLoop();
}
// ==================== 鍵盤控制 ====================
document.addEventListener('keydown', (e) => {
// 防止方向鍵滾動頁面
if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(e.key)) {
e.preventDefault();
}
switch(e.key) {
case 'ArrowUp':
// 不能直接向相反方向移動
if (direction.y !== 1) {
nextDirection = { x: 0, y: -1 };
}
break;
case 'ArrowDown':
if (direction.y !== -1) {
nextDirection = { x: 0, y: 1 };
}
break;
case 'ArrowLeft':
if (direction.x !== 1) {
nextDirection = { x: -1, y: 0 };
}
break;
case 'ArrowRight':
if (direction.x !== -1) {
nextDirection = { x: 1, y: 0 };
}
break;
}
});
// ==================== 啟動遊戲 ====================
init();
</script>
</body>
</html>🎨 客製化範例(教學用)
修改 1:更換配色主題
提示詞:
請把貪食蛇遊戲的配色改成「深色主題」:
- 背景改成深灰色 (#2C3E50)
- 蛇的顏色改成青色 (#00BCD4)
- 食物改成黃色 (#FFC107)
- 格線改成更深的灰色修改位置(CSS):
/* 修改 body 背景 */
body {
background: linear-gradient(135deg, #2C3E50 0%, #34495E 100%);
}
/* 修改畫布背景 */
#gameCanvas {
background: #1A252F;
}
/* 修改格線顏色(在 JavaScript 中) */
ctx.strokeStyle = '#34495E';
/* 修改蛇的顏色(在 JavaScript 中) */
// 蛇頭
ctx.fillStyle = '#00838F'; // 深青色
// 蛇身
ctx.fillStyle = '#00BCD4'; // 青色
/* 修改食物顏色(在 JavaScript 中) */
ctx.fillStyle = '#FFC107'; // 黃色修改 2:調整遊戲速度
提示詞:
請把遊戲速度改慢一點,從 150 毫秒改成 200 毫秒修改位置(JavaScript):
// 找到這一行:
let gameSpeed = 150;
// 改成:
let gameSpeed = 200;修改 3:改變遊戲區域大小
提示詞:
請把遊戲區域從 20x20 改成 15x15,讓遊戲更具挑戰性修改位置(JavaScript):
// 找到這一行:
const gridSize = 20;
// 改成:
const gridSize = 15;修改 4:新增難度選擇(進階)
提示詞:
請在遊戲開始前加入難度選擇:
- 簡單:250ms
- 普通:150ms
- 困難:100ms新增內容:
HTML(在資訊面板前加入):
<div class="difficulty-selector">
<label>選擇難度:</label>
<button class="difficulty-btn" onclick="setDifficulty(250)">簡單</button>
<button class="difficulty-btn" onclick="setDifficulty(150)">普通</button>
<button class="difficulty-btn" onclick="setDifficulty(100)">困難</button>
</div>CSS:
.difficulty-selector {
text-align: center;
margin-bottom: 20px;
}
.difficulty-btn {
margin: 0 5px;
padding: 10px 20px;
border: 2px solid #667eea;
background: white;
color: #667eea;
border-radius: 20px;
cursor: pointer;
transition: all 0.3s;
}
.difficulty-btn:hover {
background: #667eea;
color: white;
}JavaScript:
function setDifficulty(speed) {
gameSpeed = speed;
alert('難度已設定!速度:' + speed + 'ms');
}修改 5:新增最高分紀錄(進階)
提示詞:
請加入「最高分」功能,使用 localStorage 儲存,
即使關閉瀏覽器後再開啟,最高分也會保留修改內容:
HTML:
<div class="info-panel">
<div class="score">分數:<span id="score">0</span></div>
<div class="high-score">最高分:<span id="highScore">0</span></div>
<div class="controls-hint">使用 ↑↓←→ 控制</div>
</div>CSS:
.high-score {
font-size: 1.2em;
font-weight: bold;
color: #FF9800;
}JavaScript:
// 在遊戲初始化時加入
let highScore = localStorage.getItem('snakeHighScore') || 0;
document.getElementById('highScore').textContent = highScore;
// 在 update() 函數中,當吃到食物時:
if (newHead.x === food.x && newHead.y === food.y) {
score += 10;
scoreElement.textContent = score;
// 更新最高分
if (score > highScore) {
highScore = score;
localStorage.setItem('snakeHighScore', highScore);
document.getElementById('highScore').textContent = highScore;
}
generateFood();
}📚 教學指引(給講師)
教學流程建議
1. 展示成品(5 分鐘)
- 先讓學員看到完整的遊戲
- 展示可以玩、可以操作
- 說明接下來會一步步完成
2. 理解提示詞(10 分鐘)
- 帶學員讀一次提示詞
- 解釋為什麼要這樣寫
- 強調「具體」和「明確」的重要性
3. 生成程式碼(10 分鐘)
- 學員在 Claude 中貼上提示詞
- 等待生成完整程式碼
- 測試執行
4. 理解程式結構(10 分鐘)
帶學員快速瀏覽程式碼的主要部分:
// 這裡定義遊戲設定(可以修改的數值)
const gridSize = 20;
let gameSpeed = 150;
// 這裡繪製遊戲畫面(蛇和食物的顏色)
function draw() { ... }
// 這裡處理遊戲邏輯(移動、碰撞)
function update() { ... }
// 這裡監聽鍵盤(控制方向)
document.addEventListener('keydown', ...) { ... }5. 客製化練習(20 分鐘)
讓學員選擇 2-3 個修改任務:
簡單任務(5 分鐘內完成):
- 改變蛇和食物的顏色
- 調整遊戲速度
- 改變遊戲區域大小
中等任務(10 分鐘內完成):
- 新增難度選擇按鈕
- 加入音效(使用 Web Audio API)
- 改變計分方式(連續吃到食物加成)
進階任務(15 分鐘以上):
- 新增暫停功能
- 儲存最高分紀錄
- 加入障礙物
- 手機觸控支援
6. 常見問題處理
問題 1:蛇移動太快或太慢
// 找到這行並修改數值
let gameSpeed = 150; // 數字越小越快,越大越慢問題 2:遊戲區域太大或太小
// 修改格子數量
const gridSize = 20; // 改成 15 或 25問題 3:顏色看不清楚
// 在 draw() 函數中修改
ctx.fillStyle = '#4CAF50'; // 改成你喜歡的顏色代碼🎯 學習重點
學員應該學到:
提示詞撰寫
- 如何清楚描述需求
- 如何指定技術細節
- 如何表達視覺設計
程式碼結構理解
- HTML 負責結構
- CSS 負責樣式
- JavaScript 負責互動邏輯
修改與除錯
- 如何找到要修改的位置
- 如何測試修改結果
- 如何使用 Claude 協助除錯
遊戲邏輯思維
- 碰撞偵測
- 座標系統
- 遊戲循環概念
🚀 延伸挑戰
課後可以嘗試的進階功能:
難度 ⭐⭐
- 加入「穿牆」模式(從左邊出去會從右邊出來)
- 改變蛇的形狀(用圖片或emoji代替方塊)
- 加入背景音樂
難度 ⭐⭐⭐
- 多種食物(不同食物不同分數)
- 道具系統(加速、減速、無敵)
- 排行榜功能(記錄前 10 名)
難度 ⭐⭐⭐⭐
- 雙人對戰模式
- 隨機障礙物
- 關卡系統(不同關卡不同地圖)
💾 完整檔案下載
完整的 HTML 檔案可以:
- 直接在瀏覽器中開啟
- 放到 GitHub Pages 部署
- 用 Netlify/Vercel 免費託管
部署步驟:
- 註冊 GitHub 帳號
- 創建新的 Repository
- 上傳
snake-game.html - 在 Settings > Pages 啟用 GitHub Pages
- 獲得專屬網址,分享給朋友!
範例版本: v1.0
測試環境: Chrome, Firefox, Safari
適用於: AI 協作開發工作坊
難度等級: 零基礎友善