-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathotrio.html
More file actions
878 lines (840 loc) · 34 KB
/
otrio.html
File metadata and controls
878 lines (840 loc) · 34 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
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
<!doctype html>
<html>
<head>
<title>
Games
</title>
<link rel="icon" href="Otrio favicon.ico">
<base target="_blank">
<script src="https://www.gstatic.com/firebasejs/4.6.1/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.6.1/firebase-firestore.js"></script>
<script src="https://epicenterprograms.github.io/standards/behavior/firebaseinit.js"></script>
<script src="https://epicenterprograms.github.io/standards/behavior/storage.js"></script>
<script src="https://epicenterprograms.github.io/standards/behavior/general.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
var messages = []; // messages shared by online players
var serverChecker; // an interval reference which checks for changes on the server
var lastSentData = 0; // the timestamp of the last time data was sent to the server
var messageBackground = Math.round(Math.random() * 360); // a random HSL hue to identify messages from this user
var messageBorder = Math.round(Math.random() * 360); // a random HSL hue to identify messages from this user
var blabbermouth; // the thing that could speak new incoming messages out loud
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 pieceRemains(playerNumber, pieceSize) {
/**
checks whether a player has any pieces left of a given size
*/
return standbys[playerNumber][pieceSize].length > 0;
}
function showWhoseTurn(increment = true) {
if (increment) {
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("employBot").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("employBot").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 = [];
var smartChoicePref = S.getId("dumberOpponent").checked ? 40 : 1000; // how much the smart choice should be preferred
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) { // if it's for a biggest or smallest piece
optionWeights.push(3);
} else {
optionWeights.push(1);
}
} else {
if (zIndex == 0 || zIndex == size.z - 1) { // if it's for a biggest or smallest piece
optionWeights.push(1);
} else {
optionWeights.push(3);
}
}
}
});
});
});
// checks whether it's possible to win
let canWin = false;
S.forEach(optionsAvailable, function (o, index) {
let potentialState = JSON.parse(JSON.stringify(gameState));
if (pieceRemains(playerNumber, o.z)) { // 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
//// needs to learn how to take into account whether a player is out of pieces to block with
let nextPlayer = playerNumber;
let winningMoves = []; // the places where anyone can win in the current round ({player: number, option: index})
let dangers = []; // the potential winning moves of other players
let extraWorries = []; // later potential winning moves (allows preferring double blocks)
let totalWins = 0; // the total possible wins for all players combined
let sneakyWins = []; // the ways a player can win even if blocking doesn't seem urgent
S.forEach(3, function (_, nextIndex) {
nextPlayer++;
nextPlayer %= 4;
let wins = 0; // the number of ways a given player can win
let winOptions = [];
S.forEach(optionsAvailable, function (o, index) {
let potentialState = JSON.parse(JSON.stringify(gameState));
if (pieceRemains(nextPlayer, o.z)) { // if the next player can place a piece there
potentialState[o.x][o.y][o.z] = nextPlayer;
if (playerHasWon(nextPlayer, potentialState)) {
winningMoves.push({ player: nextPlayer, option: index });
wins++;
totalWins++;
winOptions.push(index);
if (pieceRemains(playerNumber, o.z)) { // if the original player can place a piece there
optionWeights[index] = 4;
}
}
}
});
if (wins > nextIndex) { // if the ways of winning outnumber the number of people left to block
if (dangers.length == 0) { // if there isn't already a player going to win sooner
dangers = winOptions;
} else {
extraWorries = [...extraWorries, ...winOptions];
}
} else if (wins > 0) { // if the player might be able to sneak in a win
sneakyWins = winOptions;
}
});
if (totalWins > 2) { // if a player will be able to sneak in a win
extraWorries = [...extraWorries, ...sneakyWins];
}
if (totalWins > 3) { // if someone else is going to win no matter what
console.log("All is lost! (Probably)");
}
if (dangers.length > 0) { // if someone else is about to win
//// dangers = dangers.sort(() => Math.random() - 0.5); // randomizes which danger to address first
S.forEach(dangers, function (d) {
if (pieceRemains(playerNumber, optionsAvailable[d].z)) { // if the player can place a piece there
if (extraWorries.includes(d)) { // if the player can block multiple wins at once
optionWeights[d] = smartChoicePref * 10;
} else {
optionWeights[d] = smartChoicePref;
}
}
});
/// this should be made to prefer blocking where other players can't move
} else if (totalWins > 2) { // if there are too many ways to win for all future players to block
//// there should be double blocking here as well
S.forEach(sneakyWins, function (d) {
if (standbys[playerNumber][optionsAvailable[d].z].length > 0) { // if the player can place a piece there
optionWeights[d] = smartChoicePref;
}
});
} else {
let preoccupied = false; // if the opponent has other priorities
if (winningMoves.length > 0) { // if someone can win at some point
S.forEach(winningMoves, function (move) {
if (optionWeights[move.index] <= 20) { // if the opponent isn't already trying to move there
if (move.player == (playerNumber + 2) % 4) {
////
} else if (move.player == (playerNumber + 3) % 4) {
////
}
//// block possible wins that other players don't have the pieces to block
}
});
}
if (!preoccupied) {
// plans ahead if it has the freedom to do so
//// strategy here
}
}
}
// makes a final decision on a move
let chosenMove = weightedRandomChoice(optionsAvailable, optionWeights);
console.log(colors[playerNumber]);
console.log(optionWeights);
console.log(chosenMove);
console.log(optionWeights[optionsAvailable.indexOf(chosenMove)]);
moveAPiece(playerNumber, chosenMove.x, chosenMove.y, chosenMove.z);
// sends the updated game state to the server if necessary
if (hasGameCode("otrio")) {
sendData();
}
}
};
function resetBoard() {
// 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);
// sends the updated game state to the server if necessary
if (hasGameCode("otrio")) {
sendData();
}
}
});
});
});
// 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;
showWhoseTurn(false);
// sends the updated currentPlayer to the server if necessary
if (hasGameCode("otrio")) {
sendData();
}
});
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);
S.getId("gameScreen").style.pointerEvents = "auto";
S.getId("employBot").disabled = false;
}
S.listen("play", "click", function () {
resetBoard();
if (hasGameCode("otrio")) {
sendData();
}
this.textContent = "Restart";
});
function sendData() {
let data = {
gameState: JSON.stringify(gameState), // nested arrays aren't allowed to be stored
currentPlayer: currentPlayer,
messages: messages,
lastUpdated: new Date().getTime()
}
M.server.store("./", data).catch(function (error) {
S.makeDialog("There was a problem sending your data.");
console.error(error);
});
lastSentData = data.lastUpdated;
}
function updateGame(newState) {
if (JSON.stringify(newState) != JSON.stringify(gameState)) { // if the current display doesn't match what's on the server
let usedSpots = 0; // the number of spaces used according to the server
S.forEach(newState, function (yList, x) {
S.forEach(yList, function (zList, y) {
S.forEach(zList, function (playerNum, z) {
if (playerNum != -1) {
usedSpots++;
if (gameState[x][y][z] != playerNum) { // if a space is open that shouldn't be
moveAPiece(playerNum, x, y, z);
}
}
});
});
});
if (usedSpots == 0) { // if the game has been reset
resetBoard();
}
}
}
function updateMessages(providedMsgs) {
// create a Set of timestamps for quick lookup
const existingTimestamps = new Set(messages.map(msg => msg.timestamp));
// filter newMsgs to include only items that don't already exist
let newMsgs = providedMsgs.filter(msg => !existingTimestamps.has(msg.timestamp));
// add missing messages to the message board
S.forEach(newMsgs, function (msg) {
let msgBox = document.createElement("div");
msgBox.textContent = msg.text;
msgBox.innerHTML = msgBox.textContent.replace(/(^|[^:])\/\/(.+?)\/\//g, "$1<em>$2</em>").replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>").replace(/__(.+?)__/g, '<span style="text-decoration:underline">$1</span>').replace(/(https?:\/\/[^. \n]+(?:\.[^. \n]+)+)/g, "<a href='$1'>$1</a>");
msgBox.style.background = "hsla(" + msg.background + ", 100%, 50%, 50%)";
msgBox.style.borderColor = "hsla(" + msg.border + ", 100%, 50%, 50%)";
S.getId("messageBoard").prepend(msgBox);
if (blabbermouth) { // if the new message should be spoken
if (S.getId("messageDraft").value != msg.text) { // if the current user didn't type the message
blabbermouth.speak(msgBox.textContent);
}
}
});
messages = providedMsgs;
}
function alignWithServer(override) {
M.server.recall("./").then(function (data) {
if (data.lastUpdated > lastSentData || override) { // if the server data is newer than the local data
updateGame(JSON.parse(data.gameState));
currentPlayer = data.currentPlayer;
showWhoseTurn(false);
updateMessages(data.messages);
}
}).catch(function (error) {
console.error("There was an error syncing the game state.");
console.error(error);
});
}
function monitorStatus() {
if (hasGameCode("otrio")) {
serverChecker = setInterval(alignWithServer, 3000); // rechecks every 3 seconds
}
}
S.listen("setCodeButton", "click", function () {
setGameCode("otrio").then(function (status) {
if (status == "created") { // if starting with a new game code
S.getId("play").click();
monitorStatus();
} else if (status == "joined") { // if using a preexisting game code
resetBoard();
alignWithServer();
monitorStatus();
S.getId("play").textContent = "Restart";
} else if (status == "left") { // if the player left the specified game
if (serverChecker) {
clearInterval(serverChecker); // stops updating the game
}
}
});
});
S.listen("shareCodeButton", "click", function () {
if (hasGameCode("otrio")) {
let link = window.location.href.split("?")[0] + "?" +
S.http_build_query({ gc: M.session.recall("/games/otrio/game code") });
navigator.clipboard.writeText(link).then(function () {
S.makeDialog("Copied!");
}).catch(function (error) {
S.makeDialog("There was a problem copying the link.");
console.error(error);
});
} else {
navigator.clipboard.writeText(window.location.href.split("?")[0])
// S.makeDialog("You need to set a game code first.");
}
});
S.listen("realignWithServer", "click", function () { // puts everyone on the same page if something weird happened
if (hasGameCode("otrio")) {
clearInterval(serverChecker);
resetBoard();
alignWithServer(true); // align even if this device last updated the game
monitorStatus();
S.getId("play").textContent = "Restart";
}
});
function sendMessage() {
if (S.getId("messageDraft").value.trim()) { // if there's a message to send
let newMessage = {
text: S.getId("messageDraft").value.trim(),
background: messageBackground,
border: messageBorder,
timestamp: new Date().getTime()
};
M.server.recall("messages").then(function (serverMsgs) {
serverMsgs.push(newMessage);
Promise.all([
M.server.store("messages", serverMsgs),
M.server.store("lastUpdated", new Date().getTime())
]).catch(function (error) {
S.makeDialog("There was a problem sending your message.");
console.error("The messages couldn't be stored.");
console.error(error);
});
}).catch(function (error) {
S.makeDialog("There was a problem sending your message.");
console.error("The messages couldn't be recalled.");
console.error(error);
});
updateMessages([...messages, newMessage]);
messages.push(newMessage);
S.getId("messageDraft").value = "";
}
}
S.listen("sendMessage", "click", sendMessage);
S.listen("messageDraft", "keyup", function (event) {
if (event.key == "Enter") {
sendMessage();
}
});
S.listen("msgBgColor", "input", function () {
messageBackground = this.value;
S.getId("msgSample").style.background = "hsla(" + messageBackground + ", 100%, 50%, 50%)";
this.style.accentColor = "hsla(" + messageBackground + ", 100%, 50%, 50%)";
});
S.listen("msgBdColor", "input", function () {
messageBorder = this.value;
S.getId("msgSample").style.borderColor = "hsla(" + messageBorder + ", 100%, 50%, 50%)";
this.style.accentColor = "hsla(" + messageBorder + ", 100%, 50%, 50%)";
});
S.listen("speakMessages", "click", function () {
if (this.checked) {
blabbermouth = new S.Speaker();
} else {
blabbermouth = undefined;
}
});
S.listen("employBot", "click", function () {
new Opponent(currentPlayer).takeATurn();
});
S.onLoad(function () {
tryLoadingGame("otrio");
S.getId("msgBgColor").value = messageBackground;
S.getId("msgBdColor").value = messageBorder;
S.getId("msgBgColor").dispatchEvent(new Event("input"));
S.getId("msgBdColor").dispatchEvent(new Event("input"));
if (window.location.href.includes("?")) { // if there's data in the URL
let data = S.parse_str(window.location.href);
if (data.hasOwnProperty("gc")) { // if the game code is in the URL
S.getId("gameCodeInput").value = data.gc;
setGameCode("otrio", data.gc, { fromURL: true }).then(function (status) {
if (status == "joined") { // if joining an existing game
resetBoard();
alignWithServer();
monitorStatus();
S.getId("play").textContent = "Restart";
} else { // if the game code couldn't be found
S.getId("gameCodeInput").value = "";
}
});
}
}
});
</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;
}
.playing-space::before { /* adds snowflakes in the game spaces */
content: "\2744\fe0f";
display: none; /* hides the snowflakes */
position: absolute;
left: 0rem;
top: 0rem;
font-size: calc(var(--game-space-width) / 1.5);
opacity: .5;
}
.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;
}
#messageBoard {
width: 80%;
height: 9em;
overflow: auto;
}
#messageBoard div {
display: block;
margin: .5em;
border-width: .25em;
border-radius: .5em;
border-style: solid;
padding: .5em;
}
#msgSample {
display: block;
border-width: .2em;
border-style: solid;
width: 1em;
height: 1em;
}
@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.
</section>
<section>
Letting the bot take a turn will cause the program to automatically make a reasonably strategic move. When the bot isn't less likely to block wins, it's rather difficult to sneak in a win, but sometimes strategy (or luck) can win out. Also, the bot will always block the person who's going to win the soonest, and it currently isn't able to take into account whether a following player won't have the proper piece to block a player from winning, so maybe you can use that to your advantage.
</section>
<section>
Setting a game code allows you to play with others online who use the same save code, and it allows you to message them as well. Pieces aren't assigned to specific players, so any piece can be moved by anyone. Also, although it shouldn't be a problem if you play the game right, there's likely to be an issue if two people playing the same game try to make a move at nearly the same time. Make sure the people you play with aren't troublemakers. Game codes are automatically cleared after 48 hours of inactivity.
</section>
<section style="text-align:center">
<input type="text" id="gameCodeInput" placeholder="Game code">
<button id="setCodeButton">
Submit game code
</button>
<br>
<button id="shareCodeButton">
Copy link to game
</button>
<button id="realignWithServer">
Realign with server
</button>
</section>
<button id="play">
Play
</button>
<button id="employBot" disabled>
Let the bot<br>take a turn
</button>
<br>
<div class="generic-background" id="gameScreen"></div>
<h3>
Message board
</h3>
<div class="generic-background" id="messageBoard"></div>
<br>
<input type="text" id="messageDraft" placeholder="Type your message">
<button id="sendMessage">
Send
</button>
<section>
(Your colors = <div class="generic-background" style="margin-bottom:-.2em"><span id="msgSample"></span></div>)
</section>
<table class="labeled-list">
<tr>
<th>Background color:</th>
<td><input type="range" min="0" max="360" id="msgBgColor"></td>
</tr>
<tr>
<th>Border color:</th>
<td><input type="range" min="0" max="360" id="msgBdColor"></td>
</tr>
</table>
<section>
<span class="elaborate" style="text-align:center; text-decoration:dotted underline;">[Learn how to make special formatting]</span>
</section>
<aside data-heading="Formatting help">
<h3>Italics</h3>
<section>Surround the word or words to be italicized with two slashes.</section>
<section>//Stuff// = <em>Stuff</em></section>
<h3>Bolding</h3>
<section>Surround the word or words to be bolded with two asterisks.</section>
<section>**Stuff** = <strong>Stuff</strong></section>
<h3>Underlining</h3>
<section>Surround the word or words to be underlined with two underscores.</section>
<section>__Stuff__ = <span style="text-decoration:underline">Stuff</span></section>
<h3>Combining</h3>
<section>Text can have more than one type of formatting as long as the markup doesn't have to cross any other markup. (Treat them like parentheses.)</section>
<section>//**__Stuff__**// = <em><strong><span style="text-decoration:underline">Stuff</span></strong></em></section>
<section><del style="color:red">//**__Stuff//**__</del></section>
<section>//**Stuff**// **and stuffity stuff** = <em><strong>Stuff</strong></em> <strong>and stuffity stuff</strong></section>
<section>**//Stuff// and stuffity stuff** = <strong><em>Stuff</em> and stuffity stuff</strong></section>
<section><del style="color:red">//**Stuff// and stuffity stuff**</del></section>
<h3>Other</h3>
<section>Full links will become clickable.</section>
<section>https://coolprogramminguser.github.io/games/ = <a href="https://coolprogramminguser.github.io/games/">https://coolprogramminguser.github.io/games/</a></section>
</aside>
<input type="checkbox" id="speakMessages">
<label for="speakMessages">Say new messages out loud</label>
<br>
<br>
<h2>
Bot settings
</h2>
<input type="checkbox" id="dumberOpponent"> <label for="dumberOpponent">Make less likely to block wins</label>
</main>
</body>
</html>