Terminé hace poco un curso en Codecademy y por curiosidad intenté hacer un programa que sirva para jugar "Tres en raya", "Tatetí" o "Tic-Tac-Toe". Sin embargo el programa se cierra, lo abra como ejecutable o lo abra desde una consola ya abierta. Adjunto el código de los tres archivos: main.cpp
, fns.cpp
y fns.hpp
.
main.cpp
:
#include <iostream>
#include <cmath>
#include <string>
#include <vector>
#include "fns.hpp"
int main(){
board game1;
int xaxis, yaxis;
char player;
for(int i=0; i<9; i++){
if(i%2==0){
player = 'X';
}else{
player = 'O';
}
std::cout << "X:";
std::cin >> xaxis;
std::cout << "Y:";
std::cin >> yaxis;
game1.set(xaxis, yaxis, player, i);
std::cout << game1.state();
if(game1.win() == true){
std::cout << "And the winner is... " << game1.winner;
}
}
std::cout << "That's a tie!";
}
fns.hpp
:
#include <iostream>
#include <cmath>
#include <string>
#include <vector>
class board{
std::vector<std::vector<char>> space;
public:
char winner;
board();
void set(int x, int y, char symbol, int &ref_i);
std::string state();
bool win();
};
fns.cpp
:
#include <iostream>
#include <cmath>
#include <string>
#include <vector>
#include "fns.hpp"
board::board(){
for(int i = 0; i<3; i++){
space[i][0] = ' ';
space[i][1] = ' ';
space[i][2] = ' ';
}
}
void board::set(int x, int y, char symbol, int &ref_i){
if(space[x][y] == ' '){
space[x][y] = symbol;
}else{
std::cout << "This place is already occupied :(";
ref_i--;
}
}
bool board::win(){
//Vertical
for(int i=0; i<3; i++){
if(space[i][0] == space[i][1] && space[i][1] == space[i][2]){
winner = space[i][0];
return true;
}
}
//Horizontal
for(int i=0; i<3; i++){
if(space[0][i] == space[1][i] && space[1][i] == space[2][i]){
winner = space[0][i];
return true;
}
}
//Diagonal
if(space[0][0] == space[1][1] && space[1][1] == space[2][2]){
winner = space[0][0];
return true;
}
if(space[2][0] == space[1][1] && space[1][1] == space[0][2]){
winner = space[2][0];
return true;
}
return false;
}
std::string board::state(){
std::string temp = "";
for(int i = 0; i < 3; i++){
temp = temp + space[0][i] + space[1][i] + space[2][i] + " \n ";
}
return temp;
}