blob: ebccfd43169d5d8b227e5125301583264b867217 (
plain) (
blame)
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
|
#include <conio.h>
#include <stdio.h>
#include "consts.h"
#include "protos.h"
char is_board_solved(BOARD board) {
char cases[8] = {EMPTY};
char i;
// rows and cols
for (i = 0; i < 3; i++) {
cases[i] = board[i][0] * board[i][1] * board[i][2];
cases[i + 3] = board[0][i] * board[1][i] * board[2][i];
}
// diagonals
cases[6] = board[0][0] * board[1][1] * board[2][2];
cases[7] = board[0][2] * board[1][1] * board[2][0];
// check cases for winner
for (i = 0; i < 8; i++) {
if (cases[i] == 1) {
// X won
return X;
} else if (cases[i] == 8) {
// O won
return O;
}
}
// check cases for remaining moves
for (i = 0; i < 9; i++) {
if (cases[i] == EMPTY) {
// more spaces left; game continues
return EMPTY;
}
}
// stalemate
return TIE;
}
void print_board(BOARD board) {
char i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("%d ", board[i][j]);
}
printf("\n");
}
}
int main() {
char solution = EMPTY;
char move = EMPTY;
char move_x = EMPTY;
char move_y = EMPTY;
BOARD board = {{EMPTY}, {EMPTY}, {EMPTY}};
while (1) {
print_board(board);
solution = is_board_solved(board);
switch (solution) {
case X:
printf("X won");
break;
case O:
printf("O won");
break;
case TIE:
printf("Stalemate");
break;
default:
printf("Enter a move...");
}
printf("\n");
cursor(1);
move = cgetc() - '0' - 1;
// if move is not a number then bail
// if (move < 1 || move > 8) { invalid! }
move_x = move % 3;
move_y = move / 3;
// if move not already taken
board[move_y][move_x] = X;
}
return 0;
}
|