-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.c
More file actions
116 lines (94 loc) · 2.22 KB
/
Main.c
File metadata and controls
116 lines (94 loc) · 2.22 KB
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
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void drawBoard(const char* board)
{
printf("\n");
printf(" %c | %c | %c\n", board[0], board[1], board[2]);
printf("---+---+---\n");
printf(" %c | %c | %c\n", board[3], board[4], board[5]);
printf("---+---+---\n");
printf(" %c | %c | %c\n", board[6], board[7], board[8]);
printf("\n");
}
void playerMove(char* board, const char player)
{
int number;
do
{
printf("Enter a number (1-9): ");
scanf_s("%1d", &number);
number--;
if (board[number] == ' ')
{
board[number] = player;
break;
}
} while (!number > 0 || !number < 8);
}
void computerMove(char* board, const char computer)
{
srand(time(NULL));
int number;
while (1)
{
number = rand() % 9;
if (board[number] == ' ')
{
board[number] = computer;
break;
}
}
}
int checkWinner(char* board, const char player, const char computer)
{
int i;
int start[] = { 0, 3, 6, 0, 1, 2, 0, 2 };
int step[] = { 1, 1, 1, 3, 3, 3, 4, 2 };
int size = sizeof(start) / sizeof(int);
for (i = 0; i < size; i++)
{
if (board[start[i]] != ' ' && board[start[i]] == board[start[i] + step[i]] && board[start[i] + step[i]] == board[start[i] + step[i] * 2])
{
printf("%s won!\n", board[start[i]] == player ? "You" : "Computer");
return 1;
}
}
return 0;
}
int checkTie(char* board)
{
int i;
for (i = 0; i < 9; i++)
{
if (board[i] == ' ')
{
return 0;
}
}
printf("Tie!\n");
return 1;
}
int main()
{
char board[] = { ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' };
const char player = 'X';
const char computer = 'O';
printf("Tic-tac-toe\n");
drawBoard(board);
while (1)
{
playerMove(board, player);
drawBoard(board);
if (checkWinner(board, player, computer) || checkTie(board))
{
break;
}
computerMove(board, computer);
drawBoard(board);
if (checkWinner(board, player, computer) || checkTie(board))
{
break;
}
}
}