使用【c++】写【石头剪刀布游戏】的代码
时间: 2024-10-19 17:06:51 浏览: 40
c++石头剪刀布游戏控制台实现
好的,下面是一个简单的C++代码示例,用于实现石头、剪刀、布游戏。这个程序会提示用户输入他们的选择,并随机生成计算机的选择,然后判断胜负:
```cpp
#include <iostream>
#include <ctime>
#include <cstdlib>
enum Choices { ROCK = 0, PAPER, SCISSORS };
std::string choices[] = {"石头", "纸", "剪刀"};
int get_user_choice() {
int choice;
std::cout << "请输入你的选择(0-石头,1-剪刀,2-布): ";
std::cin >> choice;
return choice % 3; // 转换到0-2范围
}
int get_computer_choice() {
srand(time(0)); // 设置随机数种子
return rand() % 3; // 随机选择0-2
}
bool check_win(int user, int computer) {
if (user == computer) return false; // 平局
switch ((user + computer) % 3) {
case 0: return computer == ROCK; // 用户出剪刀,电脑出布胜
case 1: return computer == PAPER; // 用户出布,电脑出石头胜
case 2: return computer == SCISSORS; // 用户出石头,电脑出剪刀胜
}
}
void play_game() {
int user_choice = get_user_choice();
int computer_choice = get_computer_choice();
std::cout << "你出了:" << choices[user_choice] << "\n";
std::cout << "电脑出了:" << choices[computer_choice] << "\n";
if (check_win(user_choice, computer_choice)) {
std::cout << "你赢了!\n";
} else {
std::cout << "电脑赢了!\n";
}
}
int main() {
while (true) {
play_game();
char continue_choice;
std::cout << "是否再玩一次?请输入'y'继续,其他键退出:";
std::cin >> continue_choice;
if (continue_choice != 'y') break;
}
return 0;
}
```
阅读全文