summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorKai Stevenson <kai@kaistevenson.com>2022-11-21 16:58:26 -0800
committerKai Stevenson <kai@kaistevenson.com>2022-11-21 16:58:26 -0800
commitbd1eef9e049982028b78934f0de16c7e4369bdc2 (patch)
treef7d832050d52570ffe5790f6ef39e41bae9cf319
parent1ed2dc5006f9e4b7c4203003de741ba0057387be (diff)
added draw handling and player alternation
-rw-r--r--ttt.c41
1 files changed, 33 insertions, 8 deletions
diff --git a/ttt.c b/ttt.c
index 9ca248d..843f6a3 100644
--- a/ttt.c
+++ b/ttt.c
@@ -11,7 +11,7 @@ void draw_board(int boardState[3][3]) {
line[c] = 'x';
}
else if(boardState[c][r] == 2) {
- line[c] = 'y';
+ line[c] = 'o';
}
else {
line[c] = 'E';
@@ -81,12 +81,27 @@ int check_win(int boardState[3][3]) {
int is_full(int boardState[3][3]) {
//if all squares full, return 1
//else return 0
-
+ for(int r = 0; r < 3; r++) {
+ for(int c = 0; c < 3; c++) {
+ if(boardState[c][r] == 0) {
+ return 0;
+ }
+ }
+ }
+ return 1;
}
-int is_drawn(int boardState[3][3]) {
- //checks if board is full and if no win is on the board
- //returns 1 if so, else 0
-
+int get_game_state(int boardState[3][3]) {
+ //0 if game in progress, 1 if x win, 2 if o win, 3 if drawn
+ int w = check_win(boardState);
+ if(w == 1 || w == 2) {
+ return w;
+ }
+ else if(is_full(boardState)) {
+ return 3;
+ }
+ else {
+ return 0;
+ }
}
int* user_input_pos() {
int* ip = malloc(2 * sizeof(int));
@@ -102,17 +117,27 @@ void clear_screen()
}
int main() {
int board[3][3] = { { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 } };
+ int turn = 0;
while(1) {
clear_screen();
draw_board(board);
int* tl = user_input_pos();
- board[tl[0] - 1][3 - tl[1]] = 1;
+ board[tl[0] - 1][3 - tl[1]] = turn + 1;
free(tl);
- if(check_win(board) != 0) {
+ int s = get_game_state(board);
+ if(s == 1 || s == 2) {
+ clear_screen();
+ draw_board(board);
printf("Someone won!");
printf("\n");
break;
}
+ if(s == 3) {
+ printf("Game is drawn!");
+ printf("\n");
+ break;
+ }
+ turn = !turn;
}
return 0;
}