常见算法-双骰子游戏(Craps)
1、说明
一个简单的双骰子游戏,游戏规则如下:
玩家掷两个骰子,点数为1到6,
- 如果第一次点数和为7或11,则玩家胜,
- 如果点数和为2、3或12,则玩家输,
- 如果和为其它点数,则记录第一次的点数和,然后继续掷骰,直至点数和等于第一次掷出的点数和,则玩家胜,如果在这之前掷出了点数和为7,则玩家输。
规则看来有些复杂,但是其实只要使用switch配合if条件判断来撰写即可,小心不要弄错胜负顺序即可。
2、C++代码
#include<iostream>
using namespace std;enum State {Win,Lost,Continue
};unsigned int RollDice() {unsigned int die1 = 1 + rand() % 6;unsigned int die2 = 1 + rand() % 6;unsigned int sum = die1 + die2;cout << die1 << " + " << die2 << " = " << sum << endl;return sum;
}void Dice() {unsigned int point = 0;State state = Continue;unsigned int sumDice = RollDice();switch (sumDice) {case 7:case 11:state = Win;break;case 2:case 3:case 12:state = Lost;break;default:state = Continue;point = sumDice;break;}while (state == Continue) {sumDice = RollDice();if (sumDice == point)state = Win;else if (sumDice == 7)state = Lost;}if (state == Win)cout << " You Win" << endl;elsecout << " You Lost" << endl;
}int main() {srand(static_cast<unsigned int>(time(0)));Dice();return 0;
}
输出结果