【AI4CODE】目錄
【AI4CODE】1 Trae CN 錐安裝配置與遷移
【AI4CODE】2 Trae 錘一個 To-Do-List
這次還是采用 HTML/CSS/JAVASCRIPT 技術棧 Trae 錘一個貪吃蛇的小游戲。
1 環境準備
創建一個 Snake 的子文件夾,清除以前的會話記錄。
2 開始構建
2.1 輸入會話提詞
比如:
用html/css/javascript技術棧構建一個簡潔美觀的貪吃蛇小游戲,要求有開始游戲按鈕,保存最高得分記錄到本地
2.2 思考過程
2.3 構建過程
2.4 Live Server 啟動服務試試
畫面出來了,開始游戲發現,蛇的移動數據太快了,修改一下移動速度。
輸入提詞:蛇的移動數據太快了
了解您希望調整貪吃蛇的移動速度。當前游戲邏輯使用requestAnimationFrame實現循環,可以通過添加移動間隔控制機制來調節速度。建議在update函數中增加時間間隔判斷,例如每200毫秒更新一次蛇的位置。同時保留原有動畫幀調用以保證畫面流暢。這樣既能保持畫面渲染流暢度,又能獨立控制蛇的移動速度。
現在為貪吃蛇游戲添加移動間隔控制機制來降低移動速度。將在game.js中新增lastMoveTime變量和時間間隔判斷邏輯,保持畫面流暢的同時實現速度控制。
2.5 OK 可以玩了
蛇的移動移動速度,也可以自己修改 game.js的
const moveInterval = 300;
這里的單位是毫秒。
3 代碼貼出來
所有的代碼都 Trae 自動錘出來的,我沒有寫一行代碼,共三個代碼文件:index.html/game.js/style.css
3.1 Index.html
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>經典貪吃蛇</title><link rel="stylesheet" href="style.css">
</head>
<body><div class="game-container"><canvas id="gameCanvas" width="400" height="400"></canvas><div class="control-panel"><button id="startBtn" class="game-btn">開始游戲</button><div class="score-board"><span>當前得分:<span id="currentScore">0</span></span><span>最高得分:<span id="highScore">0</span></span></div></div></div><script src="game.js"></script>
</body>
</html>
3.2 Style.css
body {display: flex;justify-content: center;align-items: center;min-height: 100vh;margin: 0;background: #2c3e50;font-family: Arial, sans-serif;
}.game-container {position: relative;background: #ecf0f1;padding: 20px;border-radius: 10px;box-shadow: 0 0 20px rgba(0,0,0,0.3);
}#gameCanvas {border: 2px solid #34495e;
}.control-panel {margin-top: 20px;display: flex;flex-direction: column;align-items: center;
}.game-btn {padding: 12px 30px;font-size: 18px;background: #27ae60;color: white;border: none;border-radius: 5px;cursor: pointer;transition: background 0.3s;
}.game-btn:hover {background: #219a52;
}.score-board {margin-top: 15px;font-size: 16px;color: #2c3e50;display: flex;gap: 20px;
}@media (max-width: 480px) {#gameCanvas {width: 300px;height: 300px;}
}
3.3 Game.js
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const startBtn = document.getElementById('startBtn');
const currentScoreSpan = document.getElementById('currentScore');
const highScoreSpan = document.getElementById('highScore');const gridSize = 20;
let snake = [];
let food = {};
let direction = 'right';
let nextDirection = 'right';
let gameLoop;
let score = 0;
let highScore = localStorage.getItem('snakeHighScore') || 0;highScoreSpan.textContent = highScore;function initGame() {snake = [{x: 5, y: 5}];score = 0;currentScoreSpan.textContent = score;direction = 'right';nextDirection = 'right';generateFood();
}function generateFood() {food = {x: Math.floor(Math.random() * (canvas.width/gridSize)),y: Math.floor(Math.random() * (canvas.height/gridSize))};// 防止食物生成在蛇身上while(snake.some(segment => segment.x === food.x && segment.y === food.y)) {food = {x: Math.floor(Math.random() * (canvas.width/gridSize)),y: Math.floor(Math.random() * (canvas.height/gridSize))};}
}function update() {const head = {...snake[0]};direction = nextDirection;switch(direction) {case 'up': head.y--; break;case 'down': head.y++; break;case 'left': head.x--; break;case 'right': head.x++; break;}// 碰撞檢測if (head.x < 0 || head.x >= canvas.width/gridSize || head.y < 0 || head.y >= canvas.height/gridSize ||snake.some(segment => segment.x === head.x && segment.y === head.y)) {gameOver();return;}snake.unshift(head);// 吃食物if (head.x === food.x && head.y === food.y) {score += 10;currentScoreSpan.textContent = score;generateFood();} else {snake.pop();}
}function draw() {// 清空畫布ctx.fillStyle = '#ecf0f1';ctx.fillRect(0, 0, canvas.width, canvas.height);// 繪制蛇ctx.fillStyle = '#27ae60';snake.forEach(segment => {ctx.fillRect(segment.x*gridSize, segment.y*gridSize, gridSize-2, gridSize-2);});// 繪制食物ctx.fillStyle = '#e74c3c';ctx.fillRect(food.x*gridSize, food.y*gridSize, gridSize-2, gridSize-2);
}function gameOver() {cancelAnimationFrame(gameLoop);startBtn.textContent = '開始游戲';if (score > highScore) {highScore = score;localStorage.setItem('snakeHighScore', highScore);highScoreSpan.textContent = highScore;}
}// 事件監聽
let lastMoveTime = 0;
const moveInterval = 300;function animate(timestamp) {if (!lastMoveTime) {lastMoveTime = timestamp;}const elapsed = timestamp - lastMoveTime;if (elapsed >= moveInterval) {update();lastMoveTime = timestamp;}draw();gameLoop = requestAnimationFrame(animate);
}// 修改游戲啟動邏輯
startBtn.addEventListener('click', () => {if (!gameLoop) {initGame();startBtn.textContent = '暫停游戲';lastMoveTime = 0; // 重置計時器gameLoop = requestAnimationFrame(animate);} else {cancelAnimationFrame(gameLoop);gameLoop = null;startBtn.textContent = '繼續游戲';}
});// 鍵盤控制
document.addEventListener('keydown', (e) => {switch(e.key.toLowerCase()) {case 'arrowup':case 'w':if (direction !== 'down') nextDirection = 'up';break;case 'arrowdown':case 's':if (direction !== 'up') nextDirection = 'down';break;case 'arrowleft':case 'a':if (direction !== 'right') nextDirection = 'left';break;case 'arrowright':case 'd':if (direction !== 'left') nextDirection = 'right';break;}
});
本文完