1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>greedy snake</title> </head>
<style> * { margin: 0; padding: 0; box-sizing: border-box; --background-color: #2C3E50; --snake-color: #4CAF50; --food-color: #E74C3C; } body { min-height: 100vh; min-width: 100vw; background-color: var(--background-color); } </style>
<body> <canvas id="mycanvas"></canvas> </body> <script> const colors = { background: '#2c3e50', snake: '#42b983', food: '#e74c3c', grid: '#34495e', };
const canvas = document.getElementById('mycanvas'); const ctx = canvas.getContext('2d'); const body = document.body;
let width = canvas.width = window.innerWidth; let height = canvas.height = window.innerHeight;
const currentMousePosition = { x: height / 2, y: width / 2 };
// 世界座標偏移 // 螢幕位置 = 世界位置 - camera 偏移量 // 世界位置 = 螢幕位置 + camera 偏移量 const camera = { x: 0, y: 0 };
const speed = 2; const snakeSize = 16; const foodSize = 6;
const snakePath = []; // 紀錄蛇頭的世界座標路徑(每幀) let totalSegments = 1; // 身體節點數量 const segmentDistance = 8; // 身體每個節點之間的間隔距離(每隔8幀才是第二個身體節點)
const aiSnakes = []; const numAiSnakes = 10; // AI 蛇的數量
for (let i = 0; i < numAiSnakes; i++) { aiSnakes.push({ worldX: (Math.random() - 0.5) * 2000, worldY: (Math.random() - 0.5) * 2000, angle: Math.random() * Math.PI * 2, speed: 1, // AI 稍微慢一點 snakePath: [], totalSegments: 10, color: `hsl(${Math.random() * 360}, 70%, 50%)` // 隨機顏色 }); }
const foots = []; // 隨機生成新食物 for(let i = 0; i < 50; i++){ foots.push({ x: (Math.random() - 0.5) * 2000, y: (Math.random() - 0.5) * 2000 }); }
window.addEventListener('mousemove', (e) => { currentMousePosition.x = e.clientX; currentMousePosition.y = e.clientY; });
function drawGrid(){ const gridSize = 50; console.log(-camera.x % gridSize); ctx.strokeStyle = colors.grid; ctx.lineWidth = 1; for(let x = -camera.x % gridSize; x < width; x += gridSize){ ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, height); ctx.stroke(); ctx.closePath(); } for(let y = -camera.y % gridSize; y < height; y += gridSize){ ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(width, y); ctx.stroke(); ctx.closePath(); }
}
function redraw() { ctx.clearRect(0, 0, canvas.width, canvas.height); // draw background drawGrid();
aiSnakes.forEach(ai => { for (let i = ai.totalSegments - 1; i >= 0; i--) { const pathIndex = i * segmentDistance; const point = ai.snakePath[pathIndex]; if (point) { // AI 世界座標 - 相機偏移 = 螢幕位置 const screenX = point.worldX - camera.x - snakeSize / 2; const screenY = point.worldY - camera.y - snakeSize / 2; ctx.fillStyle = i === 0 ? ai.color : ai.color + "88"; // 身體半透明 ctx.fillRect(screenX, screenY, snakeSize, snakeSize); } } }); // 繪製蛇身 for (let i = 0; i < totalSegments; i++) { // 取得該節點在路徑中的索引 const pathIndex = i * segmentDistance; const point = snakePath[pathIndex]; if (point) { // 將「世界座標」轉換回「螢幕座標」進行繪製 const screenX = point.worldX - camera.x; const screenY = point.worldY - camera.y;
ctx.fillStyle = i === 0 ? colors.snake : '#388E3C'; // 頭用亮色,身體深色 ctx.fillRect(screenX, screenY, snakeSize, snakeSize); } } // draw foots foots.forEach(foot => { ctx.fillStyle = colors.food; ctx.beginPath(); ctx.arc(foot.x - camera.x, foot.y - camera.y, foodSize/2, 0, Math.PI * 2); ctx.fill(); ctx.closePath(); }); }
function updateAi() { aiSnakes.forEach(ai => { // 1. 隨機改變方向 (每幀有 2% 的機率轉彎) if (Math.random() < 0.02) { ai.angle += (Math.random() - 0.5) * 2; }
// 2. 根據角度更新世界座標 ai.worldX += Math.cos(ai.angle) * ai.speed; ai.worldY += Math.sin(ai.angle) * ai.speed;
// 3. 記錄路徑 (用於畫身體) ai.snakePath.unshift({ worldX: ai.worldX, worldY: ai.worldY }); if (ai.snakePath.length > ai.totalSegments * segmentDistance) { ai.snakePath.pop(); }
// 4. AI 也可以吃食物 foots.forEach((foot, index) => { const dx = ai.worldX - foot.x; const dy = ai.worldY - foot.y; const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < snakeSize) { foots.splice(index, 1); ai.totalSegments += 2; // 補償食物 foots.push({ x: (Math.random() - 0.5) * 2000, y: (Math.random() - 0.5) * 2000 }); } }); }); }
function moving(){ const x = currentMousePosition.x - width / 2; const y = currentMousePosition.y - height / 2; const angle = Math.atan2(y, x) const dx = Math.cos(angle) * speed; const dy = Math.sin(angle) * speed; // console.log(`Angle: ${angle}, dx: ${dx}, dy: ${dy}`); camera.x += dx; camera.y += dy;
snakePath.unshift({ worldX: width / 2 + camera.x, worldY: height / 2 + camera.y }); if(snakePath.length > totalSegments * segmentDistance){ snakePath.pop(); }
}
function eating(){ const head = snakePath[0]; foots.forEach((foot, index) => { if(head.worldX < foot.x + foodSize && head.worldX + snakeSize > foot.x && head.worldY < foot.y + foodSize && head.worldY + snakeSize > foot.y){ foots.splice(index, 1); // 增加蛇的長度 totalSegments += 5; for(let i = 0; i < 5; i++){ // 隨機生成新食物 foots.push({ x: (Math.random() - 0.5) * 2000, y: (Math.random() - 0.5) * 2000 }); } } });
}
function checkCollisions() { const playerWorldHead = { x: snakePath[0].worldX, y: snakePath[0].worldY };
aiSnakes.forEach((ai, aiIndex) => { // --- 玩家撞到 AI 的身體 --- // 跳過 AI 的頭部幾節,避免誤判 for (let i = segmentDistance * 2; i < ai.snakePath.length; i += segmentDistance) { const segment = ai.snakePath[i]; const dx = playerWorldHead.x - segment.worldX; const dy = playerWorldHead.y - segment.worldY; const distance = Math.sqrt(dx * dx + dy * dy);
if (distance < snakeSize) { // 玩家死亡 alert("遊戲結束!你被 AI 蛇吃掉了。"); setTimeout(() => { location.reload(); // 簡單處理:重新整理網頁 }, 0); } }
// --- AI 撞到玩家的身體 --- const aiWorldHead = { x: ai.worldX, y: ai.worldY }; for (let i = segmentDistance * 2; i < snakePath.length; i += segmentDistance) { const segment = snakePath[i]; const dx = aiWorldHead.x - segment.worldX; const dy = aiWorldHead.y - segment.worldY; const distance = Math.sqrt(dx * dx + dy * dy);
if (distance < snakeSize) { // AI 死亡 for(let j = 0; j < ai.snakePath.length; j++){ // 玩家吃掉 AI 後,生成一些食物作為獎勵 foots.push({ x: ai.snakePath[j].worldX, y: ai.snakePath[j].worldY }); } aiSnakes.splice(aiIndex, 1); spawnNewAi(); // 生成新 AI 補充 return; } } }); }
// 生成新的 AI 蛇 function spawnNewAi() { aiSnakes.push({ worldX: (Math.random() - 0.5) * 2000, worldY: (Math.random() - 0.5) * 2000, angle: Math.random() * Math.PI * 2, speed: 1, snakePath: [], totalSegments: 10, color: `hsl(${Math.random() * 360}, 70%, 50%)` }); }
function repeating(){ redraw(); moving(); updateAi(); checkCollisions(); eating(); requestAnimationFrame(repeating); }
const frameId = requestAnimationFrame(repeating);
// 监听窗口大小变化 window.addEventListener('resize', () => { width = canvas.width = window.innerWidth; height = canvas.height = window.innerHeight; });
</script> </html>
|