我正在C++中开发一个小的骰子游戏,我的C++技能有点生疏。我真的需要有人审查我的代码,以确保我正确地实现了游戏的规则。
#include <iostream>
#include <ctime>
using namespace std;
bool checkWinning(int roll);
int main(int argc, const char * argv[])
{
//create player aka shooter
//create pair of dice
unsigned int dice1=0;
unsigned int dice2 = 0;
//create roll
unsigned int roll = 0;
//create game loop
while(checkWinning(roll) == true)
{
dice1 = rand() % 6 + 1;
dice2 = rand() % 6 + 1;
roll = dice1 + dice2;
cout<< dice1<<" +"<< dice2<<" = "<< roll << endl;
//cout<< checkWinning(2) <<endl;
}
return 0;
}
bool checkWinning(int roll)
{
bool winner = true;
if( roll == 2 || roll == 3 || roll == 12)
return winner= false;
else
if(roll == 7 || roll == 11 )
return winner;
else
return winner;
};发布于 2013-09-18 05:16:54
using namespace std。main()中的参数才是必需的。std::srand(),也不包括。但是,如果您使用的是C++11,则由于某些计算复杂性,不建议同时使用std::srand和std::rand (在下可以找到C++11伪随机数生成器)。但是,对于一个简单的程序来说,这可能并不重要。通常,如果生成//警告//如果使用std::srand() std::srand(static_cast(std::time( NULL )可能会丢失数据//偏好nullptr而不是NULL,那么只需要调用C++11 ://强制转换;只需将此包含一次,最好是在main()顶部。这是首选的,因为dice1和dice2可以在while-loop中初始化:无符号int dice1 = rand() %6+ 1;无符号int dice2 = rand() %6+ 1;然而,roll需要停留在原地,以便循环工作。bool-checking可以缩短: //这些是相似的时间(checkWinning(卷) == true),而(checkWinning(卷)) //这些也是相似的时间(checkWinning(卷) == false)但是(!checkWinning(卷))checkWinning()接受int roll,但roll已经是unsigned int了。他们应该匹配。checkWinning()'s的闭幕式卷发支撑不应该有;,它不是一种类型。bool winner似乎是多余的;只需返回true或false。而且,情况似乎有点不明朗。如果和构成赢或重滚,你如何具体区分这两者?他们都会返回true。为了澄清,我至少要重命名这个函数。也有一个布尔枚举,但这可能会导致过度(甚至没有必要,因为只有两个结束的结果)。发布于 2013-09-18 15:22:22
在兰特中使用%是错误的。
假设您的RAND_MAX与我的2147483647相同,那么每个数字的概率是:
dice1 = rand() % 6 + 1;
1: 357913942/2147483647 Notice a slightly higher probability for a 1.
2: 357913941/2147483647
3: 357913941/2147483647
4: 357913941/2147483647
5: 357913941/2147483647
6: 357913941/2147483647该解决方案使用C++11随机功能。
修正C++03's rand()中的偏斜
不幸的是,我无法找到正确的答案,所以使用rand()。
int dieRoll() // return a number between 1 and 6
{
static int maxRange = RAND_MAX / 6 * 6; // note static so calculated once.
int result;
do
{
result = rand();
}
while(result > maxRange); // Anything outside the range will skew the result
return result % 6 + 1; // So throw away the answer and try again.
}注意:
int result = rand() * 1.0 / range; // does not help with distribution发布于 2013-09-18 05:37:25
除了@Jamal所说的,…
“骰子”的单数是“死”,因此请相应地命名变量。它是C++,所以Die应该是一个类,它有一个Die.roll()方法。构造函数可以调用std::srand()。
你应该使用一个并发循环。然后,可以避免人为地将所有值初始化为非法的0值。
您的checkWinning()函数可能只是一个switch语句。它不需要一个winner变量,可以立即返回结果。我知道您在哪里实现了规则1.1和1.2,但在代码中看不到任何其他游戏规则的表达。
https://codereview.stackexchange.com/questions/31451
复制相似问题