初学Python游戏。创建记录文件

时间:2016-10-31 15:26:52

标签: python-2.7 save records

我正在学习Python,并尝试猜测计算机生成的数字。

from random import randint


def guess():
    play = 0    
    while play != 'exit':    
        numbercomp = randint(1, 9)
        tries = 0
        humanno = 0    
        while numbercomp != humanno:
            humanno = int(raw_input("What is my number, from 1 to 9? "))

            if numbercomp == humanno:
                tries = tries + 1
                print('you are right, nice!')

            elif numbercomp < humanno:
                tries = tries + 1
                print('my number is smaller than yours')

            else:
                tries = tries + 1
                print('my number is bigger than yours')

        print 'you got it in', tries, 'tries'
        play = raw_input('press any key to play , type "exit" to leave')
    print "Good bye!"
    exit()


while True:
    try:
        guess()

    except ValueError:
        print('that was not a number from 1 to 9!')

我想知道什么是将最佳分数(减少尝试次数)和持有者名称保存到文件中的方法,并让程序在每次启动时都显示此信息。不太重要的是以某种方式加密这个文件。

另外,如果你发现可以以更优雅的方式完成,我会很感激反馈。

1 个答案:

答案 0 :(得分:0)

例如你可以这样的东西

if tries > score:
            pickle.dump( favorite_color, open( "save.p", "wb" ) )

如果trys低于高分,那么它会改变最高分。

然后打开它就行了

highscore = pickle.load( open( "save.p", "rb" ) )

并且您可以在首次运行该功能时打印高分。

相关问题