骰子游戏,使每个骰子滚动不同
Dice Game, making each Die roll differently
好的,我刚刚完成了我的练习,并坚持如何让每个骰子掷出自己的随机生成的数字。该程序实际上确实掷出随机数,只是每次您重新掷骰子时总是掷出完全相同的数字。这个简单但令人头疼的问题发生了,出于某种原因,我也有
cout << "Adding both dices up you rolled a total of: " << totalScore() << "." << endl;
一位同学还告诉我,我的面值是非法值,应该设置为合法值。我不太明白他的意思,我相信这会(不是很多)降低我的一些成绩。
#include "stdafx.h"
#include <iostream>
#include <string>
#include <ctime>
using namespace std;
class PairOfDice
{
private:
int diceOne;
int diceTwo;
int score;
int faceVaule;
public:
PairOfDice(){
srand(time(NULL));
roll();
}
void roll(){
diceOne = (rand() % 6) + 1;
diceTwo = (rand() % 6) + 1;
setdiceOne(diceOne);
setdiceTwo(diceTwo);
}
void setdiceOne(int value){
faceVaule = value;
}
int getdiceOne(){
return faceVaule;
}
void setdiceTwo(int value){
faceVaule = value;
}
int getdiceTwo(){
return faceVaule;
}
void totalScore(){
score = diceOne + diceTwo;
}
void display(){
cout << "The first Dice rolled a " << getdiceOne() << " ." << endl;
cout << "The second Dice rolled a " << getdiceTwo() << " ." << endl;
// adding both dices gives an: No operator " < < " matches these operands
cout << "Adding both dices up you rolled a total of: " << totalScore() << "." << endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
PairOfDice game;
game.roll();
game.display();
game.totalScore();
return 0;
}
首先:你掷两个骰子,将结果存储在 dice1 和 dice2 中,然后你把这些值发送到两个函数,这两个函数将值放入一个名为 faceValue 的变量中。取回值将只返回第二个骰子值是合乎逻辑的,因为这是您上次在 faceValue 中输入的值。
这就是为什么两个骰子都显示相同的值。
现在对于错误:您的 totalScore 函数返回一个 void,而 <<运算符需要某种类型。totalScore 函数将两个骰子相加(顺便说一下,正确的值)并将结果放入 score 中,但无处返回分数中的值。
你的代码真的很乱。不应有一个成员变量 (faceValue) 保存两个不同值的副本。你根本不应该有这个成员。只需使用骰子一和骰子两个值。当设置值时 ( = rand() % 6 + 1 ),不应通过调用 set-function 再次设置它们:要么创建一个正确的 set-函数(因为这个不正确)并将随机作为参数放入其中,要么像您已经做的那样直接在构造函数中设置成员变量 diceOne 和 diceTwo。不要两者兼而有之。当返回两个骰子的总和时,为什么不直接返回这个总和(提示:函数 totalScore 应该返回 int 类型的内容)。为什么要将求和结果放入成员变量中?没有必要这样做。
我可以在这里发布更正后的代码,但似乎您真的必须自己学习。
编辑:顺便说一下:如上所述,学习使用调试器。你很快就会发现我告诉你的事情是正确的。你会注意到,faceValue首先得到diceOne的值,然后得到diceTwo的值,永远不会得到diceOne的值。
- 使用一个考虑到std::map中键值的滚动或换行的键
- 在C++游戏中与库存系统作斗争
- 换位表导致测试失败(但在游戏中运行良好)
- QScrollArea:由垂直滚动条引起的水平滚动条
- 跟踪滚动条上的鼠标事件
- Craps游戏问题,忽略if语句
- 矢量下标超出SFML游戏中的范围
- 我是 c++ 的新手.学习基本知识后,我想做井字游戏.对于印刷板,我在下面写代码,但它显示错误
- 我在贪吃蛇游戏中收到了错误代码 -1073741571
- 如何在不使用滚动条的情况下使视图更改
- 如何为对象生成滚动效果?
- 如何模拟不同边数的骰子滚动?
- 我应该在简单的策略游戏中为各个派系使用类吗 - C++
- 从而在2D侧滚动游戏中创建障碍物的组合
- 如何创建一个简单的侧滚动游戏
- 实现了2D重力和基本碰撞C++和OpenGL基于Tile的侧滚动游戏
- 骰子游戏,使每个骰子滚动不同
- 使用 glOrtho 进行滚动游戏。宇宙飞船"shudders"
- 如何制作一个程序,如游戏制造商或滚动游戏开发工具包2
- 如何在没有平铺地图的情况下使用Cocos2D制作滚动游戏