Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在基于文本的游戏中使用库存和房间系统的困难_Python_Python 3.x_Class_Dictionary_Game Engine - Fatal编程技术网

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

Python 在基于文本的游戏中使用库存和房间系统的困难,python,python-3.x,class,dictionary,game-engine,Python,Python 3.x,Class,Dictionary,Game Engine,我是一个相当新的程序员,几年来断断续续地努力学习几种语言。我试图最终牢牢掌握Python,为此,我目前的项目是设计一个简单的基于文本的游戏,如“Zork” 我已经成功地使用每个房间的函数制作了一个非常简单的版本,但是这根本不是通用的。在解释我目前正在做的工作之前,我将链接代码。现在,正如你所看到的,这是一种非常低效的构建房间的方法,因为它需要大量的代码,除了这个确切的游戏,我不能使用它 首先,我创建了一个列表,用作播放器目录 inventory = [] def addToInven

我是一个相当新的程序员,几年来断断续续地努力学习几种语言。我试图最终牢牢掌握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)
这是我试图设计用来创建房间的类。它尚未实施。现在我面临的问题是无法将武器类的实例添加到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/操作评估分离

就维护状态而言,一种可能性(以
introSwarm
为例)是修改动作中包含的
Room
,更改未来可用的动作

您必须更改Python3的
输入
输出
定义。希望这些是唯一需要的改变

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('#')

是什么阻止你把论点传给你的
房间
班级?它告诉我论点是未定义的,例如入口=房间(“这是入口”,“N”,“搜索地面”,剑)它会告诉我剑是未定义的。@Schrodinger'sStat如果要使用全局变量,请确保在第一次使用它们之前定义它们。所以
剑=武器(“剑”,7,5,5)
必须在
入口=房间(“这是一个入口”,“N”,“搜索地面”,剑)