重新运行Simplegui游戏

时间:2013-12-17 22:06:42

标签: python loops codeskulptor

我是一个相当新的程序员,我正在学习如何使用codeskulptor中的simplegui!我做了一个猜谜游戏,我制作了一个带有2个按钮的画布。 1个按钮设置他们可以从0到100猜测的数字范围,另一个设置从0到1000.我想添加第三个按钮,显示“新游戏!”当他们推动它时,一切都会重置,他们可以再次播放,而不必退出框架。您可以在http://www.codeskulptor.org/#user27_FQ1uDycAiykat13_0.py查看我的代码,感谢您的帮助!

#imports 
import math
import simplegui
import random

#global variables
secret_num = random.randint(0, 100)
max_guesses = 7

#define event handlers for control panel

def range100():
    global secret_num, max_guesses
    secret_num = random.randint(0, 100)
    max_guesses = 7
    print "You've selected to guess a number between 0 and 100! Good luck!\n"
    #button that changes range to [0,100)

def range1000():
    global secret_num, max_guesses
    secret_num = random.randint(0, 1000)
    max_guesses = 10
    print "You've selected to guess a number between 0 and 1000! Good luck!\n"
#button that changes range to 0,1000

def get_input(guess):
    global count, max_guesses
    max_guesses -= 1
    num_guessed = int(guess)
    if num_guessed == secret_num:
        print guess + " IS CORRECT! YOU WIN!\n"
    elif max_guesses > 0:
        if num_guessed > secret_num:
            print "You guessed", num_guessed, "."
            print "You need to guess LOWER! You have", max_guesses, "guesses          remaining!\n"
        elif num_guessed < secret_num:
            print "You guessed", num_guessed, "."
            print "You need to guess HIGHER! You have", max_guesses, "guesses remaining!\n"
    else:
        print "YOU LOSE, LOSER! TRY AGAIN FOR BETTER LUCK!"
        print "The correct answer was", secret_num

#create a frame
f = simplegui.create_frame('Guessing Game!', 250, 250)
f.set_canvas_background('Cyan')

#create buttons
    f.add_button("Guess between (0,100)", range100)
    f.add_button("Guess between (0,1000)", range1000)
    f.add_button("New game!", get_input)
    f.add_input("Enter a guess!", get_input, 200)
    f.start()
    print "Welcome to Matt Schaefer's guessing game!"
    print "Please select the number range you wish to guess, and start your game!\n"

2 个答案:

答案 0 :(得分:0)

我也是python的新手:)

我通常会定义一个代表游戏本身的函数:

例如

def game
  rand num
  rand num2

  def range1
  def range 2
  def guesses

  button 1
  button2
  button3 (game) prints "begin game again"

我希望我帮助过你:)

P.S。很明显,我写的代码并不意味着什么;)

答案 1 :(得分:0)

每次点击其他按钮range100range1000时,都会启动新游戏。 get_input功能是您的猜测,而不是您想要的新游戏。您希望此New game!按钮与按钮的不同之处是什么?如果您想从上次设置开始,那么可能是另一个函数,就像range100函数一样,另一个全局变量保存最后一个游戏信息,并设置range100range1000中的最后一个游戏信息当你设置这个当前游戏全局变量?

当然,这只是众多方法中的一种。看起来您正在参加Coursera课程“Python中的交互式编程简介”?如果是这种情况,您应该参考forum寻求帮助,而不是在这里。