鱼C论坛

 找回密码
 立即注册
查看: 380|回复: 10

石头剪刀布的代码

[复制链接]
发表于 2025-3-23 18:05:28 | 显示全部楼层 |阅读模式
1鱼币
求助
悬赏令
石头剪刀布代码
2个鱼币!!!!!!!!!!!!!!!!’

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2025-3-23 18:05:40 | 显示全部楼层
石头剪刀布游戏代码  

下面是一个简单的Python实现,支持玩家与计算机对战:  
  
import random  

def get_computer_choice():  
    return random.choice(["石头", "剪刀", "布"])  

def get_winner(player, computer):  
    if player == computer:  
        return "平局!"  
    elif (player == "石头" and computer == "剪刀") or \  
         (player == "剪刀" and computer == "布") or \  
         (player == "布" and computer == "石头"):  
        return "你赢了!"  
    else:  
        return "你输了!"  

def main():  
    print("欢迎来到石头剪刀布游戏!")  
    player_choice = input("请输入 石头/剪刀/布: ")  
    if player_choice not in ["石头", "剪刀", "布"]:  
        print("输入无效,请输入 石头/剪刀/布")  
        return  

    computer_choice = get_computer_choice()  
    print(f"电脑选择了: {computer_choice}")  
    print(get_winner(player_choice, computer_choice))  

if __name__ == "__main__":  
    main()  


这个代码会让玩家输入 石头剪刀,然后与计算机随机选择的结果进行比较,判断输赢。希望对你有帮助!{:5_144:}

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2025-3-23 21:38:18 | 显示全部楼层
import random
d = ('剪刀' , '石头' , '布')
while True :
    k = input('1 - %s , 2 - %s , 3 - %s : ' % (d[0] , d[1] , d[2]))
    if k:
        if k in '123' :
            x = int(k) - 1
            z = random . randint(0 , 2)
            if x == z :
                p = 0
            elif x > z :
                p = 1 if x - z == 1 else 2
            else :
                p = 2 if z - x == 1 else 1
            if p == 0 :
                print('您:%s - 计算机:%s , 【%s】' % (d[x] , d[z] , '平'))
            elif p == 1 :
                print('您:%s - 计算机:%s , 您【%s】' % (d[x] , d[z] , '赢'))
            else :
                print('您:%s - 计算机:%s , 您【%s】' % (d[x] , d[z] , '输')) 
        print()                               
    else :
        break
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2025-3-23 22:36:16 | 显示全部楼层
import tkinter as tk
from tkinter import font
import random

class RockPaperScissorsGame:
    def __init__(self, master):
        self.master = master
        master.title("石头剪刀布")
        master.geometry("400x400")
        master.configure(bg="#F0F0F0")

        # 初始化得分
        self.player_score = 0
        self.computer_score = 0

        # 创建自定义字体
        self.title_font = font.Font(family="Arial", size=16, weight="bold")
        self.result_font = font.Font(family="Arial", size=14)
        self.score_font = font.Font(family="Arial", size=12)

        # 创建界面元素
        self.create_widgets()

    def create_widgets(self):
        # 电脑选择显示
        self.computer_choice_label = tk.Label(
            self.master,
            text="电脑出拳:等待中...",
            font=self.title_font,
            bg="#F0F0F0"
        )
        self.computer_choice_label.pack(pady=10)

        # 结果显示
        self.result_label = tk.Label(
            self.master,
            text="点击下方按钮开始游戏",
            font=self.result_font,
            bg="#F0F0F0",
            fg="#333333"
        )
        self.result_label.pack(pady=15)

        # 玩家选择按钮
        button_frame = tk.Frame(self.master, bg="#F0F0F0")
        button_frame.pack(pady=10)

        choices = ["石头", "剪刀", "布"]
        colors = ["#FF6666", "#66CC66", "#6666FF"]
        for choice, color in zip(choices, colors):
            btn = tk.Button(
                button_frame,
                text=choice,
                font=self.title_font,
                bg=color,
                width=8,
                command=lambda c=choice: self.play_round(c)
            )
            btn.pack(side=tk.LEFT, padx=5)

        # 比分显示
        self.score_label = tk.Label(
            self.master,
            text=f"玩家 {self.player_score} : {self.computer_score} 电脑",
            font=self.score_font,
            bg="#F0F0F0",
            fg="#444444"
        )
        self.score_label.pack(pady=20)

        # 重置按钮
        reset_btn = tk.Button(
            self.master,
            text="重置比分",
            font=self.score_font,
            command=self.reset_scores
        )
        reset_btn.pack()

    def play_round(self, player_choice):
        # 电脑随机选择
        computer_choice = random.choice(["石头", "剪刀", "布"])
        self.computer_choice_label.config(text=f"电脑出拳:{computer_choice}")

        # 判断胜负
        result = self.get_result(player_choice, computer_choice)

        # 更新比分和显示
        if "赢" in result:
            self.player_score += 1
            color = "green"
        elif "输" in result:
            self.computer_score += 1
            color = "red"
        else:
            color = "blue"

        self.result_label.config(text=result, fg=color)
        self.score_label.config(text=f"玩家 {self.player_score} : {self.computer_score} 电脑")

    def get_result(self, player, computer):
        if player == computer:
            return "平局!"
        winning_combinations = {
            "石头": "剪刀",
            "剪刀": "布",
            "布": "石头"
        }
        if winning_combinations[player] == computer:
            return "你赢了!(*^▽^*)"
        return "你输了!(>﹏<)"

    def reset_scores(self):
        self.player_score = 0
        self.computer_score = 0
        self.score_label.config(text=f"玩家 {self.player_score} : {self.computer_score} 电脑")
        self.computer_choice_label.config(text="电脑出拳:等待中...")
        self.result_label.config(text="比分已重置", fg="#333333")


if __name__ == "__main__":
    root = tk.Tk()
    game = RockPaperScissorsGame(root)
    root.mainloop()
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 7 天前 | 显示全部楼层
import random

choices = ['石头', '剪刀', '布']

while True:
    user_choice = input('请输入你的选择(石头/剪刀/布,输入q退出):')
    if user_choice == 'q':
        break
    if user_choice not in choices:
        print('输入无效,请重新输入。')
        continue
    computer_choice = random.choice(choices)
    print(f'你选择了:{user_choice},电脑选择了:{computer_choice}')
    if user_choice == computer_choice:
        print('平局!')
    elif (user_choice == '石头' and computer_choice == '剪刀') or (user_choice == '剪刀' and computer_choice == '布') or (user_choice == '布' and computer_choice == '石头'):
        print('你赢了!')
    else:
        print('你输了!')
这段代码通过一个无限循环让玩家可以持续进行游戏,直到输入 'q' 退出。每次游戏时,玩家输入自己的选择,程序随机生成电脑的选择,然后根据规则判断胜负并输出结果。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 5 天前 | 显示全部楼层
都是大神啊,我什么时候才能达到这种水准啊!!!!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 4 天前 | 显示全部楼层
DeepSeek的代码程序:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <limits>

using namespace std;

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

    do {
        // 用户输入部分
        int userChoice;
        while (true) {
            cout << "\n请出拳(1-石头,2-剪刀,3-布): ";
            if (cin >> userChoice) {
                if (userChoice >= 1 && userChoice <= 3) {
                    break;
                }
                cout << "无效输入,请输入1-3之间的数字!\n";
            } else {
                cout << "无效输入,请输入数字!\n";
                cin.clear();
                cin.ignore(numeric_limits<streamsize>::max(), '\n');
            }
        }

        // 电脑随机出拳
        int computerChoice = rand() % 3 + 1;
        string choices[] = {"石头", "剪刀", "布"};
        
        cout << "\n你出了: " << choices[userChoice-1];
        cout << "\n电脑出了: " << choices[computerChoice-1] << endl;

        // 胜负判断
        if (userChoice == computerChoice) {
            cout << "平局!" << endl;
        } else if ((userChoice == 1 && computerChoice == 2) ||
                   (userChoice == 2 && computerChoice == 3) ||
                   (userChoice == 3 && computerChoice == 1)) {
            cout << "你赢了!" << endl;
        } else {
            cout << "电脑赢了!" << endl;
        }

        // 是否继续游戏
        cout << "\n是否继续游戏?(y/n): ";
        cin >> playAgain;
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    } while (tolower(playAgain) == 'y');

    cout << "游戏结束,谢谢参与!" << endl;
    return 0;
}
代码特点:

输入验证:确保用户输入的是有效数字(1-3),处理非数字输入的情况

随机生成电脑出拳结果(使用时间作为随机种子)

使用数组存储和显示中文出拳结果

清晰的胜负判断逻辑

支持重复游戏直到用户选择退出

友好的用户提示信息

游戏规则:

石头(1)赢剪刀(2)

剪刀(2)赢布(3)

布(3)赢石头(1)

使用方法:

运行程序后会提示输入数字选择出拳

电脑会随机生成出拳结果

程序会自动判断胜负并显示结果

每次游戏结束后可选择继续或退出

DeepSeek的思考过程:
嗯,用户让我用C++写一个石头剪刀布的代码。首先,我得考虑用户的需求是什么。可能是一个简单的控制台游戏,让用户和电脑对战,对吧?那我得先理清楚游戏的流程。

首先,游戏需要用户输入他们的选择,石头、剪刀或者布。然后电脑随机生成一个选择。接下来比较两者的选择,判断胜负。这个过程需要循环,可能让用户多次玩,直到他们决定退出。

那我得考虑如何获取用户的输入。可能用数字代替,比如1代表石头,2代表剪刀,3代表布,或者用字符R、S、P之类的。不过数字可能更容易处理,特别是对于新手来说,输入数字比较方便。

然后是电脑的选择。需要生成一个随机数,范围在1到3之间。C++中可以用rand()函数,不过记得要先播种,用srand和时间函数来初始化,这样每次运行的结果才会不同。比如srand(time(0))。

接下来是比较用户和电脑的选择。石头赢剪刀,剪刀赢布,布赢石头。这部分逻辑需要处理所有可能的组合。可以用if-else语句来判断,或者用一些数学技巧,比如模运算来判断胜负,这样代码可能更简洁。例如,(userChoice - computerChoice + 3) % 3,如果结果是1,用户输;如果是2,用户赢,平局的话就是0。不过这种方法可能需要解释,用户可能更易读的条件语句。

另外,要处理无效输入的情况。如果用户输入的不是1、2、3,应该提示错误,并重新输入。这时候可能需要一个循环,直到输入有效为止。

游戏是否循环进行也是一个点。每次结束后询问用户是否继续,输入y或n之类的。所以主循环应该是一个do-while结构,条件取决于用户是否继续。

然后输出结果要友好,显示电脑的选择和胜负情况。比如“电脑出了石头,你赢了!”之类的提示。

现在把这些步骤拆解成代码结构。主函数里有一个do-while循环,每次循环中:

1. 显示选项:石头、剪刀、布,提示用户输入。

2. 读取用户输入,验证是否有效,无效则提示重新输入。

3. 生成电脑的选择。

4. 比较两者,判断胜负。

5. 输出结果。

6. 询问是否继续。

另外,可能需要将比较逻辑封装成一个函数,或者直接在main里处理。考虑到代码的简洁性,可能直接在main里处理。

可能的错误点:用户输入处理时,如果输入的是非数字,会导致cin进入错误状态,需要用cin.clear()和忽略缓冲区中的无效字符。比如,如果用户输入了字母,cin会失败,这时候需要处理。

所以,在用户输入的部分,应该检查输入是否成功,并处理无效的情况。例如:

int userChoice;

while (true) {

cout << "请输入你的选择:";

if (cin >> userChoice) {

if (userChoice >=1 && userChoice <=3) {

break;

} else {

cout << "无效输入,请重新输入1、2或3。" << endl;

}

} else {

cout << "无效输入,请输入数字。" << endl;

cin.clear();

cin.ignore(numeric_limits<streamsize>::max(), '\n');

}

}

这样处理可以确保用户输入的是有效的数字。

然后是电脑的选择,使用rand()%3 +1来得到1-3的随机数。

比较部分,可以用多个if条件判断。比如:

if (userChoice == computerChoice) {

// 平局

} else if ((userChoice == 1 && computerChoice == 2) ||

(userChoice == 2 && computerChoice == 3) ||

(userChoice == 3 && computerChoice == 1)) {

// 用户赢

} else {

// 电脑赢

}

或者用更简洁的方式,比如之前提到的模运算方法。但为了可读性,可能用条件判断更直观。

然后显示结果时,需要将数字转换为对应的字符串,比如1变成“石头”,可以用一个数组或者switch语句来处理。

例如:

string choices[] = {"石头", "剪刀", "布"};

cout << "电脑出了" << choices[computerChoice -1] << endl;

这样,当computerChoice是1时,对应数组下标0,即“石头”。

最后,询问是否继续,用户输入y或n,处理大小写,比如转换为小写,判断是否继续。

综上,把这些部分整合起来,就能写出完整的代码了。测试的时候要确保各种情况都能正确处理,包括平局、胜负,以及无效输入的情况。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 3 天前 | 显示全部楼层

看看我写的可对

本帖最后由 wangxingjie_123 于 2025-3-28 16:34 编辑

#\user\python
import random
computer = random.tandint(a:1,b:3)
uif (user == 1 and computer == 2) or (user == 2 and computer == 3) or (user == 3 and computer == 1):
    print('哈哈哈...你赢了!')
elif (user == 1 and computer == 3) or (user == 2 and computer == 1) or (user == 3 and computer == 2):
    print('哎呀...你输了!')
else:
    print('平局,再来一局!')ser = int(input(“请输入你的招数(1:石头,2:剪刀,3:布):”))
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 3 天前 From FishC Mobile | 显示全部楼层
import random  

def get_computer_choice():  
    return random.choice(["石头", "剪刀", "布"])  

def get_winner(player, computer):  
    if player == computer:  
        return "平局!"  
    elif (player == "石头" and computer == "剪刀") or \  
         (player == "剪刀" and computer == "布") or \  
         (player == "布" and computer == "石头"):  
        return "你赢了!"  
    else:  
        return "你输了!"  

def main():  
    print("欢迎来到石头剪刀布游戏!")  
    player_choice = input("请输入 石头/剪刀/布: ")  
    if player_choice not in ["石头", "剪刀", "布"]:  
        print("输入无效,请输入 石头/剪刀/布")  
        return  

    computer_choice = get_computer_choice()  
    print(f"电脑选择了: {computer_choice}")  
    print(get_winner(player_choice, computer_choice))  

if __name__ == "__main__":  
    main()  
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 前天 12:33 | 显示全部楼层
学习来了
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 前天 18:10 | 显示全部楼层
import random

def get_user_choice():
    while True:
        user_choice = input("请输入你的选择(石头、剪刀、布):").strip()
        if user_choice in ["石头", "剪刀", "布"]:
            return user_choice
        else:
            print("输入无效,请重新输入。")

def get_computer_choice():
    choices = ["石头", "剪刀", "布"]
    return random.choice(choices)

def determine_winner(user_choice, computer_choice):
    if user_choice == computer_choice:
        return "平局"
    elif (
        (user_choice == "石头" and computer_choice == "剪刀") or
        (user_choice == "剪刀" and computer_choice == "布") or
        (user_choice == "布" and computer_choice == "石头")
    ):
        return "你赢了"
    else:
        return "你输了"

def play_game():
    user_choice = get_user_choice()
    computer_choice = get_computer_choice()
    print(f"你选择了:{user_choice}")
    print(f"电脑选择了:{computer_choice}")
    result = determine_winner(user_choice, computer_choice)
    print(result)

if __name__ == "__main__":
    play_game()
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-3-31 09:12

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表