用c++做21点游戏完整代码
时间: 2024-01-15 21:48:09 浏览: 31
以下是一个简单的C++ 21点游戏代码,使用了随机数生成器和基本的逻辑运算符。注意:该代码只是一个示例,可能存在漏洞或需要改进之处。
```cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand(time(NULL)); // 初始化随机数生成器
int player_total = 0; // 玩家的牌总数
int dealer_total = 0; // 庄家的牌总数
// 玩家抽取两张牌
int card1 = rand() % 10 + 1;
int card2 = rand() % 10 + 1;
player_total = card1 + card2;
cout << "你的牌是 " << card1 << " 和 " << card2 << endl;
cout << "你的总牌数是 " << player_total << endl;
// 庄家抽取一张牌
int dealer_card = rand() % 10 + 1;
dealer_total = dealer_card;
cout << "庄家的牌是 " << dealer_card << endl;
// 玩家选择是否要继续抽牌
char choice;
do {
cout << "是否要再抽一张牌?(Y/N)" << endl;
cin >> choice;
if (choice == 'Y' || choice == 'y') {
int new_card = rand() % 10 + 1;
player_total += new_card;
cout << "你的新牌是 " << new_card << endl;
cout << "你的总牌数是 " << player_total << endl;
}
} while ((choice == 'Y' || choice == 'y') && player_total <= 21);
// 庄家继续抽牌,直到牌总数大于等于17
while (dealer_total < 17) {
int new_card = rand() % 10 + 1;
dealer_total += new_card;
cout << "庄家的新牌是 " << new_card << endl;
cout << "庄家的总牌数是 " << dealer_total << endl;
}
// 判断胜负
if (player_total > 21) {
cout << "你爆了,庄家赢了!" << endl;
} else if (dealer_total > 21) {
cout << "庄家爆了,你赢了!" << endl;
} else if (player_total > dealer_total) {
cout << "你的牌大,你赢了!" << endl;
} else if (dealer_total > player_total) {
cout << "庄家的牌大,庄家赢了!" << endl;
} else {
cout << "平局!" << endl;
}
return 0;
}
```
在这个代码中,玩家和庄家抽取的牌都是随机生成的,且每张牌的点数都是1-10之间的整数。玩家可以选择是否要继续抽牌,直到牌总数超过21或者选择停止抽牌。然后庄家会继续抽牌,直到牌总数大于等于17。最后比较玩家和庄家的牌总数,判断胜负。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)