0

我在 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
4

1 回答 1

0

在initialize()下添加一个return

    elif user_guess < secret_number:
    print "Lower!"
else:
    print "Correct ... You WIN!"
    initialize()
    return
于 2013-05-04T20:55:49.480 回答