我犯了一个巨大的错误:Python编码

2024-05-26 22:58:29 发布

您现在位置:Python中文网/ 问答频道 /正文

好的。我一直在和朋友玩龙与地下城的纸笔角色扮演游戏。你必须有一个字符表和库存表,但它变得非常混乱,一切都被删除和重写了十几次。所以我决定做一个python程序来代替我的论文。所以我开始编写非常基本的python代码,比如

print ""
print "What would you like to know?"
option = raw_input("--> ")
if option == 'name':
    name()

然后有大约60个循环的东西,你可以去包括钱。你知道吗

elif option == 'money':
    money()
elif option == 'add gold':
    addgold()

global gold
gold = 10

def money():
    print ""
    print "Gold: ",gold,""

def addgold():
    print ""
    global gold
    addg = raw_input("How much gold would you like to add: ")
    if addg >= 0:
        gold = gold + (int(addg))
    print ""
    print "Your total gold is now: ",gold,""

我现在意识到,我犯了一个巨大的错误,因为有大约2000行过于复杂的代码,花了我很长时间来编写,我不想浪费这一切。不过,我知道有更好的方法可以做到这一点。因为我做这件事的方式,我很难从我提出的其他问题中得到建议。因此,如果我只想做一个系统,其中gold的值存储在一个单独的文件中(可能使用我前面问题中描述的方法之一),并且我可以使用addgold()更改变量的值。我再次为我的问题道歉。在深入研究代码之前,我应该做更多的研究和学习。谢谢。你知道吗


Tags: to代码nameyouinputrawiflike
1条回答
网友
1楼 · 发布于 2024-05-26 22:58:29

我不知道“D&D”的所有可能的统计信息是什么,但是正如其他用户建议的那样,您可能应该考虑使用对象,即类。最基本的实现可以是这样的:

    class Items():
         def __init__(self,items=[]):
              self.items = items

         def add(self,item):
              self.items.append(item)

         def remove(self,item):
              self.items.remove(item)

         def showItems(self):
              print(self.items)

    class Wallet():
         def __init__(self,gold=0):
              self.gold = gold

         def add(self,number):
              self.gold = self.gold + number

         def remove(self,number):
             if self.gold-number<0:
                   print("Sweat runs down your cheek as you notice you are short of", self.gold-number, "coins.")
                   return False
             else:
                  self.gold = self.gold - number
                  print("You spend ", number, "coins.")
                  return True

    class Character():
         # You'll define you character with name,gender and species
         # (it's an example obviously, you can put anything) 
         def __init__(self,name,gender,species):
              # Storing the input arguments inside class
              self.name    = name
              self.gender  = gender
              self.species = species

              self.events = []
              self.wallet  = Wallet()
              self.items   = Items()

         def buy(self,item,cost):
             if self.wallet.remove(cost):
                   self.items.add(item)

         def sell(self,item,cost):
             self.items.remove(item)
             self.wallet.add(cost)

从这一点上,您可以通过简单的说明来管理您的角色:

    GwarTheDwarf = Character('Gwar','Female','Dwarf')
    GwarTheDwarf.buy('Great Axe',154)

,这将导致:

    Sweat runs down your cheek as you notice you are short of -154 coins.

学习使用对象是实现你想要做的事情的完美方法。另外,对于其他问题(将内容保存到文件中),如果选择使用pickle保存类(例如您的角色),那么最好的开始方式是。但是一次只解决一个问题。你知道吗

相关问题 更多 >

    热门问题