My If condition within a while loop doesnt break the loop

2024/10/5 19:58:11

Struggling to get my code for the final room to finish the text-based game assigned to me. I essentially want the player to be forced to get all 6 items prior to entry. Any help is greatly appreciated. I have tried looking at similar projects from others, can't get that part right. The rest of the game functions appropriately, so this is my last big hill to get over.

How can I have my if condition within a while loop break the loop and end the game?

rooms = {'Jail Cell': {'name': 'Jail Cell', 'South': 'Barracks','text': 'You\'re in the Jail Cell.', 'item': 'whole lot of nothing'},'Barracks': {'name': 'the Barracks', 'West': 'Dining Hall', 'North': 'Jail Cell','text': 'You\'re in the Barracks.', 'item': 'Strange Potion'},'Dining Hall': {'name': 'the Dining Hall', 'West': 'Queens Chamber', 'North': 'Alchemist Room','South': 'Bedchamber', 'East': 'Barracks','text': 'You\'re in the Dining hall.', 'item': 'Stained Wine Glass'},'Queens Chamber': {'name': 'the Queens Chamber', 'East': 'Dining Hall','text': 'You\'re in the Queen\'s Chamber.', 'item': 'nothing'},'Bedchamber': {'name': 'the Bedchamber', 'East': 'Religious Shrine', 'North': 'Dining Hall','text': 'You\'re in the Bedchamber.', 'item': 'Rumor Book'},'Religious Shrine': {'name': 'Religious Shrine', 'West': 'Bedchamber','text': 'You\'re in the Religious Shrine.', 'item': 'Dagger Sheath'},'Alchemist Room': {'name': 'Alchemist Room', 'East': 'Commanders Chamber', 'South': 'Dining Hall','text': 'You\'re in the Alchemist\'s Room.', 'item': 'Potion Recipe'},'Commanders Chamber': {'name': 'Commanders Chamber', 'West': 'Alchemist Room','text': 'You\'re in the Commander\'s Chamber.', 'item': 'Queen\'s Chamber Key'}}directions = ['North', 'South', 'East', 'West']
current_room = rooms['Jail Cell']
inventory = []
item = ['Strange Potion', 'Stained Wine Glass', 'Rumor Book', 'Potion Recipe', 'Queen\'s Chamber Key']# Beginning display
def menu():print('The Secret of the Forgotten Queen: A Text Based Adventure')print('To move, type: North, South, East, or West.')print('To search a room, type "Search Room".')print('To pick up an item, type: "Take" followed by the item name.')print('Collect all 6 items to discover what has happened to the Queen.')print('\nYou awaken in an old Jail Cell. An apparition appears! It\'s a beautiful lady who explains that you must ''find the secrets of this castle so that the Queen may finally rest.')menu()# Loop for gamewhile True:if current_room['name'] != 'Queens Chamber':print('You\'re in the {}.'.format(current_room['name']))print('Inventory:', inventory)# User inputcommand = input('\nWhat\'s your next move Hero?')if current_room['name'] == 'Queens Chamber':if len(inventory) == '6':print('The Queen and her lover the Commander of the Knights. Another unfortunate Romeo and Juliet scenario.''What\'s the moral of this story?')break# The movementif command in directions:if command in current_room:current_room = rooms[current_room[command]]else:# No room in that directionprint('Nothing found in that direction. Which direction now?')elif command == 'Take ' + (current_room['item']):if (current_room['item']) not in inventory:inventory.append(current_room['item'])else:print('\nYou have already picked this item up!\n')elif command == 'Search Room':print('You find a {}.'.format(current_room['item']))# To quit gameelif command == 'Quit':print('See ya next time!')break# Invalid commandelse:print('Invalid input. Review the instructions!')
Answer
  • Use None and not the strings players can append the strings with any name. I was able to add "nothing" to my inventory and complete the game!
  • Remove "the" from the names to compare properly
  • "==" returns True ONLY if it exactly matches.
    For eg: "the Queen's Chamber" == "Queen's Chamber" returns False.
  • You were comparing the length of a string to "6" a string. len returns integer type.

    Note: Try debugging yourself too using debuggers present in text editors like VS Code. You will face many such problems when you code
# Remove "the" from the names to compare properly
# Use none and not strings players can append the strings with any name
rooms = {'Jail Cell': {'name': 'Jail Cell', 'South': 'Barracks','text': 'You\'re in the Jail Cell.', 'item': None},'Barracks': {'name': 'Barracks', 'West': 'Dining Hall', 'North': 'Jail Cell','text': 'You\'re in the Barracks.', 'item': 'Strange Potion'},'Dining Hall': {'name': 'Dining Hall', 'West': 'Queens Chamber', 'North': 'Alchemist Room','South': 'Bedchamber', 'East': 'Barracks','text': 'You\'re in the Dining hall.', 'item': 'Stained Wine Glass'},'Queens Chamber': {'name': 'Queens Chamber', 'East': 'Dining Hall','text': 'You\'re in the Queen\'s Chamber.', 'item': None},'Bedchamber': {'name': 'Bedchamber', 'East': 'Religious Shrine', 'North': 'Dining Hall','text': 'You\'re in the Bedchamber.', 'item': 'Rumor Book'},'Religious Shrine': {'name': 'Religious Shrine', 'West': 'Bedchamber','text': 'You\'re in the Religious Shrine.', 'item': 'Dagger Sheath'},'Alchemist Room': {'name': 'Alchemist Room', 'East': 'Commanders Chamber', 'South': 'Dining Hall','text': 'You\'re in the Alchemist\'s Room.', 'item': 'Potion Recipe'},'Commanders Chamber': {'name': 'Commanders Chamber', 'West': 'Alchemist Room','text': 'You\'re in the Commander\'s Chamber.', 'item': 'Queen\'s Chamber Key'}}directions = ['North', 'South', 'East', 'West']
current_room = rooms['Jail Cell']
inventory = []
item =['Strange Potion', 'Stained Wine Glass', 'Rumor Book', 'Potion Recipe', 'Queen\'s Chamber Key','Dagger Sheath']# Beginning display
def menu():print('The Secret of the Forgotten Queen: A Text Based Adventure')print('To move, type: North, South, East, or West.')print('To search a room, type "Search Room".')print('To pick up an item, type: "Take" followed by the item name.')print('Collect all 6 items to discover what has happened to the Queen.')print('\nYou awaken in an old Jail Cell. An apparition appears! It\'s a beautiful lady who explains that you must ''find the secrets of this castle so that the Queen may finally rest.')menu()# Loop for gamewhile True:# Players need to know if they are in Queens Chamber print('You\'re in the {}.'.format(current_room['name']))print('Inventory:', inventory)# User inputcommand = input('\nWhat\'s your next move Hero?')#There was the in name and "==" retruns True ONLY if it exactly matchesif current_room['name'] == 'Queens Chamber':print(len(inventory))if len(inventory) == 6: # Use integer 6print('The Queen and her lover the Commander of the Knights. Another unfortunate Romeo and Juliet scenario.''What\'s the moral of this story?')break   # The movementif command in directions:if command in current_room:current_room = rooms[current_room[command]]else:# No room in that directionprint('Nothing found in that direction. Which direction now?')elif command == 'Take ' + (current_room['item']):if (current_room['item']) not in inventory:inventory.append(current_room['item'])else:print('\nYou have already picked this item up!\n')elif command == 'Search Room':print('You find a {}.'.format(current_room['item']))# To quit gameelif command == 'Quit':print('See ya next time!')break# Invalid commandelse:print('Invalid input. Review the instructions!')
https://en.xdnf.cn/q/119950.html

Related Q&A

Adding strings, first, first + second, etc

Program has to be able adding strings from the list and output them in sequence but in the way: 1 string 1 + 2 string 1 + 2 + 3 string ...def spacey(array):passe = ""i = ""m = []for…

Store Variables in Lists python

So I have tried to do this, and I think its clear what I want, I want to store the message variables that I have made in a List and then use this for printing, I wonder why does this not work?items = …

How can I kill the explorer.exe process?

Im writing a script which is meant to kill explorer.exe. I searched a bit about it and the best answer Ive seen uses the taskkill command. I tried it, but when I run it on my computer it says it worked…

A presence/activity set command?

So, I was wondering if there could be a command I could write that allows me to set the bots presence and activity (ex. ~~set presence idle or ~~set activity watching "people typing ~~help") …

Inverted Index in Python not returning desired results

Im having trouble returning proper results for an inverted index in python. Im trying to load a list of strings in the variable strlist and then with my Inverse index looping over the strings to return…

Remove white space from an image using python

There are multiple images that have white spaces that I need to remove. Simply crop the image so as to get rid of the white spaces Heres the code I tried so far (this is a result of search) import nump…

How to calculate the ratio between two numbers in python

I have to calculate the ratio between 0.000857179311146189 and 0.026955533883055983 but am unsure how to do this other than by dividing the two numbers. Is it possible to calculate this with the result…

Built-in variable to get current function

I have a lot of functions like the following, which recursively call themselves to get one or many returns depending on the type of the argument: def get_data_sensor(self, sensorname):if isinstance(sen…

Python run from subdirectory

I have the following file hierarchy structure:main.py Main/A/a.pyb.pyc.pyB/a.pyb.pyc.pyC/a.pyb.pyc.pyFrom main.py I would like to execute any of the scripts in any of the subfolders. The user will pass…

How to create duplicate for each value in a python list given the number of dups I want?

I have this list: a=[7086, 4914, 1321, 1887, 7060]. Now, I want to create duplicate of each value n-times. Such as: n=2a=[7086,7086,4914,4914,1321,1321,7060,7060]How would I do this best? I tried a lo…