在python文本冒险中简单随机的遭遇......我卡住了

时间:2016-09-22 19:34:37

标签: python python-3.x random

我最近开始使用python 3进行简单编码,而且我遇到了一个简单的问题:

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 - 函数然后打印出一个包含种族/武器等的文本而不为每个敌人写一个新文本。

我知道这是一个菜鸟问题,但我自己无法解决这个问题。

1 个答案:

答案 0 :(得分:1)

dicts和你的函数实际上是毫无意义的,他们需要实际返回一些东西,这样你就可以随机选择一对:

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))