【问题标题】:Python Formatting OutputPython 格式化输出
【发布时间】:2017-07-04 18:42:07
【问题描述】:

我有以下代码:

import options
import random


class Player():
    def __init__(self):
        self.name = None
        self.gold = 100
        self.maxhealth = 100
        self.health = self.maxhealth
        self.level = 1
        self.exp = 0
        self.levelUp = 50
        self.gainedexp = self.levelUp - self.exp


    def get_name(self):
        self.name = input("Hey there, traveller! What's your name?\n~~>")
        print("Since you are new around here, 100 gold doubloons have been given to you, {}!".format(self.name))

    def gold_counter(self):
        print("You currently have {} gold!".format(player.gold))


class Dragon():
    def __init__(self):
        self.name = "Dragon"
        self.dropgold = random.randint(13,20)
        self.minexp = int(15 * round(player.level * 1.5))
        self.maxexp = int(30 * round(player.level * 1.5))  
        self.expgain = random.randint({}, {}.format(self.minexp, self.maxexp))
        self.maxhealth = 80
        self.health = self.maxhealth




def intro():
    wrong_input = 0
    nar_name = "Narrator"
    print("{}: Uhhhm...".format(nar_name))
    print("{}: Let me check my list...".format(nar_name))
    print("{0}: Ah! Yes! {1}, that's right. I heard you were supposed to be arriving today.".format(nar_name, player.name))

我还使用了另外两个模块,但我 99% 确信它们不会影响这一点。我得到以下输出:

Hey there, traveller! What's your name?
~~>Savage Potato
Since you are new around here, 100 gold doubloons have been given to you, Savage Potato!
Do you want to see your balance?
~~> Yes
You currently have 100 gold.
Narrator: Uhhhm...
Narrator: Let me check my list...
Narrator: Ah! Yes! None, that's right. I heard you were supposed to be arriving today.

在最后一行,它打印出讲述人的名字,而不是用户输入的名字。我还查看了 their website 上的 python 文档,但找不到修复程序。关于如何阻止它输出None 作为用户名的任何想法?

编辑 #1:我在模块后面编写了 player = Player()。

编辑#2:这是我使用的所有代码:

模块 1 (main.py)

import prints
import random

class Player():
    def __init__(self):
        self.name = None
        self.gold = 100
        self.maxhealth = 100
        self.health = self.maxhealth
        self.level = 1
        self.exp = 0
        self.levelUp = 50
        self.gainedexp = self.levelUp - self.exp


    def get_name(self):
        self.name = input("Hey there, traveller! What's your name?\n~~>")
        print("Since you are new around here, 100 gold doubloons have been given to you, {}!".format(self.name))




class Dragon():
    def __init__(self):
        self.name = "Dragon"
        self.dropgold = random.randint(13,20)
        self.minexp = int(15 * round(player.level * 1.5))
        self.maxexp = int(30 * round(player.level * 1.5))  
        self.expgain = random.randint({}, {}.format(self.minexp, self.maxexp))
        self.maxhealth = 80
        self.health = self.maxhealth




#while player.exp >= player.levelUp:
    #player.levelUp += 1
    #player.exp = player.exp - player.levelUp
    #player.levelUp = round(player.levelUp * 1.5)
    #print("Congrats! You just levelled up to level {} by gaining {} experience!".format(player.level, player.gainedexp))


def start():
    player.get_name()
    prints.gold_counter()
    prints.intro()
    prints.encounter()





player = Player()    


start()

模块 2 (prints.py)

import options
import random


class Player():
    def __init__(self):
        self.name = None
        self.gold = 100
        self.maxhealth = 100
        self.health = self.maxhealth
        self.level = 1
        self.exp = 0
        self.levelUp = 50
        self.gainedexp = self.levelUp - self.exp


    def get_name(self):
        self.name = input("Hey there, traveller! What's your name?\n~~>")
        print("Since you are new around here, 100 gold doubloons have been given to you, {}!".format(self.name))

    def gold_counter(self):
        print("You currently have {} gold!".format(player.gold))


class Dragon():
    def __init__(self):
        self.name = "Dragon"
        self.dropgold = random.randint(13,20)
        self.minexp = int(15 * round(player.level * 1.5))
        self.maxexp = int(30 * round(player.level * 1.5))  
        self.expgain = random.randint({}, {}.format(self.minexp, self.maxexp))
        self.maxhealth = 80
        self.health = self.maxhealth




def intro():
    wrong_input = 0
    nar_name = "Narrator"
    print("{}: Uhhhm...".format(nar_name))
    print("{}: Let me check my list...".format(nar_name))
    print("{0}: Ah! Yes! {1}, that's right. I heard you were supposed to be arriving today.".format(nar_name, player.name))
    print("{}: Welcome to... THE DRAGON FIGHTER GAME!".format(nar_name))
    print("{}: I know, it isn't the most imaginative name.".format(nar_name))
    print("{}: Don't look at me like that, I tried my hardest!".format(nar_name))
    print("{}: Anyhoo, let's carry on.".format(nar_name))
    print("{}: For some stupid reason, the creator of this game didn't give me an actual name, so\nmy name is just \"Narrator\" or \"N\", but you can call me Larry.".format(nar_name))
    while True:
        option = input("Narrator: Actually, which name would you prefer to call me?\n").upper()
        if option in options.nar_larry_opt:
            nar_name = "Larry"
        elif option in options.nar_narrator_opt:
            nar_name = "Narrator"
            while True:
                ask = input("{}: Maybe \"N\" for short?".format(nar_name)).upper()
                if ask in options.inp_yes_opt:
                    nar_name = "N"
                elif ask in options.inp_no_opt:
                    break
                else:
                    wrong_input += 1
                    if wrong_input == 1:  
                        print("Please try again.")
                    elif wrong_input == 2:
                        print("Try to not put the same thing in next time.")
                    elif wrong_input == 3:
                        print("This isn't funny.")
                    elif wrong_input == 4:
                        print("Seriously.")
                    elif wrong_input == 5:
                        print("OKAY! THIS IS IT! GO BACK TO THE BEGINNING!")
                        intro()

                    continue
                break
        else:
            print("Please try again.")
            continue
        break
    print("{}: So, as I was saying, this game is basically just some dragon quest thingy.".format(nar_name))
    print("{}: You'll probably get tips from me every now and again if I can be bothered.".format(nar_name))
    print("{}: I'll get an test encounter ready.".format(nar_name))



def gold_counter():
    while True:
        option = input("Do you want to see your balance?\n~~> ").upper()
        if option in options.inp_yes_opt:
            print("You currently have {} gold.".format(player.gold))
        elif option in options.inp_no_opt:
            print("You can check your balance later in the game.")
        else:
            print("Please try again.")
            continue
        break



def encounter():
    while True:
        dragon_appear = random.randint(1,2)
        if dragon_appear == 1:
            print("What's that? Looks like a huge bir... \nA DRAGON! A MAJESTIC DRAGON JUST FLEW DOWN FROM THE SKY!")
        else:
            print("What's that? Looks like a huge bir... \n Yeah. Just a giganta-bird.")

    while encounter().dragon_appear != 2:
        print("So that's the message you'll get when a dragon appears.")
        print("And you will be prompted whether you want to run or fight, like so:")
        while True:
            wrong_input = 0
            ask = input("Run away like a coward, or fight the majestic beast?")
            if ask in options.enc_run_opt:
                escape = random.randint(1,2)
                if escape == 1:
                    print("You managed to get away!")
                else:
                    print("You didn't get away. Better luck next time!")
            elif ask in options.enc_attack_opt:
                pass
            else:
                wrong_input += 1
                if wrong_input == 1:  
                    print("Please try again.")
                elif wrong_input == 2:
                    print("Try to not put the same thing in next time.")
                elif wrong_input == 3:
                    print("This isn't funny.")
                elif wrong_input == 4:
                    print("Seriously.")
                continue
            break




player = Player() 

模块 3 (options.py)

inp_yes_opt = {"Y", "YE", "YES", "YEAH", "PLEASE", "YES PLEASE"}
inp_no_opt = {"N", "NO", "NOPE", "NAH"}

nar_larry_opt = {"LARRY", "LARR", "LAR", "LA", "L", "LARRY PLEASE"}
nar_narrator_opt = {"NARRATOR", "NARR", "N", "NAR", "NARRATE", "NOT LARRY"}

enc_run_opt = {"RUN", "RU", "R", "SCRAM", "RUN AWAY", "RUUUUN"}
enc_attack_opt = {"ATTACK", "ATTAK", "A", "FIGHT", "F", "ATTACK", ""}

【问题讨论】:

  • 看来你使用的不是同一个播放器实例,尝试将它创建到介绍函数中,它应该可以工作
  • 我会试试的,我会回复你的。我只是认为将它变成一个类然后在需要时调用它会更简单。在我的脑海里,把它放在课堂上更有意义..
  • 您应该看到对象的可见性。如果它是全局的,它可以工作,因为每个函数都可以访问它,但如果它是本地的,例如你已经将它放入一个函数或另一个类中,它不会保留更改的记忆,因为你指的是另一个对象。跨度>

标签: python formatting output


【解决方案1】:

如果要打印出播放器的名字,需要将播放器对象作为参数传入intro函数。假设 intro 没有捕获播放器对象并且播放器对象不是全局的

目前,似乎函数范围内没有可访问的玩家对象,这就是它输出 None 的原因

【讨论】:

  • 能分享一下调用intro函数的代码吗?
  • 我在想如果这个函数定义在最顶部,它不能像你想要的那样捕获播放器实例,所以你应该将播放器作为参数传入它会解决你的问题
  • 是的,刚刚添加了我当前使用的所有代码。我真的看不出有什么问题。我还尝试通过执行from main import Player()from main import class Player()from main import *import main 将 main.py 中的类调用到 prints.py,但这些都不起作用,但我现在正在做什么很好,所以我会在以后修复它。
猜你喜欢
  • 2013-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-26
  • 1970-01-01
  • 2012-03-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多