首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何正确声明函数之外的变量,以便在微型文本冒险中运行test()

如何正确声明函数之外的变量,以便在微型文本冒险中运行test()
EN

Stack Overflow用户
提问于 2019-03-25 02:17:54
回答 2查看 42关注 0票数 0

我正在做一个迷你文字角色扮演游戏,你必须与国王共进晚餐。我基本上是在声明if语句中的变量,根据用户输入的内容,使变量成为一个特定的值。我想我需要在函数之外声明它们,但我不确定我对python相当陌生。

代码语言:javascript
复制
def creation_role():
    print("""What is your character's role?\n
A: Lord (Base stats: Charisma  7, Wit 3, Valor 5)
B: Peaseant (Base stats: Charisma  5, Wit 7, Valor 3)
C: Knight (Base stats: Charisma  3, Wit 5, Valor 7)""")
    role = input("> ")
    role = role.lower()

    if "a" in role:
        role = "lord"
        charisma = 7
        wit = 3
        valor = 5
    elif "b" in role:
        role = "peaseant"
        charisma = 5
        wit = 7
        valor = 3
    elif "c" in role:
        role = "knight"
        charisma = 3
        wit = 5
        valor = 3
    else:
        error()
        creation_role()



def creation_home():
    print("""Choose where you hail from:\n
A. Hillford: Lush foliage as far as the eyes can see, the enchanted trees
bear the fruit of wisdom.\n
B. Aermagh: A land as beautiful as it is cold, it's people learn strength
from the first day of life fighting frostbite as a babe.\n
C. Venzor: The rich island nation some call it the pearl of Skystead,
In recent decades it's seen outsiders giddy to make quick riches.""")
    home = input("> ")
    home = home.lower()

    if "a" in home:
        home = "Hillford"
        wit + 2
    elif "b" in home:
        home = "Aermagh"
        valor + 2
    elif "c" in home:
        home = "Venzor"
        charisma + 2
    else:
        error()
        creation_home()

def test():
    creation_role()
    creation_home()
    print(home, "\n", charisma, "\n", wit, "\n", valor)

test()
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-03-25 02:39:13

测试函数不知道主变量、魅力变量、智慧变量和勇敢变量。

为了让它了解它们,您需要从其他函数中返回这些值。例如:

代码语言:javascript
复制
def creation_role():
  ...logic
  return role, charisma, wit, valor

然后,您可以在测试中使用这些变量。

代码语言:javascript
复制
def test():
    role, charisma, wit, valor = creation_role()
    home, charisma, wit, valor = creation_home(charisma, wit, valor)
    print(home, "\n", charisma, "\n", wit, "\n", valor)

注意,还需要修改creation_home函数以接受这些变量,并返回新值。

代码语言:javascript
复制
def creation_home(charisma, wit, valor):
    ....
    return home, charisma, wit, valor

编辑:在修改统计数据时还会出现一些语法错误。它应该是

代码语言:javascript
复制
wit += 2

而不是

代码语言:javascript
复制
wit + 2
票数 0
EN

Stack Overflow用户

发布于 2019-03-25 02:37:12

您应该创建类MiniText或其他什么,然后将这些变量初始化为init的一部分。我看到的另一个问题是

代码语言:javascript
复制
charisma + 2

您没有存储结果值。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55330491

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档