基于文本的游戏中的库存和会议室系统难度

时间:2017-07-06 17:11:47

标签: python python-3.x class dictionary game-engine

我是一个相当新的程序员,几年来一直在与几种语言短暂接触而苦苦挣扎。我试图最终牢牢掌握Python,为此我目前的项目是设计一个简单的基于文本的游戏,如“Zork”。

我已经使用每个房间的功能成功地制作了一个非常简单的版本,但这根本不是一般性的。在我解释我目前正在进行的工作之前,我将链接代码。现在你可以看到,这是一种非常低效的建造房间的方式,因为它需要大量的代码,除了这个确切的游戏,我不能用它做任何事情。

首先,我创建了一个用作播放器广告资源的列表

    inventory = []


def addToInventory(item):
    inventory.append(item)

这是我用来制造武器的类,也是我开始麻烦的地方。该类工作正常,我甚至可以成功地将它的实例添加到我的库存清单。

class Weapon:

    def __init__(self, name, damage, speed, weight):
        self.name = name
        self.damage = damage 
        self.speed = speed
        self.weight = weight

sword = Weapon("Sword", 7, 5, 5)
knife = Weapon("Knife", 5, 7, 3)
stick = Weapon("Stick", 2, 3, 3)

这是我试图设计创建房间的课程。它尚未实施。现在我面临的问题是无法将Weapon类的实例添加到Roominv的参数中。因此,例如,我无法使用武器类的剑形实例作为房间内容的参数,它告诉我剑是未定义的。

Entrance = Room("You are at an entrance", "N", "Search the ground", sword)

现在我对这个项目的目标确实是学习,所以我不想要任何代码,但我是否正在走这条路?如何将武器类的某些实例绑定到某些房间?我应该使用字典来构建房间吗?如果我应该使用词典,我是否必须为每个房间创建一个单独的字典或嵌套字典?

我已经搜索了很多这些问题的答案,因为我确信已经提出了类似的问题,但我似乎无法找到答案。

class Room:

def __init__(self, description, exits, actions, Roominv): #Runs every time a new room is created
    self.description = description
    self.exits = exits
    self.actions = actions
    self.Roominv = Roominv


def GAMEOVER():
    print("Oh no, it appears you have died. Press 1 to restart")

    choice = input(">>> ")

    if choice == "1":
        intro()

def introstrt(): 
    print("WELCOME TO FLUBBO'S MAGIC FOREST! HAVE YOU EVER WONDERED WHAT IT WAS LIKE TO")
    print("PLAY A VIDEO GAME THAT MORE OR LESS RELIES ENTIRELY ON IMAGINATION?")
    print("THEN LOOK NO FURTHER!")
    print("BEFORE YOU BEGIN, BE FOREWARNED THAT THIS ADVENTURE WILL BE VIOLENT, CRUDE,")
    print("AND ALSO VERY POOR QUALITY OVERALL, BECAUSE CLEARLY")
    print("THE DEVELOPER IS A TALENTLESS HACK WITH NO BUSINESS BEHIND A KEYBOARD.")
    print("AND NOW, FOR YOUR PLEASURE, FLUBBO'S MAGIC FOREST!!")
    print("  A     A     A      A     ooo")
    print(" vvv   vvv   vvv    vvv   ooooo")
    print("vvvvv vvvvv vvvvv  vvvvv   ooo")
    print("  H     H     H      H")
    print("  A     A     A      A")
    print(" vvv   vvv   vvv    vvv    | O  __")
    print("vvvvv vvvvv vvvvv  vvvvv   +-|-(__) ")
    print("  H     H     H      H      / \ ")
    print("~~~~~~~~~~~~~~~~~~~~~~~~~~")
    print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
    print("PRESS 1 TO BEGIN")

    choice = input(">>> ")


    if choice == "1":
        intro()
    else:
        print("I can't understand that command")
        intro()

def intro():
    global inventory
    print("You are in a forest, you can hear wildlife all around you. Your sword lies at your feet. There seems to be a clearing in the distance.")
    print("You can:")
    print("1.Look for sticks")
    print("2. Do a backflip")
    print("3.Attempt to befriend wildlife")
    print("4.Go to Clearing ")
    print("5.View Intro")

    choice = input(">>> ")

if choice == "1":
    print("You don't find any sticks. This is a poorly designed forest.")
    intro()
elif choice == "2":
    print("Sweet backflip, what now?")
    intro()
elif choice == "3":
    print("Attempting to befriend what you believe to be a cuddly critter in a nearby bush, you are surprised as a bear appears to your left and mauls you to death.")
    print("GAME OVER.")
    GAMEOVER()
elif choice == "4":
    print("You move towards the clearing.")
    clearing()
elif choice == "Pick up sword":
    addToInventory(sword)
    print("Your bag contains", inventory)
    intro()
elif choice == "5":
    introstrt()
else:
    print("I can't understand that command")
    intro()
def clearing():
    print("You are in a clearing surrounded by forest. Sunlight is streaming in, illuminating a bright white flower in the center of the clearing. In the distance a harp can be heard.")
    print("You can:")
    print("1.Pick the flower")
    print("2.Go towards the harp")
    print("3.Curse the sun whilst masturbating vigorously")
    print("4.Go back")

    choice = input(">>> ")

    if choice == "1":
        print("You pick the white flower and put it in your bag. You notice that it glows slightly.")
        clearingnofl()
    elif choice == "2":
        print("You can't tell which direction the music is coming from!.")
        clearing()
    elif choice == "3":
        print("CURSE YOU FIERY BALL OF SATAN!!! You below with fury as you cum all over the clearing.")
        print("The sun is deeply offended and goes away. It is dark now.")
        clearingdrk()
    elif choice == "4":
        print("You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.")
        intro()
    else:
        print("I can't understand that command")
    clearing()

def clearingnofl():
    print("You are in a clearing surrounded by forest. Sunlight is streaming in, illuminating the center of the clearing. In the distance a harp can be heard.")
    print("You can:")
    print("1.Go towards the harp")
    print("2.Curse the sun whilst masturbating vigorously")
    print("3.Go back")

    choice = input(">>> ")

    if choice == "1":
        print("You can't tell which direction the music is coming from!.")
        clearingnofl()
    elif choice == "2":
        print("CURSE YOU FIERY BALL OF SATAN!!! You below with fury as you cum all over the clearing.")
        print("The sun is deeply offended and goes away. It is dark now.")
        print("You notice the flower glowing brightly in your bag.")
        clearingnofldrk()
    elif choice == "3":
         print("You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.")
        intronofl()
    else:
        print("I can't understand that command")
        clearingnofl()
def clearingdrk():
    print("You are in a clearing surrounded by forest. Moonlight is streaming in, illuminating a bright white flower in the center of the clearing. In the distance a harp can be heard.")
    print("You can:")
    print("1.Pick the flower")
    print("2.Go towards the harp")
    print("3.Apologize to the sun, promise that you'll change and things will be like they used to be.")
    print("4.Go back")

    choice = input(">>> ")

    if choice == "1":
        print("You pick the white flower and put it in your bag. You notice that it glows brightly in the dark.")
        clearingnofldrk()
    elif choice == "2":
        print("You can't tell which direction the music is coming from!.")
        clearingdrk()
    elif choice == "3":
        print("The sun reluctantly forgives you, it is sunny again.")
        clearing()
    elif choice == "4":
        print("You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.")
        introdrk()
    else:
        print("I can't understand that command")
        clearingdrk()
def clearingnofldrk():
    print("You are in a clearing surrounded by forest. Moonlight is streaming in, illuminating the center of the clearing. In the distance a harp can be heard.")
    print("You can:")
    print("1.Go towards the harp")
    print("2.Apologize to the sun, promise that you'll change and things will be like they used to be.")
   print("3.Go back")

    choice = input(">>> ")

    if choice == "1":
        print("You can't tell which direction the music is coming from!.")
        clearingnofldrk()
    elif choice == "2":
        print("The sun reluctantly forgives you, it is sunny again.")
    clearingnofl()
    elif choice == "3":
        print("You are in a forest, you can hear wildlife all around you. It is dark. There seems to be a clearing in the distance.")
        intronofldrk()
    else:
        print("I can't understand that command")
        clearingnofldrk()
def intronofldrk():
    print("You are in a forest, you can hear wildlife all around you. It is dark. There seems to be a clearing in the distance.")
    print("You can:")
    print("1.Look for sticks")
    print("2.Do a backflip")
    print("3.Attempt to befriend wildlife")
    print("4.Go to Clearing ")

    choice = input(">>> ")

    if choice == "1":
        print("You don't find any sticks. This is a poorly designed forest AND it's dark now.")
        intronofldrk()
    elif choice == "2":
        print("Sweet backflip, what now?")
        intronofldrk()
    elif choice == "3":
        print("Attempting to befriend what you believe to be a cuddly critter in a nearby bush, you are surprised as a bear appears to your left and mauls you to death. GAME OVER.")
    elif choice == "4":
        print("You move towards the clearing.")
        clearingnofldrk()
    else:
        print("I can't understand that command")
        intronofldrk()
def introdrk():
    print("You are in a forest, you can hear wildlife all around you. It is dark. There seems to be a clearing in the distance.")
    print("You can:")
    print("1.Look for sticks")
    print("2.Do a backflip")
    print("3.Attempt to befriend wildlife")
    print("4.Go to Clearing ")

    choice = input(">>> ")

    if choice == "1":
        print("You don't find any sticks. This is a poorly designed forest AND it's dark now.")
        introdrk()
    elif choice == "2":
        print("Sweet backflip, what now?")
        introdrk()
    elif choice == "3":
        print("Attempting to befriend what you believe to be a cuddly critter in a nearby bush, you are surprised as a bear appears to your left and mauls you to death. GAME OVER.")
    elif choice == "4":
        print("You move towards the clearing.")
        clearingdrk()
    else:
        print("I can't understand that command")
    introdrk()
def intronofl():
    print("You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.")
    print("You can:")
    print("1.Look for sticks")
    print("2.Do a backflip")
    print("3.Attempt to befriend wildlife")
    print("4.Go to Clearing ")

    choice = input(">>> ")

    if choice == "1":
        print("You don't find any sticks. This is a poorly designed forest.")
        intronofl()
    elif choice == "2":
        print("Sweet backflip, what now?")
        intronofl()
    elif choice == "3":
        print("Attempting to befriend what you believe to be a cuddly critter in a nearby bush, you are surprised as a bear appears to your left and mauls you to death. GAME OVER.")
    elif choice == "4":
        print("You move towards the clearing.")
        clearingnofl()
    else:
        print("I can't understand that command")
        intronofl()
introstrt()

1 个答案:

答案 0 :(得分:1)

我首先要添加更多结构,将房间的定义与IO /行动评估分开。

就maintining状态而言,一种可能性(使用introSword作为示例)是修改操作中的包含Room,更改可用的未来操作。

您必须更改Python 3的inputoutput定义。希望这些是唯一需要的更改。

import traceback as tb

try:
  input = raw_input

  def output(*args):
    print ''.join(map(str,args))

  inventory = []

  class Weapon:
    def __init__(self, name, damage, speed, weight):
      self.name = name
      self.damage = damage 
      self.speed = speed
      self.weight = weight

    def __repr__(self):
      return self.name

  sword = Weapon("Sword", 7, 5, 5)
  knife = Weapon("Knife", 5, 7, 3)
  stick = Weapon("Stick", 2, 3, 3)

  class Room:
    def __init__(self,description,exits,actions,others=[]):
      self.description = description
      self.exits = exits
      self.actions = actions
      self.others = others

    def render(self):
      output(self.description)

      if self.actions:
        output('You can:')
        for id,name,_ in self.actions:
          output(id,'. ',name)

      choice = input('>>> ').upper()

      for id,_,action in self.actions:
        if choice == id.upper():
          action(self)
          break
      else:
        for id,action in self.others:
          if choice == id.upper():
            action(self)
            break
        else:
          output('I can\'t understand that command')
          self.render()

  quit = False

  while not quit:
    def introstrtBegin(room):
      intro.render()

    introstrt = Room(
      '''
WELCOME TO FLUBBO'S MAGIC FOREST! HAVE YOU EVER WONDERED WHAT IT WAS LIKE TO
PLAY A VIDEO GAME THAT MORE OR LESS RELIES ENTIRELY ON IMAGINATION?
THEN LOOK NO FURTHER!
BEFORE YOU BEGIN, BE FOREWARNED THAT THIS ADVENTURE WILL BE VIOLENT, CRUDE,
AND ALSO VERY POOR QUALITY OVERALL, BECAUSE CLEARLY
THE DEVELOPER IS A TALENTLESS HACK WITH NO BUSINESS BEHIND A KEYBOARD.
AND NOW, FOR YOUR PLEASURE, FLUBBO'S MAGIC FOREST!!
  A     A     A      A     ooo
 vvv   vvv   vvv    vvv   ooooo
vvvvv vvvvv vvvvv  vvvvv   ooo
  H     H     H      H
  A     A     A      A
 vvv   vvv   vvv    vvv    | O  __
vvvvv vvvvv vvvvv  vvvvv   +-|-(__)
  H     H     H      H      / \ 
~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~
PRESS 1 TO BEGIN
      ''',
      [],
      [],
      [('1',introstrtBegin)]
    )

    def gameoverRestart(_):
      global quit
      quit = False

    def gameoverQuit(_):
      global quit
      quit = True

    gameover = Room(
      'Oh no, it appears you have died. Press 1 to restart, or 2 to quit.',
      [],
      [],
      [('1',gameoverRestart)
      ,('2',gameoverQuit)
      ]
    )

    def introSticks(room):
      output('You don\'t find any sticks. This is a poorly designed forest.')
      room.render()

    def introBackflip(room):
      output('Sweet backflip, what now?')
      room.render()

    def introWildlife(room):
      output('Attempting to befriend what you believe to be a cuddly critter in a nearby bush, you are surprised as a bear appears to your left and mauls you to death.')
      output('GAME OVER.')
      gameover.render()

    def introClearing(room):
      output('You move towards the clearing.')
      clearing.render()

    def introNoSword(room):
      output('You already picked up the sword')
      room.render()

    def introSword(room):
      global inventory
      inventory.append(sword)
      output('Your bag contains: ',inventory)

      room.description = 'You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.'
      room.others = [
        ('pick up sword',introNoSword)
      ]

      room.render()

    intro = Room(
      '''
You are in a forest, you can hear wildlife all around you. Your sword lies at your feet. There seems to be a clearing in the distance.
      ''',
      [],
      [('1','Look for sticks',introSticks)
      ,('2','Do a backflip',introBackflip)
      ,('3','Attempt to befriend wildlife',introWildlife)
      ,('4','Go to Clearing',introClearing)
      ,('5','View Intro',lambda _: introstrt.render())
      ],
      [('pick up sword',introSword)]
    )

    def clearingFlower(room):
      output('You pick the white flower and put it in your bag. You notice that it glows slightly.')
      room.render()

    def clearingHarp(room):
      output('You can\'t tell which direction the music is coming from!.')
      room.render()

    def clearingCurse(room):
      output('CURSE YOU FIERY BALL OF SATAN!!! You below with fury as you cum all over the clearing.')
      output('The sun is deeply offended and goes away. It is dark now.')
      room.render()

    def clearingBack(room):
      output('You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.')
      intro.render()

    clearing = Room(
      '''
You are in a clearing surrounded by forest. Sunlight is streaming in, illuminating a bright white flower in the center of the clearing. In the distance a harp can be heard.
      ''',
      [],
      [('1','Pick the flower',clearingFlower)
      ,('2','Go towards the harp',clearingHarp)
      ,('3','Curse the sun whilst masturbating vigorously',clearingCurse)
      ,('4','Go back',clearingBack)
      ]
    )

    introstrt.render()
except:
  tb.print_exc()
finally:
  input('#')