掷骰子模拟器C++

Dice Roll Simulator C++

本文关键字:C++ 模拟器 掷骰子      更新时间:2023-10-16

在课堂上,我们接到了一项任务,制作一个模拟掷骰子(或多个)的C++程序。很简单,我做得非常简单,甚至让它一次掷出超过 1 个骰子并计算一个数字掷出的次数(2-12,您将在底部的代码中看到)。但后来老师又给我们布置了作业。使程序掷出用户输入的骰子数量,根据用户输入的骰子有多少边,用户希望掷骰子多少次,并能够"握住"骰子,就像在游戏中Yahtzee一样。

我和我的同学对如何做到这一点感到非常困惑,老师给我们的创建"hold"函数的提示涉及数组。我们很困惑,因为我们唯一的数组示例是我们在课堂上做的示例,我们作为示例制作的原始骰子模拟器和掷两个骰子等。

以下是我到目前为止的代码。我知道并非所有变量都有目的,我尝试使用 Array 复制下面的代码示例,我知道我做得不对,所以请放轻松。我不是要求你为我做作业,我只是需要一些关于下一步该做什么以及我做错了什么的指导。带有注释标签的代码是我提到的原始骰子模拟器,上面是我正在研究的内容。任何帮助,不胜感激。

srand (time(NULL));
int dicenumber,diceroll,sides,rolls,rolling;
//Be able to hold, ask how many dice to roll, how many sides per die, and how many rolls
cout<<"33[1;36m How many dice would you like to roll? 33[0m n";
cin>>dicenumber;
cout<<"33[1;36m How many sides per die? 33[0m n";
cin>>sides;
cout<<"33[1;36m How many times do you want to roll? 33[0m n";
cin>>rolls;
//Sets total rolls to 0
for (rolling=0;rolling<rolls;rolling++)
    diceroll=rand()%sides+1;
    cout<<diceroll;


//Initialize variables and randomness
//srand (time(NULL));
//int COUNTER,ROLLS,TOTALS[13];
        //Set totals to 0
//for (COUNTER=0;COUNTER<13;COUNTER++)
//TOTALS[COUNTER]=0;
        //Simulate 1,000,000 dice rolls
//for (ROLLS=0;ROLLS<1000;ROLLS++)
    //TOTALS[rand()%6+1+rand()%6+1]++;
        //Output the totals
//for (COUNTER=1;COUNTER<13;COUNTER++)
    //cout<<COUNTER<<" = 33[1;36m"<<TOTALS[COUNTER]<<"33[0m n";

如果您对用户可以选择的骰子数量没有上限(或者更确切地说,没有"假定"上限),那么为了存储结果,您需要根据用户的输入分配数组,这可以像这样完成:

int *results = new int[dicenumber];
for(int i = 0; i < dicenumber; i++){
    // rolling the dice and storing the values...
    *(results+i) = rand() % sides + 1;
}// end for loop
// viewing the results...
for(int i = 0; i < dicenumber; i++){
    cout << *(results+i) << endl;
}
...
// end of program; free the memory when you're done
delete[] results;

在上述情况下,您使用指针*results指向内存中的特定地址,其中使用 new 关键字为我们分配了存储空间来存储骰子的结果。在本例中,我们分配的空间大小等于骰子数量的int倍。随着 for 循环的每次迭代,我们都会递增指针,从而通过我们的数组进行索引。

但是,如果您只是被介绍给数组,我发现您的教授不太可能想到指针算术。将结果存储在静态数组中要容易得多(或至少更直观);下面是一个示例:

int results[32]; // allocated an array of size sizeof(int)*32, so space for 32 ints!
for(int i = 0; i < dicenumber; i++){
    // indexing through the array and assigning our roll...
    results[i] = rand() % sides + 1;
}// end for loop
// viewing the results...
for(int i = 0; i < dicenumber; i++){
    cout << results[i] << endl;
}// end for loop

无论哪种方式,是的,数组是存储程序结果的简单方法。正如另一个答案所暗示的那样,您确实可以使用其他自定义类/结构的std::vector<int>或向量来存储结果,但坦率地说,静态数组以外的任何内容都是矫枉过正的(至少对于编程课程......

你可以使用std::vector<int>int[DICE_COUNT],甚至std::vector<Die>,创建一个Die类。有很多方法可以做到这一点,但基本上可以将数组/向量视为存储许多骰子的当前状态,然后可以在以后调用。