-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
1263 lines (1132 loc) · 45.9 KB
/
Copy pathscript.js
File metadata and controls
1263 lines (1132 loc) · 45.9 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
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const API_KEY = "";
let colorMode = "dark";
let mobileFriendly = false;
let mode = "";
let previousInputs = [];
let currentIndex = 0;
let generationHistory = []; // Store generate command history
// On page load initializers and event listeners.
document.addEventListener("DOMContentLoaded", function () {
document.querySelector(".input-field").focus();
document.getElementById("commandInput").value = "";
appendNewlines(init);
if (
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
navigator.userAgent
)
) {
mobileFriendly = true;
} else {
const dark = document.querySelectorAll(".dark");
for (let i = 0; i < dark.length; i++) {
dark[i].classList.add("mf");
}
}
// Event listeners for the input field
document
.querySelector(".input-field")
.addEventListener("keydown", function (event) {
// Change input value based on prior inputs
if (event.key === "ArrowUp") {
event.preventDefault();
if (currentIndex > 0) {
currentIndex--;
document.querySelector(".input-field").value =
previousInputs[currentIndex];
}
} else if (event.key === "ArrowDown") {
event.preventDefault();
if (currentIndex < previousInputs.length - 1) {
currentIndex++;
document.querySelector(".input-field").value =
previousInputs[currentIndex];
} else {
// If at the end, clear the input field
currentIndex = previousInputs.length;
document.querySelector(".input-field").value = "";
}
}
});
// Add event listener for form submission
document
.querySelector(".input-container")
.addEventListener("submit", function (event) {
event.preventDefault();
const inputValue = document.getElementById("commandInput").value;
// Logic for adding element to the page
if (inputValue.trim() !== "") {
const outputElement = document.createElement("div");
outputElement.textContent = "> " + inputValue;
previousInputs.length === 0 ||
previousInputs[previousInputs.length - 1] !== inputValue
? previousInputs.push(inputValue)
: null;
currentIndex = previousInputs.length;
outputElement.classList.add("terminal-input");
document.querySelector(".body").appendChild(outputElement);
checkInput(inputValue);
document.getElementById("commandInput").value = "";
window.scrollTo(0, document.body.scrollHeight);
}
// Refocus input field
document.querySelector(".input-field").focus();
});
});
// Add encoding/decoding functionality
const cols = ['D', 'E', 'V'];
const rows = ['A', 'R', 'T'];
const coordList = [];
for (const row of rows) {
for (const col of cols) {
coordList.push(col + row);
}
}
const mapping = {};
coordList.forEach((coord, i) => mapping[i] = coord);
function letterToNum(letter) {
return letter.toUpperCase().charCodeAt(0) - 'A'.charCodeAt(0) + 1;
}
function numToLetter(num) {
return String.fromCharCode(num + 'A'.charCodeAt(0) - 1);
}
function toBase9(n) {
if (n === 0) return "0";
let digits = [];
while (n) {
digits.push(String(n % 9));
n = Math.floor(n / 9);
}
return digits.reverse().join("");
}
function decodeMessage(encodedMessage) {
// Create reverse mapping dictionary
const reverseMapping = {};
Object.entries(mapping).forEach(([k, v]) => reverseMapping[v] = k);
// Convert coordinate values back to base 9 numbers
const base9Nums = [];
for (const coord of encodedMessage) {
// Split into pairs of coordinates
const first = coord.substring(0, 2);
const second = coord.substring(2, 4);
// Convert each coordinate to its digit
base9Nums.push(reverseMapping[first] + reverseMapping[second]);
}
// Convert base 9 numbers back to decimal
const decimalNums = base9Nums.map(num => parseInt(num, 9));
// Convert numbers back to letters
const decoded = decimalNums.map(num => numToLetter(num));
// Join letters into final message
return decoded.join('');
}
function isEncodedPattern(text) {
// Clean the input by removing any extra whitespace
const cleanedText = text.trim().replace(/\s+/g, ' ');
const pattern = /^([DEV][ART]){2}( ([DEV][ART]){2})*$/;
return pattern.test(cleanedText);
}
// Modify the checkInput function to include automatic decoding
function checkInput(input) {
const i = input.toLowerCase();
if (mode == "") {
// Check for encoded pattern before other commands
if (isEncodedPattern(input)) {
const decoded = decodeMessage(input.split(' '));
appendNewlines(`${decoded}`);
return;
}
if (isMathematicalOperator(i)) {
performMath(i);
} else if (i === "h") {
appendNewlines(commands);
} else if (i === "help") {
appendNewlines(commands + "\n \n" + help);
} else if (i === "weather" || i === "wttr" || i === "w") {
getWeather();
} else if (i === "projects" || i === "project" || i === "p") {
appendNewlines(projects);
} else if (i === "contacts" || i === "contact" || i === "co") {
appendNewlines(contacts);
} else if (i === "higher-or-lower" || i === "hl") {
runMode("higher-or-lower");
} else if (i === "rock-paper-scissors" || i === "rps") {
runMode("rock-paper-scissors");
} else if (i === "blackjack" || i === "b") {
runMode("blackjack");
} else if (i === "hangman" || i === "hm") {
runMode("hangman");
} else if (i === "tic-tac-toe" || i === "ttt") {
runMode("tic-tac-toe");
} else if (i.includes("generate")) {
document.querySelector(".input-field").disabled = true;
const userQuery = i.replace("generate ", "").trim();
// Prepare the conversation history for context
let contents = [];
// Add previous conversation history if it exists
if (generationHistory.length > 0) {
contents = generationHistory.slice();
}
// Add the current user query
contents.push({ role: "user", parts: [{ text: userQuery }] });
fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${API_KEY}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ contents: contents })
}).then(response => response.json()).then(data => {
const modelResponse = data.candidates[0].content.parts[0].text;
appendNewlines(modelResponse, "lightblue");
// Store the conversation history
generationHistory.push({ role: "user", parts: [{ text: userQuery }] });
generationHistory.push({ role: "model", parts: [{ text: modelResponse }] });
// Limit conversation history to last 10 exchanges (5 turns)
if (generationHistory.length > 10) {
generationHistory = generationHistory.slice(generationHistory.length - 10);
}
document.querySelector(".input-field").disabled = false;
document.querySelector(".input-field").focus();
}).catch(error => {
appendNewlines("Error generating response: " + error, "red");
document.querySelector(".input-field").disabled = false;
document.querySelector(".input-field").focus();
});
} else if (i === "invert" || i === "i") {
invertPage();
} else if (i === "mobile-friendly" || i === "mf") {
switchMobileFriendly();
} else if (i === "clear" || i === "c") {
clearPage();
} else {
appendNewlines(error);
}
} else {
runMode(input);
}
}
// Run specific program which requires user feedback
let number = -1;
let secondaryNumber = 0;
let sentence = "";
let savedSentence = "";
let lettersUsed = [];
let deck = createDeck();
let hands = []
let ticTacToeState = [];
function runMode(input) {
// Determine input or if user wishes to exit
if (input === "exit") {
mode = "";
number = -1;
appendNewlines("Exiting.");
} else {
if (mode === "") {
switch (input) {
case "higher-or-lower":
mode = "higher-or-lower";
break;
case "rock-paper-scissors":
mode = "rock-paper-scissors";
break;
case "blackjack":
mode = "blackjack";
break;
case "hangman":
mode = "hangman";
break;
case "tic-tac-toe":
mode = "tic-tac-toe";
break;
}
}
// Run program based on mode
switch (mode) {
// Player Higher or Lower
case "higher-or-lower":
if (number == -1) {
number = Math.floor(Math.random() * 100) + 1;
secondaryNumber = 0;
appendNewlines(
"Playing Higher or Lower. Type \"exit\" to exit.\nGuess a number between 1 and 100."
);
} else {
const value = parseInt(input, 10);
if (!isNaN(value) && value >= 1 && value <= 100) {
if (value > number) {
secondaryNumber += 1;
appendNewlines("The number is lower.");
} else if (value < number) {
secondaryNumber += 1;
appendNewlines("The number is higher.");
} else {
if(secondaryNumber < getStoredScore("hl") || isNaN(getStoredScore("hl"))) {
storeScore("hl", secondaryNumber);
appendNewlines(`New High Score!`);
appendNewlines(`You got the number in ${secondaryNumber} guesses!\nExiting.`);
} else {
appendNewlines(`You got the number in ${secondaryNumber} guesses!`);
}
number = -1;
mode = "";
}
} else {
appendNewlines("Please enter a number between 1 and 100.");
}
}
break;
// Play Rock Paper Scissors
case "rock-paper-scissors":
if(isNaN(getStoredScore("rps"))) {
storeScore("rps", 0);
}
if (number == -1) {
number = Math.floor(Math.random() * 3) + 1;
appendNewlines(
"Playing Rock, Paper, Scissors. Type \"exit\" to exit.\nRock (1), Paper (2), or Scissors (3)?"
);
} else {
const value = parseInt(input, 10);
if (!isNaN(value) && value >= 1 && value <= 3) {
if (value == 1) {
if (number == 1) {
appendNewlines(`Rock vs. Rock\nIt's a tie!\nScore: ${getStoredScore("rps")}\nRock (1), Paper (2), or Scissors (3)?`);
} else if (number == 2) {
storeScore("rps", (getStoredScore("rps") - 1));
appendNewlines(`Rock vs. Paper\nYou lose!\nScore: ${getStoredScore("rps")}\nRock (1), Paper (2), or Scissors (3)?`);
} else {
storeScore("rps", (getStoredScore("rps") + 1));
appendNewlines(`Rock vs. Scissors\nYou win!\nScore: ${getStoredScore("rps")}\nRock (1), Paper (2), or Scissors (3)?`);
}
} else if (value == 2) {
if (number == 1) {
storeScore("rps", (getStoredScore("rps") + 1));
appendNewlines(`Paper vs. Rock\nYou win!\nScore: ${getStoredScore("rps")}\nRock (1), Paper (2), or Scissors (3)?`);
} else if (number == 2) {
appendNewlines(`Paper vs. Paper\nIt's a tie!\nScore: ${getStoredScore("rps")}\nRock (1), Paper (2), or Scissors (3)?`);
} else {
storeScore("rps", (getStoredScore("rps") - 1));
appendNewlines(`Paper vs. Scissors\nYou lose!\nScore: ${getStoredScore("rps")}\nRock (1), Paper (2), or Scissors (3)?`);
}
} else {
if (number == 1) {
storeScore("rps", (getStoredScore("rps") - 1));
appendNewlines(`Scissors vs. Rock\nYou lose!\nScore: ${getStoredScore("rps")}\nRock (1), Paper (2), or Scissors (3)?`);
} else if (number == 2) {
storeScore("rps", (getStoredScore("rps") + 1));
appendNewlines(`Scissors vs. Paper\nYou win!\nScore: ${getStoredScore("rps")}\nRock (1), Paper (2), or Scissors (3)?`);
} else {
appendNewlines(`Scissors vs. Scissors\nIt's a tie!\nScore: ${getStoredScore("rps")}\nRock (1), Paper (2), or Scissors (3)?`);
}
}
number = Math.floor(Math.random() * 3) + 1;
} else {
appendNewlines("Please enter a number between 1 and 3.");
}
}
break;
// Play Blackjack
case "blackjack":
if (number === -1) {
if(isNaN(getStoredScore("b"))) {
storeScore("b", 0);
}
number = 0;
appendNewlines("Playing Blackjack.")
deck = createDeck();
shuffleArray(deck);
hands = dealCards(deck, 2, 2);
const dealerHand = hands[0];
const playerHand = hands[1];
const playerTotal = getHandTotal(playerHand);
const dealerTotal = getHandTotal(dealerHand);
if(playerTotal === 21 || dealerTotal === 21) {
appendNewlines("Dealer hand: " + convertHandToString(dealerHand));
appendNewlines("Player hand: " + convertHandToString(playerHand));
if(playerTotal === 21 && dealerTotal !== 21) {
storeScore("b", getStoredScore("b") + 1)
appendNewlines(`Blackjack! You win!\nScore: ${getStoredScore("b")}\nPlay Again? (Y/N):`);
} else if (playerHand !== 21 && dealerTotal === 21) {
storeScore("b", getStoredScore("b") - 1)
appendNewlines(`Dealer 21!\nScore: ${getStoredScore("b")}\nPlay Again? (Y/N):`);
} else if (playerHand === 21 && dealerTotal === 21) {
appendNewlines(`Dealer/Player Blackjack!\nScore: ${getStoredScore("b")}\nPlay Again? (Y/N):`);
}
number = 2;
} else {
appendNewlines(`Dealer showing: ${dealerHand[0].rank}`);
appendNewlines(`Player hand: ${playerHand[0].rank}, ${playerHand[1].rank}`);
appendNewlines("Hit (H) or Stand (S)?");
}
} else if (number === 0) {
const dealerHand = hands[0];
const playerHand = hands[1];
if(input.toLowerCase() === "h") {
const newCard = deck.pop();
playerHand.push(newCard);
const score = getHandTotal(playerHand);
if(score === 21) {
appendNewlines(`Dealer showing: ${dealerHand[0].rank}`);
appendNewlines("Player hand: " + convertHandToString(playerHand));
appendNewlines("Total 21, standing.");
runMode("s");
} else if(score > 21) {
appendNewlines("Dealer hand: " + convertHandToString(dealerHand));
appendNewlines("Player hand: " + convertHandToString(playerHand));
storeScore("b", getStoredScore("b") - 1)
appendNewlines(`Bust! You lose!\nScore : ${getStoredScore("b")}\nPlay Again? (Y/N)`);
number = 2;
} else {
appendNewlines(`Dealer showing: ${dealerHand[0].rank}`);
appendNewlines("Player hand: " + convertHandToString(playerHand));
appendNewlines("Hit (H) or Stand (S)?")
}
} else if (input.toLowerCase() === "s") {
let dealerScore = getHandTotal(dealerHand);
while(dealerScore < 17) {
const newCard = deck.pop();
dealerHand.push(newCard);
dealerScore = getHandTotal(dealerHand);
}
const playerScore = getHandTotal(playerHand);
appendNewlines("Dealer Hand: " + convertHandToString(dealerHand));
appendNewlines("Player Hand: " + convertHandToString(playerHand));
if(dealerScore > 21) {
storeScore("b", getStoredScore("b") + 1)
appendNewlines(`Dealer bust! You win!\nScore : ${getStoredScore("b")}\nPlay Again? (Y/N)`);
number = 2;
} else if(dealerScore > playerScore) {
storeScore("b", getStoredScore("b") - 1)
appendNewlines(`Dealer wins!\nScore : ${getStoredScore("b")}\nPlay Again? (Y/N)`);
number = 2;
} else if(dealerScore < playerScore) {
storeScore("b", getStoredScore("b") + 1)
appendNewlines(`You win!\nScore : ${getStoredScore("b")}\nPlay Again? (Y/N)`);
number = 2;
} else {
appendNewlines(`It's a tie!\nScore : ${getStoredScore("b")}\nPlay Again? (Y/N)`);
number = 2;
}
} else {
appendNewlines("Invalid input, Hit (H) or Stand (S)?")
}
} else if(number === 2) {
if(input.toLowerCase() === "y") {
number = -1;
runMode("blackjack");
} else if(input.toLowerCase() === "n") {
number = -1;
mode = "";
appendNewlines("Exiting Blackjack.");
} else {
appendNewlines("Invalid input, Play Again? (Y/N)");
}
}
break;
case "hangman":
if(isNaN(getStoredScore("hm"))) {
storeScore("hm", 0);
}
if(number === -1) {
number = 0;
secondaryNumber = 0;
sentence = "";
lettersUsed = [];
savedSentence = generateHangmanSentence();
for (let i = 0; i < savedSentence.length; i++) {
if(savedSentence[i] !== " ") {
sentence += "_ ";
} else {
sentence += " ";
}
}
appendNewlines("Playing Hangman. Type \"exit\" to exit.\n+---+\n | |\n | \n | \n | \n | \n-\n" + sentence);
} else if(number === 0) {
const letter = input.toLowerCase();
if(letter.length === 1) {
if(lettersUsed.includes(letter)) {
appendNewlines("You've already used this letter. Try again.");
} else {
lettersUsed.push(letter);
if(savedSentence.includes(letter)) {
let newSentence = "";
for (let i = 0; i < savedSentence.length; i++) {
const currentChar = savedSentence[i];
if (lettersUsed.includes(currentChar.toLowerCase())) {
newSentence += currentChar + " ";
} else if (currentChar === ' ') {
newSentence += ' ';
} else {
newSentence += '_ ';
}
}
sentence = newSentence;
if(sentence.indexOf("_") === -1) {
storeScore("hm", getStoredScore("hm") + 1);
appendNewlines("You win!\n" + sentence + "\nScore: " + getStoredScore("hm") + "\nPlay again? (Y/N)");
number = 2;
} else {
appendNewlines("Correct!\n" + sentence);
}
} else {
secondaryNumber += 1;
if(secondaryNumber === 1) {
appendNewlines("The sentence does not contain \"" + letter + "\"\n" + sentence + "\n+---+\n | |\n | O\n | \n | \n | \n-\n");
} else if(secondaryNumber === 2) {
appendNewlines("The sentence does not contain \"" + letter + "\"\n" + sentence + "\n+---+\n | |\n | O\n | |\n | \n | \n-\n");
} else if(secondaryNumber === 3) {
appendNewlines("The sentence does not contain \"" + letter + "\"\n" + sentence + "\n+---+\n | |\n | O\n | \\|\n | \n | \n-\n");
} else if(secondaryNumber === 4) {
appendNewlines("The sentence does not contain \"" + letter + "\"\n" + sentence + "\n+---+\n | |\n | O\n | \\|/\n | \n | \n-\n");
} else if(secondaryNumber === 5) {
appendNewlines("The sentence does not contain \"" + letter + "\"\n" + sentence + "\n+---+\n | |\n | O\n | \\|/\n | /\n | \n-\n");
} else if(secondaryNumber === 6) {
storeScore("hm", getStoredScore("hm") - 1);
appendNewlines("The sentence does not contain \"" + letter + "\"\n" + sentence +
"\n+---+\n | |\n | O\n | \\|/\n | / \\\n | \n-\nYou lose!\nScore: " + getStoredScore("hm") + "\nThe sentence was: " +
savedSentence + "\nPlay again? (Y/N)");
number = 2;
}
}
}
} else {
appendNewlines("Please enter a single letter.");
}
} else if(number === 2) {
if(input.toLowerCase() === "y") {
number = -1;
runMode("hangman");
} else if(input.toLowerCase() === "n") {
number = -1;
mode = "";
appendNewlines("Exiting Hangman.");
} else {
appendNewlines("Invalid input, Play Again? (Y/N)");
}
}
break;
case "tic-tac-toe":
if(number === -1) {
if(isNaN(getStoredScore("ttt"))) {
storeScore("ttt", 0);
}
ticTacToeState = Array(9).fill('-');
appendNewlines("Playing Tic-Tac-Toe.\n | | \n-----\n | | \n-----\n | | \nYou are X.\nChoose the index to play (1-9).");
number = 0;
} else if(number === 0) {
const index = parseInt(input) - 1;
if(!isNaN(index) && index >= 0 && index < 9 && ticTacToeState[index] === "-") {
ticTacToeState[index] = "X";
let winner = checkWinner(ticTacToeState);
let isBoardFull = !ticTacToeState.includes('-');
if(isNaN(winner) && !isBoardFull) {
// AI makes a move using minimax
const nextActionIndex = findBestMove(ticTacToeState);
ticTacToeState[nextActionIndex] = "O";
let ticTacToeBoard = formatTicTacToeBoard(ticTacToeState);
winner = checkWinner(ticTacToeState);
if(isNaN(winner) && ticTacToeState.includes('-')) {
appendNewlines("You chose index " + (index + 1) + ".\nThe AI chose index " + (nextActionIndex + 1) + "\n" + ticTacToeBoard + "\nChoose the index to play (1-9).");
} else {
let resultMessage = "";
if(!isNaN(winner)) {
let icon = winner === 0 ? "X" : "O";
storeScore("ttt", getStoredScore("ttt") + (winner === 0 ? 1 : -1));
resultMessage = icon + " wins!\nScore: " + getStoredScore("ttt");
} else {
resultMessage = "It's a draw!\nScore: " + getStoredScore("ttt");
}
appendNewlines("You chose index " + (index + 1) + ".\nThe AI chose index " + (nextActionIndex + 1) + "\n" + ticTacToeBoard + "\n" + resultMessage + "\nPlay again? (Y/N)");
number = 1;
}
} else {
let ticTacToeBoard = formatTicTacToeBoard(ticTacToeState);
let resultMessage = "";
if(!isNaN(winner)) {
let icon = winner === 0 ? "X" : "O";
storeScore("ttt", getStoredScore("ttt") + (winner === 0 ? 1 : -1));
resultMessage = icon + " wins!\nScore: " + getStoredScore("ttt");
} else {
resultMessage = "It's a draw!\nScore: " + getStoredScore("ttt");
}
appendNewlines("You chose index " + (index + 1) + ".\n" + ticTacToeBoard + "\n" + resultMessage + "\nPlay again? (Y/N)");
number = 1;
}
} else {
appendNewlines("Invalid move. Please choose an empty position (1-9).");
}
} else if(number === 1) {
if(input.toLowerCase() === "y") {
number = -1;
runMode("tic-tac-toe");
} else if(input.toLowerCase() === "n") {
number = -1;
mode = "";
appendNewlines("Exiting Tic-Tac-Toe.");
} else {
appendNewlines("Invalid input, Play Again? (Y/N)");
}
}
default:
break;
}
}
}
// Format the Tic-Tac-Toe board for display
function formatTicTacToeBoard(board) {
let formattedBoard = "";
for (let i = 0; i < board.length; i++) {
if(i % 3 === 0) {
if(i !== 0) {
formattedBoard = formattedBoard.slice(0, -1); // Only remove the trailing pipe at end of row
formattedBoard += "\n-----\n";
}
}
if(board[i] !== "-") {
formattedBoard += board[i] + "|";
} else {
formattedBoard += " |";
}
}
return formattedBoard.slice(0, -1); // Remove the final trailing pipe
}
function checkWinner(board) {
const winningCombinations = [
// Rows
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
// Columns
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
// Diagonals
[0, 4, 8],
[2, 4, 6],
];
for (const combination of winningCombinations) {
const [a, b, c] = combination;
if (board[a] !== '-' && board[a] === board[b] && board[b] === board[c]) {
if (board[a] === "X") {
return 0
} else {
return 1
} // Return the winning player symbol
}
}
return NaN; // No winner yet
}
// Minimax algorithm for Tic-Tac-Toe
function minimax(board, depth, isMaximizing) {
// Check for terminal states
const winner = checkWinner(board);
// If X wins (player)
if (winner === 0) return -10 + depth;
// If O wins (AI)
if (winner === 1) return 10 - depth;
// If draw
if (!board.includes('-')) return 0;
if (isMaximizing) {
let bestScore = -Infinity;
for (let i = 0; i < board.length; i++) {
if (board[i] === '-') {
board[i] = 'O';
let score = minimax(board, depth + 1, false);
board[i] = '-';
bestScore = Math.max(score, bestScore);
}
}
return bestScore;
} else {
let bestScore = Infinity;
for (let i = 0; i < board.length; i++) {
if (board[i] === '-') {
board[i] = 'X';
let score = minimax(board, depth + 1, true);
board[i] = '-';
bestScore = Math.min(score, bestScore);
}
}
return bestScore;
}
}
// Find the best move for the AI
function findBestMove(board) {
let bestScore = -Infinity;
let bestMove = -1;
// Add some randomness for first move to make game more interesting
const emptySpaces = board.reduce((acc, cell, index) => {
if (cell === '-') acc.push(index);
return acc;
}, []);
// If it's the first move (8 or 9 empty spaces), choose randomly with 80% chance
if (emptySpaces.length >= 8 && Math.random() < 0.8) {
return emptySpaces[Math.floor(Math.random() * emptySpaces.length)];
}
for (let i = 0; i < board.length; i++) {
if (board[i] === '-') {
board[i] = 'O';
let score = minimax(board, 0, false);
board[i] = '-';
if (score > bestScore) {
bestScore = score;
bestMove = i;
}
}
}
return bestMove;
}
function generateHangmanSentence() {
const subjects = ['The cat', 'A dog', 'My friend', 'The sun', 'A bird', 'A robot', 'The ocean', 'The moon', 'The woman', 'A man', 'The child', 'Superman', 'DevArtech', 'The student'];
const verbs = ['runs', 'jumps', 'sleeps', 'flies', 'sings', 'dances', 'laughs', 'swims', 'studies', 'writes', 'plays', 'climbs', 'eats'];
const objects = ['in the garden', 'on the roof', 'under the table', 'over the rainbow', 'through the forest', 'on the beach', 'in the sky', 'between the mountains', 'in the house', 'with the man', 'with the cat', 'with the dog', 'on the tree'];
const subject = subjects[Math.floor(Math.random() * subjects.length)];
const verb = verbs[Math.floor(Math.random() * verbs.length)];
const object = objects[Math.floor(Math.random() * objects.length)];
const sentence = subject + " " + verb + " " + object;
return sentence;
}
function storeScore(index, integerValue) {
// Check if localStorage is supported by the browser
if (typeof(Storage) !== "undefined") {
localStorage.setItem(index, integerValue);
} else {
console.log("localStorage is not supported in this browser.");
}
}
function getStoredScore(index) {
// Check if localStorage is supported by the browser
if (typeof(Storage) !== "undefined") {
// Retrieve the stored value, or set a default value if it doesn't exist
let storedInteger = localStorage.getItem(index) || NaN;
return parseInt(storedInteger);
} else {
console.log("localStorage is not supported in this browser.");
return NaN;
}
}
function convertHandToString(hand) {
let handString = "";
for (let i = 0; i < hand.length; i++) {
const card = hand[i];
handString += card.rank + ", ";
}
return handString;
}
function getHandTotal(hand) {
let total = 0;
for (let i = 0; i < hand.length; i++) {
const card = hand[i];
if (card.rank === "J" || card.rank === "Q" || card.rank === "K") {
total += 10;
} else if (card.rank === "A") {
if(total + 11 > 21) {
total += 1;
} else {
total += 11;
}
} else {
total += parseInt(card.rank, 10);
}
}
return total;
}
// Logic for Blackjack
// Create the unshuffled deck
function createDeck() {
const ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'];
const suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades'];
const deck = [];
for (const suit of suits) {
for (const rank of ranks) {
deck.push({ rank, suit });
}
}
return deck;
}
// Shuffle the deck
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
// Deal cards to the players
function dealCards(deck, numPlayers, cardsPerPlayer) {
const hands = [];
// Initialize empty hands for each player
for (let i = 0; i < numPlayers; i++) {
hands.push([]);
}
// Deal cards to players
for (let i = 0; i < cardsPerPlayer; i++) {
for (let j = 0; j < numPlayers; j++) {
const card = deck.pop();
hands[j].push(card);
}
}
return hands;
}
// Determine if input is a mathematical expression
function isMathematicalOperator(input) {
const expression = /^(?:\d|\()/;
return expression.test(input);
}
// Perform math for a mathematical expression
function performMath(expression) {
const precedence = {
"+": 1,
"-": 1,
"*": 2,
"/": 2,
"^": 3,
};
function applyOperator(operator, operand1, operand2) {
if (operator === "/" && operand2 === 0) {
console.error("Error: Division by zero");
return NaN;
}
switch (operator) {
case "+":
return operand1 + operand2;
case "-":
return operand1 - operand2;
case "*":
return operand1 * operand2;
case "/":
return operand1 / operand2;
case "^":
return Math.pow(operand1, operand2);
default:
throw new Error("Unknown operator: " + operator);
}
}
function shuntingYard(expression) {
const outputQueue = [];
const operatorStack = [];
// Updated regex to support decimal numbers
const tokens = expression.match(/\d+\.\d+|\d+|\+|\-|\*|\/|\^|\(|\)/g) || [];
tokens.forEach((token) => {
if (!isNaN(token)) {
outputQueue.push(parseFloat(token));
} else if (token in precedence) {
while (
operatorStack.length > 0 &&
precedence[operatorStack[operatorStack.length - 1]] >=
precedence[token]
) {
outputQueue.push(operatorStack.pop());
}
operatorStack.push(token);
} else if (token === "(") {
operatorStack.push(token);
} else if (token === ")") {
while (
operatorStack.length > 0 &&
operatorStack[operatorStack.length - 1] !== "("
) {
outputQueue.push(operatorStack.pop());
}
operatorStack.pop();
}
});
while (operatorStack.length > 0) {
outputQueue.push(operatorStack.pop());
}
return outputQueue;
}
function evaluatePostfix(postfixExpression) {
const stack = [];
postfixExpression.forEach((token) => {
if (!isNaN(token)) {
stack.push(token);
} else {
const operand2 = stack.pop();
const operand1 = stack.pop();
const result = applyOperator(token, operand1, operand2);
stack.push(result);
}
});
return stack.pop();
}
const postfixExpression = shuntingYard(expression);
const result = evaluatePostfix(postfixExpression);
appendNewlines(result.toString());
}
// Enable/Disable effects for easier memory usage.
function switchMobileFriendly() {
const outputElement = document.createElement("div");
outputElement.textContent = "> mobile-friendly";
outputElement.classList.add("terminal-input");
previousInputs.length === 0 ||
previousInputs[previousInputs.length - 1] !== "mobile-friendly"
? previousInputs.push("mobile-friendly")
: null;
currentIndex = previousInputs.length;
if (mobileFriendly) {
const dark = document.querySelectorAll(".dark");
for (let i = 0; i < dark.length; i++) {
dark[i].classList.add("mf");
}
mobileFriendly = false;
} else {
const dark = document.querySelectorAll(".dark");
for (let i = 0; i < dark.length; i++) {
dark[i].classList.remove("mf");
}
mobileFriendly = true;
}
}
// Clear all terminal messages
function clearPage() {
previousInputs = [];
previousInputs.length = 0;
const outputElements = document.querySelectorAll(".terminal-input");
outputElements.forEach(function (element) {
element.remove();
});
appendNewlines(init);
}
// Switch to "light mode"
function invertPage() {
const outputElement = document.createElement("div");
outputElement.textContent = "> invert";
outputElement.classList.add("terminal-input");
previousInputs.length === 0 ||
previousInputs[previousInputs.length - 1] !== "invert"
? previousInputs.push("invert")
: null;
currentIndex = previousInputs.length;
let newColorMode = colorMode;
if (colorMode == "dark") {
newColorMode = "light";
} else {
newColorMode = "dark";
}
var darkElements = document.querySelectorAll("." + colorMode);
darkElements.forEach(function (element) {
if (element.classList.contains(colorMode)) {
// If it has, set it to "light"
element.classList.replace(colorMode, newColorMode);
}
});