Ir ao conteúdo

Posts recomendados

Postado
#pragma once
#include "player.h"

class jogador :public player
{
private:
	float experiencia; //% de jogos q o jogador ganhou
	float total_jogos;//total de jogos ganhos
	float jogos_ganhos;//total de jogos ganhos
public:
	jogador();
	jogador(char _simbolo, string _nome, ponto _escolhas[5], int _num_jogadas, float _experiencia, float _total_jogos, float _jogos_ganhos);
	virtual ~jogador();
	//set e get
	void SetExperiencia(float _experiencia) { this->experiencia = _experiencia; }
	void SetTotal_jogos(float _total_jogos) { this->total_jogos = _total_jogos; }
	void SetJogos_ganhos(float _jogos_ganhos) { this->jogos_ganhos = _jogos_ganhos; }
	float GetExperiencia(void) { return this->experiencia; }
	float GetTotal_jogos(void) { return this->total_jogos; }
	float GetJogos_ganhos(void) { return this->jogos_ganhos; }
	//outras
	ponto Posiçao(bool valid);//jogador escolhe a posiçao para jogar
	void ADD_Game(int opcao);//opcao=0 o jogador perde o jogo, opção =1 o jogador ganha o jogo
	void Calcula_experiencia(int opcao);//calcula a % de vitorias, opcao ADD_Game
	void show();//mostra a informaçao dos jogadores
	void operator =(const jogador p);
	void Save(ofstream & os);
	void Read(ifstream & is);

};
#include "pch.h"
#include "jogador.h"


jogador::jogador()
{
	experiencia = 0;
	total_jogos = 0;
	jogos_ganhos = 0;
}


jogador::jogador(char _simbolo, string _nome, ponto _escolhas[5], int _num_jogadas, float _experiencia, float _total_jogos, float _jogos_ganhos)
	:player(_simbolo, _nome, _escolhas[5], _num_jogadas)
{
	experiencia = _experiencia;
	total_jogos = _total_jogos;
	jogos_ganhos = _jogos_ganhos;
}


jogador::~jogador()
{
}

ponto jogador::Posiçao(bool valid)
{
	int aux = this->GetNum_jogadas();
	//verifica se a ultima jogada foi valida ou as ultimas coordenadas q o jogador escolheu ja foram tiradas
	if (valid) {
		aux++;
		this->SetNum_jogadas(aux);
	}
	cout << this->GetNome() << " faça a sua jogada: " << endl;
	ponto auxp;//auxp para ajudar a fazer a jogada
	while (!auxp.Ask2SetPonto()) {
		cout << "Escolha apenas entre 1 a 3. Insira novas coordenadas: " << endl;
	}
	this->SetEscolhas(auxp, aux);//adiciona a posicao para jogar 
	return auxp;
}

void jogador::ADD_Game(int opcao)
{
	if (opcao == 0) {//jogador perde o jogo
		this->total_jogos++;
	}
	else if (opcao == 1) {//jogador ganha o jogo
		this->total_jogos++;
		this->jogos_ganhos++;
	}
}

void jogador::Calcula_experiencia(int opcao)
{
	this->ADD_Game(opcao);
	this->experiencia = this->jogos_ganhos / this->total_jogos;
}

void jogador::show()
{
	cout << "Nome: " << this->GetNome() << endl;
	cout << "Total de jogos jogados: " << this->total_jogos << endl;
	cout << "Percentagem de vitorias: " << this->experiencia << endl << endl;
}

void jogador::operator=(const jogador p)
{
	this->experiencia = p.experiencia;
	this->total_jogos = p.total_jogos;
	this->jogos_ganhos = p.jogos_ganhos;
	player::SetNome(p.GetNome());
	for (int i = 0; i < 5; i++) {
		player::SetEscolhas(p.GetEscolhas(i), i);
	}
	player::SetNum_jogadas(p.GetNum_jogadas());
	player::SetSimbolo(p.GetSimbolo());

}

void jogador::Save(ofstream & os)
{
	player::Save(os);
	os << this->experiencia << ";" << this->total_jogos << ";" << this->jogos_ganhos << endl;
}

void jogador::Read(ifstream & is)
{
	player::Read(is);
	is >> this->experiencia;
	is.ignore(INT16_MAX, ';');
	is >> this->total_jogos;
	is.ignore(INT16_MAX, ';');
	is >> this->jogos_ganhos;
}
 
#include <time.h>
#include "ponto.h"
#include "Tabuleiro.h"
#include "Jogador.h"
#include "Computador.h"

using namespace std;

class Jogo
{
private:
	bool bot;//bot esta a jogar? true=sim, false=nao
protected:
	jogador player1, player2;
	Computador bot1;
	int count;//conta quantas posiçoes do tabuleiro ja foram tomadas
	Tabuleiro tab;//tabuleiro
public:
	Jogo();
	Jogo(Tabuleiro _tabuleiro, jogador _player1, jogador _player2, Computador _bot1, int _contador, bool _computador);
	virtual ~Jogo();

	//Sets and gets
	void SetTabuleiro(Tabuleiro _tabuleiro) { this->tab = _tabuleiro; }
	void SetJogador1(jogador _player1) { this->player1 = _player1; }
	void SetJogador2(jogador _player2) { this->player2 = _player2; }
	void SetBOT1(Computador _bot1) { this->bot1 = _bot1; }
	void SetContador(int _contador) { this->count = _contador; }
	void SetComputador(bool _computador) { this->bot = _computador; }
	int GetContadort() { return this->count; }
	bool GetBot() { return this->bot; }
	Tabuleiro GetTabuleiro() { return this->tab; }
	jogador GetJogador1() { return this->player1; }
	jogador GetJogador2() { return this->player2; }
	Computador GetBOT1() { return this->bot1; }
	//outros
	void FullReset();//alterar a redefinição do gamemod

	void operator=(const Jogo newgame);//sobrecarga para o construtor
//Começar o jogo
	int First2Play();// decide quem joga primeiro
	void Set_Player_Name();//pedir nome aos jogadores
	void Set_Players_Symbol();//definir símbolo;
	int Begin_Game(int option);// Definir tipo de jogo// opcao = 1 -> newgame; 2-> jogar Agian;
	virtual int Read();//recarrega o jogo
	virtual void Save_Mode();// salva o modo de jogo
	// mode = 1-> classic vs bot
	// = 2 -> clássico contra jogador
	// = 3 -> campeonato contra bot
	// = 4 -> campeonato contra jogador

	// durante o jogo
	void Make_Play(int aux);// jogadores fazem suas jogadas, aux = Game aux
	virtual void Save(int aux);// salve o jogo, aux = primeiro a jogar
	// Fim do Jogo
	char Check_Winner();//verificar se já existe um vencedor
	void Validate_Winner(char caux);//caux = símbolo que ganhou
	void ResetGame();//Atributos do jogo redefinidos
	int Play_Again();//joga novamente
	void Show_Player_Stats();//mostrar estatísticas do jogador
	void Empty_Save_File();//esvazie o arquivo que salva o jogo quando o jogo terminar
//Jogo completo
	virtual void Complete_Game(int option, int f2p);// f2p -> recarrega a variável do jogo. diz ao programa quem é o primeiro a jogar
	// option = opção begin_game
};

#include "pch.h"
#include "Jogo.h"


Jogo::Jogo()
{
	tab = Tabuleiro();//construtor da classe tab
	player1 = jogador();//construtor da classe jog
	player2 = jogador();
	bot1 = Computador();//construtor da classe comp
	count = 0;
	bot = false;//nao esta a jogar
}

Jogo::Jogo(Tabuleiro _tabuleiro, jogador _player1, jogador _player2, Computador _bot1, int _contador, bool _computador)
{
	tab = _tabuleiro;
	player1 = _player1;
	player2 = _player2;
	bot1 = _bot1;
	count = _contador;
	bot = _computador;
}


Jogo::~Jogo()
{
}

void Jogo::FullReset()
{
	Jogo();
}

void Jogo::operator=(const Jogo newgame)
{
	this->player1 = newgame.player1;
	this->player2 = newgame.player2;
	this->bot1 = newgame.bot1;
	this->bot = newgame.bot;
	this->count = newgame.count;
	this->tab = newgame.tab;
}

int Jogo::First2Play()
{
	int aux;

	srand(time(NULL));
	aux = (rand() % 2);

	return aux; // se o retorno 1 - jogador1 jogar primeiro; se retornar 0 - o jogador2 joga primeiro;
}

void Jogo::Set_Player_Name()
{
	string aux;
	cout << "Insert Player1's name: ";
	cin.ignore(INT16_MAX, '\n');
	getline(cin, aux);
	this->player1.SetNome(aux);

	if (!this->bot)
	{
		cout << "Insert Player2's name: ";
		getline(cin, aux);
		this->player2.SetNome(aux);
	}
}

void Jogo::Set_Players_Symbol()
{
	srand(time(NULL));
	if ((rand() % 2) == 1)
	{
		cout << this->player1.GetNome() << " e as 'O'." << endl;
		this->player1.SetSimbolo('O');
		if (!this->bot)
		{
			cout << this->player2.GetNome() << " e as 'X'." << endl;
			this->player2.SetSimbolo('X');
		}
		else
		{
			cout << "Computador e as 'X'." << endl;
			this->bot1.SetSimbolo('X');
		}

	}
	else
	{
		cout << this->player1.GetNome() << " e as 'X'." << endl;
		this->player1.SetSimbolo('X');
		if (!this->bot)
		{
			cout << this->player2.GetNome() << " e as 'X'." << endl;
			this->player2.SetSimbolo('O');
		}
		else
		{
			cout << "Computador e as 'X'." << endl;
			this->bot1.SetSimbolo('O');
		}
	}
}

int Jogo::Begin_Game(int option)
{
	if (option == 1) //novo jogo
	{
		this->Set_Player_Name(); //player 1 nome
		this->Set_Players_Symbol(); //definir bot e jogador símbolos
		return this->First2Play(); //escolha quem joga primeiro
	}
	else // continuar jogo anterior
		return this->First2Play(); //escolha o primeiro a jogar até o próximo jogo mais retorne 100;
}

int Jogo::Read()
{
	int aux;
	ifstream is;

	is.open("reload_game.txt");

	if (!is.is_open())
		return -1;

	is >> this->count;
	is.ignore(INT16_MAX, ';');
	is >> aux;
	if (this->bot)
	{
		this->player1.Read(is);
		this->bot1.Read(is);
	}
	else if (!this->bot)
	{
		this->player1.Read(is);
		this->player2.Read(is);
	}
	this->tab.Read(is);
	is.close();

	return aux;
}

void Jogo::Save_Mode()
{
	ofstream os;

	os.open("mode.txt");
	if (!os.is_open())
	{
		cout << "ERROR ficheiro mode.txt (save)" << endl;
		return;
	}

	if (this->bot == true) //joga contra computador
		os << "1";
	else //contra jogador
		os << "2";

	os.close();//fecha ficheiro
}

void Jogo::Make_Play(int aux)
{
	bool valid = true; //ve se a posiçao escolhoida é valida
	if ((this->count + aux) % 2 == 0) //jogador1 joga
	{
		while (!this->tab.SetMatriz_posicao(this->player1.GetSimbolo(), this->player1.play(valid)))
		{//verifica se a posição é válida e livre
			valid = false;
			cout << "Insira uma posicao vazia!" << endl;
		}
	}
	else if ((this->count + aux) % 2 == 1) //joga o computqador ou o kog2
	{
		if (this->bot) //joga computador
		{
			int i = 0;
			while (!this->tab.SetMatriz_posicao(this->bot1.GetSimbolo(), this->bot1.play(valid)))
			{
				i++;
				valid = false;
				if (i == 10)
					cout << "O computador está um pouco lento hoje!" << endl;
			}
		}
		else if (!this->bot) //joga o jog2
		{
			while (!this->tab.SetMatriz_posicao(this->player2.GetSimbolo(), this->player2.play(valid)))
			{//faz um jogo. verifica se a posição é válida e livre
				valid = false;
				cout << "Insira uma posicao vazia!" << endl;
			}
		}
	}
}

void Jogo::Save(int aux)
{
	ofstream os;

	//abrir ficheiro
	os.open("reload_game.txt");

	if (!os.is_open())
		return;

	os << this->count << ";" << aux << endl;

	if (this->bot)
	{//players info
		this->player1.Save(os);
		this->bot1.Save(os);
	}
	else
	{//players info
		this->player1.Save(os);
		this->player2.Save(os);
	}
	this->tab.Save(os);
	os.close();
}

char Jogo::Check_Winner()
{
	jogador p1;
	//horizontal and vertical
	for (int i = 0; i < 3; i++)
	{
		if ((this->tab.GetMatriz_posicao(i, 0) == this->tab.GetMatriz_posicao(i, 1)) && (this->tab.GetMatriz_posicao(i, 0) == this->tab.GetMatriz_posicao(i, 2))
			&& (this->tab.GetMatriz_posicao(i, 0) == 'O' || this->tab.GetMatriz_posicao(i, 0) == 'X')) //check horizontal lines
		{
			return this->tab.GetMatriz_posicao(i, 0);
		}
		if (this->tab.GetMatriz_posicao(0, i) == this->tab.GetMatriz_posicao(1, i) && (this->tab.GetMatriz_posicao(0, i) == this->tab.GetMatriz_posicao(2, i))
			&& (this->tab.GetMatriz_posicao(0, i) == 'O' || this->tab.GetMatriz_posicao(0, i) == 'X')) //check vertical lines
		{
			return this->tab.GetMatriz_posicao(0, i);
		}
	}
	if ((this->tab.GetMatriz_posicao(1, 1) == this->tab.GetMatriz_posicao(2, 2) && this->tab.GetMatriz_posicao(1, 1) == this->tab.GetMatriz_posicao(0, 0))
		|| (this->tab.GetMatriz_posicao(2, 0) == this->tab.GetMatriz_posicao(1, 1) && (this->tab.GetMatriz_posicao(2, 0) == this->tab.GetMatriz_posicao(0, 2)))
		&& (this->tab.GetMatriz_posicao(1, 1) == 'O' || this->tab.GetMatriz_posicao(1, 1) == 'X')) //check diagonal lines
	{
		return this->tab.GetMatriz_posicao(1, 1);
	}
	else return '?';
}

void Jogo::Validate_Winner(char caux)
{
	//empate
	if (caux == '?')
	{
		cout << "O tabuleiro está cheio.Nenhum jogador como 3 símbolos em uma linha.É UM EMPATE!" << endl;

		// se estiver jogando 1 jogador e um computador
		if (this->bot)
			this->player1.Calcula_experiencia(0); //atualizar jogador experiencia
		//se estiver jogando 2 jogadores
		else if (!this->bot)
		{
			this->player1.Calcula_experiencia(0); //atualizar jogador experiencia
			this->player2.Calcula_experiencia(0); //atualizar jogador experiencia
		}
	}


	//jogador1 ganha
	if (caux == this->player1.GetSimbolo())
	{
		cout << this->player1.GetNome() << "foi o primeiro a obter 3 símbolos em uma linha." << this->player1.GetNome() << " won!" << endl;
		this->player1.Calcula_experiencia(1);

		//se estiver jogando 2 jogadores
		if (!this->bot)
			this->player2.Calcula_experiencia(0);
	}


	//se jogador2 ou bot1 ganhar
	if (this->bot) //brincando com bot
	{
		//bot1 ganha
		if (caux == this->bot1.GetSimbolo())
		{
			cout << "O computador foi o primeiro a receber 3 símbolos em uma linha. Computador vence!" << endl;
			this->player1.Calcula_experiencia(0);
		}
	}
	else if (!this->bot)  //jogando com o player2

	{
		//jogador2 ganha
		if (caux == this->player2.GetSimbolo())
		{
			cout << this->player2.GetNome() << "foi o primeiro a obter 3 símbolos em uma linha." << this->player2.GetNome() << " Ganhou!" << endl;
			this->player2.Calcula_experiencia(1);
			this->player1.Calcula_experiencia(0);
		}
	}
	Sleep(3000); //pare o jogo por 3 segundos
}

void Jogo::ResetGame()
{
	this->tab = Tabuleiro();
	this->count = 0;
	this->player1.Game_Reset();
	if (this->bot)
		this->bot1.reset();
	else
		this->player2.Game_Reset();
}

int Jogo::Play_Again()
{
	int aux;

	do
	{
		do
		{
			system("CLS");
			cout << "1 - jogar novamente" << endl
				<< "2 - Verificar as estatísticas do jogador" << endl
				<< "3 - Retornar ao menu" << endl
				<< "  Opcao: ";
			cin >> aux;

			if (aux == 2)//estatísticas do jogador
				this->Show_Player_Stats();
		} while (aux == 2);

		if (aux < 1 || aux > 3)//validar opção
		{
			cout << "Insira uma opcao valida;";
			Sleep(3000);
		}
	} while (aux < 1 || aux > 3);
	return aux++; //+1 porque no begin_game, a opção 2 é reproduzida novamente;
}

void Jogo::Show_Player_Stats()
{
	system("CLS");
	this->player1.show();
	if (!this->bot)//contra jog2
		this->player2.show();

	system("PAUSE");
}

void Jogo::Empty_Save_File()
{
	ofstream os;

	os.open("reload_game.txt");

	if (!os.is_open())
	{
		cout << "ERROR file reload_game(empty)" << endl;
		return;
	}

	os.close();
}

void Jogo::Complete_Game(int option, int f2p)
{
	int auxoption = option;
	int aux = -1; // aux que ajuda decido quem está jogando
	char caux; //aux que ajuda a identificar quem ganhou


	do
	{
		this->Save_Mode(); //salvar o modo de jogo;

		system("CLS");
		caux = '?'; // redefinir variavel
		//inicio
		if (f2p == -1)  //novo jogo
			aux = this->Begin_Game(auxoption); // selecione o jeito de começar o jogo
		else if (f2p == 0 || f2p == 1) //jogo guardado
			aux = f2p;

		this->tab.DesenhaTabuleiro();

		//Meio do jogo
		do
		{
			this->count++;
			this->Make_Play(aux); //os jogadores fazem suas jogadas
			system("CLS");
			this->tab.DesenhaTabuleiro();
			this->Save(aux); // salva automaticamente o jogo

			if (this->count >= 5)
				caux = this->Check_Winner(); //verifique se existe algum vencedor
		} while ((this->count < 9) && (caux == '?'));

		//End Game
		this->Validate_Winner(caux); //validar vencedor
		this->Empty_Save_File(); //esvazia o arquivo porque o jogo terminou
		this->ResetGame();
	} while ((auxoption = this->Play_Again()) == 1);
}

Ola no jogo do galo da me um erro na classe jogo diz " 'jogador':cannot instantiate abstract class " eu nao estou a conseguir resolver, uma ajudinha dava jeito.

 

Postado

A classe "jogador" não está implementado todos as funções declaradas. Será que você não esqueceu de implementar alguma função virtual da classe pai "player"? A classe "player" é abstrata não é? você tem que implementar TODAS as funções virutais da classe pai na filha, caso contrário a filha também será considerada abstrata. 

Exemplo: 

 

#include <iostream>

using namespace std;
class pai
{
  virtual int funcao() = 0;
};

class filho : pai
{

};
int main()
{
    filho teste;
    cout<<"Hello World";

    return 0;
}

Dá o mesmo erro, porque "pai" é abstrata e "filho", derivada de "pai", não implementou a função "funcao", e, portanto, é considerada abstrata também. Para consertar, basta implementar a função virtual:

#include <iostream>

using namespace std;
class pai
{
  virtual int funcao() = 0;
};

class filho : pai
{
  int funcao() {return 0;}
};
int main()
{
    filho teste;
    cout<<"Hello World";

    return 0;
}

Agora não dá mais o erro. Espero ter ajudado.

Crie uma conta ou entre para comentar

Você precisa ser um usuário para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar agora

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...

LANÇAMENTO!

eletronica2025-popup.jpg


CLIQUE AQUI E BAIXE AGORA MESMO!