Skip to content

Commit 8fc5d2e

Browse files
committed
tictactoe
1 parent 6c7a5c5 commit 8fc5d2e

File tree

2 files changed

+98
-0
lines changed

2 files changed

+98
-0
lines changed

2025/links.html

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,9 @@ <h2>🖼️ Projects</h2>
126126
<div class="link-item highlight">
127127
<a href="guessing.cpp" target="_blank">Guessing Game</a>
128128
</div>
129+
<div class="link-item highlight">
130+
<a href="tictactoe.cpp" target="_blank">Tic Tac Toe</a>
131+
</div>
129132
<div class="link-item">
130133
<a href="breakout.sb3" target="_blank">Scratch Breakout</a>
131134
<div class="description">The breakout game made during camp</div>

2025/tictactoe.cpp

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
#include <iostream>
2+
#include <random>
3+
#include <ctime>
4+
using namespace std;
5+
6+
int main() {
7+
srand(time(0));
8+
9+
char game[3][3] = {
10+
{'1', '2', '3'} ,
11+
{'4', '5', '6'},
12+
{'7', '8', '9'}
13+
};
14+
15+
bool gameOn = true;
16+
char winner = ' ';
17+
char moves = 0;
18+
while (gameOn) {
19+
for (int i = 0; i < 3; i++) {
20+
cout << ' ';
21+
for (int j = 0; j < 3; j++) {
22+
cout << game[i][j] << ' ';
23+
if (j == 2) {
24+
cout << "| ";
25+
}
26+
}
27+
if (i != 2) {
28+
cout << endl << "-----------";
29+
}
30+
cout << endl;
31+
}
32+
33+
cout << "Pick a square! ";
34+
int square = -1;
35+
char value;
36+
while (square < 0) {
37+
cin >> square;
38+
square = square - 1;
39+
value = game[square % 3][square / 3];
40+
if (value == 'X' || value == 'O') {
41+
square = -1;
42+
cout << "Already occupied." << endl << "Pick a square! ";
43+
}
44+
}
45+
game[square / 3][square % 3] = 'X';
46+
value = 'X';
47+
moves++;
48+
while (moves < 9 && (value == 'X' || value == 'O')) {
49+
square = rand() % 9;
50+
value = game[square / 3][square % 3];
51+
}
52+
if (moves < 9) {
53+
game[square / 3][square % 3] = 'O';
54+
moves++;
55+
}
56+
57+
for (int i = 0; i < 3; i++) {
58+
if (game[i][0] == game[i][1] && game[i][1] == game[i][2]) {
59+
gameOn = false;
60+
winner = game[i][0];
61+
}
62+
if (game[0][i] == game[1][i] && game[1][i] == game[2][i]) {
63+
gameOn = false;
64+
winner = game[i][0];
65+
}
66+
}
67+
if (game[0][0] == game[1][1] && game[1][1] == game[2][2]) {
68+
gameOn = false;
69+
winner = game[0][0];
70+
}if (game[2][0] == game[1][1] && game[1][1] == game[0][2]) {
71+
gameOn = false;
72+
winner = game[2][0];
73+
}
74+
75+
if (gameOn && moves == 9) {
76+
gameOn = false;
77+
}
78+
}
79+
80+
for (int i = 0; i < 3; i++) {
81+
cout << ' ';
82+
for (int j = 0; j < 3; j++) {
83+
cout << game[i][j] << ' ';
84+
if (j != 2) {
85+
cout << "| ";
86+
}
87+
}
88+
if (i != 2) {
89+
cout << endl << "-----------";
90+
}
91+
cout << endl;
92+
}
93+
cout << "Player " << winner << " wins!";
94+
return 0;
95+
}

0 commit comments

Comments
 (0)