1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
|
//Copyright 2017 Hayley Walker hayleyjw@bu.edu
//C++ program w4tttanalyse.cpp that reads tic-tac-toe scenarios from a file and determines the status of each game.
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
using std::cout;
using std::endl;
using std::cin;
using std::string;
using std::vector;
using std::getline;
string gameline;
char space = '#'; //empty space
char x = 'x';
char o = 'o';
char winner;
int wincount = 0;
int idx1;
int idx2;
int idx3;
//check for a winner given 3 indices. If a winner exists, return true
//and set "winner" to the winning char. Otherwise return false.
bool getWinner(int idx1, int idx2, int idx3, char winner) {
if (gameline[idx1] == gameline[idx2] && gameline[idx2] == gameline[idx3]) {
if (gameline[idx1] != space) {
winner = gameline[idx1];
wincount++;
return true;
}
}
return false;
}
int main () {
std::ifstream myfile;
vector <std::string> gamevec;
myfile.open ("tictactoeboards.txt");
if (myfile.is_open())
{ while (std::getline (myfile, gameline))
{ gamevec.push_back(gameline);}
myfile.close();
}
for (string gameline : gamevec) {
int countspace = 0;
int countx = 0;
int counto = 0;
for (int i = 0 ; i < 9; i++) {
if (gameline[i] == space) {
countspace++;}
if (gameline[i] == 'x') {
countx++;}
if (gameline[i] == 'o') {
counto++;
}
} //invalid based on number of x's and o's (x plays first, so we can't have more o's than x's)
if (counto > countx || countx > counto + 1) {
std::cout << gameline << " " << "i" << std::endl;}
else
{ //Ways that x or o can win
if (getWinner(0,3,6,winner) || getWinner(1,4,7,winner) ||
getWinner(2,5,8,winner) || getWinner(0,4,8,winner) ||
getWinner(2,4,6,winner) || getWinner(0,1,2,winner) ||
getWinner(3,4,5,winner) || getWinner(6,7,8,winner)) {
std::cout << gameline << " " << winner << std::endl;
}
//other cases, if invalid or if nobody wins (i denotes invalid)
else if ((winner == 'o' and counto != countx) || (winner == 'x' and counto == countx)) {
std::cout << gameline << " " << "i" << std::endl;
}
//tie games: if game is finished and nobody won (winner does not equal x or o)
else if (countspace == 0 and getWinner == false) {
std::cout << gameline << " " << "t" << std::endl;
}
//games in progress: if nobody won yet and game isnt finished, and its a valid game so far
else if (countspace != 0 and getWinner == false) {
std::cout << gameline << " " << "c" << std::endl;}
}
}
return 0;
}
|