Python中的剪刀石头布游戏

使用的模块:
在此脚本中,我们将使用python的名为random的内置模块。

random模块:
random是Python的内置模块,它将帮助我们从列表或元素数组中选择任何随机元素。在此,我们将使用此模块代表计算机随机选择选项。

游戏规则为:

Rock will be at 1.
Paper will be at 2.
Scissor will be at 3.

Rock vs Scissor => Rock wins.
Rock vs Paper => Paper wins.
Paper vs Scissor=> Scissor wins.

程序:

# 导入模块
import random

Name=input("输入你的名字: ")
print("游戏规则如下:\n"
      "1) Rock at 1.\n2) Paper at 2."
      "\n3) Scissor at 3."
      "\nRock vs Paper=> Paper wins"
      "\nRock vs Scissor=>Rock wins"
      "\nPaper vs Scissor=> Scissor wins")

# 如果进入循环 
# 用户想要一次又一次地播放
while True:
    print("Enter the choice:\n"
          "1) Rock\n"
          "2) Paper\n"
          "3) Scissor")
    
    # 用户转向
    choice=int(input("User turn:"))
    
    # 如果我们做出无效选择,那么我们将
    # 再次接受输入,直到我们输入正确的
    # 一
    while choice<1 or choice>3:
        choice=int(input("Invalid Choice Enter Again"))
    if choice==1:
        user_choice="Rock"
    if choice==2:
        user_choice="Paper"
    if choice==3:
        user_choice="Scissor"
    print("User choice is "+user_choice)
    
    # 用户转
    print("Computers turn")
    
    # 使用随机选择计算机
    # 使用randint函数选择随机
    # 从1到3
    computer_choice=random.randint(1,3)
    
    # 如果用户选择与计算机选择相同,则
    # 再次,我们将选择直到。
    while choice==computer_choice:
        computer_choice=random.randint(1,3)
    if computer_choice==1:
        comp_choice="Rock"
    if computer_choice==2:
        comp_choice="Paper"
    if computer_choice==3:
        comp_choice="Scissor"
    print("Computer choice is "+comp_choice)
    # 获胜的条件
    # 坚如磐石的条件
    if (choice==1 and computer_choice==3) or (choice==3 and computer_choice==1):
        print("Rock Wins")
        result="Rock"
    elif (choice==1 and computer_choice==2) or (choice==2 and computer_choice==1):
        print("Paper Wins")
        result="Paper"
    else:
        print("Scissor Wins")
        result="Scissor"
    if result==user_choice:
        print(f"{Name} wins")
    else:
        print("Computer wins")
    c=input("是否继续(Y/N)")
    if c=="n" or c=="N":
        break

输出:

输入你的名字: Abhinav
游戏规则如下:
1) Rock at 1.
2) Paper at 2.
3) Scissor at 3.
Rock vs Paper=> Paper wins
Rock vs Scissor=>Rock wins
Paper vs Scissor=> Scissor wins
Enter the choice:
1) Rock
2) Paper
3) Scissor
User turn:2
User choice is Paper
Computers turn
Computer choice is Scissor
Scissor Wins
Computer wins
是否继续(Y/N)y
Enter the choice:
1) Rock
2) Paper
3) Scissor
User turn:1
User choice is Rock
Computers turn
Computer choice is Scissor
Rock Wins
Abhinav wins
If you want to Continue(Y/N)n