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