-
Notifications
You must be signed in to change notification settings - Fork 5
/
tic-tac-toe.c
139 lines (123 loc) · 2.84 KB
/
tic-tac-toe.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
#include <stdio.h>
#include <stdlib.h>
#define BOARD_SIZE 3
void print_board(char board[BOARD_SIZE][BOARD_SIZE])
{
for (int i = 0; i < BOARD_SIZE; i++)
{
for (int j = 0; j < BOARD_SIZE; j++)
{
printf(" %c ", board[i][j]);
if (j != BOARD_SIZE - 1)
printf("|");
}
printf("\n");
if (i != BOARD_SIZE - 1)
printf("---+---+---\n");
}
}
int check_win(char board[BOARD_SIZE][BOARD_SIZE], char symbol)
{
// Check rows
for (int i = 0; i < BOARD_SIZE; i++)
{
int win = 1;
for (int j = 0; j < BOARD_SIZE; j++)
{
if (board[i][j] != symbol)
{
win = 0;
break;
}
}
if (win)
return 1;
}
// Check columns
for (int j = 0; j < BOARD_SIZE; j++)
{
int win = 1;
for (int i = 0; i < BOARD_SIZE; i++)
{
if (board[i][j] != symbol)
{
win = 0;
break;
}
}
if (win)
return 1;
}
// Check diagonals
int win = 1;
for (int i = 0; i < BOARD_SIZE; i++)
{
if (board[i][i] != symbol)
{
win = 0;
break;
}
}
if (win)
return 1;
win = 1;
for (int i = 0; i < BOARD_SIZE; i++)
{
if (board[i][BOARD_SIZE - 1 - i] != symbol)
{
win = 0;
break;
}
}
if (win)
return 1;
return 0;
}
int main()
{
char board[BOARD_SIZE][BOARD_SIZE];
for (int i = 0; i < BOARD_SIZE; i++)
{
for (int j = 0; j < BOARD_SIZE; j++)
{
board[i][j] = ' ';
}
}
printf("Welcome to Tic-Tac-Toe!\n");
printf("Player 1 uses 'X' and Player 2 uses 'O'.\n");
printf("The board is numbered like this:\n");
printf(" 1 | 2 | 3 \n");
printf("---+---+---\n");
printf(" 4 | 5 | 6 \n");
printf("---+---+---\n");
printf(" 7 | 8 | 9 \n");
int player = 1;
int moves = 0;
while (1)
{
printf("Player %d's turn:\n", player);
int row, col, pos;
do
{
printf("Enter a position (1-9): ");
scanf("%d", &pos);
row = (pos - 1) / BOARD_SIZE;
col = (pos - 1) % BOARD_SIZE;
} while (pos < 1 || pos > BOARD_SIZE * BOARD_SIZE || board[row][col] != ' ');
board[row][col] = (player == 1) ? 'X' : 'O';
moves++;
print_board(board);
if (check_win(board, (player == 1) ? 'X' : 'O'))
{
printf("Player %d wins!\n", player);
break;
}
if (moves == BOARD_SIZE * BOARD_SIZE)
{
printf("Tie game!\n");
break;
}
player = (player == 1) ? 2 : 1;
}
return 0;
}