2015-04-22 67 views
0

因此,對於我的介紹性編程課程,我們必須創建一個具有保存/加載功能的遊戲,並且我正在嘗試測試一些代碼以確保其正常工作。保存文件功能

由於某些原因,我無法獲得以下功能正常工作。我已經嘗試過在Idle中逐行進行,它在那裏工作得很好,但是一旦我嘗試在一個函數中使用同一個系統,它就不起作用。請幫助?

def save(name,inventory,mapGrid,x,y,enemy):` 

    choice = 0 

    file = shelve.open("save_files")  
    save = {'save1':file['save1'],'save2':file['save2'],'save3':file['save3']} 

    print("Where would you like to save?") 
    print("Save 1 -", save['save1']['name']) 
    print("Save 2 -", save['save2']['name']) 
    print("Save 3 -", save['save3']['name']) 
    choice = input("Enter Number:\t") 

    if choice == 1: 
     save['save1']['name'] = name 
     save['save1']['inventory'] = inventory 
     save['save1']['mapGrid'] = mapGrid 
     save['save1']['x'] = x 
     save['save1']['y'] = y 
     save['save1']['enemy'] = enemy 
     file['save1'] = save['save1'] 
     file.sync() 
    if choice == 2: 
     save['save2']['name'] = name 
     save['save2']['inventory'] = inventory 
     save['save2']['mapGrid'] = mapGrid 
     save['save2']['x'] = x 
     save['save2']['y'] = y 
     save['save2']['enemy'] = enemy 
     file['save2'] = save['save2'] 
     file.sync() 
    if choice == 3: 
     save['save3']['name'] = name 
     save['save3']['inventory'] = inventory 
     save['save3']['mapGrid'] = mapGrid 
     save['save3']['x'] = x 
     save['save3']['y'] = y 
     save['save3']['enemy'] = enemy 
     file['save3'] = save['save3'] 
     file.sync() 

    file.close() 

    print("Game Saved") 

編輯:應該保存字典運行功能後提交[「保存#」],讓我訪問後的數據,但數據不會保存到貨架文件,當我嘗試再次訪問它沒有什麼。 ((對不起,應該把它放在正確的位置))

例如,如果我再次運行save()函數,它應該顯示與保存文件相關的名稱,但它只顯示'EMPTY'。

我必須設置爲是

文件save_files民生之本[ '保存#'] = { '名': '空'}

+0

它是如何不起作用類型的一致性?爲什麼它不起作用? – miradulo

+0

您應該更新帖子並提供錯誤信息等等,以及預期的輸出結果。檢查[mcve](http://stackoverflow.com/help/mcve) –

+0

運行該函數後,它應該將字典保存到文件['save#']並允許我稍後訪問數據,但數據不會'保存到擱置文件中,當我嘗試再次訪問它時,沒有任何內容。 – Sebastian

回答

0

由於您的if語句比較int,確保choice也是一個整數。有可能choice實際上是一個字符串,在這種情況下,沒有一個比較是真的。基本上是:

choice = int(input("Enter Number:\t")) 

另外,您可以更改爲字符串的所有比較,但重要的是要保證在比較

+0

哦,我的天啊,我是個白癡謝謝你 – Sebastian

+1

沒問題。請標記爲已解決。 – ODiogoSilva