九道门丨教你用 Python 创建“石头剪刀布”的游戏

大家都知道石头剪刀布的游戏吧,石头赢剪刀,布赢石头,剪刀赢布。在本教程中,我就要用 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!")

简单说一下这段代码是如何工作的:

  • 首先从 Python 的随机模块中导入了一个名为 randint() 的内置函数,然后我们以列表的形式添加了这些动作。玩家和计算机将根据此列表选择动作,在动作中添加了石头、剪刀、布的元素。
  • 之后,我创建了一个欢迎字条,并记录用户的名字。
  • 接下来,我创建了一个连续的 while 循环。在这个循环中,计算机和玩家必须先选择他们的动作。计算机将使用 randint() 函数从列表中生成随机移动,然后我们将从玩家那里获取输入。
  • 最后为这个游戏设定条件。这些条件背后的逻辑如下所示:

条件1:如果玩家给出“q”作为输入值,那么结束这个游戏!

条件2:如果玩家和电脑的走法相同,则平局!

条件3:如果用户选择“Rock”,而计算机选择“Paper”,则你获胜。

条件4:如果用户选择“Paper”,而计算机选择“Scissors”,那么你输了。

条件5:如果用户选择“Rock”,而计算机选择“Paper”,那么你输了。

条件6:如果用户给出了无效的输入或在我们的动作列表中不可用,则显示您选择了无效动作的消息。

最后欣赏一下成果:

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章