Untitled
4 years ago in Plain Text
#include <iostream>
#include <string>
std::string playerNames[2];
std::string playerSymbols[2] = {"X","O"};
bool turn; // 0
int map[3][3] = {
{-1,-1,-1},
{-1,-1,-1},
{-1,-1,-1}
};
void askForNames() {
std::cout << "Podaj nazwe gracza 1 (X): ";
std::cin >> playerNames[0];
std::cout << "Podaj nazwe gracza 2 (O): ";
std::cin >> playerNames[1];
}
int getInput() {
int input = 0;
std::cout << "Podaj pozycję od 1-9: ";
std::cin >> input;
if(input >= 1 && input <= 9) {
return input;
} else {
return getInput();
}
}
void displayMap() {
for(int i = 0; i<3; i++) {
std::cout << " | | \n";
for(int j = 0; j<3; j++) {
if(map[i][j]==-1) {
std::cout << " "; // empty cell
} else if(map[i][j]==0) {
std::cout << " X "; // cell taken by player 1
} else {
std::cout << " O "; // cell taken by player 2
}
if(j<2) std::cout << "|";
}
if(i<2) std::cout << "\n___|___|___\n";
else std::cout << "\n | | \n";
}
}
int checkForWinner(int player) {
if(map[0][0] == map[1][1] && map[1][1] == map[2][2] && map[0][0] == player) return player;
else if(map[0][2] == map[1][1] && map[1][1] == map[2][0] && map[0][2] == player) return player;
//straight
else if(map[0][0] == map[0][1] && map[0][1] == map[0][2] && map[0][0] == player) return player;
else if(map[1][0] == map[1][1] && map[1][1] == map[1][2] && map[1][0] == player) return player;
else if(map[2][0] == map[2][1] && map[2][1] == map[2][2] && map[2][0] == player) return player;
else if(map[0][0] == map[1][0] && map[1][0] == map[2][0] && map[0][0] == player) return player;
else if(map[0][1] == map[1][1] && map[1][1] == map[2][1] && map[0][1] == player) return player;
else if(map[0][2] == map[1][2] && map[1][2] == map[2][2] && map[0][2] == player) return player;
else return -1;
}
void playTurn() {
std::cout << "\nTura gracza " << playerNames[turn] << " (" << playerSymbols[turn] << ")\n";
displayMap();
int position = getInput();
int i = (position-1)/3;
int j = (position-1)%3;
int winner = -1;
if(map[i][j]==-1) { // viable move
map[i][j] = turn;
winner = checkForWinner(turn);
turn = !turn;
}
if(winner !=-1) {
displayMap();
std::cout << "Wygrał gracz " << playerNames[winner] << " (" << playerSymbols[winner] << ")!\n";
std::cin;
} else playTurn();
}
int main()
{
askForNames();
turn = 0;
playTurn();
}