五子棋小游戏

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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>五子棋游戏</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>五子棋游戏</h1>
<div class="game-container">
<div class="side-panel">
<div id="left-info" class="info-panel">
<h2>游戏信息</h2>
<div class="info-item">
<span class="info-label">游戏状态:</span>
<span id="game-status" class="info-value">游戏进行中</span>
</div>
<div class="info-item">
<span class="info-label">当前玩家:</span>
<span id="current-player" class="info-value">黑方</span>
</div>
</div>
<div id="game-rules" class="info-panel">
<h2>游戏规则</h2>
<p>1. 黑方先手,双方轮流落子。</p>
<p>2. 先在棋盘上形成5颗相同颜色的棋子连成一线(横、竖、斜均可)的一方获胜。</p>
<p>3. 可以使用悔棋按钮撤销上一步操作。</p>
<p>4. 点击重新开始可以随时重置游戏。</p>
</div>
</div>
<div id="game-board"></div>
<div id="right-info" class="info-panel">
<h2>计时器</h2>
<div class="info-item">
<span class="info-label">黑方时间:</span>
<span id="black-timer" class="info-value">00:00</span>
</div>
<div class="info-item">
<span class="info-label">白方时间:</span>
<span id="white-timer" class="info-value">00:00</span>
</div>
</div>
</div>
<div id="game-controls">
<button id="undo-btn">悔棋</button>
<button id="restart-btn">重新开始</button>
</div>
<div id="victory-message"></div>
<script src="script.js"></script>
</body>
</html>

css

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
body {
display: flex;
flex-direction: column;
align-items: center;
font-family: 'Arial', sans-serif;
background-color: #f0f0f0;
color: #333;
}

h1 {
margin-top: 20px;
font-size: 2.5em;
color: #2c3e50;
text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
}

.game-container {
display: flex;
justify-content: center;
align-items: flex-start;
margin-top: 20px;
}

.side-panel {
display: flex;
flex-direction: column;
gap: 20px;
}

.info-panel {
width: 200px;
padding: 15px;
background-color: #fff;
border-radius: 10px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.info-panel h2 {
font-size: 1.2em;
color: #2c3e50;
margin-bottom: 15px;
text-align: center;
border-bottom: 2px solid #3498db;
padding-bottom: 5px;
}

.info-item {
margin-bottom: 10px;
}

.info-label {
font-weight: bold;
color: #7f8c8d;
}

.info-value {
margin-left: 5px;
color: #2c3e50;
}

#game-board {
display: grid;
grid-template-columns: repeat(15, 40px);
grid-template-rows: repeat(15, 40px);
gap: 1px;
background-color: #deb887;
padding: 10px;
border-radius: 5px;
box-shadow: 0 0 15px rgba(0,0,0,0.1);
}

.cell {
width: 40px;
height: 40px;
background-color: #f0d9b5;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
border-radius: 50%;
transition: background-color 0.3s ease;
}

.cell:hover {
background-color: #e6c9a3;
}

.cell.black {
background-color: #333;
box-shadow: inset 0 0 8px rgba(255,255,255,0.5);
}

.cell.white {
background-color: #fff;
box-shadow: inset 0 0 8px rgba(0,0,0,0.2);
}

#game-controls {
margin-top: 20px;
}

button {
padding: 10px 20px;
font-size: 16px;
background-color: #3498db;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
margin: 0 10px;
transition: background-color 0.3s ease;
}

button:hover {
background-color: #2980b9;
}

button:disabled {
background-color: #bdc3c7;
cursor: not-allowed;
}

#victory-message {
font-size: 24px;
font-weight: bold;
color: #27ae60;
margin-top: 20px;
text-align: center;
}

@media (max-width: 800px) {
.game-container {
flex-direction: column;
align-items: center;
}

.side-panel, .info-panel {
width: 90%;
margin: 10px 0;
}

#game-board {
grid-template-columns: repeat(15, 5.5vw);
grid-template-rows: repeat(15, 5.5vw);
}

.cell {
width: 5.5vw;
height: 5.5vw;
}

#game-controls {
display: flex;
flex-direction: column;
align-items: center;
}

button {
margin: 5px 0;
width: 80%;
}
}

#game-info p {
margin: 5px 0;
}

.cell.last-move {
box-shadow: 0 0 10px 3px rgba(255, 215, 0, 0.7);
}

.cell.black, .cell.white {
transition: transform 0.3s ease;
}

.cell.black:not(.last-move), .cell.white:not(.last-move) {
transform: scale(0.9);
}

.cell.last-move {
animation: pulse 1s infinite alternate;
}

@keyframes pulse {
from {
transform: scale(0.95);
}
to {
transform: scale(1.05);
}
}

#game-rules p {
font-size: 0.9em;
margin: 5px 0;
}

#black-timer, #white-timer {
font-family: 'Courier New', monospace;
}

js

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
console.log("脚本已加载");

const boardSize = 15;
const board = [];
let currentPlayer = 'black';
let moveHistory = [];
let gameStatus = '游戏进行中';
let blackTimer = 0;
let whiteTimer = 0;
let currentTimerInterval = null;
let lastTimerUpdate = null;
let lastMove = null;
let timerStarted = false;

function createBoard() {
const gameBoard = document.getElementById('game-board');
gameBoard.innerHTML = ''; // 清空棋盘
for (let i = 0; i < boardSize; i++) {
board[i] = [];
for (let j = 0; j < boardSize; j++) {
const cell = document.createElement('div');
cell.classList.add('cell');
cell.dataset.row = i;
cell.dataset.col = j;
cell.addEventListener('click', handleCellClick);
gameBoard.appendChild(cell);
board[i][j] = null;
}
}
}

function handleCellClick(event) {
const row = parseInt(event.target.dataset.row);
const col = parseInt(event.target.dataset.col);

if (board[row][col] === null && gameStatus !== '游戏结束') {
if (!timerStarted) {
startTimer();
timerStarted = true;
} else {
stopTimer();
}

board[row][col] = currentPlayer;
event.target.classList.add(currentPlayer);

if (lastMove) {
document.querySelector(`[data-row="${lastMove.row}"][data-col="${lastMove.col}"]`).classList.remove('last-move');
}

event.target.classList.add('last-move');
lastMove = {row, col};

moveHistory.push({row, col, player: currentPlayer});

if (checkWin(row, col)) {
const winner = currentPlayer === 'black' ? '黑方' : '白方';
document.getElementById('victory-message').textContent = `${winner} 赢了!`;
updateGameStatus('游戏结束');
stopTimer();
disableBoard();
} else {
stopTimer(); // 停止当前玩家的计时器
currentPlayer = currentPlayer === 'black' ? 'white' : 'black';
updateCurrentPlayerDisplay();
startTimer(); // 开始新玩家的计时器
}

updateUndoButton();
saveGameState();
}
}

function startTimer() {
if (currentTimerInterval) {
clearInterval(currentTimerInterval);
}
lastTimerUpdate = Date.now();
currentTimerInterval = setInterval(updateTimer, 10); // 每10毫秒更新一次
}

function stopTimer() {
if (currentTimerInterval) {
clearInterval(currentTimerInterval);
currentTimerInterval = null;
}
updateTimer(); // 确保最后一次更新
}

function updateTimer() {
const now = Date.now();
const elapsed = now - lastTimerUpdate;
lastTimerUpdate = now;

if (currentPlayer === 'black') {
blackTimer += elapsed;
} else {
whiteTimer += elapsed;
}

updateTimerDisplay();
}

function updateTimerDisplay() {
document.getElementById('black-timer').textContent = formatTime(blackTimer);
document.getElementById('white-timer').textContent = formatTime(whiteTimer);
}

function formatTime(milliseconds) {
const totalSeconds = Math.floor(milliseconds / 1000);
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
const ms = milliseconds % 1000;
return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}.${ms.toString().padStart(3, '0')}`;
}

function updateCurrentPlayerDisplay() {
const currentPlayerDisplay = document.getElementById('current-player');
currentPlayerDisplay.textContent = currentPlayer === 'black' ? '黑方' : '白方';
}

function checkWin(row, col) {
const directions = [
[1, 0], // 水平
[0, 1], // 垂直
[1, 1], // 对角线(左上到右下)
[1, -1] // 对角线(右上到左下)
];

for (const [dx, dy] of directions) {
const line = checkDirection(row, col, dx, dy);
if (line.length >= 5) {
highlightWinningLine(line);
return true;
}
}
return false;
}

function checkDirection(row, col, rowDir, colDir) {
const line = [{row, col}];
let count = 1;
let r = parseInt(row);
let c = parseInt(col);

// 向一个方向检查
for (let i = 1; i < 5; i++) {
r += rowDir;
c += colDir;
if (r >= 0 && r < boardSize && c >= 0 && c < boardSize && board[r][c] === currentPlayer) {
count++;
line.push({row: r, col: c});
} else {
break;
}
}

// 重置初始位置
r = parseInt(row);
c = parseInt(col);

// 向相反方向检查
for (let i = 1; i < 5; i++) {
r -= rowDir;
c -= colDir;
if (r >= 0 && r < boardSize && c >= 0 && c < boardSize && board[r][c] === currentPlayer) {
count++;
line.unshift({row: r, col: c});
} else {
break;
}
}

return line;
}

function highlightWinningLine(line) {
for (const {row, col} of line) {
const cell = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
cell.classList.add('winning-cell');
}
}

function resetGame() {
const gameBoard = document.getElementById('game-board');
gameBoard.innerHTML = '';
board.length = 0;
moveHistory = [];
createBoard();
currentPlayer = 'black';
updateCurrentPlayerDisplay();
updateUndoButton();
enableBoard();
updateGameStatus('游戏进行中');
document.getElementById('victory-message').textContent = '';
stopTimer();
resetTimers();
timerStarted = false;
}

function undo() {
if (moveHistory.length > 0) {
const lastMove = moveHistory.pop();
const cell = document.querySelector(`[data-row="${lastMove.row}"][data-col="${lastMove.col}"]`);
cell.classList.remove(lastMove.player, 'last-move');
board[lastMove.row][lastMove.col] = null;
currentPlayer = lastMove.player;
updateCurrentPlayerDisplay();
updateUndoButton();
enableBoard();

// 更新最后一步的高亮
if (moveHistory.length > 0) {
const newLastMove = moveHistory[moveHistory.length - 1];
document.querySelector(`[data-row="${newLastMove.row}"][data-col="${newLastMove.col}"]`).classList.add('last-move');
lastMove = newLastMove;
} else {
lastMove = null;
}
}
}

function updateUndoButton() {
const undoBtn = document.getElementById('undo-btn');
undoBtn.disabled = moveHistory.length === 0;
}

function disableBoard() {
const cells = document.querySelectorAll('.cell');
cells.forEach(cell => cell.removeEventListener('click', handleCellClick));
}

function enableBoard() {
const cells = document.querySelectorAll('.cell');
cells.forEach(cell => cell.addEventListener('click', handleCellClick));
}

function updateGameStatus(status) {
gameStatus = status;
document.getElementById('game-status').textContent = status;
}

function saveGameState() {
const gameState = {
board,
currentPlayer,
moveHistory,
gameStatus,
blackTimer,
whiteTimer,
lastMove
};
localStorage.setItem('gomokuGameState', JSON.stringify(gameState));
}

function loadGameState() {
const savedState = localStorage.getItem('gomokuGameState');
if (savedState) {
const gameState = JSON.parse(savedState);
board = gameState.board;
currentPlayer = gameState.currentPlayer;
moveHistory = gameState.moveHistory;
gameStatus = gameState.gameStatus;
blackTimer = gameState.blackTimer;
whiteTimer = gameState.whiteTimer;
lastMove = gameState.lastMove;

createBoard();
for (let i = 0; i < boardSize; i++) {
for (let j = 0; j < boardSize; j++) {
if (board[i][j]) {
const cell = document.querySelector(`[data-row="${i}"][data-col="${j}"]`);
cell.classList.add(board[i][j]);
if (lastMove && lastMove.row === i && lastMove.col === j) {
cell.classList.add('last-move');
}
}
}
}

updateCurrentPlayerDisplay();
updateGameStatus(gameStatus);
updateTimerDisplay();
updateUndoButton();
if (gameStatus === '游戏结束') {
disableBoard();
} else if (moveHistory.length > 0) {
timerStarted = true;
startTimer();
} else {
timerStarted = false;
}
} else {
createBoard();
resetTimers();
timerStarted = false;
}
}

function resetTimers() {
blackTimer = 0;
whiteTimer = 0;
updateTimerDisplay();
}

// 初始化游戏
window.addEventListener('load', () => {
loadGameState();
// 移除这里的 startTimer 调用
});

// 添加事件监听器
document.getElementById('undo-btn').addEventListener('click', undo);
document.getElementById('restart-btn').addEventListener('click', resetGame);

// 直接调用 createBoard 函数
createBoard();

放到同一目录下就可以使用