与AI对手进行石头剪刀布

#include <iostream>
#include <cstdlib>  // For rand() and srand()
#include <ctime>    // For time()

using namespace std;

// 函数用于获取随机生成的手势(0为石头, 1为剪刀, 2为布)
int getAiChoice() {
    return rand() % 3;
}

// 打印选择结果,参数分别为玩家选择和AI选择
void printChoices(int playerChoice, int aiChoice) {
    const char* choices[3] = {"石头", "剪刀", "布"};
    cout << "你出了: " << choices[playerChoice] << endl;
    cout << "AI出了: " << choices[aiChoice] << endl;
}

// 判断胜负并输出结果
void determineWinner(int playerChoice, int aiChoice) {
    if (playerChoice == aiChoice) {
        cout << "平局!" << endl;
    } else if ((playerChoice == 0 && aiChoice == 1) ||
               (playerChoice == 1 && aiChoice == 2) ||
               (playerChoice == 2 && aiChoice == 0)) {
        cout << "你赢了!" << endl;
    } else {
        cout << "你输了!" << endl;
    }
}

int main() {
    srand(time(0));  // 初始化随机数种子

    while (true) {
        int choice;
        cout << "请输入你的选择(0=石头, 1=剪刀, 2=布,-1退出游戏): ";
        cin >> choice;

        if (choice == -1) {
            break;
        }

        if (choice >= 0 && choice <= 2) {
            int aiChoice = getAiChoice();
            printChoices(choice, aiChoice);
            determineWinner(choice, aiChoice);
        } else {
            cout << "无效输入,请重新输入。" << endl;
        }
    }

    cout << "游戏结束,感谢参与!" << endl;
    return 0;
}
//这段代码定义了一个简单的命令行游戏循环,其中包含了一个与AI对手进行石头剪刀布对决的功能。AI的选择是通过随机函数生成的,因此每次运行时AI的选择都是不确定的。玩家通过输入数字来选择自己的手势,然后程序会显示双方的选择,并根据规则判断胜利者。如果想要退出游戏,只需输入-1即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值