简体   繁体   English

保存用户输入字典

[英]Save user input dictionary

Im trying to find a suitable method to save a dictionary that has user input data and also data that comes from my program (battleship game).我试图找到一种合适的方法来保存包含用户输入数据和来自我的程序(战舰游戏)的数据的字典。 The user input data is player name and the rest is the state of the game (like current game, scores, ...).用户输入的数据是玩家姓名,其余的是游戏状态(如当前游戏、分数等)。

I did some searching and tried to use Pickle to save this data.我做了一些搜索并尝试使用 Pickle 来保存这些数据。 My dictionary is stored here:我的字典存储在这里:

def game():
    return {
        'players': [],
        'active_players':[],
        'running_game': False,

Im getting the player data from here:我从这里获取玩家数据:

def player_register(mm,name):
    board1_for_ship_placement = create_grid(columns_size,rows_size)
    board2_for_showing = create_grid(columns_size,rows_size)
    player = {
        'name':name,
        'played_games': 0,
        'victory': 0,
        'ships_available' : {
            "lancha":0,
            "submarino":0,
            "fragata":0,
            "cruzador":0,
            "porta_avioes":0
        },
        'ships_in_use':[],
        'board1': board1_for_ship_placement,
        'board2': board2_for_showing
    }

    mm['players'].append(player)

THIS is the data I need to save and be able to load again on my program.这是我需要保存并能够在我的程序中再次加载的数据。 Name , played games and victorys .名字玩过的游戏胜利

This method gathers info from dictionaries.此方法从字典中收集信息。

Now I have seen some examples like this:现在我看到了一些这样的例子:

import pickle
my_dict = {“example”:”dog”, “example2″:”cat”}
with open(‘myfile.txt’, ‘wb’) as f:
pickle.dump(mydict, f)

Load:加载:

f = open(‘myfile.txt’, ‘rb’)
new_dict = pickle.load(f)
f.close()

Now, how can I modify this to save my data?现在,我该如何修改它以保存我的数据? I have tried this but with no results:我试过这个,但没有结果:

import pickle
**my_dict = game()**
with open(‘myfile.txt’, ‘wb’) as f:
pickle.dump(mydict, f)

Anyone can help me?任何人都可以帮助我吗? I doesn't need to by pickle, JSON is also fine.我不需要泡菜,JSON 也可以。

I added some sample data to the game function and it worked fine.我在game功能中添加了一些示例数据,效果很好。 If you don't get the right result, maybe something is wrong with your game function.如果你没有得到正确的结果,可能你的game功能有问题。

Save:节省:

import pickle


def game():
    return {
        'players': ['p1', 'p2'],
        'active_players': ['a_p1', 'a_p2'],
        'running_game': False
    }


my_dict = game()
with open("my_data.pkl", "wb") as f:
    pickle.dump(my_dict, f)

Load:加载:

import pickle

with open("my_data.pkl", "rb") as f:
    my_data = pickle.load(f)

print(my_data)
# Output:
# {'players': ['p1', 'p2'], 'active_players': ['a_p1', 'a_p2'], 'running_game': False}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM