变量值自动更改

时间:2013-05-04 20:48:08

标签: python python-3.x

我在coursera.org上解决了“Python中交互式编程简介”课程的作业#2。根据规格,我的任务工作正常。但是,当用户正确猜出数字并重新开始游戏时,会有一个机会自动减少。当机会数量耗尽时,情况就不会发生。两种条件的逻辑是相同的。任何人都可以解释并修复它。

这是我的代码:

# template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console

import simplegui
import random

# initialize global variables used in your code
secret_number=0
guess_counter=0
init_var = 1


# define event handlers for control panel

def range100():
    # button that changes range to range [0,100) and restarts
    global secret_number, guess_counter, init_var
    secret_number = random.randrange(0, 100, 1)
    guess_counter = 7
    print ""
    print "New Game: The range is from 0 to 100"
    print "Number of guesses is ", guess_counter
    #print secret_number


def range1000():
    # button that changes range to range [0,1000) and restarts
    global secret_number, guess_counter, init_var
    secret_number = random.randrange(0, 1000, 1)
    guess_counter = 10
    init_var = 2
    print ""
    print "New Game: The range is from 0 to 1000"
    print "Number of guesses is ", guess_counter
   #print secret_number

def get_input(guess):
    # main game logic goes here 
    global secret_number, guess_counter
    user_guess = int(guess)
    print ""
    print "Guess was", user_guess
    if user_guess > secret_number:
        print "Higher!"
    elif user_guess < secret_number:
        print "Lower!"
    else:
        print "Correct ... You WIN!"
        initialize()


    guess_counter -= 1
    if guess_counter == 0:
        print "You Lost, all guesses are consumed"
        initialize()
    else:
        print "Number of remaining guesses is ", guess_counter

def initialize():
    #restart the game, when all the guesses are exhaust
    if init_var == 1:
        range100()
    else:
        range1000()

# create frame
frame = simplegui.create_frame("Guess the number", 300, 200)

# register event handlers for control elements
frame.add_button("Range is [0, 100]", range100, 200)
frame.add_button("Range is [0, 1000]", range1000, 200)
frame.add_input("Enter a guess", get_input, 200)

initialize()

# start frame
frame.start()

# always remember to check your completed program against the grading rubric

1 个答案:

答案 0 :(得分:0)

在initialize()

下添加一个回复
    elif user_guess < secret_number:
    print "Lower!"
else:
    print "Correct ... You WIN!"
    initialize()
    return