-
Notifications
You must be signed in to change notification settings - Fork 2
/
connect-four.js
276 lines (249 loc) · 14.1 KB
/
connect-four.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
import { Move } from "./classes.js";
export class ConnectFour {
// Return the game explanation prompt.
static explainGame() {
return "Connect-Four is a two-player game played on a 6 by 7 grid. The first player uses red (R) discs, and the second player uses yellow (Y) discs. Players take turns dropping their discs into a column from the top row where there is still at least one empty space. The dropped disc falls straight down, occupying the lowest available row within the column. The objective is to align four of your discs either horizontally, vertically, or diagonally. The player who first aligns four of their discs wins the game. Strategic placement is crucial; besides aiming to align their discs, players must also block their opponent's potential alignments to avoid defeat. \n";
}
// Return the prompt instructing the LLM on how to format its next move.
static formatNextMove() {
return " Suggest your next move in the following JSON format: {'column': ColumnNumber}. Do not include any additional commentary in your response. Replace ColumnNumber with the appropriate number for your move. ColumnNumber starts at 1 (the leftmost column is {'column': 1}). The maximum value for ColumnNumber is 7, as the grid is 7 columns wide. \n";
}
// Return the system prompt for the LLM.
static systemPrompt() {
return this.formatNextMove();
}
// Return a prompt that warns the LLM about the disqualification policy.
static invalidMoveWarning() {
return " Please note that your move will be considered invalid if your response does not follow the specified format, if you provide a ColumnNumber that is out of the allowed range, or if the column is already full (i.e., all rows in the column are occupied). Making more than " + this.getMaxInvalidMoves() + " invalid moves will result in disqualification. \n";
}
// Return the prompt version in YYYY-MM-DD format.
static promptVersion() {
return "2024-06-12";
}
// Return the maximum total allowed moves for the game.
static getMaxMoves() {
return 80;
}
// Return the maximum allowed invalid moves for a player. If a player exceeds this amount of invalid moves in a game, they will be disqualified in that match.
static getMaxInvalidMoves() {
return 7;
}
static boardInitialized = false; // Flag indicating whether the board has been initialized.
// Return a list of coordinates of moves for a given player.
static listPlayerMoves(player) {
let movesList = [];
let playerColor = (player === 1) ? "red" : "yellow";
// Loop through each row and column
for (let i = 0; i < 6; i++) {
for (let j = 0; j < 7; j++) {
let cell = document.getElementById("connect-four-" + (i + 1) + "-" + (j + 1)).querySelector('.connect-four-space');
if (cell.style.backgroundColor === playerColor) {
movesList.push((i + 1) + "," + (j + 1));
}
}
}
return movesList;
}
// Convey the board state using move coordinates.
static listBoard() {
let gameStatus = "";
let firstPlayerMoves = this.listPlayerMoves(1);
let secondPlayerMoves = this.listPlayerMoves(2);
gameStatus += " The current state of the game is recorded in a specific format: each occupied location is delineated by a semicolon (';'), and for each occupied location, the row number is listed first, followed by the column number, separated by a comma (','). If no locations are occupied by a player, 'None' is noted. Both the row and column numbers start from 1, with the top left corner of the grid indicated by 1,1. \n";
gameStatus += " The current state of the game is as follows: \n";
gameStatus += " The locations occupied by the first player: ";
gameStatus += (firstPlayerMoves.length ? firstPlayerMoves.join("; ") : "None") + " \n";
gameStatus += " The locations occupied by the second player: ";
gameStatus += (secondPlayerMoves.length ? secondPlayerMoves.join("; ") : "None") + " \n";
return gameStatus;
}
// Draw the board in text format.
static drawBoard() {
let gameStatus = "";
gameStatus += " The current state of the game is displayed on a 6 by 7 grid. 'R' represents positions taken by the first player and 'Y' represents positions taken by the second player, while 'e' indicates an empty (available) position. \n";
gameStatus += " The current state of the game is as follows: \n";
for (let i = 0; i < 6; i++) {
for (let j = 0; j < 7; j++) {
let cellColor = document.getElementById("connect-four-" + (i + 1) + "-" + (j + 1)).querySelector('.connect-four-space').style.backgroundColor;
switch (cellColor) {
case "red":
gameStatus += "R";
break;
case "yellow":
gameStatus += "Y";
break;
default:
gameStatus += "e";
break;
}
}
gameStatus += " \n";
}
return gameStatus;
}
// Return the prompt describing the board screenshot.
static imagePrompt() {
return " The current state of the game is depicted in an image showing a 6 by 7 grid, where red discs represent positions taken by the first player and yellow discs represent positions taken by the second player. \n";
}
// Take a screenshot of the board and encode it using base64.
static async screenshotBoard() {
return new Promise((resolve, reject) => {
// Screenshot size is standardized at 512px * 512px, regardless of user's window dimensions.
html2canvas(document.querySelector("#connect-four-board"), { width: 512, height: 512, windowWidth: 1677, windowHeight: 854, scale: 1, logging: false }).then((canvas) => {
// Download screenshot of board (for testing purposes).
//canvas.toBlob(function(blob) {
//saveAs(blob, "Connect Four Game Board.png");
//});
// Return base64-encoded board screenshot.
return canvas.toDataURL("image/png;base64");
}).then(data => {
resolve(data);
}).catch(error => {
reject(error);
});
});
}
// Generate a random move for the "Random Play" player type.
static randomMove() {
let col = Math.floor(Math.random() * 7) + 1; // Obtain a random column number between 1 and 7.
return "{\"column\": " + col + "}";
}
// Construct a Move object given the model's response and display the move if it is valid.
static processMove(response, currentPlayer, model, currentMoveCount, currentStatus, useConsoleLogging) {
let col;
let color = (currentPlayer === 1) ? "red" : "yellow";
// Initialize the board if not already done
if (!ConnectFour.boardInitialized) {
for (let i = 0; i < 6; i++) {
for (let j = 0; j < 7; j++) {
//document.getElementById(`connect-four-${i}-${j}`).querySelector('.connect-four-space').style.backgroundColor = "white";
document.getElementById("connect-four-" + (i + 1) + "-" + (j + 1)).querySelector('.connect-four-space').style.backgroundColor = "white";
}
}
ConnectFour.boardInitialized = true; // Set the flag to true after initialization
}
if (response.column !== undefined && typeof response.column === "number") {
col = response.column;
} else {
return new Move(currentMoveCount, currentPlayer, -1, -1, "Invalid Format", currentStatus, JSON.stringify(response));
}
// If response's JSON object has any more items than 'column', it is invalid.
if (Object.keys(response).length > 1) {
throw new Error();
}
// Validate the column
if (col >= 1 && col <= 7) {
// Check from the bottom of the column up to find the first empty space
for (let row = 6; row > 0; row--) {
if (document.getElementById("connect-four-" + row + "-" + col).querySelector('.connect-four-space').style.backgroundColor === "white") {
// Update the background color to red or yellow.
document.getElementById("connect-four-" + row + "-" + col).querySelector('.connect-four-space').style.backgroundColor = color;
// Return successful move.
if (useConsoleLogging) console.log("Move " + currentMoveCount + ": " + model.getName() + " (" + color + ") places at column " + col + ".");
return new Move(currentMoveCount, currentPlayer, row, col, "Valid", currentStatus, JSON.stringify(response));
}
}
// Return unsuccessful move because the column is full
if (useConsoleLogging) console.log("Move " + currentMoveCount + ": " + model.getName() + " (" + color + ") tried to place in full column " + col + ".");
return new Move(currentMoveCount, currentPlayer, -1, col, "Already Taken", currentStatus, JSON.stringify(response));
}
else {
// Return unsuccessful move because AI attempted to play in a column that was out of bounds.
if (useConsoleLogging) console.log("Move " + currentMoveCount + ": " + model.getName() + " (" + color + ") tried to place at column " + col + " which is out of bounds.");
return new Move(currentMoveCount, currentPlayer, -1, col, "Out of Bounds", currentStatus, JSON.stringify(response));
}
}
// Visualize the board state in a text-based format to be used for the visual game logs in the text files.
// Note that this format is different from the output given from the "drawBoard()" function, adding extra separators |.
static visualizeBoardState() {
let boardState = "";
for (let i = 0; i < 6; i++) {
for (let j = 0; j < 7; j++) {
let cell = document.getElementById("connect-four-" + (i + 1) + "-" + (j + 1)).querySelector('.connect-four-space');
let cellColor = cell.style.backgroundColor;
// Assign symbols based on color
let symbol = 'e';
if (cellColor === "red") {
symbol = 'R';
} else if (cellColor === "yellow") {
symbol = 'Y';
}
boardState += symbol;
if (j < 7 - 1) {
boardState += "|";
}
}
boardState += "\n";
}
return boardState + "\n";
}
// Check to see if a player has won. If so, return true.
static checkForWin() {
let rows = 6;
let cols = 7;
let field = new Array(rows);
for (let i = 0; i < rows; i++) {
field[i] = new Array(cols);
}
// Populate the field array with the background colors of the cells
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
let cell = document.getElementById("connect-four-" + (i + 1) + "-" + (j + 1)).querySelector('.connect-four-space');
field[i][j] = cell.style.backgroundColor; // Get the background color
}
}
// Check horizontal lines
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols - 3; j++) {
if (field[i][j] !== "white" && field[i][j] === field[i][j + 1] && field[i][j] === field[i][j + 2] && field[i][j] === field[i][j + 3]) {
return true; // Found a win
}
}
}
// Check vertical lines
for (let j = 0; j < cols; j++) {
for (let i = 0; i < rows - 3; i++) {
if (field[i][j] !== "white" && field[i][j] === field[i + 1][j] && field[i][j] === field[i + 2][j] && field[i][j] === field[i + 3][j]) {
return true; // Found a win
}
}
}
// Check diagonal (top-left to bottom-right)
for (let i = 0; i < rows - 3; i++) {
for (let j = 0; j < cols - 3; j++) {
if (field[i][j] !== "white" && field[i][j] === field[i + 1][j + 1] && field[i][j] === field[i + 2][j + 2] && field[i][j] === field[i + 3][j + 3]) {
return true; // Found a win
}
}
}
// Check diagonal (bottom-left to top-right)
for (let i = 3; i < rows; i++) {
for (let j = 0; j < cols - 3; j++) {
if (field[i][j] !== "white" && field[i][j] === field[i - 1][j + 1] && field[i][j] === field[i - 2][j + 2] && field[i][j] === field[i - 3][j + 3]) {
return true; // Found a win
}
}
}
return false; // No win found
}
// Check to see if the board is full. If so, return true.
static checkForFullBoard() {
for (let i = 0; i < 6; i++) {
for (let j = 0; j < 7; j++) {
let cellColor = document.getElementById("connect-four-" + (i + 1) + "-" + (j + 1)).querySelector('.connect-four-space').style.backgroundColor;
if (cellColor === "white") {
return false; // Board is not full
}
}
}
return true; // Board is full
}
// Delete all moves from the board.
static resetBoard() {
for (let i = 0; i < 6; i++) {
for (let j = 0; j < 7; j++) {
document.getElementById("connect-four-" + (i + 1) + "-" + (j + 1)).querySelector('.connect-four-space').style.backgroundColor = "white";
}
}
}
}