adjacency matrix map manipulation - python
0
I'm making a simple text based adventure game. My code uses an adjacency matrix as a map. I would like to navigate the map by direction ex(N,E,S,W) my current attempt can only navigate via the name of the location
current output
You are currently in Foyer.
From this location, you could go to any of the following:
Living Room
Where would you like to go? Living Room
You are currently in Living Room.
From this location, you could go to any of the following:
Foyer
Bedroom 2
Powder Room
Kitchen
Where would you like to go? -__________________________________________________
I would like an output like
You are currently in Foyer.
From this location, you could go to any of the following:
South
Where would you like to go? South
You are currently in Living Room.
From this location, you could go to any of the following:
North
West
South
East
Where would you like to go?
import pygame
Inventory = []
names = ["Foyer", "Living Room", "Bedroom 2", "Full Bath", "Bedroom 3","Powder Room","Dinning", "Home Office", "Kitchen","Walkin Closet", "Hallway", "Bedroom1", "Sitting Room","Balcony", "Storage", "Garage", "Supply Closet", "Utility Closet", "Front Yard", "Sidewalk"]
graph = [[0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [1,0,1,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0], [0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,1,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0],[0,1,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,1,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0]]
directions =["North", "East", "South", "West"]
curr_location = "Foyer"
while True:
print("You are currently in ", curr_location, ".", sep = '')
print()
exits = []
print("From this location, you could go to any of the following:")
indx_location = names.index(curr_location)
for each in range(len(graph[indx_location])):
if graph[indx_location][each] == 1:
print("\t", names[each])
exits.append(names[each])
print()
next_location = input("Where would you like to go? ")
if not (next_location in exits):
print()
print("You cannot go this way.")
else:
curr_location = next_location
print()
Maybe add North, South, East, West to exits conditionally if it's possible to move in that direction?
Related
Picking a restaurant based off mood
Im trying to have python look at a list of restaurants I've made, each one being in a category (ex. McDonalds, Burger King, Canes are all in the american category). I would then like to input my mood (american, asian, chicken, etc.), and have python choose a place at random from that category. But so far it just chooses a place at random, no matter what I enter. import random # create list of food choices american = ['Mcdonalds', 'Burger King', 'Culvers', 'Wendys', 'KFC'] asian = ['Panda Express', 'Miso Japan', 'Sakura'] burger = ['Mcdonalds', 'Burger King', 'Culvers', 'Wendys'] chicken = ['Canes', 'KFC'] healthy = ['Panera'] rest = [american, asian, burger, chicken, healthy] # pick random restaurant based off mood print('What Mood Are You In?') mood = input() mood_choice = random.choice(rest) final_choice = random.choice(mood_choice) print(final_choice)
You should use a dict, storing the different categories as the keys and the list restaurants as the value. Then you can ask for user-input and select the appropriate key to get the list of restaurants which you can then feed to random.choice to get the desired result. import random food = { "american" : ['Mcdonalds', 'Burger King', 'Culvers', 'Wendys', 'KFC'], "asian" : ['Panda Express', 'Miso Japan', 'Sakura'], "burger" : ['Mcdonalds', 'Burger King', 'Culvers', 'Wendys'], "chicken" : ['Canes', 'KFC'], "healthy" : ['Panera'] } mood = input('What Mood Are You In? ') choices = food[mood.lower()] # use str.lower in case input is 'Healthy' mood_choice = random.choice(choices) print(mood_choice)
If you have several arrays, how can you randomly choose one of the several arrays?
I'm currently doing a project relating to a music playlist and I need to be able to print the first letter of a specific artist and song for the user to guess however the artist and song must be random. I have made a separate array for each artist and song but I don't know how to randomly select one of these arrays for me to use. This is my code of arrays: BTS = ["Idol", "BTS"] SWIFTY = ["Love Story", "Taylor Swift"] RUTH = ["Lost Boy", "RuthB"] ED = ["Perfect", "Ed Sheeran"] ARIANA = ["No Tears Left To Cry", "Ariana Grande"] DRAKE = ["In My Feeling", "Drake"] RICKY = ["La Vida Loca", "Ricky Martin"] IU = ["BBIBBI", "IU"] BTS2 = ["Magic Shop", "BTS"] PSY = ["Gangnam Style", "PSY"] How can I randomly choose one of these arrays?
random.choice() does the trick. import random random.choice((BTS,SWIFTY,RUTH,ED,ARIANA,DRAKE,RICKY,IU,BTS2,PSY)) You should use a dictionary, it will make your code easier to maintain if the number of tracks grows : musics = { 'BTS' : ["Idol", "BTS"], 'SWIFTY' : ["Love Story", "Taylor Swift"], 'RUTH' : ["Lost Boy", "RuthB"], 'ED' : ["Perfect", "Ed Sheeran"], 'ARIANA' : ["No Tears Left To Cry", "Ariana Grande"], 'DRAKE' : ["In My Feeling", "Drake"], 'RICKY' : ["La Vida Loca", "Ricky Martin"], 'IU' : ["BBIBBI", "IU"], 'BTS2' : ["Magic Shop", "BTS"], 'PSY' : ["Gangnam Style", "PSY"]} import random random.choice(list(musics.values()))
How to print list of lists without extra brackets and quotes?
I'm working on assignment for my Python 3 programming class. It's a database to look up movies and the year they came out. However, I'm having a hard time printing the output without extra brackets and quotes: # Build a dictionary containing the specified movie collection list_2005 = [["Munich", "Steven Spielberg"]] list_2006 = [["The Departed", "Martin Scorsese"], ["The Prestige", "Christopher Nolan"]] list_2007 = [["Into the Wild", "Sean Penn"]] movies = { '2005': list_2005, '2006': list_2006, '2007': list_2007 } # Prompt the user for a year # Displaying the title(s) and directors(s) from that year user_year = str(input("Enter a year between 2005 and 2007:\n")) if user_year in movies: for name in movies[user_year]: print("%s" % ', '.join(name)) print() elif user_year not in movies: print("N/A") # Display menu user_choice = '' while user_choice != 'q': print("MENU\nSort by:\ny - Year\nd - Director\nt - Movie title\nq - Quit") print() user_choice = str(input("Choose an option:\n")) if user_choice == 'y': for key, value in sorted(movies.items()): print("%s:" % key) print(" %s" % ''.join(str(movies[key]))) # Carry out the desired option: Display movies by year, # display movies by director, display movies by movie title, or quit I would like this output to be: 2005: Munich, Steven Spielberg 2006: The Prestige, Christopher Nolan The Departed, Martin Scorsese etc. The output I am getting: 2005: ['Munich', 'Steven Spielberg'] 2006: [['The Prestige', 'Christopher Nolan'], ['The Departed', 'Martin Scorsese']] etc.
Replace print(" %s" % ''.join(str(movies[key]))) with print("\t" + '\n\t'.join("{}, {}".format(m[0], m[1]) for m in movies[key]))
Python: How do you add a list to a list of lists in python?
I am learning python so this question may be a simple question, I am creating a list of cars and their details in a list as bellow: car_specs = [("1. Ford Fiesta - Studio", ["3", "54mpg", "Manual", "£9,995"]), ("2. Ford Focous - Studio", ["5", "48mpg", "Manual", "£17,295"]), ("3. Vauxhall Corsa STING", ["3", "53mpg", "Manual", "£8,995"]), ("4. VW Golf - S", ["5", "88mpg", "Manual", "£17,175"]) ] I have then created a part for adding another car as follows: new_name = input("What is the name of the new car?") new_doors = input("How many doors does it have?") new_efficency = input("What is the fuel efficency of the new car?") new_gearbox = input("What type of gearbox?") new_price = input("How much does the new car cost?") car_specs.insert(len(car_specs), (new_name[new_doors, new_efficency, new_gearbox, new_price])) It isnt working though and comes up with this error: Would you like to add a new car?(Y/N)Y What is the name of the new car?test How many doors does it have?123456 What is the fuel efficency of the new car?23456 What type of gearbox?234567 How much does the new car cost?234567 Traceback (most recent call last): File "/Users/JagoStrong-Wright/Documents/School Work/Computer Science/car list.py", line 35, in <module> car_specs.insert(len(car_specs), (new_name[new_doors, new_efficency, new_gearbox, new_price])) TypeError: string indices must be integers >>> Anyones help would be greatly appreciated, thanks.
Just append the tuple to the list making sure to separate new_name from the list with a ,: new_name = input("What is the name of the new car?") new_doors = input("How many doors does it have?") new_efficency = input("What is the fuel efficency of the new car?") new_gearbox = input("What type of gearbox?") new_price = input("How much does the new car cost?") car_specs.append(("{}. {}".format(len(car_specs) + 1,new_name),[new_doors, new_efficency, new_gearbox, new_price])) I would use a dict to store the data instead: car_specs = {'2. Ford Focous - Studio': ['5', '48mpg', 'Manual', '\xc2\xa317,295'], '1. Ford Fiesta - Studio': ['3', '54mpg', 'Manual', '\xc2\xa39,995'], '3. Vauxhall Corsa STING': ['3', '53mpg', 'Manual', '\xc2\xa38,995'], '4. VW Golf - S': ['5', '88mpg', 'Manual', '\xc2\xa317,175']} Then add new cars using: car_specs["{}. {}".format(len(car_specs)+1,new_name)] = [new_doors, new_efficency, new_gearbox, new_price]
You are not setting the first element go your tuple correctly. You are appending the name to the length of car specs as you expect. Also new_name is as string, when you do new_name[x] your asking python for the x+1th character in that string. new_name = input("What is the name of the new car?") new_doors = input("How many doors does it have?") new_efficency = input("What is the fuel efficency of the new car?") new_gearbox = input("What type of gearbox?") new_price = input("How much does the new car cost?") car_specs.insert(str(len(car_specs + 1))+'. - ' + name, [new_doors, new_efficency, new_gearbox, new_price])
python: local variable referenced before assignment error
I am completing a text based game for an intro to python class. It is not complete but I was working on the main_menu function and the functions called within the main_menu function when I ran into this error message. I have encountered this error several times in my learning experience and it was usually attributed to a basic mistake when assigning variables, but this one has me stumped... This is the script in question (lines in traceback commented in BOLD): import random from sys import exit # Item variables coal = ('Coal', 'some coal which can be used in a furnace.') eng_key = ('Key', 'a key to a house.') bomb = ('Bomb', 'a combustible device which creates a powerfull explosion. Possibly used for demolition...') tonic = ('Tonic', 'a weak healing tonic. Adds \'5\' health points.') sTonic = ('Super Tonic', 'a strong healing tonic. Adds \'10\' health points.') # LOCATIONS # Below are the possible locations you can 'travel' to, along with a title (first item in tuple), a description, any items that might be found in the location which can be discovered and entered into 'inventory' through 'search' command # location variable = (title, description, item for discovery) sub_base = ('Sub-Base', 'This is DeepBlue\'s base of operations in the Atlantis excavation zone. Your submarine is docked ahead', 'nothing useful here.') cave = ('Underwater Cave', 'You have entered the mouth of an underwater cave with your sub.', 'nothing useful here.') cemetery = ('Cemetery Chamber', 'You are in a large chamber within the cave. This seems to be a cemetery. There are symmetrically lined mounds of dirt, with obelisks at the head.', 'nothing useful here.') city_gate = ('City Gate', 'You stand at a crossroad of sorts, at the bottom of an upward sloping ramp.', 'nothing useful here.') city_outskirts = ('City Outskirts', 'You find yourself just outside the city walls.', 'nothing useful here.') castle_outskirts = ('Rear of Castle Ruins', 'You are standing at the rear of the castle ruins. There is a layer of rubble blocking the way, but you can clearly see a passage leading inside. Perhaps you can devise a way to move it...', 'nothing useful here.') castle_inside = ('Inside the Grand Castle of Atlantis', 'You have made it inside of the castle. All the advanced knowledge of the Atlanteans is at your disposal.', 'nothing useful here.') city_block0 = ('Beginning of Main Avenue in City', 'You are standing at the beginning of the main avenue of the city.', 'nothing useful here.') ruins1 = ('Rubble of Dilapidated House', 'You are standing in the middle of the ruins of what seems to have been a house.', tonic) mystic_house = ('Mystic House', 'You are standing inside the city Mystic\'s house.', sTonic) city_block1 = ('Second Block in City', 'You have moved to the second block of the city\'s main avenue.', 'nothing useful here.') abandoned_house = ('Abandoned House', 'You are standing in the middle of an abandoned house.', eng_key) blacksmith_house = ('Blacksmith\'s House', 'You are standing in what seems to be a blacksmith\'s building. There is a furnace, iron ore, smith\'s tools and various components for making swords. No coal though...', 'nothing useful here. But with the right items, something can be created here...') city_block2 = ('Third Block in City', 'You have moved to the third block of the city\'s main avenue.', 'nothing useful here.') marketplace = ('Abandoned Marketplace', 'You are standing in the middle of an abandoned marketplace. There might be some useful items laying around...', coal) engineer_house = ('Engineer\'s House', 'You are standing in the engineer\'s house. There might be some useful items lying around...', bomb) castle_main = ('Castle Main Entrance', 'You are standing in front of the main entrance of a huge castle. The grand entrance is blocked off by massive amounts of rubble. There must be another way in...', 'nothing useful here.') # ITEMS # below are the items which may be added to the inventory items = { coal: (engineer_house,), eng_key: (engineer_house,), bomb: (castle_inside,), tonic: ('anywhere',), sTonic: ('anywhere',) } # INTERACTIONS(location-based) # below is a dictionary of events. Each location has certain events which can only take place there. # interactions dictionary = {location: (use+item response, search response)} lEvents = {sub_base: (cave,), cave: (sub_base, cemetery, city_gate), cemetery: (cave, city_outskirts), city_gate: (cave, city_outskirts, city_block0), city_outskirts: (cemetery, castle_outskirts, city_gate), castle_outskirts: (city_outskirts,castle_inside), castle_inside: (castle_outskirts,), city_block0: (city_gate, ruins1, mystic_house, city_block1), ruins1: (city_block0,), mystic_house: (city_block0,), city_block1: (city_block0, abandoned_house, blacksmith_house, city_block2), abandoned_house: (city_block1,), blacksmith_house: (city_block1,), city_block2: (city_block1, marketplace, engineer_house, castle_main), marketplace: (city_block2,), engineer_house: (city_block2,), castle_main: (city_block2,) } # TRAVEL OPTIONS # Below is a dictionary outlining the possible places to travel to depending on where you are currently located, this peice is essential to the travel function travelOpt = { sub_base: (cave,), cave: (sub_base, cemetery, city_gate), cemetery: (cave, city_outskirts), city_gate: (cave, city_outskirts, city_block0), city_outskirts: (cemetery, castle_outskirts, city_gate), castle_outskirts: (city_outskirts,castle_inside), castle_inside: (castle_outskirts,), city_block0: (city_gate, ruins1, mystic_house, city_block1), ruins1: (city_block0,), mystic_house: (city_block0,), city_block1: (city_block0, abandoned_house, blacksmith_house, city_block2), abandoned_house: (city_block1,), blacksmith_house: (city_block1,), city_block2: (city_block1, marketplace, engineer_house, castle_main), marketplace: (city_block2,), engineer_house: (city_block2,), castle_main: (city_block2,) } def eHouseAccess(action, location, eHouse): if eHouse == 'locked': print "The door is locked! You need to find a key for this door." travel(location) else: location = travelOpt[location][action - 1] travel(location) def cInsideAccess(action, location, cInside): if cInside == 'blocked': print "The path is blocked by rubble! You need to find a way to clear the rubble." travel(location) else: location = travelOpt[location][action - 1] travel(location) def travel(location): while True: print "You are in the", location[0]+"." print location[1] print 'You can travel to:' for (i, t) in enumerate(travelOpt[location]): print i + 1, t[0] action = raw_input("Pick a destination, or enter 'menu' for the main menu: ") if action == 'menu': main_menu(location, inventory, items) else: action = int(action) if travelOpt[location][action - 1] == engineer_house: eHouseAccess(action, location, eHouse) elif travelOpt[location][action - 1] == castle_inside: cInsideAccess(action, location, cInside) else: location = travelOpt[location][action - 1] def main_menu(location, inventory, items): travel = travel(location) # **this is line 133** invtry = showInv(inventory) use = use(items, inventory) quit = exit(0) while True: print "You are in the", location[0] menu_list = [('Travel', travel), ('Inventory', invtry), ('Use', use), ('Search', search), ('Map', map), ('Quit', quit)] print "Choose one:" for (num, t) in enumerate(menu_list): print num + 1, t[0] main_choice = int(raw_input("> ")) action = menu_list[main_choice - 1] action[1] def search(location): pass def map(location): pass def showInv(inventory): if inventory == []: print "Your inventory is empty" inv = 'empty' return inv else: for (num, i) in enumerate(inventory): print num + 1, i inv = inventory return inv def use(items, inventory): a = showInv(inventory) if a == 'empty': print "There is nothing to use." else: showInv(inventory) uItem = int(raw_input("Choose an item to use: ")) location = sub_base inventory = [] eHouse = 'locked' cInside = 'blocked' hp = 20 map = """ Key: * = indicates a point of entry ______ ______ |Castle|Castle| |Outsk-| | |irts | ___|**____|__**__| | City | | | |Outsk-| | City | | irts | | | _____|*____*|___|*_____| | | | | | Grave | | City | | Yard | | Gates | |_____**|__|*______| | | | Cave | | | |__**___| | | | Sub- | | Base | |_______| """ cityMap = """ Key: * = indicates a point of entry ________ | | | Castle | | | ______|___**___|________ | | City | Engin- | |Market| Block | eer | |Place * 3 * House | |______|___ ___|________| |Aband-| City | Black- | | oned | Block | smith | |House * 2 * House | |______|___**___|________| | | City | | |Rubble| Block |Mystic's| | * 1 * House | |______|________|________| """ name = raw_input("Enter your name: ") print "Welcome to the Atlantis Excavation Zone, %s." % name print "Your first day on the job and we already have a new cave for you to map... LUCKY!" print "The DeepBlue team takes you down to the sub base. Time to get to work." main_menu(location, inventory, items) # **this is line 236** And here is the traceback: Traceback (most recent call last): File "ex36_2.py", line 236, in <module> main_menu(location, inventory, items) File "ex36_2.py", line 133, in main_menu travel = travel(location) UnboundLocalError: local variable 'travel' referenced before assignment I thought the variable had been assigned in line 133. What am I missing here?
The first line travel = travel(location) implicitly marks the name travel as local for the whole function. All look-ups for this name look for a local name, including the one on the right-hand side of the cited line. At that time, there is no value assigned to the local name, though, hence the error. There might be a global name travel, but since the compiler identified travel as a local name, it will only look in the local namespace. Use a different name for the local variable.