【问题标题】:Simplify Python code (Rock, Paper, Scissors)简化 Python 代码(石头、纸、剪刀)
【发布时间】:2018-07-22 17:39:20
【问题描述】:

我是一个完整的python新手,这是我关于stackoverflow的第一个问题,所以请耐心等待:)

因此,为了获得一些锻炼,我尝试用 Python 编写自己的石头、剪子布游戏。但是,与其他石头、剪子布程序相比,我的代码相对较长。这是因为我编写了游戏中每一个可能的选项。是否有可能简化此代码?就像不必对游戏中的每一个可能性都进行编程一样?因为在石头、纸、剪刀中这样做可能是可能的,但在更高级的问题中可能不行。

告诉我你的想法,谢谢!!!

一切顺利, 卢卡·韦斯贝克

代码:

#Rock, Paper, Scissors
while True:
    Game_list = ["Rock", "Paper", "Scissors"]
        User_1 = str(input("Rock, Paper, Scissors?"))
    #Let the computer make its choice
        import random
        Computer_1 = random.choice(Game_list)
    #Possibility of a draw
        if str(Computer_1) == User_1:
            Draw_choice = str(input("It's a draw. Do you want to replay?(Y/N)"))
            if Draw_choice == "Y":
                continue
            else:
                break
    #Possibility of player winning
        if str(Computer_1) == "Rock" and User_1 == "Paper" or str(Computer_1) == 
    "Paper" and User_1 == "Scissors" or str(Computer_1) == "Scissors" and User_1 
    == "Rock":
            UW1 = str(input("You won. The computer chose:" + Computer_1 + " Do 
    you want to play again? (Y/N)"))
            if UW1 == "Y":
                continue
            else:
            break
    #Possibility of computer winning
        if str(Computer_1) == "Rock" and User_1 == "Scissors" or str(Computer_1) 
    == "Paper" and User_1 == "Rock" or str(Computer_1) == "Scissors" and User_1 
    == "Paper":
            UL1 = str(input("You lost. The Compuer chose:" + Computer_1 + " Do 
    you want to play again? (Y/N)"))
            if UL1 == "Y":
                continue
            else:
                break
    #End sentence                  
    print("Bye, thank you for playing!")

【问题讨论】:

  • 对于初学者,请正确格式化缩进并删除 allstr() 的调用。您所有的数据都已经是字符串。之后,你的“玩家获胜的可能性”可以写成if Computer_1,User_1 in zip(Game_list, Game_list[1:]+Game_list[:1]),不管选择多少。
  • 作为 Python 约定,所有variable_names 都应该小写。只有ClassName 应该以大写开头并包含大写。
  • 哦,我不知道。感谢您的提醒!

标签: python simplify


【解决方案1】:

这个程序中有很多重复的字符串。它们可以折叠。

import random
States = ['Rock','Paper','Scissors']
playAgain = True
while playAgain:
    User = str(input("Choose your play: "))
    try:
        User = States.index(User)
    except: 
        print('Your choice is not one of the choices in Rock, Paper, Scissors')
        break
    Comp = random.randint(0,2)
    winner = (Comp-User)%3
    if winner==0:
        print("There is a tie. Both User and Computer chose " + States[User])
    elif winner==1:
        print("Computer wins. Computer chose "+States[Comp]+" and User chose "+States[User])
    else:
        print("User wins. Computer chose "+States[Comp]+" and User chose "+States[User])
    if str(input("Do you want to play again? (Y/N)")) == "N":
        playAgain = False
print("Thanks for playing!")

【讨论】:

  • 谢谢!我将不得不查看代码一段时间,因为有一些新的epressions,但是现在代码很短。
【解决方案2】:

您可以尝试存储获胜的可能性。

win_case = [['rock','scissor'], ['scissor','paper'], ['paper','rock']]

那么主程序会是这样的

if (user == comp):
     // draw
elif ([user,comp] in win_case):
     // user win
else:
     // comp win

【讨论】:

  • 有道理。会使程序变得很短,谢谢!
【解决方案3】:

代码长度是一回事。组织和可读性是另一个(更重要的)之一。通常有帮助的是代码和配置的分离。先设置常量、设置、消息,然后在代码中使用:

import random

# game config
R, P, S = "Rock", "Paper", "Scissors"
BEATS = {R: S, P: R, S: P}
MESSAGES = {
    "draw": "It's a draw. Play again? (Y/N)\n",
    "win": "You won. Comp chose: {}. Play again? (Y/N)\n",
    "loss": "You lost. Comp chose: {}. Play again? (Y/N)\n",
    "invalid": "Invalid input: {}. Play again? (Y/N)\n",
}

# game code
play = "Y"
while play.upper() == "Y":
    u1 = str(input("{}, {}, {}?\n".format(R, P, S)))
    c1 = random.choice([R, P, S])

    if u1 not in BEATS:
        play = input(MESSAGES["invalid"].format(u1))
    elif c1 == u1:
        play = input(MESSAGES["draw"])
    elif BEATS[u1] == c1:
        play = input(MESSAGES["win"].format(c1))               
    else:
        play = input(MESSAGES["loss"].format(c1))

【讨论】:

  • 真的不需要最后一个 elif,这对初学者来说可能有点太花哨了,不是吗?
  • @RushabhMehta 关于 elif 是正确的,但显式优于隐式;)不同意这种幻想。该结构相当容易理解,结构更加结构化,实际上也不那么复杂(花哨)。
  • 谢谢。特别是作为初学者,我很感激任何提示!
猜你喜欢
  • 1970-01-01
  • 2020-06-20
  • 1970-01-01
  • 1970-01-01
  • 2020-10-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-09
  • 1970-01-01
相关资源
最近更新 更多