我犯了一个大错:Python编码

时间:2016-03-17 04:38:04

标签: python python-2.7

确定。我一直在玩地下城&和我的朋友们一起玩笔和纸。你必须有一个角色表和一个库存表,但它变得非常混乱,一切都被删除并重写了十几次。所以我决定制作一个python程序来替换我的论文。所以我开始编写非常基本的python代码,如

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

然后theres大约有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行代码过于复杂,这花了我很长时间才写完,我不想浪费这一切。但是我知道有更好的方法可以做到这一点。因为我这样做的方式,我很难实现我提出的其他问题的建议。所以,如果我只是想做一个系统,其中黄金的值存储在一个单独的文件中(可能使用我之前的问题中描述的方法之一),我将能够使用addgold()更改变量的值应该做。我再一次为我的问题道歉。在我深入学习代码之前,我应该做更多的学习和学习。感谢。

1 个答案:

答案 0 :(得分:0)

我不知道“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选择保存类(例如您的角色),则最佳启动方式。但是一次只考虑一个问题。