我在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
感謝您的回答,但我在range100重新分配的值()和range1000()。它會不會重置guess_counter? – Khurram 2013-05-04 20:52:37