-1

我做了一个小猜数游戏,如果你愿意,我已经让它重新启动。但是它通过回到开头并再次询问“myname”来重新启动,我怎样才能让它回到它想到一个数字的位置,并从第一次记住我的名字?

import random
restart = '1'
def main():
    guessestaken = 0

    print ('Hello, what is your name?')
    myname = raw_input()


    number = random.randint(1, 50)
    print ('Okay ' + myname + ', I am thinking of a number between 1 and 50. You have 5 guesses.')

    while guessestaken < 5:
        print ('Take a guess.')
        guess = input()
        guess = int(guess)

        guessestaken = guessestaken + 1

        if guess < number:
            print ('Your guess is too low.')

        if guess > number:
            print ('Your guess is too high.')

        if guess == number:
            break

    if guess == number:
        guessestaken = str(guessestaken)
        print ('Good job ' + myname + ', you got the correct answer in ' + guessestaken + ' guesses')


    if guess != number:
        number = str(number)
        print ('Oh dear ' + myname + ', the number I was thinking of was ' + number + '.')

while restart == '1':
    main()
    restart = raw_input('Would you like to try again? Press 1 for Yes, and 2 for No: ')

此刻它再次询问我的名字。我的意思是,它是功能性的,只是烦人。

谢谢

4

3 回答 3

1

你可以简单地移动

print ('Hello, what is your name?')
myname = raw_input()

main()函数之前,所以它只会运行一次。

您还需要在函数中使用raw_input()而不是 。input()main()

于 2012-11-22T13:11:55.630 回答
0

最简单的方法是在函数之外询问名称main(),然后为每个游戏传递它。从技术上讲,您不必传入它(python 仍然可以访问该变量),但这样做是更好的做法。

def main(myname):
    # Remove the name prompt from here

...

print ('Hello, what is your name?')
myname = raw_input()

while restart == '1':
    main(myname)
    restart = raw_input('Would you like to try again? Press 1 for Yes, and 2 for No: ')
于 2012-11-22T13:12:02.027 回答
0

一个简单的解决方法是在myname之外进行初始化,方法是在 .下方main放置. 然后,如果他的名字未知,只询问玩家的名字,即:myname = ''restart = '1'

if myname == '':
    print ('Hello, what is your name?')
    myname = raw_input()
于 2012-11-22T13:12:29.773 回答