如何修复在Python文字游戏中离开第一个房间的问题?

huangapple go评论64阅读模式
英文:

How to fix issue moving out of first room in Python word game?

问题

以下是您要翻译的代码部分:

class Room:
    def __init__(self, name, description):
        self.name = name
        self.description = description
        self.exits = {}
        self.items = []

    def add_exit(self, direction, room):
        self.exits[direction] = room

    def add_item(self, item):
        self.items.append(item)

    def remove_item(self, item):
        self.items.remove(item)

    def __str__(self):
        return f"{self.name}\n\n{self.description}"


class Item:
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.name


class Player:
    def __init__(self):
        self.inventory = []

    def add_item(self, item):
        self.inventory.append(item)

    def has_item(self, item_name):
        return any(item.name.lower() == item_name.lower() for item in self.inventory)

# Create rooms
start_room = Room("Start Room", "You find yourself at the beginning of a treacherous journey.")
enchanted_forest = Room("Enchanted Forest", "You are surrounded by mystical trees and faint whispers.")
ancient_library = Room("Ancient Library", "The shelves are filled with dusty tomes and ancient knowledge.")
underground_caverns = Room("Underground Caverns", "Stalactites and stalagmites create a maze of shadows.")
tower_of_wisdom = Room("Tower of Wisdom", "A towering structure filled with ancient artifacts and arcane symbols.")
forgotten_crypt = Room("Forgotten Crypt", "The air is heavy with the scent of decay and long-forgotten spirits.")
labyrinth_of_shadows = Room("Labyrinth of Shadows", "A twisting maze where darkness conceals unseen dangers.")
chamber_of_the_balrog = Room("Chamber of the Balrog", "The ground trembles as a fiery presence awaits.")

# Connect rooms
start_room.add_exit("N", enchanted_forest)
enchanted_forest.add_exit("S", start_room)
enchanted_forest.add_exit("E", ancient_library)
ancient_library.add_exit("W", enchanted_forest)
ancient_library.add_exit("S", underground_caverns)
underground_caverns.add_exit("N", ancient_library)
underground_caverns.add_exit("E", tower_of_wisdom)
tower_of_wisdom.add_exit("W", underground_caverns)
tower_of_wisdom.add_exit("E", forgotten_crypt)
forgotten_crypt.add_exit("W", tower_of_wisdom)
forgotten_crypt.add_exit("S", labyrinth_of_shadows)
labyrinth_of_shadows.add_exit("N", forgotten_crypt)
labyrinth_of_shadows.add_exit("E", chamber_of_the_balrog)

# Create items
magic_amulet = Item("Magic Amulet")
spellbook = Item("Spellbook")
crystal_sword = Item("Crystal Sword")
enchanted_staff = Item("Enchanted Staff")
healing_potion = Item("Healing Potion")
cloak_of_invisibility = Item("Cloak of Invisibility")

# Add items to rooms
enchanted_forest.add_item(magic_amulet)
ancient_library.add_item(spellbook)
underground_caverns.add_item(crystal_sword)
tower_of_wisdom.add_item(enchanted_staff)
forgotten_crypt.add_item(healing_potion)
labyrinth_of_shadows.add_item(cloak_of_invisibility)

# Set up player
player = Player()

# Game loop
current_room = start_room

while True:
    print(current_room)
    print("Available exits:", ", ".join(current_room.exits.keys()))
    print("Your inventory:", [str(item) for item in player.inventory])

    command = input("Enter a command: ").strip().lower()

    if command in current_room.exits:
        current_room = current_room.exits[command]
    elif command.startswith("pickup "):
        item_name = command.split(" ", 1)[1]
        if current_room.has_item(item_name):
            item = next(item for item in current_room.items if item.name.lower() == item_name.lower())
            player.add_item(item)
            current_room.remove_item(item)
            print(f"You have picked up {item}.")
        else:
            print("There is no such item in this room.")
    else:
        print("Invalid command. Please enter a valid command.")

    if current_room is chamber_of_the_balrog:
        if len(player.inventory) == 6:
            print("You have collected all the items! It's time to face the Balrog!")
            break
        else:
            print("You are not yet ready to face the Balrog. Collect all the items first.")

print("Congratulations! You have defeated the Balrog and won the game!")
英文:

Creating a word game for my first Python Class.
Project guideline:
The basic gameplay will require the player to move between different rooms to gather all of the items. A player wins the game by collecting all the items before encountering the villain. The player will have two options for commands in the game: moving to a different room, and getting an item from the room they are in. Movement between rooms happens in four simple directions: North, South, East, and West.

I have coded this in a way that it runs, however I am unable to move out of the first room, I have the exit set as North "N" but when that is entered it just starts back in the start room.

Trying to be able to move out of the first room but unable to with stated command "N"

class Room:
def __init__(self, name, description):
self.name = name
self.description = description
self.exits = {}
self.items = []
def add_exit(self, direction, room):
self.exits[direction] = room
def add_item(self, item):
self.items.append(item)
def remove_item(self, item):
self.items.remove(item)
def __str__(self):
return f"{self.name}\n\n{self.description}"
class Item:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
class Player:
def __init__(self):
self.inventory = []
def add_item(self, item):
self.inventory.append(item)
def has_item(self, item_name):
return any(item.name.lower() == item_name.lower() for item in self.inventory)
# Create rooms
start_room = Room("Start Room", "You find yourself at the beginning of a treacherous journey.")
enchanted_forest = Room("Enchanted Forest", "You are surrounded by mystical trees and faint whispers.")
ancient_library = Room("Ancient Library", "The shelves are filled with dusty tomes and ancient knowledge.")
underground_caverns = Room("Underground Caverns", "Stalactites and stalagmites create a maze of shadows.")
tower_of_wisdom = Room("Tower of Wisdom", "A towering structure filled with ancient artifacts and arcane symbols.")
forgotten_crypt = Room("Forgotten Crypt", "The air is heavy with the scent of decay and long-forgotten spirits.")
labyrinth_of_shadows = Room("Labyrinth of Shadows", "A twisting maze where darkness conceals unseen dangers.")
chamber_of_the_balrog = Room("Chamber of the Balrog", "The ground trembles as a fiery presence awaits.")
# Connect rooms
start_room.add_exit("N", enchanted_forest)
enchanted_forest.add_exit("S", start_room)
enchanted_forest.add_exit("E", ancient_library)
ancient_library.add_exit("W", enchanted_forest)
ancient_library.add_exit("S", underground_caverns)
underground_caverns.add_exit("N", ancient_library)
underground_caverns.add_exit("E", tower_of_wisdom)
tower_of_wisdom.add_exit("W", underground_caverns)
tower_of_wisdom.add_exit("E", forgotten_crypt)
forgotten_crypt.add_exit("W", tower_of_wisdom)
forgotten_crypt.add_exit("S", labyrinth_of_shadows)
labyrinth_of_shadows.add_exit("N", forgotten_crypt)
labyrinth_of_shadows.add_exit("E", chamber_of_the_balrog)
chamber_of_the_balrog.add_exit("W", labyrinth_of_shadows)
# Create items
magic_amulet = Item("Magic Amulet")
spellbook = Item("Spellbook")
crystal_sword = Item("Crystal Sword")
enchanted_staff = Item("Enchanted Staff")
healing_potion = Item("Healing Potion")
cloak_of_invisibility = Item("Cloak of Invisibility")
# Add items to rooms
enchanted_forest.add_item(magic_amulet)
ancient_library.add_item(spellbook)
underground_caverns.add_item(crystal_sword)
tower_of_wisdom.add_item(enchanted_staff)
forgotten_crypt.add_item(healing_potion)
labyrinth_of_shadows.add_item(cloak_of_invisibility)
# Set up player
player = Player()
# Game loop
current_room = start_room
while True:
print(current_room)
print("Available exits:", ", ".join(current_room.exits.keys()))
print("Your inventory:", [str(item) for item in player.inventory])
command = input("Enter a command: ").strip().lower()
if command in current_room.exits:
current_room = current_room.exits[command]
elif command.startswith("pickup "):
item_name = command.split(" ", 1)[1]
if current_room.has_item(item_name):
item = next(item for item in current_room.items if item.name.lower() == item_name.lower())
player.add_item(item)
current_room.remove_item(item)
print(f"You have picked up {item}.")
else:
print("There is no such item in this room.")
else:
print("Invalid command. Please enter a valid command.")
if current_room is chamber_of_the_balrog:
if len(player.inventory) == 6:
print("You have collected all the items! It's time to face the Balrog!")
break
else:
print("You are not yet ready to face the Balrog. Collect all the items first.")
print("Congratulations! You have defeated the Balrog and won the game!")

答案1

得分: 1

看起来你将玩家输入的命令转换为小写字母。

command = input("输入一个命令:").strip().lower()

因为"N"与"n"不相同,而你的退出命令字典不包含小写命令字符串,所以它变成了一个无效的命令并重新启动了游戏。

移除.lower()方法可以解决这个问题。

正确的代码:

command = input("输入一个命令:").strip()
英文:

It seems that you're turning the command entered by the player into a lowercase letter.

command = input("Enter a command: ").strip().lower()

since "N" is not the same as "n" and your dictionary of exit commands doesn't contain lowercase command strings it becomes an invalid command and restarts the game.

removing the .lower() method can solve this.

correct code:
command = input("Enter a command: ").strip()

huangapple
  • 本文由 发表于 2023年6月5日 06:52:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76402713.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定