Hello I'm a complete beginner in c++.I tried to make a tic-tac-toe game. |
That’s usually a suggested exercise to learn about
arrays and
loops.
You can solve it even without loops, because the winning and losing conditions are a reasonable finite number, but I don’t know if it’s useful, because the code becomes just a list of statements which repeat several times with tiny variations.
I’d wait to learn about arrays and loops before undertaking this exercise, but if you really want to try:
1) Do not care about graphic at the beginning. You data just need to be readable, not perfect. You can adjust it later.
So you have 9 variables (chars or std::strings) you need to display into a 3 x 3 table. Something like this could be a tolerable start:
1 2 3
|
std::cout << pos_0_0 << ' ' << pos_0_1 << ' ' << pos_0_2 << '\n'
<< pos_1_0 << ' ' << pos_1_1 << ' ' << pos_1_2 << '\n'
<< pos_2_0 << ' ' << pos_2_1 << ' ' << pos_2_2 << '\n';
|
2) Now you need to ask the user about their move.
This is a far harder challenge.
You could start asking which row s/he wants to modify. According to their answer, you can divide your variables in three groups:
- pos_0_0, pos_0_1 and pos_0_2 if the user wants to assign in the first row
- pos_1_0, pos_1_1 and pos_1_2 if the user wants to assign in the second row
- pos_2_0, pos_2_1 and pos_2_2 if the user wants to assign in the third row.
Once you’ve selected the right group, you can ask about the column, which tells you exactly which variable to update.
A bit awkward, isn’t it? ;-)
3) The winning conditions are:
- compare with each other pos_0_0, pos_0_1 and pos_0_2
If no winner:
- compare with each other pos_1_0, pos_1_1 and pos_1_2
If no winner:
- compare with each other pos_2_0, pos_2_1 and pos_2_2
If no winner:
- compare with each other pos_0_0, pos_1_0 and pos_2_0
If no winner:
- compare with each other pos_0_1, pos_1_1 and pos_2_1
If no winner:
- compare with each other pos_0_2, pos_1_2 and pos_2_2
If no winner:
- compare with each other pos_0_0, pos_1_1 and pos_2_2
If no winner:
- compare with each other pos_2_0, pos_1_1 and pos_0_2
You need to perform the above check after every move.
4) If you want to implement an AI to let the user play against the pc… There are good tutorials on internet :-)
Happy coding!