我的python代码有问题:从文件加载不能作为函数工作,必须在游戏循环中。为什么?

2024-04-25 00:48:01 发布

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

我正在用python编写一个简单的基于文本的冒险游戏。我将包括所有的代码,因为我不知道是什么问题(它不太长,而且非常简单)。在

为了保存,我正在将“currentRoom”的名称和每个项目写入到一个文本文件中你。库存'. 然后当我加载时,我使用'readline()'来检索数据并重置变量。我有一个“游戏循环”,在这里我得到下一个命令并执行与命令匹配的任何函数。当我为'load'编写以下代码时,它将无法正常工作。为了测试保存/加载,我开始游戏拿起一些物品,然后向北进入一个不是起始房间的位置,然后保存。然后我退出,再次运行游戏,输入相同的名称当然,然后给命令'加载'。注意,保存的文件是正确的。我甚至在打印的load函数中包含了print语句当前房间名称,这是正确的,但是当我调用look函数时,它会执行完全相同的“print”当前房间名称'我已经被搬回起始房间了!?有趣的是,存货装得很好,只是位置不对。我一辈子都搞不懂。在

为了解决这个问题,我不得不将load()函数移到游戏循环体中,在'elif com==“load”…,而不是将其作为函数调用,然后它就可以工作了!?我怀疑我在全局变量和局部变量上做错了什么,但我看不出是什么。在

代码如下:(很抱歉缩进错误,剪切和粘贴效果不佳)

class Character(object):
inventory = []
hitPoints = 20
def __init__(self, name):
    self.name=name

class Room(object):
  def __init__(self, name, exits):
    self.name=name
    self.exits=exits
    self.contents=[]

class Item(object):
  def __init__(self, name, itemType, keyWords):
    self.name = name
    self.itemType = itemType
    self.keyWords = keyWords
def __repr__(self):
    return self.name
#Item types: weapon1 (one handed), weapon 2 (2handed), head, body, hands, feet, arms,     legs, ring, necklace
#****************** I T E M S *************************

sword1 = Item("A short sword", "weapon1", ["sword1","sword","shortsword"])
sword1.roomDescription = "A short sword made of steel lies here."
sword1.description = "It is a small sword of average quality, made of steel."

helmet1 = Item("A metal helmet", "head", ["helmet1", "helmet", "metal"])
helmet1.roomDescription = "A simple metal helmet sits on the ground."
helmet1.description = "It's a simple helmet with a few dings and dents, but otherwise     good condition."

coat1 = Item("A leather coat", "body", ["coat1", "coat", "leather"])
coat1.roomDescription = "A rugged leather coat lies crumpled at your feet."
coat1.description = "It's a thick leather coat.  It looks like it might offer some protection."

ring1 = Item("A brass ring", "ring", ["ring1", "ring", "brass"])
ring1.roomDescription = "A small brass ring is here."
ring1.description = "It's a simple brass ring.  Not very exciting."

necklace1 = Item("A silver necklace", "necklace", ["necklace1", "necklace", "brass"])
necklace1.roomDescription = "A thin silver necklace has been cast aside."
necklace1.description = "It's a shiny silver necklace."

#****************** PEOPLE AND NPC's *************************

you = Character("Monty")

#****************** R O O M S *************************

r0 = Room("Purgatory", [])

r1 = Room("Home",["north"])
r1.description = "You are in your home.  It's a small room.  There is a door in the north wall."
r1.contents = [sword1, sword1, ring1, necklace1, coat1]
r1.id = "r1"

r2 = Room("Main Street", ["south"])
r2.description = "You are north of your home in Main street.  The only exit is south."
r2.contents = [helmet1, coat1, sword1, sword1, coat1, coat1, coat1, coat1, coat1, coat1,  coat1, coat1, coat1, coat1, coat1]
r2.id = "r2"

#****************** E X I T S *************************

r1.n = r2
r2.s = r1

#****************** V A R I A B L E S *************************

nextRoom=0
nextMove="z"
quitVar=0
currentRoom = r1

#****************** F U N C T I O N S *************************

def printExits():
  print currentRoom.exits
  return

def look():
  print currentRoom.name
  print currentRoom.description
  if currentRoom.contents != []:
    for i in currentRoom.contents:
        print "- "+i.roomDescription

def save():
f = open(you.name+"saved.txt","w")
f.write(currentRoom.id+"\n")
for i in you.inventory:
    f.write(i.keyWords[0]+"\n")
f.write("*end*")
f.close()
print "Saved!"

def load():
f = open(you.name+"saved.txt","r")
currentRoom=eval(f.readline())
tempItem="none"
while tempItem != "*end*":
    tempItem = f.readline()
    if tempItem != "*end*":
        inventoryItem=eval(tempItem)
        you.inventory.append(inventoryItem)
f.close()
print "Loaded!"
print"****",
print currentRoom.name
look()

def printInventory():
print "You are carrying:"
if you.inventory ==[]:
    print "Nothing!"
    return
for i in you.inventory:
    print i

def getItem(itemKeyword0, typed_string): #itemKeyword0 is first keyWord (same as variable name for object) in first item in room that matches typed input
                                                   #typed_string is exactly what the user types following 'get '
if len(you.inventory)>=15:
    print "You can't carry any more!"
    return
currentRoom.contents.remove(eval(itemKeyword0)) #remove picked up item from room
you.inventory.append(eval(itemKeyword0))  #add picked up item to inventory
print 'You get the %s.' % (typed_string)

def dropItem(itemKeyword0, typed_string): #itemKeyword0 is first keyWord in first item in inventory that matches typed string
you.inventory.remove(eval(itemKeyword0)) #remove object from inventory that matches keyword0
currentRoom.contents.append(eval(itemKeyword0)) #add object to room that matches keyword0
print 'You drop the %s.' % (typed_string)
you.name = (raw_input("What is your name?")).lower()

look()
while quitVar < 1:
  com = (raw_input(">>")).lower() #get next command in lower case
  nextMove="z" #reset nextMove
  print ""
  if com == "help":
    print"north(n), south(s), east(e), west(w), quit, help, look(l), exits,   inventory(i), get, drop"
elif com == "load":
    load()
elif com == "quit":
    quitVar += 10
elif com == "exits":
    printExits()
elif com == "look" or com == "l":
    look()
elif com == "get all":
    itemGotCounter = 0 #needed counter to make it not say 'There's nothing here!' after getting all
    while len(currentRoom.contents)>0 and len(you.inventory)<15: #for some reason the following for i excluded the last item in the room.
        for i in currentRoom.contents:
            getItem(i.keyWords[0],i.keyWords[1])
            itemGotCounter = 1
    else:
        if len(currentRoom.contents)==0 and itemGotCounter == 0:
            print "There's nothing here!"
        if len(you.inventory) >= 15:
            print "You can't carry any more!"       
elif com[0:4] == "get " and com != "get all":
    gottenItem = com[4:] #set equal to string user typed
    for i in currentRoom.contents: #loop through room items, setting equal to i
        if gottenItem in i.keyWords: #if typed string matches with i.keywords
            getItem(i.keyWords[0], gottenItem) #send first keyword of item to getItem function, and send typed string
            break
    else:
        print "You do not see that here!"
elif com == "drop all":
    while len(you.inventory)>0:
        for i in you.inventory:
            dropItem(i.keyWords[0], i.keyWords[1])
elif com[0:5] == "drop " and com != "drop all":
    droppedItem = com[5:] #equal to string user typed
    if you.inventory == []: #check if user is carrying anything to drop
        print "You aren't carrying anything!"
    for i in you.inventory: #cycle through users inventory
        if droppedItem in i.keyWords: #if typed string matches keywords in users inventory
            dropItem(i.keyWords[0], droppedItem) #send first keyWord of that inventory item to dropItem function, and typed string
            break
    else:
        print "You don't have one!"
elif com == "inventory" or com == "i":
    printInventory()
elif com == "n" or com == "north":
    if "north" in currentRoom.exits:
        nextMove="n"
        nextRoom=currentRoom.n
    else:
        print "You can't go that way!"
elif com == "s" or com == "south":
    if "south" in currentRoom.exits:
        nextMove="s"
        nextRoom=currentRoom.s
    else:
        print "You can't go that way!"
elif com == "e" or com == "east":
    if "east" in currentRoom.exits:
        nextMove="e"
        nextRoom=currentRoom.e
    else:
        print "You can't go that way!"
elif com == "w" or com == "west":
    if "west" in currentRoom.exits:
        nextMove="w"
        nextRoom=currentRoom.w
    else:
        print "You can't go that way!"
elif com == "":
    pass
elif com == "save":
    save()

else:
    print "Huh?"
print "****"
print nextMove
print currentRoom.name
print "****"

if nextMove !="z": #If a move has occurred, move to nextRoom and look
    currentRoom = nextRoom
    look()

print "See ya later, alligator!",

Tags: nameinselfcomyoustringifinventory