如何在Python中使用Split命令?

2020-11-25 10:31:02 发布

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

我在做一个文字冒险游戏。 我对如何实现我游戏的下一部分感到困惑。 接下来我要补充的是: “添加拾取对象的功能。如果用户键入get key,则:

  1. 拆分用户输入,这样就可以分离出一个变量,它等于“key”。在

    1.使用内置在Python字符串中的split方法。例如: command_words=用户_命令.拆分(“”)

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

    1. 请更新您的指示,改为检查命令字[0]。在
    2. 添加get命令的检查。在

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条回答
网友
1楼 ·

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]))

What would you like to do? get key

You want to get the key

然后你可以编写一个函数,每次用户输入“get”作为第一个单词时都会调用这个函数

^{pr2}$

这样您就不用为用户可能想要得到的每个对象编写单独的代码。在

网友
2楼 ·

为了向你解释split,我来。。。在

在Python中,split函数用作字符串操纵器,它允许程序员或用户定义一个分隔符,用于分割和分割字符串。当在字符串的后续出现处被定义为分隔符时,将在字符串的每个出现处被转换为分隔符。在

{我们要说的是一个空格。为此,我们使用split函数。在

s = "The cow jumped over the moon"
print(s.split(' '))

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

这个原则也适用于给split函数的所有参数。如果我们决定在字母e出现时分开,我们会:

^{pr2}$

这将返回:['Th', ' cow jump', 'd ov', 'r th', ' moon']

我希望这有帮助!在

相关问题