-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
104 lines (86 loc) · 2.19 KB
/
main.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
#include "core/engine/engine.h"
#include "core/output/printtable.h"
#include "core/tictactoe/checkwinner.h"
#include "core/tictactoe/processinput.h"
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
void printwinner(int table[3][3], int who, bool who_starts)
{
printtable(table);
if (who == 2) {
printf("Draw!!\n");
} else if (who_starts == true) {
if (who == 1) {
printf("Player wins!!\n");
} else {
printf("Computer wins!!\n");
}
} else {
if (who == 0) {
printf("Player wins!!\n");
} else {
printf("Computer wins!!\n");
}
}
}
int main(int argc, char* argv[])
{
// log file
FILE* f;
f = fopen("engine.log", "w");
if (f == NULL) {
return -1;
}
// table thats used for the game itself
// where -1 means that the square is clear
// 0 means "x"
// 1 means "o"
int table[3][3] = { -1, -1, -1, -1, -1, -1, -1, -1, -1 };
// engine's string to play the moves
char* engine_c = malloc(3 * sizeof(char));
printf("WELCOME TO TIC TAC TOE VS ENGINE\n");
printf("{0} if you want to start first\n");
printf("{1} if you want the engine to start first\n:");
int* temp = malloc(sizeof(int));
do {
scanf("%i", temp);
} while (!(*temp == 0 || *temp == 1));
bool does_player_starts_first;
if (*temp == 0)
does_player_starts_first = true;
else
does_player_starts_first = false;
bool turn = true;
// main game loop
while (true) {
if (turn == does_player_starts_first) { // if it's the player's turn
printtable(table);
bool valid = false; // checks if the input from the player is valid
do {
valid = processinput(table, does_player_starts_first);
} while (valid);
} else { // if it's the engine's turn
engine(engine_c, table, does_player_starts_first, f); // function to call the engine
int row = engine_c[0] - 48;
int file = engine_c[1] - 48;
if (does_player_starts_first == true) // move from the engine it self
table[row][file] = 1;
else
table[row][file] = 0;
}
// checks if there is a winner
int winner = checkwinner(table);
if (winner != 0) {
printwinner(table, winner, does_player_starts_first);
break;
}
if (turn == true)
turn = false;
else
turn = true;
}
free(engine_c);
free(temp);
return 0;
}