Append List in a Class


from sys import exit
from sys import argv
from random import randint
from textwrap import dedent
from os.path import exists
from datetime import datetime, timedelta, date
import time

class Timer():
    def timer(self):
        pass

class Scene():
    def enter(self):
        exit(1)

class Engine():
    def __init__(self, universe_portal):
        self.universe_portal = universe_portal

    def play(self):
        current_scene = self.universe_portal.opening_scene()
        last_scene = self.universe_portal.next_scene('finished')

        while current_scene != last_scene:
            next_scene_name = current_scene.enter()
            print(">>> SCENE", next_scene_name) #finds bugs
            current_scene = self.universe_portal.next_scene(next_scene_name)
        current_scene.enter()


class Death(Scene):
    def enter(self):
        pass

class Inventory(Scene):

    inv = []

    def enter(self):
        print(dedent("""
        This is your inventory
        """))
        print(inv)

        return 'portal'

class Portal(Scene):

    def enter(self):
        print(dedent("""You are safe at home. What do you want to do?
    [ Check Inventory ] [ Adventure ] [ Brew ]
        """))

        choice = input("> ")

        if 'inventory' in choice.lower():
            return 'inventory'

        elif 'adventure' in choice.lower():
            return 'adventure'

        elif 'brew' in choice.lower():
            return 'brew_system'

        else:
            print("DOES NOT COMPUTE")
            return 'portal'

class Adventure(Scene):

    def enter(self):
        print(dedent(""""
        Where shall we start our adventure?
        [ Rivers of Plenty ] [ Sugar HELL ] [ Ginger Forest ]
        """))

        space_travel = input("> ")

        if 'rivers' in space_travel.lower():
            return 'rivers_of_plenty'

        elif 'hell' in space_travel.lower():
            return 'sugar_hell'

        elif 'ginger' in space_travel.lower():
            return 'ginger_forest'

        else:
            print("CANNOT COMPUTE")
            return 'portal'

class BrewSys(Scene):
    def enter(self):
        pass

class RiversOfPlenty(Scene):

    def enter(self):
        print(dedent("""
        You are soaked. Goddess appears before you. I grant you the power of clean water."""))
        inv.append('water')
        return 'portal'

class SugarHell(Scene):
    def enter(self):
        pass
    def SweetSatan(self):
        pass

class GingerForest(Scene):
    def enter(self):
        pass
    def GingerElve(self):
        pass

class Finished(Scene):
    def enter(self):
        pass

class UniversePortal():

    scenes = {
        'portal': Portal(),
        'inventory': Inventory(),
        'adventure': Adventure(),
        'brew_system': BrewSys(),
        'sugar_hell': SugarHell(),
        'rivers_of_plenty': RiversOfPlenty(),
        'ginger_forest': GingerForest(),
        'finished': Finished()
    }

    def __init__(self, start_scene):
        self.start_scene = start_scene

    def next_scene(self, scene_name):
        val = UniversePortal.scenes.get(scene_name)
        return val

    def opening_scene(self):
        return self.next_scene(self.start_scene)

inv = Inventory()
a_universe = UniversePortal('portal')
a_game = Engine(a_universe)
a_game.play()

I have had a really hard time getting back on track after stopping at ex. 43 trying to do my own game. I wanted to incorporate other topics learned, like appending in a list, pulling from a file, writing in a file… I think I bit off more than I could chew and I am have walked away from it so many times that I have forgotten a lot of what I learned. I do not know what the best course of action is. Should I move on to the next topic? Where should I restart? Where can I find a good summary?

Wrap your code in code tags:

[code]
# your code
[/code]

I would go back to a few exercises that cover what you feel you’ve forgotten. Don’t move on just yet, you’ll just get more frustrated. Feel free to ask any questions! :slight_smile:

1 Like

You’re not alone. I’m also getting fatigued at ex 43 and looking for other distractions. I’m sure there’s some self sabotage psychology going on here somewhere…

1 Like

I suspect it’s connected to the fact that at this point you are kind of asked to do things on your own. No more short and clear tasks to follow… It might help to try and become very organized with what you want to create. Learn to break it up into a roadmap of sub-tasks and stay focused on that. That’s really a crucial skill, not only for programming!

1 Like

I think it is embedded in Object Oriented Programing. The more I read or watch about OOP, the less I know, so I just jumped back to exercise 38 and working my way back slowly, trying to understand more than I did the first time around.

Can you please send some resources that have helped you to break it up into a roadmap of sub-tasks? Thank Florian, I appreciate your support.

Checkout Zed comment in a recent post on JSON.

It’s the approach he promotes in MorePy and it’s useful to follow:

Alright, you’re trying to think in code but you need to start with plain old English:

# open the config file
# read the file contents
# convert to json

Then translate that to pseudo-code:

# with open config.json:
# contents = config.read()
# data = json load(contents)

Then translate that to Python:

# with open config.json:
with open('config.json') as config_file:
    # contents = config.read()
    contents = config_file.read()
    # data = json load(contents)
    data = json.load(contents)

Then delete the comments once it’s working:

with open('config.json') as config_file:
    contents = config_file.read()
    data = json.load(contents)

Write out what you want your program to do in plain English comments, then slowly translate those comments to working Python. Next tip:

Run this repeatedly as you do it. Each line of Python that you can run you should run. Remember you can use pass to make an empty block:

with open('config.json') as config_file:
    pass

Run that, then add the next line, run that, then add the next line, run that. I think I run my code about 2 times for every 1 line of code I write. I run it so often I have another program that just automatically runs my code when something changes.

Now, you have the desire to “read my config, change it, write my config”. Each of these would be one operation, and you would write them out like I did above, running it each time to make sure it works.

You should also type in all of the examples from the docs to study the library:

https://docs.python.org/3/library/json.html

And, if you’re going to load the contents you want to use json.loads instead. That means I would do this so you can figure it out:

# open the config.json
# read the contents
# print out the contents
# use json.loads() to convert to Python dict (NOTE: loadSSSSSSS)
# return the loaded dict

That will help you debug it, and you should do the reverse process.

Final final note: I see you might be doing this thing where you hit a problem and immediately come asking for help. Try to spend at least 48 hours solving it yourself, and write down what you did to solve it. There’s no way you spent enough time working this between when I replied and when you wrote this. You should put in at least a couple days trying different things, googling errors, printing everything, and trying to solve it.

See you in a few days.

1 Like
A free service run by Zed A. Shaw for learncodethehardway.org.