Python 程序实现石头剪刀布游戏
pythonprogrammingserver side programming
使用 Python 我们还可以开发非常有趣的游戏。石头剪刀布游戏就是其中之一。这里我们使用 randint() 函数来生成随机数。
在这个游戏中,玩家通常数到三,或者说出游戏的名字,每次要么举起一只手握拳,在数数时挥下,要么握在身后。
示例代码
# 导入所需的随机模块 import random print("The Rules of Rock paper scissor game will be follows: \n" +"Rock vs paper --> paper wins \n" +"Rock vs scissor --> Rock wins \n" +"paper vs scissor --> scissor wins \n") while True: print("现在请输入您的选择号。\n 1. 石头 \n 2. 布 \n 3. 剪刀 \n") #获取用户的输入 ch = int(input("现在轮到你了:")) while ch> 3 or ch< 1: ch = int(input("在此处输入您的有效输入:")) if ch == 1: choice_name = 'Rock' elifch == 2: choice_name = 'paper' else: choice_name = 'scissor' # 打印用户给出的选择 print("您的选择是:" + choice_name) print("\n现在轮到计算机启动.......") # 计算机将在值 1、2 和 3 之间随机选择任意数字 #。使用 random 模块的 randint 方法 # comp_choice = random.randint(1, 3) # 循环将继续,直到 comp_choice 值 # 等于选择值 while comp_choice == ch: comp_choice = random.randint(1, 3) # 初始化变量 comp_choice_name 的值 # 与选择值对应的变量 if comp_choice == 1: comp_choice_name = 'Rock' elifcomp_choice == 2: comp_choice_name = 'paper' else: comp_choice_name = 'scissor' print("So computer choice is: " + comp_choice_name) print(choice_name + " V/s " + comp_choice_name) # condition for winning the game if((ch == 1 and comp_choice == 2) or (ch == 2 and comp_choice ==1 )): print("paper wins => ", end = "") final_result = "paper" elif((ch == 1 and comp_choice == 3) or (ch == 3 and comp_choice == 1)): print("Rock wins =>", end = "") final_result = "Rock" else: print("scissor wins =>", end = "") final_result = "scissor" # Printing either user or computer wins if final_result == choice_name: print("<== You are the winner ==>") else: print("<== Computer wins ==>") print("Do you want to play again? (Y/N)") ans = input() # if user input n or N then condition is True if ans == 'n' or ans == 'N': break # after exiting from the while loop print("\nThanks for sharing time with us...")
输出
The Rules of Rock paper scissor game will be follows: Rock vs paper --> paper wins Rock vs scissor --> Rock wins paper vs scissor --> scissor wins Now please enter your choice no. 1. Rock 2. paper 3. scissor Now Your turn: 1 Your choice is: Rock Now its computer turn to initiate....... So computer choice is: paper Rock V/s paper paper wins =><== Computer wins ==> Do you want to play again? (Y/N) y Now please enter your choice no. 1. Rock 2. paper 3. scissor Now Your turn: 2 Your choice is: paper Now its computer turn to initiate....... So computer choice is: Rock paper V/s Rock paper wins =><== You are the winner ==> Do you want to play again? (Y/N) n Thanks for sharing time with us...