Ahoj!
Ostatnio napisałem konsolową wersję znanej wszystkim gry kółko i krzyżyk. Prosiłbym o ocenę kodu i o ewentualne porady oraz wskazówki.
//main.cpp
#include "../include/functions.h"
using namespace std;
int main()
{
char again {'Y'};
while (again == 'Y' || again == 'y')
{
string square {"0123456789"};
char player {'X'};
int status {-1};
while (status == -1)
{
move(square, player);
status = check(square);
}
player = player == 'X' ? 'O' : 'X';
draw_board(square);
if (status == 1)
cout << "\nPlayer " << player << " won!\n";
else
cout << "\nGame draw!\n";
cout << "\vPlay again? (Y)es, (N)o/(E)xit? ";
cin >> again;
}
return 0;
}
//functions.cpp
#include "../include/functions.h"
using namespace std;
void draw_board(const string& s)
{
system("clear");
cout << "Tic-Tac-Toe\n\v";
for(int i=1; i!=10; ++i)
{
cout << ' ' << s[i] << ' ';
if(i % 3)
cout << '|';
else if(i != 9)
cout << "\n---+---+---\n";
else cout << endl;
}
}
void move(string& s, char& player)
{
draw_board(s);
cout << "\nPlayer " << player << " moves: ";
static int choice {0};
cin >> choice;
while (choice < 1 || choice > 9 || s[choice] > 57)
{
cout << "Invalid move!";
cin.ignore();
getchar();
draw_board(s);
cout << "\nPlayer " << player << " moves: ";
cin >> choice;
}
s[choice] = player;
player = player == 'X' ? 'O' : 'X';
}
int check(const string& s)
{
static const int ways[8][3] {{1,2,3},{4,5,6},{7,8,9},
{1,4,7},{2,5,8},{3,6,9},
{1,5,9},{3,5,7}};
for (int i=0; i!=8; ++i)
if (s[ways[i][0]] == s[ways[i][1]] && s[ways[i][1]] == s[ways[i][2]])
return 1;
int count {};
for (int i=1; i!=10; ++i)
if (s[i] != 48+i)
++count;
if (count == 9)
return 0;
return -1;
}
//functions.h
#include <iostream>
void draw_board(const std::string&);
void move(std::string&, char&);
int check(const std::string&);