92 lines
3.0 KiB
C++
92 lines
3.0 KiB
C++
#include "gameplay.h"
|
|
#include <iostream>
|
|
#include <fstream>
|
|
#include <cstdlib>
|
|
|
|
using namespace std;
|
|
|
|
Gameplay::Gameplay(int rows, int cols, Player *player1, Player *player2): board(rows, cols), player1(player1), player2(player2) {
|
|
|
|
}
|
|
|
|
void Gameplay::playGame() {
|
|
// Write board dimensions to the output file
|
|
cout << board.getRows() << " " << board.getCols() << '\n';
|
|
char currentPlayer = player1->getName(); // Start with the RandomPlayer
|
|
while (true) {
|
|
int row, col;
|
|
// Determine the move based on the current player
|
|
if (currentPlayer == player1->getName()) {
|
|
player1->selectLineLocation(board, row, col);
|
|
} else {
|
|
player2->selectLineLocation(board, row, col);
|
|
}
|
|
// Validate and place the move
|
|
if (board.isLineValid(row, col)) {
|
|
board.placeLine(row, col, currentPlayer);
|
|
cout << currentPlayer << " " << row << " " << col << '\n';
|
|
int boxesCompleted = board.checkAndMarkBox(row, col, currentPlayer);
|
|
if (boxesCompleted == 0) {
|
|
// Switch to the next player if no boxes are earned
|
|
currentPlayer = (currentPlayer == player1->getName())
|
|
? player2->getName()
|
|
: player1->getName();
|
|
}
|
|
} else {
|
|
cout << currentPlayer << " made an invalid move at (" << row << ", " << col << ")!" << '\n';
|
|
return;
|
|
}
|
|
|
|
// Check if the board is full
|
|
if (board.isFull()) {
|
|
cout<<"END"<<endl;
|
|
break;
|
|
}
|
|
}
|
|
|
|
// Print the final board state
|
|
board.printBoard();
|
|
|
|
// Determine the winner and display results
|
|
determineWinner();
|
|
}
|
|
|
|
Gameplay::~Gameplay() {
|
|
// Free the player objects
|
|
free(this->player1);
|
|
free(this->player2);
|
|
|
|
// Alternatively
|
|
/*
|
|
delete this->player1;
|
|
delete this->player2;
|
|
*/
|
|
}
|
|
|
|
void Gameplay::determineWinner() {
|
|
int randomPlayerBoxes = 0, strategicPlayerBoxes = 0;
|
|
|
|
// Iterate over the centers of boxes
|
|
for (int r = 1; r < 2 * board.getRows() - 2; r += 2) { // Center rows of boxes
|
|
for (int c = 1; c < 2 * board.getCols() - 2; c += 2) { // Center columns of boxes
|
|
char boxOwner = board.get(r, c); // Get the owner of the box
|
|
if (boxOwner == player1->getName()) {
|
|
randomPlayerBoxes++;
|
|
} else if (boxOwner == player2->getName()) {
|
|
strategicPlayerBoxes++;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Display results
|
|
cout << "Player " << player1->getName() << " has " << randomPlayerBoxes << " boxes." << '\n';
|
|
cout << "Player " << player2->getName() << " has " << strategicPlayerBoxes << " boxes." << '\n';
|
|
|
|
if (randomPlayerBoxes > strategicPlayerBoxes) {
|
|
cout << "Player " << player1->getName() << " (wins)" << '\n';
|
|
} else if (strategicPlayerBoxes > randomPlayerBoxes) {
|
|
cout << "Player " << player2->getName() << " (wins)" << '\n';
|
|
} else {
|
|
cout << "The game is a tie!" << '\n';
|
|
}
|
|
} |