gpt4 book ai didi

C++骰子游戏模拟滚动两个骰子

转载 作者:行者123 更新时间:2023-11-30 04:08:27 24 4
gpt4 key购买 nike

我是一名 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;
}

关于C++骰子游戏模拟滚动两个骰子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21820871/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com