-
Notifications
You must be signed in to change notification settings - Fork 0
/
tictactoe.c
2400 lines (1954 loc) · 86.1 KB
/
tictactoe.c
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#if defined _WIN32
#define CLEAR_CONSOLE "cls"
#elif defined __unix__ || __linux__
#define CLEAR_CONSOLE "clear"
#endif
//############################################################################################
//
// Notes
//
//############################################################################################
//
// In my lab 3, a TA mentioned that CLEAR_CONSOLE is not recognized. I've tried that to be
// working both on online compilers and in my VS Code on the local PC. I was wondering the
// TA probably forgot to copy the preprocessors at the top of the code?
//
// Another TA also tried my lab 3, and it ran without warnings.
//
//
// When a win occurs, the marking with the curly brackets work most of the time but at some
// rare times, one or more of the curly brackets go on the wrong cells. If this occurs but
// the winning announcer is correct, I hope that I don't get marks docked as it's an extra
// decorative thing I implemented. :D
//
//
// Assignment 2 Notes:
//
// 1 Duplicate players check not implemented (since not in PDF).
// 2 Feature to delete players not implemented (same reason as above). Can be deleted
// manually in from text files.
// 3 To "reset" the program, simply delete the following four text files:
// players.text
// savedgames.text
// savedboards.text
// database.text
//
// ~ Kap
//
const char * READ_DATABASE_FILE = "Number of players: %d\nNumber of saved games: %d";
const char * WRITE_DATABASE_FILE = "Number of players: %d\nNumber of saved games: %d";
const char * READ_GAMES_FILE = "GameID: %d\tBoard: %d\t Status: %[^,], playerX: %d (points: %d), playerO: %d (points: %d), nextTurn: %c, totalMoves: %d\n";
const char * WRITE_GAMES_FILE = "GameID: %d\tBoard: %d\tStatus: %s, playerX: %d (points: %d), playerO: %d (points: %d), nextTurn: %c, totalMoves: %d\n";
const char * READ_BOARDS_FILE = "%d, %d, %d, %d, %d, %d, %d, %d, %d, %d\n"; // board id, cell0-9
const char * WRITE_BOARDS_FILE = "%d, %d, %d, %d, %d, %d, %d, %d, %d, %d\n";
const char * READ_PLAYERS_FILE = "%d %s %[^,], %[^,], %d, %d, %d, %d, %d\n"; // id fName lName, email, score, games, wins, draws, losses
const char * WRITE_PLAYERS_FILE = "%d %s %s, %s, %d, %d, %d, %d, %d\n";
typedef struct {
char board[9];
int boardIndex;
} Board;
typedef struct {
int GameID; // a random unique number between 0-10,000
int player1ID;
int player2ID;
char whosTurn; // X or O
int totalMoves;
char gameStatus[25]; // X won, O own, Draw or Ongoing
int currentXpoints;
int currentOpoints;
} Game;
typedef struct {
char firstName[25];
char lastName[25];
char playerEmail[100];
int playerID;
int playerScore;
int playerGames;
int wins;
int draws;
int losses;
} Player;
//############################################################################################
// ASSIGNMENT 2 related PROTOTYPES START
//############################################################################################
// sorting related functions
void swapInt(int * a, int * b);
void swapChar(char * a, char * b);
void swapString(char * a, char * b);
void quicksort_asc(Player * list, int start, int end, int sortMode);
void quicksort_des(Player * list, int start, int end);
void copyList(Player * source, Player * des, int listSize);
int partition(Player * list, int start, int end, int sortMode);
// helper functions
void pressEnter();
void displayLogo();
void displayMainMenu();
void displayErrorMessage(int errorCode);
int getNumOf(int option);
int getRandomNum(int min, int max);
int validateInput(char * str, int maxChar, int criteriaCode, int useLimits, int lowerLimit, int upperLimit);
int overwrite_Players_File(Player * playerslist, int * numOfPlayers);
int overwrite_Games_File(Game * gameslist, Board * boardslist, int * numOfSavedGames);
int overwrite_Boards_File(Board * boardslist, int * numOfSavedGames);
int append_Players_File(Player * playerslist, int index);
int append_Games_File(Game * gameslist, Board * boardslist, int index);
int append_Boards_File(Board * boardslist, int index);
int update_Database_File(int * numOfPlayers, int * numOfSavedGames);
int load_Boards_File(Board * boardslist);
int load_Games_File(Game * gameslist, Board * boardslist);
int load_Players_File(Player * playerslist);
// "Add Players" function
int addPlayer(Player * playerslist, int * numOfPlayers, int * numOfSavedGames);
// "Create Games" related function
void optionG(int m, int n, char board[][n], int * winPosition, Board * boardslist, Game * gameslist, Player * playerslist, int * numOfSavedGames, int * numOfPlayers);
void newGame(int m, int n, char board[][n], int * winPosition, Board * boardslist, Game * gameslist, Player * playerslist, int * numOfSavedGames, int * numOfPlayers, int resumeSavedGame, int loadGameID);
int saveGame(int m, int n, char board[][n], Board * boardslist, Game * gameslist, int saveResumedGame, int savedGameIndex, int * numOfSavedGames, int * numOfPlayers);
void promptToSaveFinishedGame(int m, int n, char board[][n], Board * boardslist, Game * gameslist, int gameIndex, int * numOfSavedGames, int * numOfPlayers);
void loadGame(int m, int n, char board[][n], int * winPosition, Board * boardlist, Game * gamelist, Player * playerslist, int gameIndex, int * numOfSavedGames, int * numOfPlayers);
// "Leaderboard" function
void leaderBoard(Player * playerslist, int numOfPlayers);
//############################################################################################
// ASSIGNMENT 2 related PROTOTYPES END
//############################################################################################
//############################################################################################
// ASSIGNMENT 1 related PROTOTYPES START
//############################################################################################
int searchAndSwapCellValue(int position, int m, int n, char player, char board[][n]); // swaps the cell numbers with the user's sign, X or O, and returns 1 if it's successful or else 0 and asks user to enter in another cell or a valid input
int inputOption(char str[], int n); // takes in an input as a string
int getMovesNumber(int m, int n, char board[][n]); // to keep track of the turns, so it's the same turn # when exiting during a turn, checking prediction then coming back to continue playing
int gameStillRunning(int m, int n, char board[][n], int * winPosition); // returns 1 if game is still running (ie. if user exit while his turn so he can continue playing when going back to the create board menu option)
void checkValid(int m, int n, char board[][n]); // display both board while showing whether it's a valid board or not
void displayFinalBoard(int m, int n, char board[][n], int * winPosition, Player * playerslist, Game * gameslist, int thisGame, char winner); // to display final board with the winner's cells hightlighted with curly brackets
void caseOne(char player, char singleList[]);
void caseTwo(char player, char singleList[]);
void caseThree(char player, char singleList[]);
void initializeBoard(int m, int n, char board[][n]);
void printBoard(int m, int n, char board[][n], int clearConsole);
void listWinningCells(char turn, int m, int n, char board[][n]);
char whoIsTheWinner(int m, int n, char board[][n], int * winPosition);
int isValidBoard(int m, int n, char board[][n]);
//############################################################################################
// ASSIGNMENT 1 related PROTOTYPES END
//############################################################################################
//############################################################################################
//
// Game Storage 15 points
//
//############################################################################################
//
// Players, Saved Games, Saved Boards and Game info (aka Database) are stored in
// dynamic memory structs during the program run time.
//
// When program closes, they're stored in:
//
// Players list in players.txt
// Saved games list in savedgames.txt
// Saved boards list in savedboards.txt
// Database in database.txt
//############################################################################################
//
// Main Function 10 points
//
//############################################################################################
int main() {
int m = 3, n = 3; // board is a 3x3, so m and n are predetermined
char board[m][n];
initializeBoard(m, n, board); // initialize board
int errorCheck = 0; // used for counting an invalid input, so when error = 1, a reprompt message and error is shown
char optionChoice[2];
int reprompt = 0; // if 1, the input reprompts to enter a valid input
int clearBeforeMenu = 1; // if 1, then screen clear occurs, otherwise no
int numOfPlayers;
int numOfSavedGames;
int numOfSavedBoards;
int winPosition = 0;
/*
winPosition Numbers:
1 top row
2 mid row
3 bot row
4 left col
5 mid col
6 right col
7 forward diag
8 reversed diag
*/
// create the necessary files
FILE * file1 = fopen("players.txt", "a");
if (file1 == NULL) {
return 1;
}
fseek(file1, 0, SEEK_END);
if (!ftell(file1)) {
numOfPlayers = 0;
} else {
numOfPlayers = getNumOf(1);
}
fclose(file1);
FILE * file2 = fopen("savedgames.txt", "a");
if (file2 == NULL) {
return 1;
}
fseek(file2, 0, SEEK_END);
if (!ftell(file2)) {
numOfSavedGames = 0;
} else {
numOfSavedGames = getNumOf(2);
}
fclose(file2);
FILE * file3 = fopen("savedboards.txt", "a");
if (file3 == NULL) {
return 1;
}
fclose(file3);
numOfSavedBoards = numOfSavedGames;
FILE * file4 = fopen("database.txt", "w+");
if (file4 == NULL) {
return 1;
}
fprintf(file4, WRITE_DATABASE_FILE, numOfPlayers, numOfSavedGames);
fclose(file4);
// if both numbers are 0, then start with space for 5 players and 10 games, if not, add space for 5 players and 10 games more
Player * playerslist;
Game * gameslist;
Board * boardslist;
if (!numOfPlayers) {
playerslist = (Player *) malloc(5*sizeof(Player));
} else if (numOfPlayers > 0) {
playerslist = (Player *) malloc((numOfPlayers+(numOfPlayers/2))*sizeof(Player));
}
if (!numOfSavedGames) {
gameslist = (Game *) malloc(10*sizeof(Game));
} else if (numOfSavedGames > 0) {
gameslist = (Game *) malloc((numOfSavedGames+(numOfSavedGames/2))*sizeof(Game));
}
if (!numOfSavedBoards) {
boardslist = (Board *) malloc(10*sizeof(Board));
} else {
boardslist = (Board *) malloc((numOfSavedBoards+(numOfSavedBoards/2))*sizeof(Board));
}
// load in the data
if (numOfPlayers) {
load_Players_File(playerslist);
}
if (numOfSavedGames) {
load_Games_File(gameslist, boardslist);
}
if (numOfSavedBoards) {
load_Boards_File(boardslist);
}
do {
if (clearBeforeMenu) {
system(CLEAR_CONSOLE);
}
displayLogo();
printf(" Players: %d | Saved Games: %d\n\n", numOfPlayers, numOfSavedGames);
displayMainMenu();
if (errorCheck > 0) {
printf("> Error! Enter one of the available options.\n\n");
}
printf(
" Option: ");
inputOption(optionChoice, 2);
switch(optionChoice[0]) {
case 'p':
case 'P': reprompt = 2; clearBeforeMenu = 1; addPlayer(playerslist, &numOfPlayers, &numOfSavedGames); break;
case 'g':
case 'G': reprompt = 2; clearBeforeMenu = 1; optionG(m, n, board, &winPosition, boardslist, gameslist, playerslist, &numOfSavedGames, &numOfPlayers); break;
case 'l':
case 'L': reprompt = 2; leaderBoard(playerslist, numOfPlayers); break;
case 'r':
case 'R': reprompt = 2; initializeBoard(m, n, board); clearBeforeMenu = 0; printBoard(m, n, board, 1); break;
case 'e':
case 'E': reprompt = 0; break;
default: reprompt = 1;
}
if (reprompt == 1) {
errorCheck++;
}
} while (reprompt == 1 || reprompt == 2);
free(playerslist);
free(gameslist);
free(boardslist);
return 0;
}
//############################################################################################
//
// "Add Players" related functions - START 30 points
//
//############################################################################################
int addPlayer(Player * playerslist, int * numOfPlayers, int * numOfSavedGames) {
int numOfPlayersInFile = getNumOf(1);
int nextIndex = *numOfPlayers;
char tempFirstName[30];
char tempLastName[30];
char tempEmail[105];
system(CLEAR_CONSOLE);
displayLogo();
playerslist = (Player *) realloc(playerslist, numOfPlayersInFile+3);
printf(" >> Add player\n\n");
int errorCheck = 0;
// Prompt for first name + validate
do {
if (errorCheck > 0) {
displayErrorMessage(errorCheck);
}
printf(" First name: ");
scanf(" %s", tempFirstName);
errorCheck = validateInput(tempFirstName, 25, 3, 0, 0, 0);
} while (errorCheck != 0);
// Prompt for last name + validate
do {
if (errorCheck > 0) {
displayErrorMessage(errorCheck);
}
printf(" Last name: ");
scanf(" %s", tempLastName);
errorCheck = validateInput(tempLastName, 25, 3, 0, 0, 0);
} while (errorCheck != 0);
// Prompt for email + validate
do {
if (errorCheck > 0) {
displayErrorMessage(errorCheck);
}
printf(" Email: ");
scanf(" %s", tempEmail);
errorCheck = validateInput(tempEmail, 100, 7, 0, 0, 0);
} while (errorCheck != 0);
// If all validations passed, continue below:
strcpy(playerslist[nextIndex].firstName, tempFirstName);
strcpy(playerslist[nextIndex].lastName, tempLastName);
strcpy(playerslist[nextIndex].playerEmail, tempEmail);
playerslist[nextIndex].playerID = nextIndex+1;
playerslist[nextIndex].playerGames = 0;
playerslist[nextIndex].playerScore = 100;
playerslist[nextIndex].wins = 0;
playerslist[nextIndex].draws = 0;
playerslist[nextIndex].losses = 0;
// update number of players
*numOfPlayers += 1;
// append to file
append_Players_File(playerslist, nextIndex);
// update database file
update_Database_File(numOfPlayers, numOfSavedGames);
while (getchar() != '\n');
return 0;
}
//############################################################################################
//
// "Add Players" related functions - END
//
//############################################################################################
//############################################################################################
//
// Create Games related functions - START 30 points
//
//############################################################################################
void optionG(int m, int n, char board[][n], int * winPosition, Board * boardslist, Game * gameslist, Player * playerslist, int * numOfSavedGames, int * numOfPlayers) {
int errorCheck = 0;
char option[2];
int reprompt = 1;
int gameIndex;
int resumeSavedGame = 0;
int loadGameID = 0;
do {
// Prompt for option + validate
do {
system(CLEAR_CONSOLE);
displayLogo();
printf(" >> Play game\n\n");
if (errorCheck > 0) {
displayErrorMessage(errorCheck);
}
printf(" 1. Start a new game:\n 2. Load a saved game\n 0. Back to main menu\n\n Option: ");
scanf(" %s", option);
errorCheck = validateInput(option, 1, 2, 1, 0, 2);
while (getchar() != '\n');
} while (errorCheck != 0);
int optionSwitch = atoi(option);
switch (optionSwitch) {
case 0: reprompt = 0; break;
case 1: newGame(m, n, board, winPosition, boardslist, gameslist, playerslist, numOfSavedGames, numOfPlayers, resumeSavedGame, loadGameID); break;
case 2: loadGame(m, n, board, winPosition, boardslist, gameslist, playerslist, gameIndex, numOfSavedGames, numOfPlayers); break;
}
} while (reprompt);
}
void newGame(int m, int n, char board[][n], int * winPosition, Board * boardslist, Game * gameslist, Player * playerslist, int * numOfSavedGames, int * numOfPlayers, int resumeSavedGame, int loadGameID) {
// from my understanding "createBoard" is the playing mode so I'll treat it as such.
char symbols[] = {'X', 'O'};
int totalMoves = m * n; // track the total number of turns
int cellPosition = 0; // track validity of cell value input
int cellChoice = 1; // returns 1 if cell value has been successfullly modified
int errorCheck = 0; // tracker for error code when invalid input is entered
char moveOption[2]; // cell number input char array
char whoseTurn[2]; // turn input char array
int movesTracker; // tracker for what turn number it is
char turn; // turn = X when movesTracker is odd else O when it's even
int exitCode = 0; // tracker for when user wishes to end his turn, exit code
char player[2];
int playerX;
int playerO;
char resumeChoice[2];
int gameIndex;
char currentGameStatus[25] = "Inactive";
int thisGame;
int goBackAddPlayers = 0;
int resumeBoardIndex = loadGameID - 1;
int resumeGame;
resumeSavedGame = (loadGameID >= 1 && loadGameID <= *numOfSavedGames) ? 1 : 0;
if (resumeSavedGame) {
thisGame = resumeBoardIndex;
gameIndex = resumeBoardIndex + 1;
movesTracker = gameslist[resumeBoardIndex].totalMoves + 1;
} else {
thisGame = *numOfSavedGames;
movesTracker = getMovesNumber(m, n, board) + 1;
// gameIndex = thisGame;
}
// check and prompt to continue existing game or not
if (!resumeSavedGame) {
if (!strcmp(currentGameStatus, "Ongoing")) {
do {
system(CLEAR_CONSOLE);
displayLogo();
if (errorCheck > 0) {
displayErrorMessage(errorCheck);
}
while (getchar() != '\n');
printf(" >> There's an active game currently. Resume that?\n\n 1. Yes\n 0. No\n\n Option: ");
scanf("%s", resumeChoice);
errorCheck = validateInput(resumeChoice, 1, 2, 1, 0, 1);
while (getchar() != '\n');
} while (errorCheck != 0);
}
}
resumeGame = atoi(resumeChoice);
do {
// if starting a new game
if (resumeSavedGame == 0) {
if (resumeGame == 0) {
initializeBoard(m, n, board);
movesTracker = 1;
if (*numOfPlayers == 0) {
system(CLEAR_CONSOLE);
displayLogo();
printf(" >> No players yet, add at least two first\n\n");
printf(" Press Enter to go back and add players ... ");
while (getchar() != '\n');
pressEnter();
goBackAddPlayers = 1;
} else if (*numOfPlayers == 1) {
system(CLEAR_CONSOLE);
displayLogo();
printf(" >> Not enough players, add one more first\n\n");
printf(" Press Enter to go back and add players ... ");
while (getchar() != '\n');
pressEnter();
goBackAddPlayers = 1;
} else if (*numOfPlayers >= 2) {
// player selection
for (int j = 0; j < 3; j++) {
system(CLEAR_CONSOLE);
displayLogo();
printf(" >> Who's playing\n\n");
// select player X
if (j < 2) {
for (int i = 0; i < *numOfPlayers; i++) {
printf(" %d. %s %s\n", i+1, playerslist[i].firstName, playerslist[i].lastName);
}
}
// select player O
if (j == 1) {
printf("\n X: %s %s", playerslist[playerX].firstName, playerslist[playerX].lastName);
}
// select who are playing
if (j < 2) {
// Prompt for player + validate
do {
if (errorCheck > 0) {
displayErrorMessage(errorCheck);
}
printf("\n\n Select for player %c: ", symbols[j]);
scanf("%s", player);
errorCheck = validateInput(player, 1, 2, 1, 1, *numOfPlayers);
} while (errorCheck != 0);
if (symbols[j] == 'X') {
playerX = atoi(player) - 1;
} else if (symbols[j] == 'O') {
playerO = atoi(player) - 1;
}
}
if (j == 2) {
printf(" %s %s (X)\n\n \t Vs.\n\n %s %s (O)\n\n Press Enter to Start ... ", playerslist[playerX].firstName, playerslist[playerX].lastName, playerslist[playerO].firstName, playerslist[playerO].lastName);
while (getchar() != '\n');
pressEnter();
}
}
}
}
// initialize game info
gameslist[thisGame].GameID = getRandomNum(1, 10000);
gameslist[thisGame].currentXpoints = 3;
gameslist[thisGame].currentOpoints = 3;
strcpy(gameslist[thisGame].gameStatus, "Ongoing");
strcpy(currentGameStatus, "Ongoing");
gameslist[thisGame].totalMoves = movesTracker;
gameslist[thisGame].whosTurn = 'X';
gameslist[thisGame].player1ID = playerX;
gameslist[thisGame].player2ID = playerO;
}
int showHint;
if (!resumeGame) {
showHint = 0;
}
if (resumeSavedGame) {
int i = 0;
// restore the saved board
for (int n = 0; n < 3; n++, i++) {
board[0][n] = boardslist[resumeBoardIndex].board[i];
}
for (int n = 0; n < 3; n++, i++) {
board[1][n] = boardslist[resumeBoardIndex].board[i];
}
for (int n = 0; n < 3; n++, i++) {
board[2][n] = boardslist[resumeBoardIndex].board[i];
}
// printBoard(m, n, board);
} else {
initializeBoard(m, n, board);
}
do {
errorCheck = 0; // reset error message each turn
do {
system(CLEAR_CONSOLE);
displayLogo();
printf("\t\t\t\t %s (X) Vs. %s (O)\n\n",
playerslist[gameslist[thisGame].player1ID].firstName,
playerslist[gameslist[thisGame].player2ID].firstName
);
printBoard(m, n, board, 0);
if (errorCheck > 0) {
displayErrorMessage(errorCheck);
}
if (showHint) {
listWinningCells(turn, m, n, board);
showHint = 0;
}
turn = (movesTracker % 2) ? 'X' : 'O';
gameslist[thisGame].whosTurn = turn;
printf(
"\t\t\t\t Player %c's turn\n\n"
" >> Hint points remaining:\t X: %d points\t\t Game Status: %s\n\t\t\t\t O: %d points"
"\t\t\tMove #: %d\n\n"
"\n\t\tEnter the number of the cell where you want to insert X or O\n\n \t\t\t\t Other options:\n \t\t\t\t h Show hints\n \t\t\t\t s Save game\n \t\t\t\t e Exit\n\n"
"\t\t\t\t Action: ", turn, gameslist[thisGame].currentXpoints, gameslist[thisGame].gameStatus, gameslist[thisGame].currentOpoints, movesTracker);
inputOption(moveOption, 2);
errorCheck = validateInput(moveOption, 1, 11, 1, 1, 9);
cellPosition = atoi(moveOption);
if (moveOption[0] == 'h' || moveOption[0] == 'H') {
if (turn == 'X' && gameslist[thisGame].currentXpoints > 0) {
gameslist[thisGame].currentXpoints -= 1;
showHint = 1;
movesTracker--;
} else if (turn == 'O' && gameslist[thisGame].currentOpoints > 0) {
gameslist[thisGame].currentOpoints -= 1;
showHint = 1;
movesTracker--;
}
} else if (moveOption[0] == 's' || moveOption[0] == 'S') {
gameslist[thisGame].totalMoves = movesTracker - 1;
gameslist[thisGame].whosTurn = turn;
saveGame(m, n, board, boardslist, gameslist, resumeSavedGame, thisGame, numOfSavedGames, numOfPlayers);
system(CLEAR_CONSOLE);
displayLogo();
printf(" >> Game has been saved!\n\n Press Enter to continue ... ");
pressEnter();
exitCode = 1;
} else if (moveOption[0] == 'e' || moveOption[0] == 'E') {
exitCode = 1;
} else if (cellPosition >= 1 && cellPosition <= 9) {
// cellChoice returns 0, causing error if player picks a cell already taken or out of bound values
cellChoice = searchAndSwapCellValue(cellPosition, m, n, turn, board);
} else if (!cellChoice) {
errorCheck = 10;
} else {
errorCheck = 11;
}
} while (errorCheck > 0 || !cellChoice);
if (exitCode) {
movesTracker = (m * n) + 1; // if -1, exit game
} else if (movesTracker < 9) {
switch (whoIsTheWinner(m, n, board, winPosition)) {
case 'X': strcpy(gameslist[thisGame].gameStatus, "X_Won");
strcpy(currentGameStatus, "X_Won");
gameslist[thisGame].whosTurn = '-';
gameslist[thisGame].totalMoves = movesTracker;
displayFinalBoard(m, n, board, winPosition, playerslist, gameslist, thisGame, 'X');
if (playerslist[gameslist[thisGame].player2ID].playerScore > playerslist[gameslist[thisGame].player1ID].playerScore) {
playerslist[gameslist[thisGame].player2ID].playerScore -= 2;
} else {
playerslist[gameslist[thisGame].player2ID].playerScore -= 1;
}
playerslist[gameslist[thisGame].player1ID].playerScore += gameslist[thisGame].currentXpoints;
playerslist[gameslist[thisGame].player1ID].wins++;
playerslist[gameslist[thisGame].player2ID].losses++;
playerslist[gameslist[thisGame].player1ID].playerGames++;
playerslist[gameslist[thisGame].player2ID].playerGames++;
promptToSaveFinishedGame(m, n, board, boardslist, gameslist, gameIndex, numOfSavedGames, numOfPlayers);
movesTracker = 10;
break;
case 'O': strcpy(gameslist[thisGame].gameStatus, "O_Won");
strcpy(currentGameStatus, "O_Won");
gameslist[thisGame].whosTurn = '-';
gameslist[thisGame].totalMoves = movesTracker;
displayFinalBoard(m, n, board, winPosition, playerslist, gameslist, thisGame, 'O');
if (playerslist[gameslist[thisGame].player1ID].playerScore > playerslist[gameslist[thisGame].player2ID].playerScore) {
playerslist[gameslist[thisGame].player1ID].playerScore -= 2;
} else {
playerslist[gameslist[thisGame].player2ID].playerScore -= 1;
}
playerslist[gameslist[thisGame].player2ID].playerScore += gameslist[thisGame].currentOpoints;
playerslist[gameslist[thisGame].player2ID].wins++;
playerslist[gameslist[thisGame].player1ID].losses++;
playerslist[gameslist[thisGame].player1ID].playerGames++;
playerslist[gameslist[thisGame].player2ID].playerGames++;
promptToSaveFinishedGame(m, n, board, boardslist, gameslist, gameIndex, numOfSavedGames, numOfPlayers);
movesTracker = 10;
break;
default: movesTracker++;
}
} else if (movesTracker == 9) {
switch (whoIsTheWinner(m, n, board, winPosition)) {
case 'X': strcpy(gameslist[thisGame].gameStatus, "X_Won");
strcpy(currentGameStatus, "X_Won");
gameslist[thisGame].whosTurn = '-';
gameslist[thisGame].totalMoves = movesTracker;
displayFinalBoard(m, n, board, winPosition, playerslist, gameslist, thisGame, 'X');
if (playerslist[gameslist[thisGame].player2ID].playerScore > playerslist[gameslist[thisGame].player1ID].playerScore) {
playerslist[gameslist[thisGame].player2ID].playerScore -= 2;
} else {
playerslist[gameslist[thisGame].player2ID].playerScore -= 1;
}
playerslist[gameslist[thisGame].player1ID].playerScore += gameslist[thisGame].currentXpoints;
playerslist[gameslist[thisGame].player1ID].wins++;
playerslist[gameslist[thisGame].player2ID].losses++;
playerslist[gameslist[thisGame].player1ID].playerGames++;
playerslist[gameslist[thisGame].player2ID].playerGames++;
promptToSaveFinishedGame(m, n, board, boardslist, gameslist, gameIndex, numOfSavedGames, numOfPlayers);
movesTracker = 10;
break;
case 'O': strcpy(gameslist[thisGame].gameStatus, "O_Won");
strcpy(currentGameStatus, "O_Won");
gameslist[thisGame].whosTurn = '-';
gameslist[thisGame].totalMoves = movesTracker;
displayFinalBoard(m, n, board, winPosition, playerslist, gameslist, thisGame, 'O');
if (playerslist[gameslist[thisGame].player1ID].playerScore > playerslist[gameslist[thisGame].player2ID].playerScore) {
playerslist[gameslist[thisGame].player1ID].playerScore -= 2;
} else {
playerslist[gameslist[thisGame].player2ID].playerScore -= 1;
}
playerslist[gameslist[thisGame].player2ID].playerScore += gameslist[thisGame].currentOpoints;
playerslist[gameslist[thisGame].player2ID].wins++;
playerslist[gameslist[thisGame].player1ID].losses++;
playerslist[gameslist[thisGame].player1ID].playerGames++;
playerslist[gameslist[thisGame].player2ID].playerGames++;
promptToSaveFinishedGame(m, n, board, boardslist, gameslist, gameIndex, numOfSavedGames, numOfPlayers);
movesTracker = 10;
break;
case 'D': strcpy(gameslist[thisGame].gameStatus, "Draw");
strcpy(currentGameStatus, "Draw");
gameslist[thisGame].whosTurn = '-';
gameslist[thisGame].totalMoves = movesTracker;
displayFinalBoard(m, n, board, winPosition, playerslist, gameslist, thisGame, 'D');
playerslist[playerO].draws++;
playerslist[playerX].playerGames++;
playerslist[playerO].playerGames++;
promptToSaveFinishedGame(m, n, board, boardslist, gameslist, gameIndex, numOfSavedGames, numOfPlayers);
movesTracker = 10; break;
}
} else {
movesTracker++; // increment turn
}
} while (movesTracker <= totalMoves);
} while (goBackAddPlayers);
// reset winPosition
*winPosition = 0;
// update players file
overwrite_Players_File(playerslist, numOfPlayers);
}
int saveGame(int m, int n, char board[][n], Board * boardslist, Game * gameslist, int saveResumedGame, int savedGameIndex, int * numOfSavedGames, int * numOfPlayers) {
int thisGame;
if (saveResumedGame) {
thisGame = savedGameIndex;
} else {
thisGame = *numOfSavedGames;
}
// if (gameIndex > 0) {
// thisGame = gameIndex - 1;
// } else {
// // increment saved games counter
// *numOfSavedGames += 1;
// }
boardslist[thisGame].boardIndex = thisGame;
// save the cell positions in board[boardIndex]
int i = 0;
for (int n = 0; n < 3; n++, i++) {
boardslist[thisGame].board[i] = board[0][n];
}
for (int n = 0; n < 3; n++, i++) {
boardslist[thisGame].board[i] = board[1][n];
}
for (int n = 0; n < 3; n++, i++) {
boardslist[thisGame].board[i] = board[2][n];
}
if (saveResumedGame) {
// overwrite current data to update the saved games with new data
overwrite_Boards_File(boardslist, numOfSavedGames);
overwrite_Games_File(gameslist, boardslist, numOfSavedGames);
} else {
// append new data to savedboards file
append_Boards_File(boardslist, thisGame);
// append new data to savedgames file
append_Games_File(gameslist, boardslist, thisGame);
*numOfSavedGames += 1;
// update the database values
update_Database_File(numOfPlayers, numOfSavedGames);
}
return 0;
}
void promptToSaveFinishedGame(int m, int n, char board[][n], Board * boardslist, Game * gameslist, int gameIndex, int * numOfSavedGames, int * numOfPlayers) {
char saveOption[2];
int errorCheck = 0;
do {
if (errorCheck > 0) {
displayErrorMessage(errorCheck);
}
printf("\t\t\t Do you want to save this game?\n\n \t\t\t 1. Yes\t2. No\n\n \t\t\t\t Option: ");
scanf(" %s", saveOption);
errorCheck = validateInput(saveOption, 1, 2, 1, 1, 2);
while (getchar() != '\n');
} while (errorCheck);
int saveOptionInt = atoi(saveOption);
switch (saveOptionInt) {
case 1: saveGame(m, n, board, boardslist, gameslist, 0, 0, numOfSavedGames, numOfPlayers); break;
default: break;
}
}
void loadGame(int m, int n, char board[][n], int * winPosition, Board * boardslist, Game * gameslist, Player * playerslist, int gameIndex, int * numOfSavedGames, int * numOfPlayers) {
int reprompt = 1;
int errorCheck = 0;
char option[2];
if (!*numOfSavedGames) {
system(CLEAR_CONSOLE);
displayLogo();
printf(" -{ Saved Games }-\n\n"
"*******************************************************************************************\n"
"\n"
" \tGame ID\t\t X\t\t O\t\tStatus\t\tTurn\tTotal Moves\n"
"\n"
"*******************************************************************************************\n\n"
);
printf(
"\t\t\t Empty! There are no saved games yet.\n\n\n"
"\t\t\t Press Enter to Return . . . \n\n\n\t\t\t\t\t ");
while (getchar() != '\n');
pressEnter();
} else {
system(CLEAR_CONSOLE);
displayLogo();
printf(" -{ Saved Games }-\n\n"
"*******************************************************************************************\n"
"\n"
" \tGame ID\t\t X\t\t O\t\tStatus\t Turn Total Moves\n"
"\n"
"*******************************************************************************************\n\n"
);
load_Games_File(gameslist, boardslist);
for (int i = 0; i < *numOfSavedGames; i++) {
printf(" %d.\t%d\t\t(%d) %s",
i+1,
gameslist[i].GameID,
gameslist[i].currentXpoints,
playerslist[gameslist[i].player1ID].firstName);
if (strlen(playerslist[gameslist[i].player1ID].firstName) < 4) {
printf("\t\t");
} else {
printf("\t");
}
printf("(%d) %s",
gameslist[i].currentOpoints,
playerslist[gameslist[i].player2ID].firstName);
if (strlen(playerslist[gameslist[i].player2ID].firstName) < 4) {
printf("\t\t");
} else {
printf("\t");
}
printf("%s\t\t%c\t %d\n",
gameslist[i].gameStatus,
gameslist[i].whosTurn,
gameslist[i].totalMoves
);
}
do {
if (errorCheck > 0) {
displayErrorMessage(errorCheck);