如何在Python中使用Split命令?

时间:2015-12-14 18:50:07

标签: python

我正在制作文字冒险游戏。 我很困惑如何实现我游戏的下一部分。 这是我接下来要添加的内容: “添加拾取对象的功能。如果用户键入get key,则:

  1. 拆分用户输入,以便拆分并只有一个等于“key”的变量。

    1.使用Python字符串中内置的split方法。例如: command_words = user_command.split(“”)

    这会将用户键入的内容拆分为列表。每个项目都根据空格分开。

    1. 更新您的路线以检查command_words [0]。
    2. 添加对get命令的检查。
  2. 2.搜索列表,直到找到与用户尝试拾取的对象相匹配的对象。

    这是我到目前为止的代码:

    done = False
    object_list = []
    room_list = []
    
    class Object():
        def __init__(self, name, description, room):
            self.name = name
            self.description = description
            self.current_room = room
    
    wand = Object("Holly Wand", "This wand is an 11\" supple wand made of holly and a single phoenix tail feather core.", 1)
    
    object_list.append(wand)
    
    dh_cloak = Object("Cloak of Invisibility", "This is part one part of the most powerful trifecta.  \nThis cloak shields you from all wandering eyes. \nFind all three parts and you may just be able to escape from this castle.", 3)
    
    object_list.append(dh_cloak)
    
    class Room():
        def __init__(self, describe, nw, n, ne, e, se, s, sw, w):
            self.description = describe
            self.northwest = nw
            self.north = n
            self.northeast = ne
            self.east = e
            self.southeast = se
            self.south = s
            self.southwest = sw
            self.west = w
    
    kitchen = Room("You are in the Kitchen. Look at the scrumptious roast chicken and kidney pudding! \nThere are doors leading to North, East, and West.", None, 4, None, 2, None, None, None, 0)
    
    room_list.append(kitchen)
    
    east_cooridor = Room("You apparated into the East Corridor. \nYou can apparate to the Northwest or the Southwest.", 8, None, None, None, None, None, 2, None)
    
    room_list.append(east_cooridor)
    
    great_hall = Room("You are in the Great Hall. What is that great smell? \nThere appears to be doors leading to the north and the south.", None, 7, None, None, None, 1, None, None)
    
    room_list.append(great_hall)
    
    owlery = Room("You are in the Owlery. WHOOs got mail? There is a glass door overlooking the Forbidden Forest. \nThere are doors in every direction.", None, 9, None, 8, None, 4, None, 6)
    
    room_list.append(owlery)
    
    room_list.append(forbidden_forest)
    
    current_room = 4
    while not done:
        print(room_list[current_room].description)
    
    key = current_room
    i = 0
    while i < len(object_list) and object_list[i].current_room != key:
        i += 1
    
    if i < len(object_list):
        print("There is an object you can pick up in this room.")
        print()
    
    direction = input("Which direction would you like to travel? ")
    print()
    
    if direction.lower() == "n" and current_room == 9 or direction.lower() == "north" and current_room == 9:
        print("You wandered too far into the Forbidden Forest with out all of the Deathly Hallows to protect you. \nYou have died.")
        done = True
    
    elif direction.lower() == "nw" or direction.lower() == "northwest":
        next_room = room_list[current_room].northwest
        if next_room == None:
            print("TROLL! Troll in the dungeon!!")
        else:
            current_room = next_room
        print()
    
    elif direction.lower() == "n" or direction.lower() == "north":
        next_room = room_list[current_room].north
        if next_room == None:
            print("Run away!!!!")
        else:
            current_room = next_room
        print()
    
    elif direction.lower() == "ne" or direction.lower() == "northeast":
        next_room = room_list[current_room].northeast
        if next_room == None:
            print("Oh cool! Pixies! Wait...yikes! Bad idea!")
        else:
            current_room = next_room
        print()    
    
    elif direction.lower() == "e" or direction.lower() == "east":
        next_room = room_list[current_room].east
        if next_room == None:
            print("Don't go over there! The Whomping Willow is over there!")
        else:
            current_room = next_room
        print()
    
    elif direction.lower() == "se" or direction.lower() == "southeast":
        next_room = room_list[current_room].southeast
        if next_room == None:
            print("Don't go in there...")
        else:
            current_room = next_room
        print()
    
    elif direction.lower() == "s" or direction.lower() == "south":
        next_room = room_list[current_room].south
        if next_room == None:
            print("AHHH! It's Fluffy, the three-headed dog!")
        else:
            current_room = next_room
        print()
    
    elif direction.lower() == "sw" or direction.lower() == "southwest":
        next_room = room_list[current_room].southwest
        if next_room == None:
            print("The third floor corridor is forbidden.")
        else:
            current_room = next_room
        print()
    
    elif direction.lower() == "w" or direction.lower() == "west":
        next_room = room_list[current_room].west
        if next_room == None:
            print("I wouldn't go that way if I were you. You may run into something dangerous!")
        else:
            current_room = next_room
        print()
    
    elif direction.lower() == "q" or direction.lower() == quit:
        done = True
    
    else:
        print("What kind of sorcery is this!? Try going an actual direction.")
        print()
    

    我试图按照给我的指示,但我们没有被告知拆分命令,我找不到任何可以在网上解释的东西。
    我希望有人能够向我解释如何使用split命令将用户键入的内容“拆分”到列表中。我不太明白我是怎么做或为什么这样做的。 任何关于从哪里出发的建议都将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:0)

split方法通常用于解析包含由空格或标点符号分隔的单词的用户命令。例如......

brief_directions = ['n', 's', 'e', 'w', 'ne', 'nw', 'se', 'sw']
full_directions = ['north', 'south', 'east', 'west', 'northeast',
                   'northwest', 'southeast', 'southwest']
user_command = input('What would you like to do? ')
if user_command in brief_directions + full_directions:
    print('You want to go {}'.format(user_command))
else:
    command_words = user_command.split()
    print('You want to {verb} the {noun}'.format(verb=command_words[0], 
                                                 noun=command_words[1]))
  

你想做什么?得到钥匙

     

您想获得密钥

然后你可以编写一个函数,每当用户输入“get”作为第一个单词时调用该函数,例如

if command_words[0] == "get":
    get_object(command_words[1])

这样可以避免为用户可能想要获得的每个对象编写单独的代码。

答案 1 :(得分:0)

为了向你解释split,我在这里......

在Python中,"The cow jumped over the moon."函数用作字符串操纵器,允许程序员或用户定义一个字符串将被分割的分隔符。当对字符串执行该函数时,该字符串将转换为原始的后续字符串列表,这些字符串在每次出现定义的分隔符时被分隔并编入索引。

例如,假设我们有一个字符串split,我们想要删除有空格的字符串。为此,我们使用s = "The cow jumped over the moon" print(s.split(' ')) 函数。

space

在此细分中,我将分隔符定义为['The', 'cow', 'jumped', 'over', 'the', 'moon']。代码段的结果将打印:split。正如您所看到的,它返回了原始所有子串的列表,其中有一个空格。

此原则也适用于e函数的所有参数。如果我们决定在出现字母s.split('e') 时分开,我们会这样做:

['Th', ' cow jump', 'd ov', 'r th', ' moon']

这将返回:while(reader.Read()) { Id = Convert.IsDbNull(reader[0]) ? Convert.ToInt32(0) : Convert.ToInt32(reader[0]); Name = Convert.IsDbNull(reader[1]) ? string.Empty : reader[1].ToString(); FinalOutcome = Convert.IsDbNull(reader[2]) ? FinalOutcome.DontKnow : (Outcome) Convert.ToInt32(reader[2]); }

我希望这有帮助!

相关问题