Home > Blockchain >  Text based game. main function
Text based game. main function

Time:12-23

so I am an idiot and pretty much wrote mina code outside of the main function. Im still new and learning so when I do move code into main function I lost access to defined variables. my location and inventory because they are defined within the main function so when i try to call status() doesnt properly work. but when i move inventory and location outside of main function, inventory loses access to rooms. Can anyone point me in the right direction on resolving this issue. Thanks

def instructions():
 print("\n      Super Humans Adventure Game")
 print("-------------Instructions-------------")
 print("Collect the 6 items within the rooms to")
 print("defeat the scientist and win.")
 print("To move type: North, South, West, or East")
 print('-' * 38)


def status():
 print('-' * 20)
 print('You are in the {}'.format(location['name']))
 print('Your current inventory: {}\n'.format(inventory))
 if location['item']:
     print('Item in room: {}'.format(', '.join(location['item'])))
     print('')


#calls instructions
instructions()


def main():
 rooms = {

     'Main Entrance': {
         'name': 'Main Entrance',
         'item': [],
         'East': 'Dining Room'},
     'Dining Room': {
         'name': 'Dining Room',
         'item': ['potion'],
         'West': 'Main Entrance',
         'North': 'Laboratory',
         'East': 'Break Room',
         'South': 'Holding Cells'},
     'Laboratory': {
         'name': 'Laboratory',
         'item': ['shield'],
         'East': 'Office',
         'South': 'Dining Room'},
     'Office': {
         'name': 'Office',
         'item': [],
         'West': 'Laboratory'},  # Villian
     'Break Room': {
         'name': 'Break Room',
         'item': ['key'],
         'West': 'Dining Room',
         'East': 'Bathroom'},
     'Bathroom': {
         'name': 'Bathroom',
         'item': ['suit'],
         'West': 'Break Room'},
     'Holding Cells': {
         'name': 'Holding Cells',
         'item': [],
         'East': 'Armory',
         'North': 'Dining Room'},
     'Armory': {
         'name': 'Armory',
         'item': ['weapon'],
         'North': 'Power Room',
         'West': 'Holding Cells'},
     'Power Room': {
         'name': 'Power Room',
         'item': ['power'],
         'South': 'Armory'}

 }

 location = rooms['Holding Cells']
 directions = ['North', 'East', 'South', 'West']
 inventory = []


 while True:
     if location == rooms['Office'] and len(inventory) > 5:
         print('')
         print('You have defeated the scientist and escaped! Congratulations')
     elif location == rooms['Office'] and len(inventory) < 6:
         print('')
         print('You have reached the scientist but you are too weak!')
         print('You have died')
         break
 # shows current location
     status()
 # user input
     cmd = input('Enter move: ').capitalize().strip()
     if cmd in directions:
         if cmd in location:
             location = rooms[location[cmd]]
             print('You successfully moved locations.')
         else:
             print('')
             print('You can not go that way!')
 # quit game
     elif cmd.lower in ('q', 'quit'):
         print('You have quit the game, thanks for playing!')
         break

 # get item
     elif cmd.lower().split()[0] == 'get':
         item = cmd.lower().split()[1]
         if item in location['item']:
             location['item'].remove(item)
             inventory.append(item)
         else:
             print('There is no item here.')
     else:
         print('That is not a valid input')
    
  
main()



CodePudding user response:

You could

  • create an OBJECT called "warehouse" within Main and each item and it's inventory could be maintained within the warehouse object so you don't need it to be a subroutine, and/or
  • you could create "global variables" outside of main or your other subroutines to be defined as the code starts, or
  • You could pass a variable to your subroutines (from Main) and pass back a return value to main when the subroutine is completed.

CodePudding user response:

Passing them as parameters actually was the solution. Someone mentioned this and it was exactly what I needed. here's the update code

def status(location, inventory, rooms):
    print('-' * 20)
    print('You are in the {}'.format(location['name']))
    print('Your current inventory: {}\n'.format(inventory))
    if location['item']:
        print('Item in room: {}'.format(', '.join(location['item'])))
        print('')

then when calling the function I just filled in the parameters.

    # shows current location
        status(location, inventory, rooms)
  • Related