需要以及如何插入/修改代码?

时间:2015-10-22 18:42:20

标签: python python-2.7 python-3.x wxpython ipython

如何以下列格式修改和显示帮助信息,以便儿子更容易理解?

示例:帮助 - 显示此游戏中使用的所有可能操作?得分了 -  显示您当前的分数?库存 - 显示所有库存?

如何创建所有命令的快捷方式?

修改游戏以便玩家可以通过在此任务中输入“退出”,“退出”或退出功能退出,并且必须退出while循环?

为“新游戏”,“继续”,“退出”制作菜单?

Python代码:

 import random import sys

 #############################################################################################################
 # GAME DATA                                                                                                 #
 #############################################################################################################

 # SOME CONSTANTS
 HERO_INVENTORY_POS = 99

 DirectionsList = ['SE', 'WE',  'WE',  'SWE', 'WE',   'WE',  'SWE',  'WS', #0-7
                    'NS', 'SE',  'WE',  'NW',  'SE',   'W',   'NE',   'NSW', #8-15
                    'NS', 'NS',  'SE',  'WE',  'NW', 'SE',  'WS', 'NS', #16-23
                    'N',  'NS',  'NSE',  'WE',  'WE',   'NSW', 'NS',   'NS', # 24 - 31
                    'S',  'NSE', 'NSW', 'S',   'NS', 'N',   'N',    'NS', #32 - 39
                    'NE', 'NSW',  'NE',  'W',   'NSE',  'WE',  'W',    'NS', #40 - 47
                    'SE', 'NSW', 'E',   'WE',  'NW',   'SE',   'SWE',   'NW', #48 - 55
                    'NE', 'NWE', 'WE',  'WE',  'WE',   'NWE', 'NWE',  'W'] #56 - 63



 # '\' below is a continuation character, it tells Python that the current statement continues to the next line.
 LocationsList = \
 [ 'DARK CORNER',                  'OVERGROWN GARDEN',       'BY LARGE WOODPILE',         'YARD BY RUBBISH',
   'WEEDPATCH',                    'FOREST',                 'THICK FOREST',              'BLASTED TREE',
   'CORNER OF HOUSE',              'ENTRANCE TO KITCHEN',    'KITCHEN & GRIMY COOKER',    'SCULLERY DOOR',
   'ROOM WITH INCHES OF DUST',     'REAR TURRET ROOM',       'CLEARING BY HOUSE',         'PATH',
   'SIDE OF HOUSE',                'BACK OF HALLWAY',        'DARK ALCOVE',               'SHALL DARK ROOM',
   'BOTTOM OF SPIRAL STAIRCASE',   'WIDE PASSAGE',           'SLIPPERY STEPS',            'CLIFFTOP',
   'NEAR CRUMBLING WALL',          'GLOOMY PASSAGE',         'POOL OF LIGHT',             'IMPRESSIVE VAULTED HALLWAY',
   'HALL BY THICK WOODEN DOOR',    'TROPHY ROOM',            'CELLAR WITH BARRED WINDOW', 'CLIFF PATH',
   'CUPBOARD WITH HANGING COAT',   'FRONT HALL',             'SITTING ROOM',              'SECRET ROOM',
   'STEEP MARBLE STAIRS',          'DINING ROOM',            'DEEP CELLAR WITH COFFIN',   'CLIFF PATH',
   'CLOSET',                       'FRONT LOBBY',            'LIBRARY OF EVIL BOOKS',   'STUDY WITH DESK & HOLE IN WALL',
   'WEIRD COBWEBBY ROOM',          'VERY COLD CHAMBER',      'SPOOKY ROOM',               'CLIFF PATH BY MARSH',
   'RUBBLE-STREWN VERANDAH',       'FRONT PORCH',            'FRONT TOWER',               'SLOPING CORRIDOR',
   'UPPER GALLERY',                'MARSH BY WALL',          'MARSH',                     'SOGGY PATH',
   'BY TWISTED RAILING',           'PATH THROUGH IRON GATE', 'BY RAILINGS',               'BENEATH FRONT TOWER',
   'DEBRIS FROM CRUMBLING FACADE', 'LARGE FALLEN BRICKWORK', 'ROTTING STONE ARCH',        'CRUMBLING CLIFFTOP']

 VerbList = ['HELP', 'CARRYING?', 'GO',    'N',       'S',       'W',     'E',   'U',      'D',
             'GET',  'TAKE',      'OPEN',  'EXAMINE', 'READ',    'SAY',
             'DIG',  'SWING',     'CLIMB', 'LIGHT',   'UNLIGHT', 'SPRAY', 'USE', 'UNLOCK', 'DROP', 'SCORE']


 ItemList = ['PAINTING', 'RING',      'MAGIC SPELLS', 'GOBLET', 'SCROLL', 'COINS', 'STATUE',  'CANDLESTICK', 'MATCHES',
             'VACUUM',   'BATTERIES', 'SHOVEL',       'AXE',    'ROPE',   'BOAT',  'AEROSOL', 'CANDLE',      'KEY']

 PositionOfItems = [46, 38, 35, 50, 13, 18, 28, 42, 10, 25, 26, 4, 2, 7, 47, 60, 100, 100]

 VisitedLocations =[0]

 # This variable represents player's current location. Initial location is 0
 currentLocation = 0


 #############################################################################################################
 # HELPER FUNCTIONS                                                                                          #
 #############################################################################################################


 def isMultiwordStatement(value):
     return value.find(" ") != -1

 def isItemAvailableAtLocation(ItemID,location):
     return PositionOfItems[ItemID] == location

 def isItemInInventory(itemName):
     ItemID = GetItemID(itemName)
     return PositionOfItems[ItemID] == HERO_INVENTORY_POS
 def isItemHidden(itemName):
     # 100 is the location for hidden items. 
     ItemID = GetItemID(itemName)
     return PositionOfItems[ItemID] == 100

 def GetItemID(item):
     for ItemID in range(0, len(ItemList), 1):
         if item == ItemList[ItemID]:
             return ItemID
     return -1




 #############################################################################################
 # GAME LOGIC                                                                                #
 #############################################################################################

 def GetVerbFromSentence(sentence):
     if not isMultiwordStatement(sentence):
         return sentence
     locationOfSpace=sentence.find(" ")
     return sentence[:locationOfSpace]

 def GetNounFromSentence(sentence):
     if not isMultiwordStatement(sentence):
         return ""
     locationOfSpace=sentence.find(" ") + 1
     return sentence[locationOfSpace:]

 def isMovementAvailable(directioncharacter):
     """
     isMovementAvailable checks whether it is possible to move in a direction in the current location
     directioncharacter - intended direction to move toward at the currentLocation
     returns True or False - based on whether the directioncharacter can be found in the String from DirectionsList[currentLocation]

     Example: 
     if directioncharacter is 'N' and DirectionsList[currentLocation] is 'NSW', this function returns True
     """

     dirString = DirectionsList[currentLocation]
     result = dirString.find(directioncharacter)
     if result >= 0:
         return True
     else:
         return False


 def GetMovementDirection(statement):
     verb=GetVerbFromSentence(statement)
     noun=GetNounFromSentence(statement)
     if len(verb)==1:
         return verb
     if verb == 'GO':
         return noun[:1]
     return ''

 def GetScore():
     score = 0
     for name in ItemList:
         if isItemInInventory(name):
             score +=1
     return score

 #############################################################################################
 # END GAME LOGIC                                                                            #
 #############################################################################################

 #############################################################################################
 # BEGIN PRESENTATION LOGIC                                                                  #
 #############################################################################################

 def DisplayCongratulation():
     print("""
  __     __                    _       
  \ \   / /                   (_)      
   \ \_/ /__  _   _  __      ___ _ __  
    \   / _ \| | | | \ \ /\ / / | '_ \ 
     | | (_) | |_| |  \ V  V /| | | | |
     |_|\___/ \__,_|   \_/\_/ |_|_| |_|

  """)                                     


 def DisplayInventory():
     strItems=""
     for i in range(len(PositionOfItems)):
         if PositionOfItems[i] == HERO_INVENTORY_POS:
             strItems = strItems + " "+ ItemList[i]

     if len(strItems) == 0:
         strItems = "NOTHING"
     print("YOU ARE CARRYING:" + strItems)


 def DisplayMap():

     """
      Each row of the map is consisted of 3 lines
      The first line - contains exit to North
      The second line - contains exits to West and East plus room no.
      The third line - contains exit to South

     """
     Line1 = ""
     Line2 = ""
     Line3 = ""
     # Use a FOR loop to draw every room
     for Index in range (0, 64, 1):
         if Index in VisitedLocations:
             # assign the exits at location 'Index' to currentValues
             # e.g. "NSW" if there are exits to North, South, and West
             currentValues=DirectionsList[Index]

             # if there is exit to the north draw a gap between the blocks
             if "N" in currentValues:
                 Line1 += "█  █"
             # otherwise, draw a wall
             else:
                 Line1 += "████"

             if "W" in currentValues:
                 Line2 += (" ") + PrintableInts(Index)
             else:
                 Line2 += ("█") + PrintableInts(Index)


             if "E" in currentValues:
                 Line2 += " "
             else:
                 Line2 += "█"

             if "S" in currentValues:
                 Line3 += "█  █"
             else:
                 Line3 += "████"
         else:
             Line1 += "    "
             Line2 += "    "
             Line3 += "    "
         # Draw the first row of rooms if 8 rooms have been processed.     
         if (Index + 1) % 8 == 0:
             print (Line1)
             print (Line2)
             print (Line3)
             # Emptying the lines for the next row of 8 rooms.
             Line1 = ""
             Line2 = ""
             Line3 = "" 

 ###
 def ExamineCoat():
     if currentLocation == 32 and isItemHidden("Key"):
         PositionOfItems[GetItemID("KEY")] = 32
         print ("YOU EXAMINE THE COAT AND FIND A KEY IN THE POCKET")
     elif currentLocation == 32 and not isItemHidden("Key"):
         print ("IT\'S A DIRTY OLD COAT")
     else:
         print ("WHAT COAT?")

 def ExamineDrawer():
     if currentLocation == 43 and isItemInInventory("KEY") :
         print ("YOU UNLOCK THE DRAWER AND FIND IT IS EMPTY")
     elif currentLocation == 43 and not isItemInInventory("KEY") :
         print ("UNFORTUNATELY THE DRAWER IS LOCKED")
     else:
         print ("WHAT DRAWER?")


 def ExamineRubbish():
     if currentLocation == 3:
         print ("THE RUBBISH IS FILTHY")
     else:
         print ("WHAT RUBBISH?")

 def ExamineWall():
     if currentLocation == 43:
         LocationsList[currentLocation] = "STUDY WITH DESK"
         DirectionsList[currentLocation]="NW"
         print ("YOU LOOK AT THE WALL AND DISCOVER IT IS FALSE!\nYOU DISCOVER A NEW EXIT")
     else:
         print ("NO INTERESTING WALLS HERE")
 def ExamineDoor():
     if currentLocation == 28 and  isItemInInventory("KEY"):
         DirectionsList[currentLocation]="SEW"
         print ("YOU UNLOCK THE DOOR AND DISCOVER A NEW LOCATION!")
     elif currentLocation == 28 and  not isItemInInventory("KEY"):
         print ("UNFORTUNATELY THE DOOR IS LOCKED")
     else:
         print ("NO INTERESTING DOOR HERE")

 def ExamineBooks():
     if currentLocation == 42 and isItemHidden("CANDLE"):
         print ("YOU LOOK AT THE BOOKS AND FOUND A CANDLE IN BETWEEN BOOKS!")
         PositionOfItems[GetItemID("CANDLE")] = 42
     elif currentLocattion == 42 and not isItemHidden("CANDLE"):
         print ("THE BOOKS LOOK EVIL")
     else:
         print ("NO BOOKS HERE")
 def DoExamine(noun) :
     if noun == "COAT":
         ExamineCoat()
     elif noun == "DRAWER":
         ExamineDrawer( )
     elif noun == "RUBBISH":
         ExamineRubbish()
     elif noun == "WALL":
         ExamineWall()
     elif noun == "DOOR":
         ExamineDoor()
     elif noun == "BOOKS":
         ExamineBooks()
     else:
         print ("WHAT "+noun+"?")



 def PrintableInts(value):
     if(value<10):
         return " "+str(value)
     return str(value)


 #############################################################################################
 # END PRESENTATION LOGIC                                                                    #
 #############################################################################################


 def ListItemsAtPosition():
     strItems=""
     for i in range(0, len(PositionOfItems), 1):
         if PositionOfItems[i] == currentLocation:
             strItems = strItems + " "+ ItemList[i]
     return strItems

 def ItemsAvailableAtPosition():
     for i in range(0, len(PositionOfItems), 1):
         if PositionOfItems[i] == currentLocation:
             return True
     return False


 def Go(statement, nowLocation):
     directioncharacter = ''

     verb=GetVerbFromSentence(statement)
     noun=GetNounFromSentence(statement)

     directioncharacter = verb
     if verb == 'GO':
         directioncharacter = noun[:1]

     if isMovementAvailable(directioncharacter):
         if directioncharacter == 'N':
             nowLocation -= 8
         elif directioncharacter == 'S':
             nowLocation += 8
         elif directioncharacter == 'W':
             nowLocation -= 1
         elif directioncharacter == 'E':
             nowLocation += 1
     return nowLocation

 def GetItem(noun):
     ItemID = GetItemID(noun)
     if isItemAvailableAtLocation(ItemID,currentLocation):
         PositionOfItems[ItemID]=HERO_INVENTORY_POS
         print("YOU ARE NOW CARRYING A",noun, file=sys.stderr)
     else:
         print("SORRY YOU CANNOT TAKE A ", noun)


 def DropItem(noun):
     ItemID = GetItemID(noun)
     if isItemAvailableAtLocation(ItemID, HERO_INVENTORY_POS):
         PositionOfItems[ItemID] = currentLocation
         print("YOU HAVE DROPPED THE ", noun)
     else:
         print("YOU CANNOT DROP THAT WHICH YOU DO NOT POSSESS")

 ###
 def OpenDoor():
     if currentLocation == 28 and isItemInInventory("KEY"):
         DirectionsList[currentLocation]="SEW"
         print("THE DOOR IS NOW OPEN! REVEALLING A NEW EXIT!")
     else:
         print("THE DOOR IS LOCKED")


 def ProcessStatement(statement):
     global currentLocation
     '''
       A statement can be either a verb or a verb + a noun
       If a statement is consisted of 1 verb and 1 noun, (separated by a space), it can looks like 'examine desk', 'get axe' ..etc
     '''

     verb=GetVerbFromSentence(statement)
     noun=GetNounFromSentence(statement)    

     if verb == "HELP":
         print ("I UNDERSTAND THE FOLLOWING WORDS:")

         print(VerbList)

     elif verb == "SCORE":
         print("YOUR CURRENT SCORE IS:", GetScore())

     elif verb == "INVENTORY" :
         DisplayInventory()

     elif verb == "GET" :
         GetItem(noun)

     elif verb == "OPEN" and noun == "DOOR":
         OpenDoor()

     elif verb == "DROP":
         DropItem(noun)

     elif verb == "EXAMINE":
         DoExamine(noun)

     elif verb == "SHOW" and noun == "MAP":
         DisplayMap()

     elif verb == 'N' or verb == 'S' or verb == 'E' or verb == 'W' or verb == 'U' or verb == 'D' or verb == 'GO':  
         newLocationID = Go(statement,currentLocation)
         if currentLocation != newLocationID:
             print("YOU MOVED FROM " + LocationsList[currentLocation] + " TO " + LocationsList[newLocationID], file=sys.stderr)
         else:
             print("YOU ARE UNABLE TO MOVE IN THAT DIRECTION")
         currentLocation = newLocationID



 # Existing missions:
 # Go to location 32 and 'examine coat' to find a key
 # Go to location 28 and 'open door' with the key in inventory.

 # Go to location 43 and 'examine wall' to find a new exit into a secret room.

 def Game():
     # Win condition: pick up more than 5 items and go back to location 0
     while not (GetScore() >= 5 and currentLocation == 0):

         print("========Haunted House=========")
         print("YOU ARE LOCATED IN A ", LocationsList[currentLocation],"("+str(currentLocation)+")")
         if ItemsAvailableAtPosition():
             print("YOU CAN SEE THE FOLLOWING ITEMS AT THIS LOCATION: ", ListItemsAtPosition())
         print("VISIBLE EXITS: ", DirectionsList[currentLocation])
         DisplayMap()

         statement = input("WHAT DO YOU WANT TO DO NEXT?")
         statement = statement.upper()
         ProcessStatement(statement)
         if not (currentLocation in VisitedLocations):
             VisitedLocations.append(currentLocation)


     DisplayCongratulation()

 # Program starts here!
 Game()

1 个答案:

答案 0 :(得分:0)

酷游戏。我不知道你是否想要从头开始构建整个命令行解释器作为练习,但是通过Python cmd module

可以完成很多cli风格的python脚本。

您可以定义单个命令,维护内部状态,并为您提供cmd autoformat帮助消息。

或者,考虑将动词及其快捷方式或别名存储在字典中,该字典的值是评估语句的函数。这有助于简化那些if语句。

def do_help(args):
    print('this is the help statement')
...
verb_dictionary = {'HELP':do_help, 'h':do_help, 'N', go_north ... }