我对编程很陌生,我的任务是做一个骰子滚动游戏的挑战。它从1到6,它首先问你是否有兴趣玩。然后它就滚了。然后它吐出数字,并问你是否想再玩一次。
不过,我可以保证它会更短一些。我对这部分完全不知所措。老实说,我想批评一下如何清理我的程序。我知道我是全新的,但我想学习效率和基础,如果可能的话。
我用Python 3编程。
import random
game_start = input("Would you like to roll the dice?")
def dice_roll():
print("Your number is: " + str(random.randint(1,6)))
global play_again
play_again = input("Would you like to play again?")
if game_start == "yes":
dice_roll()
while play_again == "yes":
dice_roll()
elif game_start == "no":
print("Game Over")
else:
print("Input not recognized")
发布于 2017-08-07 02:05:28
import random
def dice_roll():
while True:
print("Your number is: " + str(random.randint(1,6)))
play_again = input("Would you like to play again? ")
while play_again != 'yes':
if play_again == 'no':
return print("Game Over")
else:
print("Input not recognized")
play_again = input("Would you like to play again? ")
def main():
game_start = input("Would you like to roll the dice?")
if game_start == 'yes':
dice_roll()
else:
print('too bad')
if __name__ == '__main__':
main()
只要你想再玩一次,while
在dice_roll()
里面就会掷骰子。我将您的官方输入作为main()
的一部分,所以如果您想从另一个程序中使用这个程序,它不会做任何事情,但是您仍然可以使用dice_roll()
函数。
发布于 2017-08-07 01:36:24
也许你可以把它放在一个循环里。可能将其全部滚动到函数中,或者将函数代码放在“while”循环所在的位置。
比如:如果是,打印(“您的号码是:”+str(random.randint(1,6)
此外,您可能根本不需要“不”选项。它可能只是有你写的“是”和其他任何事情都是“游戏结束”。但我看到,“输入不被识别”可能是你任务的一部分。
发布于 2017-08-07 04:44:22
将game_start
和play_again
合并到一个变量中--注意,它们的含义几乎相同,而且您永远不需要同时使用这两个变量。所以叫它play
、wants_to_play
或keep_playing
等等。
这将使您能够折叠一些重复的if
语句和循环。
还要注意的是,dice_roll
不仅仅是掷骰子-它还询问你是否想再玩一次。别那么做--一个函数应该只做一件事,而不是两件事。也许dice_roll
应该只做print("Your number is: " + str(random.randint(1,6)))
,或者,实际上,它应该返回random.randint(1,6)
,让其他代码担心显示--想象一下,如果您想要制作一个GUI --尝试阻止UI代码在任何地方传播。
因此,想想游戏应该如何工作(这不是python):
wants_to_play = ask "do you want to play"
while wants_to_play
roll dice, display roll
wants_to_play = ask "play again"
这应该是基本的,对吧?你能从那里填进去吗?把它变成Python?
P.S.也许ask
可以是一个函数,它处理糟糕的输入等,并将答案转换为true/false。
https://codereview.stackexchange.com/questions/172253
复制相似问题