如何将代码块集中到级别(Python)

时间:2017-02-27 13:20:26

标签: python

!我正在尝试用Python构建一个小游戏来猜测一个范围内的随机数。代码将随机选择1,20之间的数字,并要求用户猜测数字3次。

我需要帮助将下面的代码块聚类到一个级别(说级别0)。如果玩家能够正确猜测玩家进入下一级别(等级1)

我需要进一步的帮助,我将1级范围的条件更改为1,30。

import random

secretNumber = random.randint(1,20)
print(" I am thinking of a number between 1 and 20.")

#Ask the player to guess 3 times.
for guessTaken in range(1,4):
    print("Take a guess. ")
    guess1 = int(input())
    if guess < secretNumber:
        print("Your guess is too low")
    elif guess > secretNumber:
        print("Your guess is too high")
    else:
        break

if guess == secretNumber:
    print("Good job! you guessed my number in " + str(guessTaken) + " guesses! Move onto the next level")
else:
    print("Nope. The number I was thinking of was " + str(secretNumber))

secretNumber1 = random.randint(1,30)
print(" Welcome to level 1 I am thinking of a number between 1 and 30.")
for guessTaken1 in range(1,4)
    guess = int(input())
    print("Take a guess. ")
    guess1 = int(input())
    if guess1 < secretNumber1:
    print("Your guess is too low")
    elif guess1 > secretNumber:
        print("Your guess is too high")
    else:
        break

if guess == secretNumber1
    print("Good job! you guessed my number in " + str(guessTaken) + " guesses! Move onto the next level")
else:
    print("Nope. The number I was thinking of was " + str(secretNumber1))

1 个答案:

答案 0 :(得分:1)

这将有效:

import random

def guess_number(max_number):
    print(" I am thinking of a number between 1 and {0}.".format(max_number))
    secret_number = random.randint(1, max_number)

    for guess_taken in range(1,4):
        print("Take a guess. ")
        guess = int(input())
        if guess < secret_number:
            print("Your guess is too low")
        elif guess > secret_number:
            print("You guess is too high")
        else:
            return (True, guess_taken)

    return (False, secret_number)

level = 1
for max_number in range(10, 30, 5):
    print("Current level: {0}".format(level))
    guessed = guess_number(max_number)
    if guessed[0]:
        print("Good job! you guessed my number in " + str(guessed[1]) + " guesses!")
    else:
        print("Nope. The number I was thinking of was " + str(guessed[1]))
        print ("Game over!")
        break
    level += 1

示例输出:

Current level: 1
I am thinking of a number between 1 and 10.
Take a guess. 
6
You guess is too high
Take a guess. 
3
Your guess is too low
Take a guess. 
5
Good job! you guessed my number in 3 guesses!
Current level: 2
I am thinking of a number between 1 and 15.
Take a guess. 
7
Your guess is too low
Take a guess. 
10
Your guess is too low
Take a guess. 
13
You guess is too high
Take a guess. 
12
You guess is too high
Nope. The number I was thinking of was 11
Game over!