cmpsc330hw4/gameplay.cpp
2024-11-19 18:54:26 -05:00

96 lines
3.4 KiB
C++

#include "gameplay.h"
#include <iostream>
#include <fstream>
using namespace std;
Gameplay::Gameplay(int rows, int cols, Player *player1, Player *player2): board(rows, cols), player1(player1), player2(player2) {
}
Gameplay::~Gameplay() {
// TODO: needs revie
free(this->player1);
free(this->player2);
}
void Gameplay::playGame() {
std::ofstream outputFile("output.txt");
if (!outputFile) {
std::cerr << "Error: Could not open output file for writing." << std::endl;
return;
}
// Write board dimensions to the output file
outputFile << board.getRows() << " " << board.getCols() << std::endl;
std::cout << board.getRows() << " " << board.getCols() << std::endl;
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);
outputFile << currentPlayer << " " << row << " " << col << std::endl;
std::cout << currentPlayer << " " << row << " " << col << std::endl;
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 {
std::cout << currentPlayer << " made an invalid move at (" << row << ", " << col << ")!" << std::endl;
return;
}
// Check if the board is full
if (board.isFull()) {
outputFile << "END" << std::endl;
cout<<"END"<<endl;
break;
}
}
// Print the final board state
board.printBoard();
// Determine the winner and display results
determineWinner();
outputFile.close();
}
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
std::cout << "Player " << player1->getName() << " has " << randomPlayerBoxes << " boxes." << std::endl;
std::cout << "Player " << player2->getName() << " has " << strategicPlayerBoxes << " boxes." << std::endl;
if (randomPlayerBoxes > strategicPlayerBoxes) {
std::cout << "Player " << player1->getName() << " (wins)" << std::endl;
} else if (strategicPlayerBoxes > randomPlayerBoxes) {
std::cout << "Player " << player2->getName() << " (wins)" << std::endl;
} else {
std::cout << "The game is a tie!" << std::endl;
}
}