Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
320 lines (280 loc) · 10.2 KB
/
Copy pathscript.js
File metadata and controls
320 lines (280 loc) · 10.2 KB
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
314
315
316
317
318
319
320
// ---------- 游戏配置 ----------
const GRID_SIZE = 20;
const CELL_SIZE = 20;
const BASE_MOVE_INTERVAL = 80;
let snake = [];
let food = { x: 0, y: 0 };
let direction = 'right';
let nextDirection = 'right';
let score = 0;
let aiInterval = null;
let gameRunning = false;
let gameWinFlag = false;
const gameEl = document.getElementById('game');
const startAIEl = document.getElementById('startAI');
const stopAIEl = document.getElementById('stopAI');
const resetEl = document.getElementById('reset');
const statusEl = document.getElementById('status');
// ============================================================
// ============ 贪吃蛇 AI 内核(保守版:尾巴当障碍)============
// ============================================================
const N = GRID_SIZE * GRID_SIZE;
const _occ = new Uint8Array(N);
const _visited = new Uint8Array(N);
const _dist = new Int32Array(N);
const _queue = new Int32Array(N);
const _DIRS = ['up', 'down', 'left', 'right'];
const _OPPOSITE = { up:'down', down:'up', left:'right', right:'left' };
const _DELTA = { up:[0,-1], down:[0,1], left:[-1,0], right:[1,0] };
const _idx = (x, y) => y * GRID_SIZE + x;
// ★ 不再有 ignoreTail —— 尾巴永远是障碍
function _buildOcc(snakeArr, startX, startY) {
_occ.fill(0);
for (let i = 0; i < snakeArr.length; i++) {
_occ[_idx(snakeArr[i].x, snakeArr[i].y)] = 1;
}
if (startX >= 0) _occ[_idx(startX, startY)] = 0;
}
function _bfsDist(snakeArr, sx, sy, tx, ty) {
if (sx === tx && sy === ty) return 0;
_buildOcc(snakeArr, sx, sy);
_dist.fill(-1);
let qh = 0, qt = 0;
const sk = _idx(sx, sy), tk = _idx(tx, ty);
_dist[sk] = 0;
_queue[qt++] = sk;
while (qh < qt) {
const k = _queue[qh++];
const d = _dist[k];
if (k === tk) return d;
const x = k % GRID_SIZE, y = (k - x) / GRID_SIZE;
const nd = d + 1;
if (x > 0) { const nk = k - 1; if (_dist[nk] === -1 && !_occ[nk]) { _dist[nk] = nd; _queue[qt++] = nk; } }
if (x < GRID_SIZE - 1) { const nk = k + 1; if (_dist[nk] === -1 && !_occ[nk]) { _dist[nk] = nd; _queue[qt++] = nk; } }
if (y > 0) { const nk = k - GRID_SIZE; if (_dist[nk] === -1 && !_occ[nk]) { _dist[nk] = nd; _queue[qt++] = nk; } }
if (y < GRID_SIZE - 1) { const nk = k + GRID_SIZE; if (_dist[nk] === -1 && !_occ[nk]) { _dist[nk] = nd; _queue[qt++] = nk; } }
}
return Infinity;
}
function _bfsCount(snakeArr, sx, sy) {
_buildOcc(snakeArr, sx, sy);
_visited.fill(0);
let qh = 0, qt = 0;
const sk = _idx(sx, sy);
_visited[sk] = 1;
_queue[qt++] = sk;
let count = 0;
while (qh < qt) {
const k = _queue[qh++];
count++;
const x = k % GRID_SIZE, y = (k - x) / GRID_SIZE;
if (x > 0) { const nk = k - 1; if (!_visited[nk] && !_occ[nk]) { _visited[nk] = 1; _queue[qt++] = nk; } }
if (x < GRID_SIZE - 1) { const nk = k + 1; if (!_visited[nk] && !_occ[nk]) { _visited[nk] = 1; _queue[qt++] = nk; } }
if (y > 0) { const nk = k - GRID_SIZE; if (!_visited[nk] && !_occ[nk]) { _visited[nk] = 1; _queue[qt++] = nk; } }
if (y < GRID_SIZE - 1) { const nk = k + GRID_SIZE; if (!_visited[nk] && !_occ[nk]) { _visited[nk] = 1; _queue[qt++] = nk; } }
}
return count;
}
function _evaluateMove(dir) {
const head = snake[0];
const [dx, dy] = _DELTA[dir];
const nx = head.x + dx, ny = head.y + dy;
if (nx < 0 || nx >= GRID_SIZE || ny < 0 || ny >= GRID_SIZE) return -Infinity;
// ★ 保守碰撞:任何蛇身格(含尾巴)都不可进入
for (let i = 0; i < snake.length; i++) {
if (snake[i].x === nx && snake[i].y === ny) return -Infinity;
}
const ateFood = (nx === food.x && ny === food.y);
const len = snake.length;
const newLen = ateFood ? len + 1 : len;
if (newLen >= N) return 1e12;
// 构建新蛇(未吃到食物时尾巴移除)
const newSnake = new Array(newLen);
newSnake[0] = { x: nx, y: ny };
const copyCount = ateFood ? len : len - 1;
for (let i = 0; i < copyCount; i++) newSnake[i + 1] = snake[i];
// 自由度检查
let freeNeighbors = 0;
for (let di = 0; di < 4; di++) {
const d = _DIRS[di];
const ex = nx + _DELTA[d][0];
const ey = ny + _DELTA[d][1];
if (ex < 0 || ex >= GRID_SIZE || ey < 0 || ey >= GRID_SIZE) continue;
let blocked = false;
for (let i = 0; i < newLen; i++) {
if (newSnake[i].x === ex && newSnake[i].y === ey) { blocked = true; break; }
}
if (!blocked) freeNeighbors++;
}
if (freeNeighbors === 0) return -1e8; // 走进去立死
// 安全性:新头能否到达新尾(作为目标,不是通道)
const newTail = newSnake[newLen - 1];
const canReachTail = isFinite(_bfsDist(newSnake, nx, ny, newTail.x, newTail.y));
if (ateFood) {
if (canReachTail) return 1e9;
const space = _bfsCount(newSnake, nx, ny);
return space * 10;
}
if (!canReachTail) {
const space = _bfsCount(newSnake, nx, ny);
return space * 5 - 100000;
}
const foodDist = _bfsDist(newSnake, nx, ny, food.x, food.y);
if (!isFinite(foodDist)) {
const space = _bfsCount(newSnake, nx, ny);
return 10000 + space + freeNeighbors * 500;
}
return 50000 - foodDist * 100 + freeNeighbors * 100;
}
function aiDecideDirection() {
if (!gameRunning) return;
const opp = _OPPOSITE[direction];
let bestDir = null, bestScore = -Infinity;
for (const dir of _DIRS) {
if (dir === opp) continue;
const s = _evaluateMove(dir);
if (s > bestScore) {
bestScore = s;
bestDir = dir;
}
}
if (bestDir) nextDirection = bestDir;
}
// ============================================================
// ============ 游戏逻辑 ============
// ============================================================
function generateFood() {
if (snake.length >= N) { gameWin(); return; }
for (let i = 0; i < 1000; i++) {
const rx = Math.floor(Math.random() * GRID_SIZE);
const ry = Math.floor(Math.random() * GRID_SIZE);
if (!snake.some(s => s.x === rx && s.y === ry)) {
food = { x: rx, y: ry };
return;
}
}
for (let y = 0; y < GRID_SIZE; y++) {
for (let x = 0; x < GRID_SIZE; x++) {
if (!snake.some(s => s.x === x && s.y === y)) {
food = { x, y };
return;
}
}
}
gameWin();
}
function renderGrid() {
gameEl.innerHTML = '';
gameEl.style.display = 'grid';
gameEl.style.gridTemplateColumns = `repeat(${GRID_SIZE}, ${CELL_SIZE}px)`;
gameEl.style.gridTemplateRows = `repeat(${GRID_SIZE}, ${CELL_SIZE}px)`;
gameEl.style.gap = '1px';
gameEl.style.width = `${GRID_SIZE * CELL_SIZE + GRID_SIZE - 1}px`;
const headKey = snake[0] ? `${snake[0].x},${snake[0].y}` : '';
const bodySet = new Set();
for (let i = 1; i < snake.length; i++) bodySet.add(`${snake[i].x},${snake[i].y}`);
for (let y = 0; y < GRID_SIZE; y++) {
for (let x = 0; x < GRID_SIZE; x++) {
const cell = document.createElement('div');
cell.style.width = `${CELL_SIZE}px`;
cell.style.height = `${CELL_SIZE}px`;
const key = `${x},${y}`;
if (key === headKey) cell.className = 'snake-head';
else if (bodySet.has(key)) cell.className = 'snake';
else if (x === food.x && y === food.y) cell.className = 'food';
else cell.className = 'empty';
gameEl.appendChild(cell);
}
}
}
// ★ 保守移动:尾巴永远是障碍,与 AI 完全一致
function moveSnake() {
if (!gameRunning) return;
direction = nextDirection;
const head = { ...snake[0] };
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 >= GRID_SIZE || head.y < 0 || head.y >= GRID_SIZE) {
gameOver(); return;
}
// 碰撞检测:任何蛇身格(含尾巴)都不可进入
for (let i = 0; i < snake.length; i++) {
if (snake[i].x === head.x && snake[i].y === head.y) {
gameOver(); return;
}
}
snake.unshift(head);
const ate = (head.x === food.x && head.y === food.y);
if (ate) {
score += 10;
generateFood();
if (!gameRunning) return;
} else {
snake.pop();
}
renderGrid();
updateStatus();
if (snake.length === N && !gameWinFlag) gameWin();
}
function gameOver() {
if (!gameRunning) return;
gameRunning = false;
gameWinFlag = false;
stopAI();
statusEl.textContent = `状态:💀 游戏结束 | 得分:${score} | 蛇长:${snake.length}`;
alert(`游戏结束!最终得分:${score}`);
}
function gameWin() {
if (!gameRunning) return;
gameRunning = false;
gameWinFlag = true;
stopAI();
statusEl.textContent = `状态:🏆 胜利!满分通关 | 得分:${score} | 蛇长:${snake.length}`;
alert(`🎉 恭喜获胜!完美通关! 得分:${score}`);
}
function updateStatus() {
const aiStatus = aiInterval ? '🤖 AI运行中' : '⏸️ 未运行';
statusEl.innerHTML = `状态:${aiStatus} | 得分:${score} | 蛇长:${snake.length}`;
}
function initGame() {
stopAI();
snake = [
{ x: 5, y: 10 },
{ x: 4, y: 10 },
{ x: 3, y: 10 }
];
direction = 'right';
nextDirection = 'right';
score = 0;
gameRunning = true;
gameWinFlag = false;
generateFood();
renderGrid();
updateStatus();
}
function aiMove() {
if (!gameRunning) return;
aiDecideDirection();
moveSnake();
}
function startAI() {
if (!gameRunning) initGame();
if (aiInterval) clearInterval(aiInterval);
aiInterval = setInterval(aiMove, BASE_MOVE_INTERVAL);
updateStatus();
}
function stopAI() {
if (aiInterval) {
clearInterval(aiInterval);
aiInterval = null;
updateStatus();
}
}
startAIEl.addEventListener('click', startAI);
stopAIEl.addEventListener('click', stopAI);
resetEl.addEventListener('click', () => { stopAI(); initGame(); });
initGame();