0

coursera.org のコース「Python での対話型プログラミングの紹介」の課題 #2 を解決しました。仕様通りの私の課題作業OK。ただし、ユーザーが数字を正しく推測してゲームが再開されると、1 つのチャンスが自動的に減少します。これは、チャンスの数が使い果たされた場合には発生しません。両方の条件のロジックは同じです。誰でも説明して修正できますか。

これが私のコードです:

# 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 に答える