Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*############################################ #####################################
- TIC TAC TOE
- in two players
- ############################################## #####################################*/
- #include <iostream>
- #include <string.h>
- using namespace std;
- char v[10];
- void setup() {
- for (int i = 1; i <= 9; i++)
- v[i] = i + '0';
- }
- void afisare();
- int verificare();
- int main() {
- bool restart = true;
- while (restart) {
- setup();
- int turn = 0; // Whem turn it's odd, it's player's 1 turn. When it's even, it's player's two turn.
- while (verificare() == 0) {
- turn++;
- afisare();
- cout << "Player " << ((turn % 2 != 0) ? "1" : "2") << ": enter a position for your element - ";
- int pos;
- cin >> pos;
- while (pos != v[pos] - '0' || !(pos > 0 && pos < 10)) {
- cout << "\n ! Position ocuppied. Enter an available position: ";
- cin >> pos;
- }
- v[pos] = ((turn % 2) != 0 ? 'X' : 'O');
- }
- afisare();
- if (verificare() == 1)
- cout << "\n\n Player " << ((turn % 2 != 0) ? "1" : "2") << " won. Congratulations!";
- else
- cout << "\nGame draw. Nobody won :(";
- cout << "\n\n To play again, type 'restart'. To exit, type 'exit'.";
- cin.get();
- cout << endl;
- char cmd[30];
- cin.getline(cmd, 30);
- while (strcmp(cmd, "restart") && strcmp(cmd, "exit")) {
- cout << "\n !! Unknown command. Type an available command: ";
- cin.getline(cmd, 30);
- }
- if (!strcmp(cmd, "exit"))
- restart = false;
- }
- system("cls");
- cout << "\n\n\n Thank you for playing the game! \n\n\n\n\n";
- }
- void afisare() {
- system("cls");
- cout << "Player 1 (x) Player 2 (O)";
- cout << "\n | |\n "
- << v[1] << " | " << v[2] << " | " << v[3]
- << "\n ___|___|___\n | |\n "
- << v[4] << " | " << v[5] << " | " << v[6]
- << "\n ___|___|___\n | |\n "
- << v[7] << " | " << v[8] << " | " << v[9]
- << "\n | |\n";
- }
- int verificare() {
- /*
- 1 2 3
- 4 5 6
- 7 8 9
- Possible combinations for winning the game:
- 1 2 3
- 4 5 6
- 7 8 9
- 1 4 7
- 2 5 8
- 3 6 9
- 1 5 9
- 3 5 7
- */
- if (v[1] == v[2] && v[2] == v[3])
- return 1;
- if (v[4] == v[5] && v[5] == v[6])
- return 1;
- if (v[7] == v[8] && v[8] == v[9])
- return 1;
- if (v[1] == v[4] && v[4] == v[7])
- return 1;
- if (v[2] == v[5] && v[5] == v[8])
- return 1;
- if (v[3] == v[6] && v[6] == v[9])
- return 1;
- if (v[1] == v[5] && v[5] == v[9])
- return 1;
- if (v[3] == v[5] && v[5] == v[7])
- return 1;
- /*
- If all the positions on the board are occupied, the game ends with a draw
- and the functions returns -1.
- */
- if (v[1] != '1' && v[2] != '2' && v[3] != '3' && v[4] != '4' && v[5] != '5'
- && v[6] != '6' && v[7] != '7' && v[8] != '8' && v[9] != '9')
- return -1;
- /*
- Else, the game continues, and the function returns 0;
- */
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement