如何重启程序?

时间:2015-04-28 00:46:35

标签: python while-loop nested-loops

重新启动程序似乎有错误,它无法正常重启。它询问你是否想再次玩,然后要求玩家的名字告诉你目标,然后自己重​​新开始。

import random, time

#Variables
die1 = 0
die2 = 0
goal = 0


 tries1 = 0

tries2 = 0
sum = 0
sum2 = 0
choice = "y"

while choice == "y":
#Asking for the player's names
    player1 = input("What is your name, player1?")
    player2 = input("What is your name, player2?")

#The "goal"
    goal = random.randrange(5) + 1
    print("The goal is:", goal)

#First while loop for the first die rolled by the first player
    while die1 != goal:
        die1 = random.randrange(5) + 1
        time.sleep(1)
        print(player1, "Your roll is:", die1)
        tries1 = tries1 + 1
        sum = sum + die1
        time.sleep(1.5)
        print("Your sum is:", sum)
#Second while loop for the second die rolled by the second player    
    while die2 != goal:
        die2 = random.randrange(5) + 1
        time.sleep(1)
        print(player2, "Your roll is:", die2)
        tries2 = tries2 + 1
        sum2 = sum2 + die2
        time.sleep(1.5)
        print("Your sum is:", sum2)

        time.sleep(2)

#The statement at the end of the game
        print("\n\n""Player", "\t\t", "Goal", "\t\t", "# of Rolls","\t\t", "Sum of Rolls", "\n", player1, "\t\t", goal, "\t\t", tries1,"\t\t\t", sum, "\n", player2, "\t\t", goal, "\t\t", tries2, "\t\t\t", sum2)
        choice = input("Would you like to play again?: (y) or (n)")
        goal = 0
        tries1 = 0
        tries2 = 0
        sum = 0
        sum2 = 0
        break

2 个答案:

答案 0 :(得分:0)

这可能是因为在程序结束时你无论如何都会打破主循环。您应该使用选择变量用if语句包围它。最后一个语句也与第二个玩家滚动时的内联,因此它将在该循环中执行。要解决这个问题,你需要减少缩进,以便在游戏结束时执行。另外,tries1变量也缩进了空格,因此python也可能会抛出某种形式的语法错误。

答案 1 :(得分:0)

  1. 代替你的break语句,输入:

    if choice != 'y': break

  2. 如果用户键入“y”,这将导致外部while循环返回到开头。否则你将跳出循环,脚本将退出。

    1. 在while循环中将所有变量声明从die1移动到sum2;否则他们将不会被重新初始化。