大家都知道石头剪刀布的游戏吧,石头赢剪刀,布赢石头,剪刀赢布。在本教程中,我就要用 Python 来创建这个游戏。
先来看一下代码要怎么写:
#从python的random模块中导入randintfrom random import randint#添加动作moves = ["rock", "paper", "scissors"]print("Hi, welcome to the world of Rock, Paper and Scissor!")name = str(input("What's your name : "))print(f"Okay {name}, let's start the game!")#创建连续循环while True: #计算机从我们的移动列表中选择任意值 computer = moves[randint(0, 2)] #从player获取输入值 print("Choose Rock, Paper, Scissor or Press 'q' for quit the game!") player = input("Your turn : ") print("Computer turn :", computer) #添加条件 if player == 'q': print(f"The game is ended, thanks for playing {name}!") break elif player == computer: print("Oops, the game is tie!") elif player == "rock": if computer == "paper": print("You loss,", computer, "beats", player) else: print("You win,", player, "beats", computer) elif player == "paper": if computer == "scissors": print("You loss,", computer, "beats", player) else: print("You win,", player, "beats", computer) elif player == "scissors": if computer == "rock": print("You loss,", computer, "beats", player) else: print("You win,", player, "beats", computer) else: print("Sorry, your value is not valid!")
简单说一下这段代码是如何工作的:
条件1:如果玩家给出“q”作为输入值,那么结束这个游戏!
条件2:如果玩家和电脑的走法相同,则平局!
条件3:如果用户选择“Rock”,而计算机选择“Paper”,则你获胜。
条件4:如果用户选择“Paper”,而计算机选择“Scissors”,那么你输了。
条件5:如果用户选择“Rock”,而计算机选择“Paper”,那么你输了。
条件6:如果用户给出了无效的输入或在我们的动作列表中不可用,则显示您选择了无效动作的消息。
最后欣赏一下成果:
留言与评论(共有 0 条评论) “” |