Files
BasicsOfComputerSoftwareEng…/OOP/FiveInARow/main.cpp
2023-03-07 16:06:20 +08:00

120 lines
3.8 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include "fiveInARow.h"
#include <iostream>
#include <string>
int main() {
ChessBoard *aBoard;
// 获取棋盘的大小,初始化棋盘
{
int boardSize = 0;
while (true) {
std::cout << "Please enter the size of the board (5-19): ";
std::cin >> boardSize;
if (std::cin.fail() || boardSize < 5 || boardSize > 19) {
std::cout << "Invalid input, try again." << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),
'\n');
}
else {
break;
}
}
aBoard = new ChessBoard(boardSize);
}
aBoard->show();
Player *players[2];
{
Player::resetCounts();
std::string temp = "";
std::cout << "Player 1 name: ";
std::cin >> temp;
players[0] = new Player(temp, BLACK, aBoard);
std::cout << "Player 2 name: ";
std::cin >> temp;
players[1] = new Player(temp, WHITE, aBoard);
}
aBoard->show();
putChessPieceResult result;
bool nowMovePlayerIndex = false;
// 只有两种状态bool足够
do {
std::cout << players[nowMovePlayerIndex]->getName() << " ["
<< (players[nowMovePlayerIndex]->getColor() ? "○White"
: "●Black")
<< "]: "
<< "Please enter the coordinate of your new chess piece."
<< std::endl;
char row, column;
while (true) {
std::cout << "Row No. ";
std::cin >> row;
if (std::cin.fail() ||
(!(('1' <= row && row <= '9') || ('A' <= row && row <= 'F') ||
('a' <= row && row <= 'f')))) {
std::cout << "Invalid input, try again." << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),
'\n');
}
else {
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),
'\n');
break;
}
}
while (true) {
std::cout << "Column No. ";
std::cin >> column;
if (std::cin.fail() ||
(!(('1' <= row && row <= '9') || ('A' <= row && row <= 'F') ||
('a' <= row && row <= 'f')))) {
std::cout << "Invalid input, try again." << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),
'\n');
}
else {
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),
'\n');
break;
}
}
result = players[nowMovePlayerIndex]->setChess(row, column);
if (result == failed) {
continue;
}
else if (result == success) {
nowMovePlayerIndex ^= 1;
aBoard->show();
continue;
}
else {
aBoard->show();
char input;
do {
std::cout << "Reset for another round? (y/n) ";
input = getchar();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),
'\n');
} while (input != 'y' && input != 'Y' && input != 'n' &&
input != 'N');
if (input == 'y' || input == 'Y') {
aBoard->reset();
aBoard->show();
Player::resetCounts();
continue;
}
else {
break;
}
}
} while (true);
return 0;
}