Created
May 31, 2022 18:08
-
-
Save lolarobins/ecb216fc19a5180680b3c32ac392e37a to your computer and use it in GitHub Desktop.
1 player tic tac toe for ICS4U
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <stdbool.h> | |
#include <time.h> | |
char board[9]; | |
bool win() | |
{ | |
// row checking | |
for (int i = 0; i < 3; i++) | |
if (board[i] == ' ') | |
continue; | |
else if (board[i] == board[i + 3] && board[i] == board[i + 6]) | |
return true; | |
// column checking | |
for (int i = 0; i < 7; i += 3) | |
if (board[i] == ' ') | |
continue; | |
else if (board[i] == board[i + 1] && board[i] == board[i + 2]) | |
return true; | |
// diagonal checking | |
if (board[4] != ' ' && ((board[0] == board[4] && board[0] == board[8]) || (board[2] == board[4] && board[2] == board[8]))) | |
return true; | |
return false; | |
} | |
bool taken(int pos) | |
{ | |
if (board[pos] == ' ') | |
return false; | |
return true; | |
} | |
void print() | |
{ | |
// id rather not improve this | |
printf("\n %c | %c | %c \ | |
\n---+---+---\ | |
\n %c | %c | %c \ | |
\n---+---+---\ | |
\n %c | %c | %c \n\n", | |
board[0], | |
board[1], | |
board[2], | |
board[3], | |
board[4], | |
board[5], | |
board[6], | |
board[7], | |
board[8]); | |
} | |
int main() | |
{ | |
srand(time(NULL)); | |
printf("Welcome to single player Tic-Tac-Toe!\n\ | |
\nBoard Positions:\ | |
\n 1 | 2 | 3 \ | |
\n---+---+---\ | |
\n 4 | 5 | 6 \ | |
\n---+---+---\ | |
\n 7 | 8 | 9 \n\n"); | |
// clear array to space chars | |
for (int i = 0; i < 9; i++) | |
board[i] = ' '; | |
// game | |
while (true) | |
{ | |
print(); | |
int in = 0; | |
printf("Please enter a number: "); | |
scanf("%d", &in); | |
while (in == 0 || taken(in - 1) || in > 9) | |
{ | |
printf("Number invalid, please pick a different number: "); | |
scanf("%d", &in); | |
} | |
board[in - 1] = 'X'; | |
if (win()) | |
{ | |
print(); | |
printf("You won!\n"); | |
return 0; | |
} | |
int computer = 0; | |
while (computer == 0 || taken(computer - 1)) | |
computer = (rand() % 9) + 1; | |
board[computer - 1] = 'O'; | |
if (win()) | |
{ | |
print(); | |
printf("You lost!\n"); | |
return 0; | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment