English 中文(简体)
主要的游戏功能中弹
原标题:Python- Move a dictionary inside main game function

我正试图在沙里创造一种基于文字的游艇,但我是新陈词,需要一些指导! 我需要在主要游戏功能内搬动会议室字典,但我确实有错误,无论我是否尝试过。 我的《守则》是迄今得到高度赞赏的任何反馈或建议。 增 编

# Define the rooms and their properties
rooms = {
     Entrance Hall : {
         Directions : { North :  Kitchen ,  South :  Secret Passageway ,  East :  Throne Room ,  West :  Grand Hall },
         Item :  None   # Each room initially has no item
    },
     Kitchen : {
         Directions : { South :  Entrance Hall ,  East :  Dining Room },
         Item :  Diamond Crown 
    },
     Throne Room : {
         Directions : { West :  Entrance Hall ,  North :  Armory },
         Item :  Silver Scepter 
    },
     Armory : {
         Directions : { South :  Throne Room },
         Item :  Emerald Necklace 
    },
     Grand Hall : {
         Directions : { East :  Entrance Hall },
         Item :  Golden Chalice 
    },
     Dining Room : {
         Directions : { West :  Kitchen },
         Item :  Enchanted Orb 
    },
     Secret Passageway : {
         Directions : { North :  Entrance Hall ,  East : "Sorcerer s Lair"},
         Item :  Mystic Amulet 
    },
    "Sorcerer s Lair": {
         Directions : { West :  Secret Passageway }
    }
}


# Function to display player s status
def show_status(current_room, inventory):
    """Display the status of the player."""
    print(f"Current Room: {current_room}")
    print(f"Inventory: {inventory}")


# Function to update the player s current room based on the direction entered
def get_new_state(direction_from_user, current_room):
    """Update the player s current room based on the direction entered."""
    valid_directions = rooms[current_room][ Directions ].keys()
    if direction_from_user in valid_directions:
        return rooms[current_room][ Directions ].get(direction_from_user)
    else:
        print( Invalid direction! Please enter a valid direction. )
        return current_room


# Function to display a message if the player picks up an item
def display_item_pickup(current_room, inventory):
    """Display a message if the player picks up an item."""
    item = rooms[current_room][ Item ]
    if item !=  None :
        print(f You found a {item} in this room! )
        inventory.append(item)
        rooms[current_room][ Item ] =  None   # Remove the item from the room once picked up


# Function to process item collection commands
def process_item_collection(command, current_room, inventory):
    """Process item collection commands."""
    if command.startswith( get ):
        item =    .join(command.split()[1:])  # Collect item name even if it has multiple words
        if rooms[current_room][ Item ] == item:
            inventory.append(item)
            rooms[current_room][ Item ] =  None   # Remove item from room once picked up
            print( Item collected: , item)
        else:
            print( Item not found in this room. )
    else:
        print( Invalid command! Please enter a valid item collection command. )


# Main function to start the game
def main():
    """Main function to start the game."""
    # Display game instructions and movement commands
    print( Welcome to The Lost Kingdom Text Adventure Game )
    print( Collect all 6 items to defeat the Wicked Sorcerer and win the game, or endure the Wicked Sorcerer’s Spell  
           of Death )
    print( Move commands: go South, go North, go East, go West )
    print( Add to Inventory: get  item name  )
    print( ------------------------------ )  # Print line of dashes

    current_room =  Entrance Hall 
    inventory = []

    # Start the main game loop
    while not (len(inventory) == 6 and current_room == "Sorcerer s Lair") and not current_room == "Sorcerer s Lair":
        # Display player s status and room information
        show_status(current_room, inventory)

        # Check if there s an item to pick up in the current room
        display_item_pickup(current_room, inventory)

        command = input( Enter your move:  )
        print( ------------------------------ )  # Print line of dashes

        if command.startswith( go ):
            # Process movement commands
            direction = command.split()[1]
            current_room = get_new_state(direction, current_room)

        elif command.startswith( get ):
            # Process item collection commands
            process_item_collection(command, current_room, inventory)

        else:
            # Handle invalid command input
            print( Invalid command! Please enter a valid move or item. )

    # Check if the game ended due to winning or losing condition
    if len(inventory) == 6 and current_room == "Sorcerer s Lair":
        print( Congratulations! You have collected all items and defeated the Wicked Sorcerer! )
    else:
        print( The Wicked Sorcerer cast the Spell of Death on you!...GAME OVER! )

    # Display farewell message
    print( Thanks for playing. Hope you enjoyed the game! )


if __name__ ==  __main__ :
    main()

我试图将其移到主要游戏功能中,但我不能说我错做什么。 加强对我守则的任何帮助也将受到高度赞赏。

# Function to display player s status
def show_status(current_room, inventory):
    """Display the status of the player."""
    print(f"Current Room: {current_room}")
    print(f"Inventory: {inventory}")


# Function to update the player s current room based on the direction entered
def get_new_state(direction_from_user, current_room, rooms):
    """Update the player s current room based on the direction entered."""
    valid_directions = rooms[current_room][ Directions ].keys()
    if direction_from_user in valid_directions:
        return rooms[current_room][ Directions ].get(direction_from_user)
    else:
        print( Invalid direction! Please enter a valid direction. )
        return current_room


# Function to display a message if the player picks up an item
def display_item_pickup(current_room, inventory, rooms):
    """Display a message if the player picks up an item."""
    item = rooms[current_room][ Item ]
    if item !=  None :
        print(f You found a {item} in this room! )
        inventory.append(item)
        rooms[current_room][ Item ] =  None   # Remove the item from the room once picked up


# Function to process item collection commands
def process_item_collection(command, current_room, inventory, rooms):
    """Process item collection commands."""
    if command.startswith( get ):
        item =    .join(command.split()[1:])  # Collect item name even if it has multiple words
        if rooms[current_room][ Item ] == item:
            inventory.append(item)
            rooms[current_room][ Item ] =  None   # Remove item from room once picked up
            print( Item collected: , item)
        else:
            print( Item not found in this room. )
    else:
        print( Invalid command! Please enter a valid item collection command. )


# Main function to start the game
def main():
    """Main function to start the game."""
    # Define the rooms and their properties
    rooms = {
         Entrance Hall : {
             Directions : { North :  Kitchen ,  South :  Secret Passageway ,  East :  Throne Room ,  West :  Grand Hall },
             Item :  None   # Each room initially has no item
        },
         Kitchen : {
             Directions : { South :  Entrance Hall ,  East :  Dining Room },
             Item :  Diamond Crown 
        },
         Throne Room : {
             Directions : { West :  Entrance Hall ,  North :  Armory },
             Item :  Silver Scepter 
        },
         Armory : {
             Directions : { South :  Throne Room },
             Item :  Emerald Necklace 
        },
         Grand Hall : {
             Directions : { East :  Entrance Hall },
             Item :  Golden Chalice 
        },
         Dining Room : {
             Directions : { West :  Kitchen },
             Item :  Enchanted Orb 
        },
         Secret Passageway : {
             Directions : { North :  Entrance Hall ,  East : "Sorcerer s Lair"},
             Item :  Mystic Amulet 
        },
        "Sorcerer s Lair": {
             Directions : { West :  Secret Passageway }
        }
    }

    # Display game instructions and movement commands
    print( Welcome to The Lost Kingdom Text Adventure Game )
    print( Collect all 6 items to defeat the Wicked Sorcerer and win the game, or endure the Wicked Sorcerer’s Spell  
           of Death )
    print( Move commands: go South, go North, go East, go West )
    print( Add to Inventory: get  item name  )
    print( ------------------------------ )  # Print line of dashes

    current_room =  Entrance Hall 
    inventory = []

    # Start the main game loop
    while not (len(inventory) == 6 and current_room == "Sorcerer s Lair") and not current_room == "Sorcerer s Lair":
        # Display player s status and room information
        show_status(current_room, inventory)

        # Check if there s an item to pick up in the current room
        display_item_pickup(current_room, inventory, rooms)

        command = input( Enter your move:  )
        print( ------------------------------ )  # Print line of dashes

        if command.startswith( go ):
            # Process movement commands
            direction = command.split()[1]
            current_room = get_new_state(direction, current_room, rooms)

        elif command.startswith( get ):
            # Process item collection commands
            process_item_collection(command, current_room, inventory, rooms)

        else:
            # Handle invalid command input
            print( Invalid command! Please enter a valid move or item. )

    # Check if the game ended due to winning or losing condition
    if len(inventory) == 6 and current_room == "Sorcerer s Lair":
        print( Congratulations! You have collected all items and defeated the Wicked Sorcerer! )
    else:
        print( The Wicked Sorcerer cast the Spell of Death on you!...GAME OVER! )

    # Display farewell message
    print( Thanks for playing. Hope you enjoyed the game! )


if __name__ ==  __main__ :
    main()

我们现在无法对你的法典进行分类,如果你在努力,我们就建议你就此与你的教授协商。 与此同时,你可以把这作为你的游戏系统司机的参考——1) 你们需要一个新功能,把(从用户到现在的房间)作为参与者的论据和更新身份。 这一职能应进入会议室,并检查方向在会议室内。 (如果你愿意,你还可以发挥一些额外职能,向用户展示信息。) 2) 然后,你需要驾车。 你的休息时间必须检查以下条件,因为现在的房间——现有房间是否有一个收集物品,是否有人把杀人区埋在了,参与者是否发出指令或QUI,或者什么无效。 这种循环还必须把“新”功能称作“新”功能,并在角色指挥上搬入新的房间。 我们在这里给你带来了一些联系,这样,你的表率就会顺利地走到一起——感到可以自由提及他们。 参考文献 (1) 休息 (2) 职能定义 希望!

class gameKeeper():
    def __init__(self):
        # Define the rooms and their properties
        self.rooms = {
             Entrance Hall : {
                 Directions : { North :  Kitchen ,  South :  Secret Passageway ,  East :  Throne Room ,  West :  Grand Hall },
                 Item :  None   # Each room initially has no item
            },
             Kitchen : {
                 Directions : { South :  Entrance Hall ,  East :  Dining Room },
                 Item :  Diamond Crown 
            },
             Throne Room : {
                 Directions : { West :  Entrance Hall ,  North :  Armory },
                 Item :  Silver Scepter 
            },
             Armory : {
                 Directions : { South :  Throne Room },
                 Item :  Emerald Necklace 
            },
             Grand Hall : {
                 Directions : { East :  Entrance Hall },
                 Item :  Golden Chalice 
            },
             Dining Room : {
                 Directions : { West :  Kitchen },
                 Item :  Enchanted Orb 
            },
             Secret Passageway : {
                 Directions : { North :  Entrance Hall ,  East : "Sorcerer s Lair"},
                 Item :  Mystic Amulet 
            },
            "Sorcerer s Lair": {
                 Directions : { West :  Secret Passageway }
            }
        }

    # Function to display player s status
    def show_status(self, current_room, inventory):
        """Display the status of the player."""
        print(f"Current Room: {current_room}")

        # Check if there s an item in the room
        if self.rooms[current_room][ Item ] !=  None :
            print(f"Item in Room: {self.rooms[current_room][ Item ]}")
        else:
            print("No item in this room.")

        # Display player s inventory
        print("Inventory:")
        if inventory:
            for item in inventory:
                print(f"- {item}")
        else:
            print("Empty")

        # Display available directions
        print("Directions:")
        directions = self.rooms[current_room][ Directions ]
        for direction, room in directions.items():
            print(f"- {direction}: {room}")

    # Function to update the player s current room based on the direction entered
    def get_new_state(self, direction_from_user, current_room):
        """Update the player s current room based on the direction entered."""
        valid_directions = self.rooms[current_room][ Directions ].keys()
        if direction_from_user in valid_directions:
            return self.rooms[current_room][ Directions ].get(direction_from_user)
        else:
            print( Invalid direction! Please enter a valid direction. )
            return current_room

    # Function to display a message if the player picks up an item
    def display_item_pickup(self, current_room, inventory):
        """Display a message if the player picks up an item."""
        item = self.rooms[current_room][ Item ]
        if item !=  None :
            print(f You found a {item} in this room! )
            inventory.append(item)
            self.rooms[current_room][ Item ] =  None   # Remove the item from the room once picked up

    # Function to process item collection commands
    def process_item_collection(self, command, current_room, inventory):
        """Process item collection commands."""
        if command.startswith( get ):
            item =    .join(command.split()[1:])  # Collect item name even if it has multiple words
            if self.rooms[current_room][ Item ] == item:
                inventory.append(item)
                self.rooms[current_room][ Item ] =  None   # Remove item from room once picked up
                print( Item collected: , item)
            else:
                print( Item not found in this room. )
        else:
            print( Invalid command! Please enter a valid item collection command. )


# Main function to start the game
def main():
    gandalf = gameKeeper()
    """Main function to start the game."""
    # Display game instructions and movement commands
    print( Welcome to The Lost Kingdom Text Adventure Game )
    print( Collect all 6 items to defeat the Wicked Sorcerer and win the game, or endure the Wicked Sorcerer’s Spell  
           of Death )
    print( Move commands: go South, go North, go East, go West )
    print( Add to Inventory: get  item name  )
    print( ------------------------------ )  # Print line of dashes

    current_room =  Entrance Hall 
    inventory = []

    # Start the main game loop
    while not (len(inventory) == 6 and current_room == "Sorcerer s Lair") and not current_room == "Sorcerer s Lair":
        # Display player s status and room information
        gandalf.show_status(current_room, inventory)

        # Check if there s an item to pick up in the current room
        gandalf.display_item_pickup(current_room, inventory)

        command = input( Enter your move:  )
        print( ------------------------------ )  # Print line of dashes

        if command.startswith( go ):
            # Process movement commands
            direction = command.split()[1]
            current_room = gandalf.get_new_state(direction, current_room)

        elif command.startswith( get ):
            # Process item collection commands
            gandalf.process_item_collection(command, current_room, inventory)

        else:
            # Handle invalid command input
            print( Invalid command! Please enter a valid move or item. )

    # Check if the game ended due to winning or losing condition
    if len(inventory) == 6 and current_room == "Sorcerer s Lair":
        print( Congratulations! You have collected all items and defeated the Wicked Sorcerer! )
    else:
        print( The Wicked Sorcerer cast the Spell of Death on you!...GAME OVER! )

    # Display farewell message
    print( Thanks for playing. Hope you enjoyed the game! )


if __name__ ==  __main__ :
    main()

Says there is no function to centrally display status.

You will need a show_status function to print out the game status for the player when he/she lands in a room. This is what you must print in the function - 1) Which room the player is currently in. 2) What item is present in the room. 3) What items are in the inventory. 4) The directions he can move in from this room. After you code this function - make sure you call it in a driver loop that facilitates the gameplay.

问题回答

我不知道我是否理解你的问题。 如果你想在主要职能中附上你的字典,最容易的方式是创造新的变量,并指定以前成立的字典。 因此,主要职能将考虑这样的内容:

def main():
    """Main function to start the game."""
    # Display game instructions and movement commands
    print( Welcome to The Lost Kingdom Text Adventure Game )
    print( Collect all 6 items to defeat the Wicked Sorcerer and win the game, or endure the Wicked Sorcerer’s Spell  
           of Death )
    print( Move commands: go South, go North, go East, go West )
    print( Add to Inventory: get  item name  )
    print( ------------------------------ )  # Print line of dashes

    current_room =  Entrance Hall 
    rooms_dict = rooms  # Here is the rooms dict copy
    print(rooms_dict)
    inventory = []

    # Start the main game loop
    while not (len(inventory) == 6 and current_room == "Sorcerer s Lair") and not current_room == "Sorcerer s Lair":
        # Display player s status and room information
        show_status(current_room, inventory)

        # Check if there s an item to pick up in the current room
        display_item_pickup(current_room, inventory)

        command = input( Enter your move:  )
        print( ------------------------------ )  # Print line of dashes

        if command.startswith( go ):
            # Process movement commands
            direction = command.split()[1]
            current_room = get_new_state(direction, current_room)

        elif command.startswith( get ):
            # Process item collection commands
            process_item_collection(command, current_room, inventory)

        else:
            # Handle invalid command input
            print( Invalid command! Please enter a valid move or item. )

    # Check if the game ended due to winning or losing condition
    if len(inventory) == 6 and current_room == "Sorcerer s Lair":
        print( Congratulations! You have collected all items and defeated the Wicked Sorcerer! )
    else:
        print( The Wicked Sorcerer cast the Spell of Death on you!...GAME OVER! )

    # Display farewell message
    print( Thanks for playing. Hope you enjoyed the game! )

但是,我看不出产生新的变数并赋予它同样的价值,因为会议室字典具有全球范围,因此,你应该能够从主要职能中获取。

You could put rooms in a class or you could define it inside the main function, right under the main def.

def main():
   rooms = {...}
class gameKeeper():
    def __init__(self):
        # Define the rooms and their properties
        self.rooms = {
                 Entrance Hall : {
                     Directions : { North :  Kitchen ,  South :  Secret Passageway ,  East :  Throne Room ,  West :  Grand Hall },
                     Item :  None   # Each room initially has no item
                },
                 Kitchen : {
                     Directions : { South :  Entrance Hall ,  East :  Dining Room },
                     Item :  Diamond Crown 
                },
                 Throne Room : {
                     Directions : { West :  Entrance Hall ,  North :  Armory },
                     Item :  Silver Scepter 
                },
                 Armory : {
                     Directions : { South :  Throne Room },
                     Item :  Emerald Necklace 
                },
                 Grand Hall : {
                     Directions : { East :  Entrance Hall },
                     Item :  Golden Chalice 
                },
                 Dining Room : {
                     Directions : { West :  Kitchen },
                     Item :  Enchanted Orb 
                },
                 Secret Passageway : {
                     Directions : { North :  Entrance Hall ,  East : "Sorcerer s Lair"},
                     Item :  Mystic Amulet 
                },
                "Sorcerer s Lair": {
                     Directions : { West :  Secret Passageway }
                }
            }

    # Function to display player s status
    def show_status(self, current_room, inventory):
        """Display the status of the player."""
        print(f"Current Room: {current_room}")
        print(f"Inventory: {inventory}")
    
    
    # Function to update the player s current room based on the direction entered
    def get_new_state(self, direction_from_user, current_room):
        """Update the player s current room based on the direction entered."""
        valid_directions = self.rooms[current_room][ Directions ].keys()
        if direction_from_user in valid_directions:
            return  self.rooms[current_room][ Directions ].get(direction_from_user)
        else:
            print( Invalid direction! Please enter a valid direction. )
            return current_room
    
    
    # Function to display a message if the player picks up an item
    def display_item_pickup(self, current_room, inventory):
        """Display a message if the player picks up an item."""
        item =  self.rooms[current_room][ Item ]
        if item !=  None :
            print(f You found a {item} in this room! )
            inventory.append(item)
            self.rooms[current_room][ Item ] =  None   # Remove the item from the room once picked up
    
    
    # Function to process item collection commands
    def process_item_collection(self, command, current_room, inventory):
        """Process item collection commands."""
        if command.startswith( get ):
            item =    .join(command.split()[1:])  # Collect item name even if it has multiple words
            if  self.rooms[current_room][ Item ] == item:
                inventory.append(item)
                self.rooms[current_room][ Item ] =  None   # Remove item from room once picked up
                print( Item collected: , item)
            else:
                print( Item not found in this room. )
        else:
            print( Invalid command! Please enter a valid item collection command. )


# Main function to start the game
def main():
    gandalf = gameKeeper()
    """Main function to start the game."""
    # Display game instructions and movement commands
    print( Welcome to The Lost Kingdom Text Adventure Game )
    print( Collect all 6 items to defeat the Wicked Sorcerer and win the game, or endure the Wicked Sorcerer’s Spell  
           of Death )
    print( Move commands: go South, go North, go East, go West )
    print( Add to Inventory: get  item name  )
    print( ------------------------------ )  # Print line of dashes

    current_room =  Entrance Hall 
    inventory = []

    # Start the main game loop
    while not (len(inventory) == 6 and current_room == "Sorcerer s Lair") and not current_room == "Sorcerer s Lair":
        # Display player s status and room information
        gandalf.show_status(current_room, inventory)

        # Check if there s an item to pick up in the current room
        gandalf.display_item_pickup(current_room, inventory)

        command = input( Enter your move:  )
        print( ------------------------------ )  # Print line of dashes

        if command.startswith( go ):
            # Process movement commands
            direction = command.split()[1]
            current_room = gandalf.get_new_state(direction, current_room)

        elif command.startswith( get ):
            # Process item collection commands
            gandalf.process_item_collection(command, current_room, inventory)

        else:
            # Handle invalid command input
            print( Invalid command! Please enter a valid move or item. )

    # Check if the game ended due to winning or losing condition
    if len(inventory) == 6 and current_room == "Sorcerer s Lair":
        print( Congratulations! You have collected all items and defeated the Wicked Sorcerer! )
    else:
        print( The Wicked Sorcerer cast the Spell of Death on you!...GAME OVER! )

    # Display farewell message
    print( Thanks for playing. Hope you enjoyed the game! )


if __name__ ==  __main__ :
    main()




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签