-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
280 lines (250 loc) · 7.32 KB
/
index.html
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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>2048 AI</title>
<style>
body {
display: flex;
flex-direction: column;
align-items: center;
font-family: Arial, sans-serif;
}
.grid {
display: grid;
grid-template-columns: repeat(4, 80px);
grid-gap: 10px;
background: #bbada0;
padding: 10px;
border-radius: 5px;
}
.cell {
width: 80px;
height: 80px;
background: rgba(238, 228, 218, 0.35);
border-radius: 3px;
display: flex;
justify-content: center;
align-items: center;
font-size: 24px;
font-weight: bold;
}
.controls {
margin: 20px 0;
}
button {
padding: 10px 20px;
margin: 0 10px;
font-size: 16px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>2048 AI - Monte Carlo Method</h1>
<div class="controls">
<button onclick="startAI()">Start AI</button>
<button onclick="stopAI()">Stop AI</button>
<button onclick="resetGame()">Reset Game</button>
</div>
<div id="score">Score: 0</div>
<div class="grid" id="grid"></div>
<script>
class Game2048 {
constructor() {
this.grid = Array(4)
.fill()
.map(() => Array(4).fill(0));
this.score = 0;
this.addRandomTile();
this.addRandomTile();
}
clone() {
let newGame = new Game2048();
newGame.grid = this.grid.map((row) => [...row]);
newGame.score = this.score;
return newGame;
}
addRandomTile() {
const emptyCells = [];
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 4; j++) {
if (this.grid[i][j] === 0) {
emptyCells.push({ x: i, y: j });
}
}
}
if (emptyCells.length > 0) {
const cell =
emptyCells[Math.floor(Math.random() * emptyCells.length)];
this.grid[cell.x][cell.y] = Math.random() < 0.9 ? 2 : 4;
}
}
move(direction) {
let moved = false;
let points = 0;
const rotate = (grid) => {
const n = grid.length;
const rotated = Array(n)
.fill()
.map(() => Array(n).fill(0));
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
rotated[j][n - 1 - i] = grid[i][j];
}
}
return rotated;
};
const moveLeft = (grid) => {
const n = grid.length;
let moved = false;
let points = 0;
for (let i = 0; i < n; i++) {
let row = grid[i].filter((x) => x !== 0);
for (let j = 0; j < row.length - 1; j++) {
if (row[j] === row[j + 1]) {
row[j] *= 2;
points += row[j];
row.splice(j + 1, 1);
moved = true;
}
}
const newRow = row.concat(Array(n - row.length).fill(0));
if (newRow.join(",") !== grid[i].join(",")) {
moved = true;
}
grid[i] = newRow;
}
return { moved, points };
};
let newGrid = this.grid.map((row) => [...row]);
// 根据方向旋转网格
for (let i = 0; i < direction; i++) {
newGrid = rotate(newGrid);
}
// 向左移动
const result = moveLeft(newGrid);
moved = result.moved;
points = result.points;
// 旋转回原来的方向
for (let i = 0; i < (4 - direction) % 4; i++) {
newGrid = rotate(newGrid);
}
if (moved) {
this.grid = newGrid;
this.score += points;
this.addRandomTile();
}
return moved;
}
isGameOver() {
// 检查是否有空格
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 4; j++) {
if (this.grid[i][j] === 0) return false;
}
}
// 检查是否有相邻的相同数字
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 4; j++) {
const current = this.grid[i][j];
if (
(i < 3 && current === this.grid[i + 1][j]) ||
(j < 3 && current === this.grid[i][j + 1])
) {
return false;
}
}
}
return true;
}
}
class MCTS {
constructor(game, simulations = 100) {
this.game = game;
this.simulations = simulations;
}
findBestMove() {
const moves = [0, 1, 2, 3]; // 左、上、右、下
let bestScore = -1;
let bestMove = 0;
for (const move of moves) {
let totalScore = 0;
for (let i = 0; i < this.simulations; i++) {
const simulationGame = this.game.clone();
if (simulationGame.move(move)) {
totalScore += this.simulate(simulationGame);
}
}
if (totalScore > bestScore) {
bestScore = totalScore;
bestMove = move;
}
}
return bestMove;
}
simulate(game) {
let tempGame = game.clone();
let moves = 0;
while (!tempGame.isGameOver() && moves < 1000) {
const move = Math.floor(Math.random() * 4);
if (tempGame.move(move)) {
moves++;
}
}
return tempGame.score;
}
}
// UI和游戏控制
let game = new Game2048();
let aiInterval;
function updateDisplay() {
const grid = document.getElementById("grid");
grid.innerHTML = "";
document.getElementById("score").textContent = `Score: ${game.score}`;
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 4; j++) {
const cell = document.createElement("div");
cell.className = "cell";
const value = game.grid[i][j];
cell.textContent = value || "";
if (value) {
cell.style.backgroundColor = `hsl(${
Math.log2(value) * 30
}, 50%, 70%)`;
}
grid.appendChild(cell);
}
}
}
function startAI() {
if (!aiInterval) {
aiInterval = setInterval(() => {
const ai = new MCTS(game, 100);
const bestMove = ai.findBestMove();
game.move(bestMove);
updateDisplay();
if (game.isGameOver()) {
stopAI();
alert(`Game Over! Score: ${game.score}`);
}
}, 100);
}
}
function stopAI() {
if (aiInterval) {
clearInterval(aiInterval);
aiInterval = null;
}
}
function resetGame() {
stopAI();
game = new Game2048();
updateDisplay();
}
// 初始化显示
updateDisplay();
</script>
</body>
</html>