-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathotrio.html
485 lines (465 loc) · 17.9 KB
/
otrio.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
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
<!doctype html>
<html>
<head>
<title>
Games
</title>
<base target="_blank">
<script src="https://epicenterprograms.github.io/standards/behavior/general.js"></script>
<script src="https://epicenterprograms.github.io/standards/behavior/storage.js"></script>
<script src="https://epicenterprograms.github.io/standards/behavior/game.js"></script>
<!--
<script src="file:///C:/Users/rtben/Documents/GitHub/standards/behavior/game.js"></script>
-->
<script src="behavior.js"></script>
<script>
function weightedRandomChoice(items, weights) {
if (items.length !== weights.length) {
throw new Error("Items and weights must be of the same size");
}
let cumulativeWeights = [];
for (let i = 0; i < weights.length; i++) {
cumulativeWeights[i] = weights[i] + (cumulativeWeights[i - 1] || 0);
}
let randomNumber = cumulativeWeights[cumulativeWeights.length - 1] * Math.random();
for (let itemIndex = 0; itemIndex < items.length; itemIndex++) {
if (cumulativeWeights[itemIndex] >= randomNumber) {
return items[itemIndex];
}
}
}
</script>
<script>
var size = { // the size of the game board
x: 3,
y: 3,
z: 3
};
var winScore = Math.min(size.x, size.y, size.z);
var currentLayer = 0; // the current layer chosen, a.k.a. the type of piece chosen
var standbys = [[], [], [], []]; // the unused game pieces for each player
var options = []; // the potential places to put a game piece (contains the entity references)
var currentPiece = null; // the currently selected game piece
var currentPlayer = 0;
var gameState = [];
var players = 1; // the number of real players
var colors = ["red", "green", "blue", "purple"]; // the color of the player pieces clockwise from bottom
var piecesPerLayer = 3; // the number of pieces allowed per layer
function choiceAvailable(option) {
/**
checks whether the chosen option is available
*/
return option.dataset["z" + currentLayer + "IsOpen"] === "true" ? true : false;
}
function placeOpen(x, y, z, playerNumber = -1) {
/**
checks whether a location is open
additionally optionally checks whether a certain player has a piece they can put there
*/
let placeIsOpen = gameState[x][y][z] === -1 ? true : false;
if (playerNumber > -1) {
return placeIsOpen && standbys[playerNumber][z].length > 0;
} else {
return placeIsOpen;
}
}
function showWhoseTurn() {
if (currentPlayer < 3) {
currentPlayer++;
} else {
currentPlayer = 0;
}
S.getId("currentPlayer").style.width = ["100%", "calc(var(--game-space-width) + var(--size-unit) * 2.25)"][currentPlayer % 2];
S.getId("currentPlayer").style.height = ["calc(var(--game-space-width) + var(--size-unit) * 2.25)","100%"][currentPlayer % 2];
S.forEach(["bottom", "left", "top", "right"], function (side) {
S.getId("currentPlayer").style[side] = "auto";
});
S.getId("currentPlayer").style[["bottom", "left", "top", "right"][currentPlayer]] = "0em";
S.getId("currentPlayer").style[["left", "top", "right", "bottom"][currentPlayer]] = "0em";
}
function playerHasWon(playerNumber, state) {
const directions = [
{ x: 1, y: 0, z: 0 }, { x: 0, y: 1, z: 0 }, { x: 0, y: 0, z: 1 },
{ x: 1, y: 1, z: 0 }, { x: 1, y: 0, z: 1 }, { x: 0, y: 1, z: 1 },
{ x: 1, y: 1, z: 1 }, { x: -1, y: 1, z: 0 }, { x: -1, y: 0, z: 1 },
{ x: 0, y: -1, z: 1 }, { x: -1, y: 1, z: 1 }, { x: 1, y: -1, z: 1 },
{ x: 1, y: 1, z: -1 }, { x: -1, y: -1, z: 1 }, { x: -1, y: 1, z: -1 },
{ x: 1, y: -1, z: -1 }
];
// finds all of the player's pieces
for (let x = 0; x < state.length; x++) {
for (let y = 0; y < state[x].length; y++) {
for (let z = 0; z < state[x][y].length; z++) {
if (state[x][y][z] === playerNumber) {
// looks in every direction for a long enough row
for (let i = 0; i < directions.length; i++) {
let score = 1;
let cx = x, cy = y, cz = z;
const dir = directions[i];
while (true) {
cx += dir.x;
cy += dir.y;
cz += dir.z;
// follows any developing row
if (state[cx]?.[cy]?.[cz] === playerNumber) {
score++;
// declares a win if enough pieces are in a row
if (score >= winScore) return true;
} else {
break;
}
}
}
}
}
}
}
return false;
}
function gameHasEnded() {
// checks if anyone has won
let winner = -1;
S.forEach(4, function (_, playerNumber) {
if (playerHasWon(playerNumber, gameState)) {
winner = playerNumber;
return "break";
}
});
if (winner > -1) {
S.makeDialog("The " + colors[winner] + " player won!");
return true;
}
// checks if there's a stalemate
let stalemate = true;
S.forEach(options, function (xList) {
S.forEach(xList, function (option) {
S.forEach(size.z, function (_, index) {
currentLayer = index;
if (choiceAvailable(option)) {
stalemate = false;
}
});
});
});
if (stalemate) {
S.makeDialog("No more spaces are available.");
return true;
}
// checks if the next player can move
let canMove = false;
S.forEach(gameState, function (yList, xIndex) {
S.forEach(yList, function (zList, yIndex) {
S.forEach(zList, function (occupant, zIndex) {
if (occupant === -1) { // if the place is open
if (standbys[(currentPlayer + 1) % 4][zIndex].length > 0) { // if the next player can place a piece there
canMove = true;
}
}
});
});
});
if (!canMove) {
S.makeDialog("The next player can't move");
return true;
}
// says the game hasn't ended if execution got this far
return false;
}
function makeAMove(option) {
/**
moves one of a player's pieces to a space on the game board
*/
S.forEach(["top", "bottom", "left", "right"], function (side) {
currentPiece.style[side] = "auto"; // prevents irregularities from a value on a different side conflicting
});
currentPiece.style.left = "calc(" + option.style.left + " + var(--game-space-width) / 2 - " + currentPiece.style.width + " / 2)";
currentPiece.style.top = "calc(" + option.style.top + " + var(--game-space-width) / 2 - " + currentPiece.style.width + " / 2)";
gameState[option.dataset.xPosition][option.dataset.yPosition][currentLayer] = currentPlayer; // updates who's in the space
standbys[currentPlayer][currentLayer].splice(standbys[currentPlayer][currentLayer].indexOf(currentPiece), 1); // removes the current piece from the available options
currentPiece.style.pointerEvents = "none";
option.dataset["z" + currentLayer + "IsOpen"] = false;
currentPiece = null;
if (gameHasEnded()) {
S.getId("currentPlayer").style.left = "100%";
S.getId("gameScreen").style.pointerEvents = "none";
S.getId("employAI").disabled = "disabled";
} else {
showWhoseTurn();
}
}
function moveAPiece(playerNumber, x, y, z) {
currentPlayer = playerNumber;
let piece = standbys[playerNumber][z][0];
let dest = options[x][y];
S.forEach(["top", "bottom", "left", "right"], function (side) {
piece.style[side] = "auto"; // prevents irregularities from a value on a different side conflicting
});
piece.style.left = "calc(" + dest.style.left + " + var(--game-space-width) / 2 - " + piece.style.width + " / 2)";
piece.style.top = "calc(" + dest.style.top + " + var(--game-space-width) / 2 - " + piece.style.width + " / 2)";
gameState[x][y][z] = playerNumber; // updates who's in the space
standbys[playerNumber][z].splice(standbys[playerNumber][z].indexOf(piece), 1); // removes the current piece from the available options
piece.style.pointerEvents = "none";
dest.dataset["z" + z + "IsOpen"] = false;
piece = null;
if (gameHasEnded()) {
S.getId("currentPlayer").style.left = "100%";
S.getId("gameScreen").style.pointerEvents = "none";
S.getId("employAI").disabled = "disabled";
} else {
showWhoseTurn();
}
}
var Opponent = function (playerNumber) {
/**
Provides an artificial opponent to play against
*/
var opponent = this;
this.takeATurn = function () {
// finds all of the possible positions remaining
var optionsAvailable = [];
var optionWeights = [];
S.forEach(gameState, function (yList, xIndex) {
S.forEach(yList, function (zList, yIndex) {
S.forEach(zList, function (occupant, zIndex) {
if (occupant === -1) { // if the place is open
optionsAvailable.push({ x: xIndex, y: yIndex, z: zIndex });
// prefers middle pieces in the middle
let isCorner = (xIndex == 0 || xIndex == size.x - 1) && (yIndex == 0 || yIndex == size.y - 1);
if (isCorner) {
if (zIndex == 0 || zIndex == size.z - 1) {
optionWeights.push(2);
} else {
optionWeights.push(1);
}
} else {
if (zIndex == 0 || zIndex == size.z - 1) {
optionWeights.push(1);
} else {
optionWeights.push(2);
}
}
}
});
});
});
// checks whether it's possible to win
let canWin = false;
S.forEach(optionsAvailable, function (o, index) {
let potentialState = JSON.parse(JSON.stringify(gameState));
if (standbys[playerNumber][o.z].length > 0) { // if the player can place a piece there
potentialState[o.x][o.y][o.z] = playerNumber;
if (playerHasWon(playerNumber, potentialState)) {
optionWeights[index] = 1000;
canWin = true;
}
} else {
optionWeights[index] = 0;
}
});
// strategizes if a win isn't possible
if (!canWin) {
// sees if someone else is about to win
let blockNeeded = false;
let nextPlayer = playerNumber;
S.forEach(3, function (_, nextIndex) {
nextPlayer++;
nextPlayer %= 4;
let wins = 0;
S.forEach(optionsAvailable, function (o, index) {
let potentialState = JSON.parse(JSON.stringify(gameState));
if (standbys[nextPlayer][o.z].length > 0) { // if the next player can place a piece there
potentialState[o.x][o.y][o.z] = nextPlayer;
if (playerHasWon(nextPlayer, potentialState)) {
wins++;
if (standbys[playerNumber][o.z].length > 0) { // if the original player can place a piece there
if (wins > nextIndex) {
if (S.getId("dumberOpponent").checked) {
optionWeights[index] = 30;
} else {
optionWeights[index] = 1000;
}
blockNeeded = true;
} else {
optionWeights[index] = 3;
}
}
}
}
});
});
// plans ahead if it has the freedom to do so
if (!blockNeeded) {
//// strategy here
}
}
// makes a final decision on a move
let chosenMove = weightedRandomChoice(optionsAvailable, optionWeights);
moveAPiece(playerNumber, chosenMove.x, chosenMove.y, chosenMove.z);
}
};
S.listen("play", "click", function () {
// resets all of the variables
size = { // the size of the game board
x: 3,
y: 3,
z: 3
};
winScore = Math.min(size.x, size.y, size.z);
currentLayer = 0; // the current layer chosen, a.k.a. the type of piece chosen
standbys = [[], [], [], []]; // the unused game pieces for each player
options = []; // the potential places to put a game piece (contains the entity references)
currentPiece = null; // the currently selected game piece
currentPlayer = 0;
gameState = [];
players = 1; // the number of real players
colors = ["red", "green", "blue", "purple"]; // the color of the player pieces clockwise from bottom
piecesPerLayer = 3; // the number of pieces allowed per layer
// creates the game board
S.getId("gameScreen").innerHTML = "";
S.forEach(size.x, function (_, xIndex) {
options.push([]);
gameState.push([]);
S.forEach(size.y, function (_, yIndex) {
gameState[xIndex].push([]);
let square = document.createElement("div");
square.className = "playing-space generic-border";
square.style.left = "calc(var(--game-screen-width) / 2 + " + (xIndex - size.x / 2) + " * var(--game-space-width) + " + ((size.x - 1) / 2 - xIndex) + " * var(--game-space-border))";
square.style.top = "calc(var(--game-screen-width) / 2 + " + (yIndex - size.y / 2) + " * var(--game-space-width) + " + ((size.y - 1) / 2 - yIndex) + " * var(--game-space-border))";
/// middle of gameScreen + how many game spaces to move to either side + border correction
square.dataset.xPosition = xIndex;
square.dataset.yPosition = yIndex;
S.forEach(size.z, function (_, zIndex) {
gameState[xIndex][yIndex].push(-1);
square.dataset["z" + zIndex + "IsOpen"] = true;
});
options[xIndex].push(square);
S.getId("gameScreen").appendChild(square);
square.addEventListener("click", function () {
if (currentPiece !== null && choiceAvailable(this)) {
makeAMove(this);
}
});
});
});
// gives the players their pieces
S.forEach(4, function (_, playerIndex) {
S.forEach(size.z, function (_, layerIndex) {
standbys[playerIndex].push([]);
S.forEach(piecesPerLayer, function (_, pieceIndex) {
let piece = document.createElement("div");
piece.className = "game-piece";
piece.style.borderColor = colors[playerIndex];
piece.tabIndex = 0;
let pieceSize = "calc(" + (layerIndex + 1) + " * var(--game-space-width) * .75 / " + size.z + ")";
piece.style.width = pieceSize;
piece.style.height = pieceSize;
let horizontalOffset = "(" + Math.sin(2 * Math.PI * pieceIndex / piecesPerLayer) + " * var(--size-unit))";
piece.style[["left", "top", "right", "bottom"][playerIndex]] = "calc(var(--game-screen-width) / 2 + " + (layerIndex - size.x / 2) + " * var(--game-space-width) + var(--game-space-width) / 2 - " + pieceSize + " / 2 + " + horizontalOffset + ")";
/// middle of gameScreen + how many game spaces to move to either side + half a game space - half a piece width + circular offset
let verticalOffset = "(" + Math.cos(2 * Math.PI * pieceIndex / piecesPerLayer) + " * var(--size-unit))";
piece.style[["bottom", "left", "top", "right"][playerIndex]] = "calc(var(--size-unit) * 2 + (var(--game-space-width) - " + pieceSize + ") / 2 + " + verticalOffset + ")";
/// padding + piece alignment + circular offset
standbys[playerIndex][layerIndex].push(piece);
S.getId("gameScreen").appendChild(piece);
piece.addEventListener("click", function () {
currentPiece = this;
currentLayer = layerIndex;
currentPlayer = playerIndex;
});
piece.addEventListener("focus", function () {
piece.style.borderColor = "yellow";
});
piece.addEventListener("blur", function () {
piece.style.borderColor = colors[playerIndex];
});
});
});
});
// creates the box to show whose turn it is
let playerHighlight = document.createElement("div");
playerHighlight.id = "currentPlayer";
S.getId("gameScreen").appendChild(playerHighlight);
this.textContent = "Restart";
S.getId("gameScreen").style.pointerEvents = "auto";
S.getId("employAI").disabled = false;
});
S.listen("employAI", "click", function () {
new Opponent(currentPlayer).takeATurn();
});
</script>
<link rel="stylesheet" href="https://epicenterprograms.github.io/standards/formatting/foundation.css">
<link rel="stylesheet" href="https://epicenterprograms.github.io/standards/formatting/game.css">
<style>
#gameScreen {
--game-screen-width: 35rem;
--game-space-width: calc(var(--game-screen-width) / 6);
--game-space-border: calc(var(--game-screen-width) / 80);
--size-unit: calc(var(--game-screen-width) / 45);
position: relative;
width: var(--game-screen-width);
height: var(--game-screen-width);
overflow: hidden;
}
#currentPlayer {
position: absolute;
left: 100%;
border-width: var(--size-unit);
border-style: solid;
border-color: yellow;
}
.playing-space {
position: absolute;
z-index: 0;
border-width: var(--game-space-border);
width: var(--game-space-width);
height: var(--game-space-width);
cursor: pointer;
}
.game-piece {
position: absolute;
z-index: 1;
border-width: var(--size-unit);
border-style: solid;
border-radius: var(--game-space-width); /* just an abritrary number higher than will be ever used */
cursor: pointer;
transition: 1s;
}
@media (max-width: 1000px) {
main {
padding: 0em 1.25em 2em;
overflow: hidden;
}
#gameScreen {
--game-screen-width: 100vw;
margin-left: -1.25em;
}
}
</style>
</head>
<body>
<nav class="hidden-left-nav">
<iframe src="navigation.html"></iframe>
</nav>
<h1 class="main-title">
Otrio
</h1>
<main>
<section>
This game is basically 3-dimensional Tic-Tac-Toe. To win, get 3 pieces in one spot, 3 of the same size in a row, or 3 of increasing size in a row. Letting the AI take a turn will cause the program to automatically make a reasonably strategic move. When the AI isn't less likely to block wins, it should be next to impossible to sneak in a win, but the moment I stop paying attention and start pressing the button too much, people start winning somehow, so maybe you can get away with it.
</section>
<button id="play">
Play
</button>
<br>
<div class="generic-background" id="gameScreen"></div>
<br>
<button id="employAI" disabled>
Let AI take<br>a turn
</button>
<h2>
AI settings
</h2>
<input type="checkbox" id="dumberOpponent"> <label for="dumberOpponent">Make less likely to block wins</label>
</main>
</body>
</html>