2016-09-22 66 views
0

我最近开始简单的编码与Python 3和i'm坚持一个简单的问题:简单,在Python文字冒险随机遇到.. I'm卡


import random 

def enemy_bandit01(): 
    bandit01 = {'race': 'human', 'weapon': 'a sword'} 

def enemy_orc01(): 
    orc01 = {'race': 'orc', 'weapon': 'a club'} 

def enemy_wolf01(): 
    wolf01 = {'race': 'wolf', 'weapon': 'claws'} 

encounter_choice = [enemy_bandit01, enemy_orc01, enemy_wolf01] 

print('You fight against a ____. He has ____!') 

我只是想让Python选择一个随机的enemy_x函数,然后打印出包含种族/武器等的文本,而不用为每个敌人写一个新的文本。

我知道这是一个noob问题,但我无法自己弄清楚。

回答

1

该类型的字典和你的函数真的毫无意义,因为他们,他们需要实际一些回报,这样你就可以随机挑选一对:

from random import choice # use to pick a random element from encounter_choice 

def enemy_bandit01(): 
    return 'human', 'a sword' # just return a tuple 


def enemy_orc01(): 
    return 'orc', 'a club' 


def enemy_wolf01(): 
    return 'wolf', 'claws' 


encounter_choice = [enemy_bandit01, enemy_orc01, enemy_wolf01] 

# use str.format and unpack the tuple of race, weapon 
print('You fight against a {}. He has {}!'.format(*choice(encounter_choice)())) 

这可能也只是成为从列表中选择一个随机元组:

from random import choice 

encounter_choice = [('human', 'a sword'), ('orc', 'a club'), ('wolf', 'claws') ] 

print('You fight against a {}. He has {}!'.format(*choice(encounter_choice))) 

*choice(encounter_choice)相当于做:

race, weapon = choice(encounter_choice) 
print('You fight against a {}. He has {}!'.format(race, weapon)) 
+0

谢谢,雷尔我帮助了我! :) – BobJohn