Studies/C++

08 클래스 실습-주사위 게임

쿠뱃봉 2022. 1. 31. 17:21

1.Dice 클래스

(1)Dice.h

#pragma once
class Dice
{
private:

	int faceValue;
public:
	Dice();
	~Dice();
	void roll();
	int getFaceValue();
};

 

(2)Dice.cpp

#include "Dice.h"
#include<iostream>
#include<cstdlib>
#include<time.h>
using namespace std;
Dice::Dice() 
:faceValue(1)
{
	cout << "디폴트 생성자" << endl;
}
Dice::~Dice() 
{

}
void Dice::roll() {
	
	faceValue = rand() % 6 + 1;

}
int Dice:: getFaceValue() {

	return faceValue;


}

 

 

2.Player 클래스

(1)Player.h

#pragma once
#include<string>
#include"Dice.h"
using namespace std;
class Player
{
private:
	string name;
	int total;
public:
	Player();
	~Player();
	void setName(const string& name);
	string getName();
	void roll(Dice& dice1, Dice& dice2);
	int getTotal();
};

 

(2)Player.cpp

#include "Player.h"
#include"Dice.h"
#include<iostream>

using namespace std;
Player::Player()
:name("0"),total(0)
{

}


Player::~Player()
{
}

void Player::setName(const string& name)
{
	this->name = name;
}

string Player::getName()
{
	return name;
}

void Player::roll(Dice & dice1, Dice & dice2)
{
	dice1.roll();
    dice2.roll();
	total=dice1.getFaceValue() + dice2.getFaceValue();
}

int Player::getTotal()
{
	return total;
}

 

3.main 함수 

각 player당 던진 주사위 2개의 눈의 합을 비교해서 합이 큰 사람이 승자!

#include<iostream>
#include"Dice.h"
#include"Player.h"
#include<time.h>
using namespace std;
int main() {
	Player p1;
	Player p2;
	Dice d1, d2, d3, d4;
	srand(time(NULL));
	p1.setName("홍길동");
	p1.roll(d1, d2);
	int hong=p1.getTotal();
	cout<<"홍길동은 "<<p1.getTotal()<<endl;

	p2.setName("김길동");
	p2.roll(d3, d4);
	int kim=p2.getTotal();
	cout << "김길동은 " << p2.getTotal() << endl;
	string winner;
	if (hong == kim)
		cout << "무승부입니다" << endl;
	else {
		winner = hong > kim ? "홍길동" : "김길동";
		cout << "게임의 승자는 " << winner << "입니다" << endl;
	}

}

 

4.실행결과