繁体   English   中英

基于文本的游戏中的库存和房间系统存在困难

[英]Difficulty with Inventory and Room system in a text based game

我是一个相当新的程序员,几年来一直在苦苦挣扎,只是短暂地接触了几种语言。 我试图最终完全掌握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()

我将从添加更多结构开始,将房间的定义与IO /动作评估分开。

在维护状态方面,一种可能性(以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('#')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM