我可以导入吗?从先前定义的函数到类对象的信息?

时间:2014-04-17 06:55:37

标签: python class

所以我试图制作一个非常简单的基于文本的RPG作为我的编程课程的学期项目。我刚刚学会了(我的代码可能非常明显)如何定义类并感觉它们比函数更好地工作。

然而,我遇到了这个角色的问题'类。我没有预定播放器名称,而是希望用户能够输入他们自己的名字,我已经在' Intro'功能。现在我的问题是采取变量' pName'并设置为玩家的名字,这是我无法做到的。

我的问题是: 我可以这样做吗? (使用函数变量作为类属性?) 2.有更好,更有效的方法吗?和 3.你们有什么额外的信息可以告诉我关于课程的信息,或者关于如何完成这个课程的信息吗?

任何事情都很受欢迎,并提前感谢您的帮助!

import random, time

#I'm not at all hellbent on keeping this same format, it's just
#the way i've been taught and i'm most comfortable with.

def Intro():
    print('Welcome puny warrior, to my Dungeon of DOOM, and stuff.')
    pName = input('Tell me your name, puny warrior: ')
    playResponse = input('Do you want to begin puny warrior who calls himself ' + pName + '? Y/N: ')
    playResponse = playResponse.upper()
    if playResponse[0:1] == 'Y':
        pass
    else:
        print('You die now', pName)

class character(object):
    def __init__(self, name, health, attack):
        self.name = name
        self.health = health
        self.attack = attack

#this part obviously doesn't work, but I decided to leave it as a visual aid
player = character(pName, 25, 5)

#should I just make this class a child of the 'character' class?
class foes(object):
    def __init__(self, name, health, attack):
        self.name = name
        self.health = health
        self.attack = attack

zombie = foes('Zombie', 10, 3)
dragon = foes('Dragon',20, 5)
skeleton = foes('Skeleton', 8, 4)

3 个答案:

答案 0 :(得分:1)

您正在尝试调用内部Intro()变量 - 快速修复可能是这样的:

def Intro():
    print('Welcome puny warrior, to my Dungeon of DOOM, and stuff.')
    pName = input('Tell me your name, puny warrior: ')
    playResponse = input('Do you want to begin puny warrior who calls himself ' + pName + '? Y/N: ')
    playResponse = playResponse.upper()
    if playResponse[0:1] == 'Y':
        pass
    else:
        print('You die now', pName)
    return pName

class character(object):
    def __init__(self, name, health, attack):
        self.name = name
        self.health = health
        self.attack = attack

#this part obviously doesn't work, but I decided to leave it as a visual aid

player = character(Intro(), 25, 5)

#should I just make this class a child of the 'character' class?

class foes(object):
    def __init__(self, name, health, attack):
        self.name = name
        self.health = health
        self.attack = attack

zombie = foes('Zombie', 10, 3)
dragon = foes('Dragon',20, 5)
skeleton = foes('Skeleton', 8, 4)

答案 1 :(得分:0)

我不确定你的问题是什么。在类实例化中使用类似pName的变量和类似"Zombie"的字符串之间的Python没有区别。您的代码唯一的问题 是你在Intro()之外进行实例化,所以pName没有被定义。

答案 2 :(得分:0)

一些指针

  • 查看PEP8, the Style Guide for Python.

  • 使用角色类来定义玩家和敌人。

  • 实现 main()方法并正确使用它。有关此主题的更多信息,请访问this讨论。

  • 使用Python词典,因为它们非常强大。


#!/usr/bin/env python


"""Simple, text-based RPG."""


import random  # Generate pseudo-random numbers.
import time  # Time access and conversions.


class Character(object):
    """Define the character."""

    def __init__(self, name, health, attack):

        self.name = str(name)  # Expecting a string.

        self.health = int(health)  # Expecting an integer.

        self.attack = int(attack)  # Expecting an integer.

    def properties(self):
        """Returns dictionary containing the character properties."""

        # Because using dictionaries is awesome.
        characteristics = {
            'name': self.name,
            'health': self.health,
            'attack': self.attack
        }

        return characteristics  # Returns a dictionary


def get_player():
    """Acquire the name of the player, and begin the game."""

    # Newline characters should improve readability on the command line.
    print('\nWelcome puny warrior, to my Dungeon of DOOM, and stuff.\n')

    # Variable names should be easy to read and understand.
    player_name = input(
        """
        Welcome puny warrior, to my Dungeon of DOOM... and stuff.

        Tell me your name: """
    )

    # Get and store the player's response.
    player_response = input(
        """
        Do you want to begin puny warrior who calls himself %s? (Y/N): \
        """ % player_name
        )

    if player_response.upper() == "Y":
        pass

    else:
        print('\nYou die now\n', player_name)

    return player_name


def score():
    """Assign a score between 1 and 100."""

    return random.randint(1, 100)


def main():
    """Where the automagic happens."""

    # Assuming you want random integers.
    player = Character(get_player(), score(), score()).properties()
    zombie = Character('Zombie', score(), score()).properties()
    dragon = Character('Dragon', score(), score()).properties()
    skeleton = Character('Skeleton', score(), score()).properties()

    # Since you're working with a dictictionary, you can now do things like:
    print(player['name'])
    print(zombie['name'], zombie['health'])
    print("%s: %s, %s" % (dragon['name'], dragon['health'], dragon['attack']))


# The correct methodology.
if __name__ == "__main__":
    main()