2

私はかなり長い間同じ戦艦ゲームに取り組んでおり、最終段階に近づいています。次に、関数 を使用して、上位 5 つのスコアをテキスト ファイルに保存する必要がありますdef saveScoretry次に、作成したばかりのファイルを読み取り、 and exceptfor file open and closeを使用してスコアを Python コードにロードする必要があります。Python に変数を認識させる方法がわかりません。変数scoreはローカルにしかないと信じているからです。これが私が持っているものです。ピクルスの使い方がわかりません。

def main():
    board=createBoard()
    printBoard(board)
    s = [[21,22,23,24,25],
    [45,55,65,75],
    [1,2,3],
    [85,86,87],
    [5,15],
    [46,56]]
    playBattleship(s,board)
main()
4

3 に答える 3

2

pickle の使用は、Python オブジェクトをファイルにシリアライズし、そのフォーマットを再度オブジェクトに読み込む低レベルの方法です。自然に使いやすい高レベルのインターフェイスが必要な場合は、shelveモジュールを見てみてください: http://docs.python.org/library/shelve.html#example

辞書のように扱うことができ、スコアを追加して保存するだけです。ボンネットの下で酸洗いすることにより、ファイルに保存されます。

import shelve

# open a shelve file. writeback=True makes it save
# on the fly
d = shelve.open('temp.file', writeback=True)
if not d.has_key('scores'):
    d['scores'] = []

print d['scores']
# []

# add some score values
d['scores'].append(10)
d['scores'].append(20)
d.close()

# next time, open the file again. It will have
# the 'scores' key. Though you should probably check
# for it each time in case its a first run.
d = shelve.open('temp.file', writeback=True)
print d['scores']
#[10, 20]

# sort the list backwards and take the first 5 top scores
topScores = sorted(d['scores'], reverse=True)[:5]
于 2012-04-26T18:14:11.163 に答える
1

これを行う最も簡単な方法は、Pickle を使用することです。「ロード」および「ダンプ」機能を使用すると、スコア オブジェクトを簡単に保存/ロードできます。

http://docs.python.org/library/pickle.html

import pickle

def saveScore(score):
    pickle.dump(score, 'topfive2.txt')

def loadScore():
    return pickle.load('topfive2.txt')
于 2012-04-26T18:09:41.670 に答える
1

Python でのファイルの読み取りと書き込みは非常に簡単です。

# Opening a file for writing will return the file handle f
f = open('/tmp/workfile', 'w')

# You can then write to the file using the 'write' method
f.write('Hello world!\n')

# To read your data back you can use the 'read' or 'readlines' methods

# Read the entire file
str = f.read()

# Read the file one line at a time
line = f.readline()

# Read the file into a list
list = f.readlines()

最後のスコア以外のデータを保存したい場合は、SQLite3 データベースの作成を検討してください。Python には、SQLite3のサポートが組み込まれています。これはクロスプラットフォームのファイルシステム データベースです。データベースは、ディスク上の通常のテキスト ファイルにすぎませんが、データベースに期待される多くの SQL 操作をサポートしています。

于 2012-04-26T18:15:15.710 に答える