【问题标题】:using a function to call a class in a while loop在while循环中使用函数调用类
【发布时间】:2017-01-03 01:30:26
【问题描述】:

我目前正在编写一个 python gui,它最终会生成一个随机村庄,用于桌面 RPG(主要是龙与地下城)

我有下面的代码,它将根据用户想要的城镇大小生成许多小酒馆,到目前为止它运行良好。我希望 GUI 最终也会创建商店、寺庙和其他建筑物。

class NPC: 
    def __init__(self, first, last):
        self.first = first
        self.last = last
        self.name = first + ' ' + last

class Tavern: 
    def  __init__(self, name1, name2):
        self.name1 = name1
        self.name2 = name2
        self.name = 'The ' + name1 + ' ' + name2

while num_tav != 0:
    morf = random.randint(1, 2)
    if morf == 1: 
        sex = 'male'
    else:
        sex = 'female' 
    first = open(set_race + '_' + sex + '.txt')
    name1 = first.readlines()
    first = random.choice(name1).strip()

    last = open(set_race + '_surnames.txt')
    name2 = last.readlines()
    last = random.choice(name2).strip()

    npcname = NPC(first, last)

    tavern1 = open('tavnames1.txt')
    name1 = tavern1.readlines()
    name1 = random.choice(name1).strip()

    tavern2 = open('tavnames2.txt')
    name2 = tavern2.readlines()
    name2 = random.choice(name2).strip()
    tavern = Tavern(name1, name2)
    print('Taverns/Inns: ' + tavern.name + "The inkeeper is a tall " + set_race + ' ' + sex + " named " + npcname.name + '\n')
    num_tav = num_tav - 1

    w.insert(END, not_b + 'Taverns/Inns: ' + tavern.name + "The inkeeper is a tall " + set_race + ' ' + sex + " named " + npcname.name + '\n' + 'Population is approx. ' + str(population) + ' people\n') 

NPC 类基本上会生成一个随机名称,我想在其他领域(商店、市场、铁匠等)使用它,而不仅仅是生成旅馆老板的名称。

我的问题是;

是否可以创建一个将使用脚本的函数

first = open(set_race + '_' + sex + '.txt')
name1 = first.readlines()
first = random.choice(name1).strip()

last = open(set_race + '_surnames.txt')
name2 = last.readlines()
last = random.choice(name2).strip()

npcname = NPC(first, last)

作为一个调用NPC类的函数,然后只有其他while循环调用它?而不是在每个循环中重复相同的代码来生成其他建筑物?

我假设是这样,但我只是不知道它会被称为什么,因此感谢任何帮助。

【问题讨论】:

  • 是的,很抱歉在复制和粘贴到“代码”格式时出错。
  • 已修复,抱歉。

标签: python function class oop


【解决方案1】:

在一个函数中定义while循环,可能带有一个额外的参数,该参数获取它应该生成的实体类型(Tavern,shop,...),然后将其放入另一个python文件并导入它。作为一个模块。

def mynewfunction(set_race,sex):
    first = open(set_race + '_' + sex + '.txt')
    name1 = first.readlines()
    first = random.choice(name1).strip()

    last = open(set_race + '_surnames.txt')
    name2 = last.readlines()
    last = random.choice(name2).strip()


    return NPC(first, last)

然后:

while (x,y,z):
    npcname = mynewfunction(set_race):

【讨论】:

  • 这更多的是评论而不是答案。你能扩展并解释答案吗?
  • 是的,我还没有评论权限:)
猜你喜欢
  • 2015-07-13
  • 2015-07-26
  • 2023-03-19
  • 2013-11-23
  • 1970-01-01
  • 2017-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多