为游戏石头剪刀布 编写 C++ 程序
时间: 2024-10-10 21:16:59 浏览: 40
为"石头剪刀布"游戏编写C++程序,可以参考上面提供的代码片段。这个程序会提示用户输入他们的选择(R代表石头,P代表纸,S代表剪刀),然后生成计算机随机选择,再根据游戏规则判断胜负。程序会循环进行直到用户选择退出。
下面是一个简化版的代码示例:
```cpp
#include <iostream>
#include <ctime>
#include <cstdlib>
enum Choices { ROCK, PAPER, SCISSORS };
int getComputerChoice() {
srand(time(0));
return rand() % 3 + 1; // 加1是因为数组索引从1开始
}
void getUserInput() {
std::cout << "Enter your choice (rock, paper, scissors): ";
char userChoice;
std::cin >> userChoice;
if (userChoice != 'r' && userChoice != 'p' && userChoice != 's') {
std::cout << "Invalid input! Try again.\n";
getUserInput(); // 如果输入无效,再次请求
} else {
userChoice = userChoice == 'r' ? ROCK : (userChoice == 'p' ? PAPER : SCISSORS);
}
}
void determineWinner(const Choices& userChoice, const Choices& computerChoice) {
if (userChoice == computerChoice) {
std::cout << "It's a tie!\n";
} else if ((userChoice == ROCK && computerChoice == SCISSORS) ||
(userChoice == PAPER && computerChoice == ROCK) ||
(userChoice == SCISSORS && computerChoice == PAPER)) {
std::cout << "You win!\n";
} else {
std::cout << "Computer wins!\n";
}
}
int main() {
bool playAgain = true;
while (playAgain) {
Choices userChoice, computerChoice;
getUserInput();
computerChoice = getComputerChoice();
determineWinner(userChoice, computerChoice);
std::cout << "Do you want to play again? (y/n): ";
std::cin >> playAgain;
}
return 0;
}
```
阅读全文