[英]c++ dice game simulate rolling two dices
我是c ++初学者,我需要创建一个骰子游戏来模拟滚动两个骰子。 我对使用头文件感到很困惑。 但是首先,为什么我需要返回骰子的面数? 其次,int roll函数有什么作用? 要重置值和面孔? 如果是这样,默认值是多少? 最后一个函数Dice(int n),是否使用此函数控制骰子值的最大和? 该函数必须具有包含以下函数的类头文件:
class Dice{
private:
int face; // no. of faces of the dice
int value; // the face-value that shows up
public:
int getFace()// returns the no. of face of the dice
{
};
int getVal()
{
int dice1;
int dice2;
dice1 = rand() % 6 + 1;
dice2 = rand() % 6 + 1;
}; // returns the face value that shows up
int roll(); // simulate the roll pf the dice, the value field is set and returned.
Dice(); // default constructor , a standard six-face dice is created with value = 1
Dice(int size); // create a dice of given size
};
希望这能按顺序回答您的问题:
我看到返回每个骰子的面数的唯一原因是通知用户当前正在掷哪个骰子。 我在下面的代码中显示了一个示例,其中有dOne.getFaces()和dTwo.getFaces()。
我应该假设int roll()函数和getVal()是同一件事。 我继续删除了getVal(),而只使用roll()。
Dice()和Dice(int size)只是初始化每个骰子的面数。 默认骰子将具有6个面,但是用户可以掷出大于6个骰子,因此为int大小。
#include <iostream>
#include <cstdlib>
#include <time.h>
class Dice
{
private:
int faces; // no. of faces of the dice
int value; // the face-value that shows up
public:
int getFaces() {return faces;} // returns the no. of faces of the dice
int roll() // returns the face value that shows up
{
value = rand() % faces + 1;
return value;
}
Dice() : faces(6) {}; // default constructor, create a dice of standard size
Dice(int size) : faces(size) {}; // create a dice of given size
};
int main()
{
srand( time(NULL) ); // Initialize random seed
char yesNo;
std::cout << "\nWould you like to roll two normal dice? (y/n)\n";
std::cin >> yesNo;
if ( yesNo == 'y' )
{
Dice dOne, dTwo;
std::cout << "\nA dice with " << dOne.getFaces() << " faces rolled: " << dOne.roll() << '\n';
std::cout << "A dice with " << dTwo.getFaces() << " faces rolled: " << dTwo.roll() << '\n';
}
else
{
int dFaces;
std::cout << "\nHow many faces would you like each dice to have?\n\n";
std::cout << "Dice 1: ";
std::cin >> dFaces;
Dice dOne(dFaces);
std::cout << "Dice 2: ";
std::cin >> dFaces;
Dice dTwo(dFaces);
std::cout << "\nA dice with " << dOne.getFaces() << " faces rolled: " << dOne.roll() << '\n';
std::cout << "A dice with " << dTwo.getFaces() << " faces rolled: " << dTwo.roll() << '\n';
}
return 0;
}
您需要定义一个构造函数。 构造函数的作用是设置类的状态,因此在这种情况下,它要设置有关骰子的信息。
如果要将它们直接放在标题中,则构造函数的格式如下所示:
//file: dice.h
//this is default constructor, note the lack of parameters being passed in
Dice(): face(?), value(?) // here we are initializing "face" and "value", replace the question marks with the correct values as per your specification
{
}
如果您在cpp文件中执行此操作,则有些不同,但逻辑应保持不变。
//file: dice.h
Dice(); //This is only a declaration
//file: dice.cpp
#include "dice.h"
Dice::Dice(): face(?), value(?) //This is where we define the constructor. note the Dice:: part here, we need to tell the compiler where to look
{
}
其余部分非常相似。 如果您在挣扎,那么我建议您进一步学习一些c ++资源。 我会查找构造函数/析构函数以及初始化列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.