欢迎访问宙启技术站
智能推送

Python编写一个石头、剪刀、布游戏的电脑对战程序

发布时间:2023-12-04 14:08:32

下面是一个Python编写的石头、剪刀、布游戏的电脑对战程序,包含了使用例子。

import random

def get_user_choice():
    choices = {'1': '石头', '2': '剪刀', '3': '布'}
    while True:
        choice_num = input("请选择你的出拳(1:石头, 2:剪刀, 3:布): ")
        if choice_num in choices:
            return choices[choice_num]
        else:
            print("无效选择,请重新选择!")

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

def get_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():
    print("欢迎来到石头、剪刀、布游戏!")
    while True:
        user_choice = get_user_choice()
        computer_choice = get_computer_choice()
        print(f"你选择了: {user_choice}")
        print(f"电脑选择了: {computer_choice}")
        winner = get_winner(user_choice, computer_choice)
        print(winner)
        play_again = input("继续游戏吗?(y/n): ")
        if play_again.lower() != 'y':
            break

play_game()

使用例子:

欢迎来到石头、剪刀、布游戏!
请选择你的出拳(1:石头, 2:剪刀, 3:布): 2
你选择了: 剪刀
电脑选择了: 石头
你输了!
继续游戏吗?(y/n): y
请选择你的出拳(1:石头, 2:剪刀, 3:布): 1
你选择了: 石头
电脑选择了: 剪刀
你赢了!
继续游戏吗?(y/n): n