如何减少循环中的尝试次数?

时间:2019-10-08 17:31:40

标签: python-3.x loops math

我正在创建一个游戏,您在其中猜出一个点,如果猜对了,您就赢了,但是如果猜对了,您的尝试就失败了。不过,只有一个问题。尝试不会失败。对不起,我不好说。

我试图更改if语句,我试图将-=符号更改为只是-符号,哪种工作方式有效,但事实是一旦循环,它会返回到尝试之前的原始数字-1个功能。

while True:
    attempts = 5
    print(attempts)
    x = input("Guess the X coordinate.")
    y = input("Guess the Y coordinate.")

    a = random.randrange(100)
    b = random.randrange(100)

    p = Point(a,b)

    print(p)

    if x and y == a and b:
        print("Yay you did it; you found both coordinates.")
    elif x == a:
        print("You only found the X coordinate.")
    elif x == b:
        print("You only found the Y coordinate")
    else:
        print("you disgust me.")
        print(attempts - 1)

    while attempts < 5:

        if attempts > 1:
            print('you can play again')
            continue
        else:
            print('you lost')
            exit()

1 个答案:

答案 0 :(得分:0)

您需要使用attempts += -1

attempts = 5
while attempts > 0:
    print(attempts)
    x = input("Guess the X coordinate.")
    y = input("Guess the Y coordinate.")
    a = random.randrange(100)
    b = random.randrange(100)

    p = Point(a,b)

    print(p)

    if x and y == a and b:
        print("Yay you did it; you found both coordinates.")
    elif x == a:
        print("You only found the X coordinate.")
    elif x == b:
        print("You only found the Y coordinate")
    else:
        print("you disgust me.")
        attempts += -1
        print(attempts)

    if attempts > 0:
        print('you can play again')
        continue
    else:
        print('you lost')
        exit()