0

代码是:

import pickle
import random

guessesTaken = 0

print('Hello! What is your name?')
name = raw_input()

number = random.randint(1, 20)
print('Well, ' + name + ', I am thinking of a number between 1 and 20.')

while guessesTaken < 6:
    print('Take a guess.') # There are four spaces in front of print.
    guess = raw_input()
    guess = int(guess)

    guessesTaken = guessesTaken + 1

    if guess < number:
        print('Your guess is too low.') # There are eight spaces in front of print.

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

    if guess == number:
        break

if guess == number:
    guessesTaken = str(guessesTaken)
    print('Good job, ' + name + '! You guessed my number in ' + guessesTaken + ' guesses!')

if guess != number:
    number = str(number)
    print('Nope. The number I was thinking of was ' + number)
clasament= 'clasament.data'
f=open(clasament, 'wb')
pickle.dump(name, f)

我想做一个像这样的顶级:
nameguessesTaken
nameguessesTaken
....
我只能让名字出现,如果你再次玩游戏,名字会刷新。


我收到此错误。回溯(最近一次调用):文件“/home/catalin/guessnumber.py”,第 44 行,名称,dct.items()中的猜测:AttributeError:'str' 对象没有属性'项目'

4

1 回答 1

0

看起来您正试图保持高(低)分。这似乎是一本字典的工作,它pickle(或json)可以很好地处理。

try:
    with open('clasament.data') as f:
       dct = pickle.load(f)
except IOError:  #file doesn't exist, no high-scores registered.
    dct = {}

if dct:
    print "Low scores so far!"

    #you may want `sorted(dct.items()) to have a nice order...
    for name,guesses in dct.items(): 
        print(name,guesses)

#<snip>
#play game here
#</snip>

#keep low scores :-)
if name in dict and dct[name] > guessesTaken:
    dct[name] = guessesTaken

with open('clasament.data','w') as f:
    dct = pickle.dump(dct,f)
于 2012-08-22T15:11:39.880 回答