循环停止时

时间:2015-12-12 00:12:04

标签: python

代码正在运行,但是在2代码之后它会停止,这是在playagain()的部分,当我问是或否问题时它会显示错误但会在试用后停止做错了吗?

import random
import time
import getpass
import sys

def game1():
    number = (input("Please Enter Your 3 Digit Code e.g.(0 0 1): "))
    if number.isnumeric(): #if its a number
        counter = 0
        x = True
        L = 1
        H = 100
        while x == True:
            time.sleep(0.5)
            randomguess = random.randint(L,H)
            print("%03d"%randomguess)
            if randomguess > int(number):
                print("The Passcode is lower")
                H = randomguess
            elif randomguess < int(number):
                print("The Passcode is higher")
                L = randomguess
            else:
                print("The Passcode is Equal")
                x = False
            counter = counter + 1
            if randomguess == int(number):
                print("Well Done the Prisoner has Escaped, he did it in",counter,"trys")
                return playagain()

            if counter > 9:
                print("The Prisoner get it wrong",counter,"times he is locked in, Well Done Jailer")
                return playagain()

    else:
        print("This is Invalid, Please Provide a 3 Digit Code")
#This is the Section just for Reference
def playagain():
    playagain = input("Do you wish to play again (yes/no): ")
    if playagain == "yes":
        print("You chose to play again")
        return game1()
    elif playagain == "no":
        print("So you let the prisoner escape, thats it your fired")
        time.sleep(2)
        print("Thanks for Playing")
        time.sleep(2)
        #quit("Thanks for Playing") #quit game at this point
        sys.exit()
    else:
        print("Please choose a valid option")
        return

2 个答案:

答案 0 :(得分:2)

这是一个清理过的版本:

from random import randint
from time import sleep

DELAY = 0.5

def get_int(prompt, lo=None, hi=None):
    while True:
        try:
            val = int(input(prompt))
            if (lo is None or lo <= val) and (hi is None or val <= hi):
                return val
        except ValueError:
            # not an int, try again
            pass

def get_yn(prompt):
    while True:
        yn = input(prompt).strip().lower()
        if yn in {"y", "yes"}:
            return True
        elif yn in {"n", "no"}:
            return False

def game(tries=100):
    code = get_int("Please enter a 3-digit number (ie 091): ", 0, 999)
    lo, hi = 0, 999
    for attempt in range(1, tries+1):
        sleep(DELAY)
        guess = randint(lo, hi)
        if guess < code:
            print("Guessed {:03d} (too low!)".format(guess))
            lo = guess + 1
        elif guess > code:
            print("Guessed {:03d} (too high!)".format(guess))
            hi = guess - 1
        else:
            print("{:03d} was correct! The prisoner escaped on attempt {}.".format(guess, attempt))
            return True
    print("The prisoner failed to escape!")
    return False

def main():
    while True:
        game()
        if get_yn("Do you want to play again? "):
            print("You chose to play again.")
        else:
            print("Alright, bye!")
            break

if __name__=="__main__":
    main()

答案 1 :(得分:0)

def game1():        
    number = (input("Please Enter Your 3 Digit Code e.g.(0 0 1): "))
    if number.isnumeric(): #if its a number
        counter = 0
        x = True
        L = 1
        H = 100
        while x == True:
            time.sleep(0.5)
            randomguess = random.randint(L,H)
            print("%03d"%randomguess)
            if randomguess > int(number):
                print("The Passcode is lower")
                H = randomguess
            elif randomguess < int(number):
                print("The Passcode is higher")
                L = randomguess
            else:
                print("The Passcode is Equal")
                x = False
            counter = counter + 1
            if randomguess == int(number):
                print("Well Done the Prisoner has Escaped, he did it in",counter,"trys")
                x = False

            if counter > 9:
                print("The Prisoner get it wrong",counter,"times he is locked in, Well Done Jailer")
                x = False
    else:
        print("This is Invalid, Please Provide a 3 Digit Code")

    playagain()

#This is the Section just for Reference
def playagain():
    playagain = ""
    while (playagain != "yes" or playagain != "no"):
       playagain = input("Do you wish to play again (yes/no): ")
       if playagain == "yes":
           print("You chose to play again")
           return game1()
       elif playagain == "no":
           print("So you let the prisoner escape, thats it your fired")
           time.sleep(2)
           print("Thanks for Playing")
           time.sleep(2)
           #quit("Thanks for Playing") #quit game at this point
           sys.exit()
       else:
           print("Please choose a valid option")

game1()

有关工作示例,请参阅https://repl.it/B7uf/3

游戏通常在您使用while x = True实施的游戏循环中运行。游戏结束后游戏环会退出,然后要求用户重新启动它。您遇到的错误是由于游戏循环过早退出,然后才能要求用户重新启动。

上面的代码就是这个问题。还有其他一些事情可以更新以改善流程,但会留给你。

  • 使用try / catch块代替布尔检查
  • 将游戏循环分解为单独的方法