2016-10-06 31 views
0

我在寫一個謀殺案之謎 - 很像Clue。我正在使用字典存儲我的所有信息。我的問題:有沒有一種方法來混合從一組整數範圍中抽取的字典值?我希望每場比賽都能在開始新遊戲時在詞典中洗牌。現在我專注於角色擺放......我試圖找出每場比賽(位置[current_room] [「char」)洗牌角色位置的最佳方式。一旦我明白如何做到這一點,我想要應用此一堆的遊戲的其他方面 - 與創建一個全新的神祕解決每場比賽的想法有什麼建議歡迎在字典中混排特定值(Python 3.5)

編輯 謝謝你的答案,我並不想。!隨機化我的整個字典,只是改變每個遊戲中某些鍵的值,我想我可能需要另一種方式來解決這個問題,當我得到東西時,我會更新這個帖子。改變我想通過編輯詞典「洗牌」的特定鍵的值。位置[1] [「char」] = random.choice([0,1,2]),然後根據random.choice結果中的一系列IF語句更改其他值。再次感謝您的幫助。

locations = { 
1: {"name": "bedroom", 
    "msg": "There is a painting on the wall. \nThe window looks out into the garden.", 
    "char": 2, 
    "item": "matches", 
    "west": 2}, 
2: {"name": "living room", 
    "msg" : "The room is freezing cold. The fireplace is empty.", 
    "char": 1, 
    "Item": "firewood", 
    "east": 1}, 
} 

characters = { 
1: {"name": "doctor crichton", 
    "msg": "A tall, handsome archeologist home from a dig in Africa."}, 
2: {"name": "the widow", 
    "msg": "An beautiful woman with a deep air of sadness."}, 
} 
current_room = 1 

current_char = locations[current_room]["char"] 

def status(): 
    """updates player on info on current room""" 
    print("You are in the " + locations[current_room]["name"]) 
    char_status() 

def char_status(): 
    """compiles character infomation in current room""" 
    if current_char > 0: 
     char_room_info() 
    else: 
     print("\nThis room is empty.") 

def char_room_info(): 
    """NPC behavior in each room""" 
    print(characters[current_char]["name"].title() + " is in the room with you.") 

status() 
+0

'進口隨機的; random.choice(someDictionary.keys())' –

+0

[如何獲得一個隨機值在python字典中](http://stackoverflow.com/questions/4859292/how-to-get-a-random-value -in-蟒字典)的 –

回答

0

Python詞典是無序的,所以我不明白你爲什麼要「洗牌」他們。如果你想在字典中選擇隨機字符串,也許你可以使用一個列表來包裝這個字典,爲簡單起見。

像這樣:

Locations = [ {"name": "bedroom...}, {"name": "livingroom"...},...]

我想你明白了吧。所以現在來訪問它們:

Locations[random.rand]["name"]

你也可以使用此:

random.choice(locations.keys()) 

這是容易得多。

0

如果Python3.x然後執行:

import random 
random.choice(list(someDictionary.keys())) 

如果Python2.x然後執行:

import random 
random.choice(someDictionary.keys())