游戏
2026-03-11 18:57:59
发布于:浙江
#include<bits/stdc++.h>
using namespace std;
class Coin
{
private:
string sideUp;
public:
Coin() {
srand(time(0));
flip();
}
void flip() {
sideUp = (rand() % 2 == 0) ? "正面" : "反面";
}
string getSideUp() const {
return sideUp;
}
};
class CoinFlipGame {
private:
int playerScore;
int computerScore;
int totalRounds;
Coin coin;
public:
CoinFlipGame() : playerScore(0), computerScore(0), totalRounds(0) {}
void showRules() const {
cout << "\n===== 抛硬币游戏规则 =" << endl;
cout << "1. 选择正面或反面" << endl;
cout << "2. 系统将随机抛硬币" << endl;
cout << "3. 猜中则得1分,否则电脑得1分" << endl;
cout << "4. 先达到5分者获胜" << endl;
cout << "====================\n" << endl;
}
int getPlayerChoice() const {
int choice;
cout << "请选择:" << endl;
cout << "1. 正面" << endl;
cout << "2. 反面" << endl;
cout << "3. 查看规则" << endl;
cout << "4. 退出游戏" << endl;
cout << "请输入选择 (1-4): ";
cin >> choice;
return choice;
}
void showScore() const {
cout << "\n----- 当前比分 -----" << endl;
cout << "玩家: " << playerScore << " 分" << endl;
cout << "电脑: " << computerScore << " 分" << endl;
cout << "总局数: " << totalRounds << " 局" << endl;
cout << "-------------------\n" << endl;
}
void playRound(int playerChoice) {
totalRounds++;
coin.flip();
string playerSide = (playerChoice == 1) ? "正面" : "反面";
string coinSide = coin.getSideUp();
cout << "\n硬币在空中翻转..." << endl;
cout << "结果是: " << coinSide << "!" << endl;
if (playerSide == coinSide) {
playerScore++;
cout << "恭喜你猜对了! 得1分!" << endl;
} else {
computerScore++;
cout << "很遗憾猜错了! 电脑得1分!" << endl;
}
}
bool isGameOver() const {
return playerScore >= 5 || computerScore >= 5;
}
void showResult() const {
cout << "\n===== 游戏结束 =====" << endl;
if (playerScore > computerScore) {
cout << "?? 恭喜你获胜了!" << endl;
} else {
cout << "?? 很遗憾,电脑获胜了!" << endl;
}
cout << "最终比分: 玩家 " << playerScore << " : " << computerScore << " 电脑" << endl;
cout << "总共进行了 " << totalRounds << " 局游戏" << endl;
cout << "==================\n" << endl;
}
void resetGame() {
playerScore = 0;
computerScore = 0;
totalRounds = 0;
}
void run() {
cout << "欢迎来到抛硬币游戏!" << endl;
showRules();
bool playAgain = true;
while (playAgain) {
int choice = getPlayerChoice();
switch (choice) {
case 1:
case 2:
playRound(choice);
showScore();
if (isGameOver()) {
showResult();
char playAgainChoice;
cout << "是否再来一局? (y/n): ";
cin >> playAgainChoice;
if (playAgainChoice == 'y' || playAgainChoice == 'Y') {
resetGame();
} else {
playAgain = false;
cout << "感谢游戏! 再见!" << endl;
}
}
break;
case 3:
showRules();
break;
case 4:
playAgain = false;
cout << "感谢游戏! 再见!" << endl;
break;
default:
cout << "无效选择,请重新输入!" << endl;
break;
}
}
}
};
int main() {
CoinFlipGame game;
game.run();
return 0;
}
这里空空如也



















有帮助,赞一个