Category Archives: Python

Brainstorm: Grids

Hey there, this post is going to be a brainstorm point in which I just type out my thoughts as they come to me about how to implement a simple grid into my pygame program.

Alright, so first off, I need a grid because I imagine it will help out in the long run for things like movement, object creation and saving/loading mechanisms. As the game’s set up for now, movement is based on pixels, so they path-finding is quite a bit slow, with 250k (500hx500w) nodes at the moment and that’s really exceptionally high and python’s not built for speed… So anyways I need to split up the screen for that reason first.

So what is a grid then? A grid, as far as I understand it, is a way to divide the game’s surface into smaller, more manageable sections. With these sections I could possibly isolate and create new arrays specific for each section which would each contain the items I’d have laying in it. You can draw images per grid section and use that to draw your game world. There’s always more.

So in order to implement the grid into my game, I need to figure out a way to code them in. So, they’re squares that need to be adjacent to each other. They should each be in an instance of some generic Grid class that will contain basic details, like vision, allow movement or not, contain items, elevation, that sort of thing.

If I were to create it I think I should create them in a “for” loop, so something like for w in screen_width, and for h in screen_height, create Grid instance. I guess that’s good for now, what if I want to create a game world that is bigger than one single screen? I’d need to create a new variable like world_width instead and use that to create a grid.

How would I store them? I used the roguebasin tutorial for python+libtcod a while back, they appended each tile to a list within a list so if you wanted a tile at co-ords: 10,10 you’d look up gridList[10][10], accessing the width list, and then inside it, the heightlist.

That reminds me though, say I do want to create an object at co-ords 100,200; how would I figure out what grid section I’m clicking in? Would each click’s co-ords need to search through the entire list of all grids, or would I append the co-ords that each grid contains as an attribute to a grid. If I do that then, what will I do when I start scrolling the screen? Wouldn’t I need to change then all the pixels inside each Grid.coords’s list? I guess I’ll have to worry about that later.

So what I’m going to do now is to create a new small script that creates that dummy grid instance for every 5 pixels which will bring down the work the path-finding has to do five times, to 50k pixels it could have to look through. I’m not sure if that’s the best way to do it for now, but it’s never written in stone.

Until next time.

UPDATE

I’ve tried doing a few things:

        for w in xrange(0, 500 +1):
            for h in xrange(0, 500 +1):
                if h % 5 == 0:
                    #every 5 pixels wide:
                    if w % 5 == 0:
                    #if newGridStart:
                        g = Grid()
                        g.coords.append((w, h))

                        #print 'created grid at ', w, h

                    else:
                        print w, h
                elif w % 5 == 4 and h % 5 == 4:
                    self.listOfGrids.append(g)
                    print 'appended', w, h

and tried to clean it up to make it look like this:

        for w in xrange(0, 500 +1):
            for h in xrange(0, 500 +1):

                if w % 5 == 0 and h % 5 == 0:
                    g =  Grid()
                    print 'new grid started at', w, h
                elif w % 5 == 4 and h % 5 == 4:
                    self.listOfGrids.append(g)
                    print 'appended grid at', w, h

                else:
                    g.coords.append((w, h))
                    print 'appended coords at', w, h

but that added way too many coords to each grid section or too little depending on which I ran.

So I thought about it some more and I’m going to go over the pixels twice. Once to get all the topleft corners of each grid, then I’m going to fill the grids up with coords based on the topleft corner co-ord. I’ll update this later, when I write out that code.

UPDATE 2

Alright, awesome, I’m pretty happy, I managed to work it out, using pretty much what I had described above. If you try to run the code yourself, you might want to comment out that print statement that shows all the co-ords in a given grid section
    def createGrid(self):
        self.listOfGrids = []

        #go through all the pixels in a game screen
        for w in xrange(0, 500 +1):
            for h in xrange(0, 500 +1):
                #if the co-ords are both muliples of 5:
                if w % 5 == 0 and h % 5 == 0:
                    g =  Grid()
                    g.origin = w, h
                    self.listOfGrids.append(g)
                    #print 'new grid started at', w, h

        print 'done gridding, now adding all the points to each grid'

        #for each grid in list, go through at add all the pixels it covers
        for grid in self.listOfGrids:
            origin =  grid.origin #origin is the top left pixel of the grid
            for w in xrange(0, 5):
                for h in xrange(0, 5):
                    x, y =  map(sum,zip(origin,(w, h)))
                    #what this is is:
                    #zipped= zip(origin, (w,h) )
                    #map(sum, zipped)
                    new_coord =  (x, y)
                    grid.coords.append(new_coord)
                    #print 'added {0} to {1} grid'.format(new_coord, origin)
            print grid.coords, 'length :', len(grid.coords)
        print 'done adding all co-ords'

Update 3

Thanks to a commenter, Matt, I have further optimized the grid code to the following which is about five(!) times less code:

    def createGrid(self):
        self.listOfGrids = []
        
        #go through all the pixels in a game screen
        for w in xrange(0, 500 +1, 5):
            for h in xrange(0, 500 +1, 5):
                g =  Grid()
                g.origin = w, h
                self.listOfGrids.append(g)
                                       
        print 'done gridding, now adding all the points to each grid'
        
        #for each grid in list, go through at add all the pixels it covers
        for grid in self.listOfGrids:
            origin =  grid.origin  #origin is the top left pixel of the grid
            for w in xrange(0, 5):
                for h in xrange(0, 5):
                     grid.coords.append((origin[0] + w, origin[1] + h))
                    
                  
        print 'done adding all co-ords'

More refactoring progress.

The work to restore functionality to my game before it was split up continues. I solved the hyperspeed problem, and have avoided properly dealing with object management up to this point.

Like I mentioned before, Wing Pro is super helpful for refactoring. They’ve got a dedicated refactoring tool than is essentially a search and replace tool, except it tries to determine whether or not self.target in one class is the same as the self.target in the other, so it will not change it by default, but you can easily click and set a new one.

I will admit refactoring like this is a pretty boring process. It’s mostly just adding a module name before most variables, but then I start to wonder if that’s the best way to do it, if I should use local objects or not, whether I should create a class that stores all the names as an attribute, but then doesn’t a dictionary do the same thing?

The problem came from decision to split it up into modules. The old code would say something like: if self != player: target player else target allOtherCreatures sort of deal. The issue was that I’d use the actual names of the objects, since everything was created in the global namespace. When I split the project up, it was no longer to available through common means. So the way I solved was add an isPlayer attribute to the player, and added all creatures into a list, which each instance used to create a target list. If self was player, then it would take all the creatures from that list and add them to its own, otherwise the target list would be culled for the instances with isPlayer == True. I suppose that I’ll have to isMob and isItem eventually, but that’s too far into the future for now.

I’ve also been trying to clean up my many print functions used for debugging, because often times I’d just use print self.target and that’s it, but I’m trying my best to change it to something like print ‘This is the target:’, self.target . I also don’t use .format as much as I could simply because I don’t like typing up {0} all the time. Lazy, I know.

No new content though to speak of, maybe I’ll create a new WP tag, just to filter out the posts with content updates or not…

Choose Your Own Adventure is completed!

This is a post about my recently completed Choose Your Own Adventure game. It was a really small program, only about 500 lines, but it was my first program that was fully functional, first program that I compiled to .exe and shared, and first one that used a few different tkinter modules. I’m going to write about what I really enjoyed doing, and what I didn’t, as well as the features, and what I plan on doing with my CYOA program in the future.

Firstly, the feature list is small, but simple:

  • A custom file parser that looks for the tags for page name, text, and choices for where you want the story to go next
  • Dynamic pages loaded from the story file that anyone can create and load.
  • Scrollbars. I added this because what list only has two items. There is scrollbars on the history frame that tracks which pages you’ve been to, and you can go to any one of them on the fly.

So anyways, what I enjoyed doing was mainly completing the project. It didn’t take very long, just a week or two of good effort, but seeing it spit out the text that we had put into the custom file there was really nice. I realized that that was the best part of programming, seeing the application behave, or do something, that you didn’t explicitly program. Seeing it successfully run through a story makes me want to try to tackle harder challenges.

I’m proud of the way it loads up each page from the file you load into it, so you can write any story you want, so long as the file follows the following template:

~[PAGE_START~]

~[page_name= First page~]

~[sheets_in= None~]

~

~[sheets_out= SecondPage, ThirdPage, FourthPage~]

~[PAGE_END~]

So, you put in a page name, the story text and the title of the next pages that you want to load up next. There’s an extraneous ‘sheets_in’ which could be used in a later feature, but right now, it is unused. There’s also the PAGE_START and PAGE_END tags which separate each page for the parser.It’s simple, and I find it to be clean and at least decently efficient even though I haven’t tried it with a story with more than 20 or so pages.

The way each page is created independently of each other, so you can jump to any given page that you’ve already navigated to, using the history bar on the side of the text. That was my first time using the listbox and scrollbar tk widget. I was surprised to learn that the scrollbar doesn’t overlay on the widget, but is actually in the adjacent column as close as possible.

I used regex on the text file with the story, but that was really tough to get right, due to my inexperience with it. Luckily I had RegExr’s help with it, followed by the Online Python Regex Tool to try the regex in actual code. Regex is definitely powerful, but its syntax is one of the least readable things for a newbie like me. Still though, I’m sure with time it’ll be easier and easier. It was probably the least fun I had with the entire program, because sometimes I was unable to understand why it would work with some strings, and not with other similar ones.

Another tool I used for the first time was Py2exe and another similar tool. I tried to use py2exe and it didn’t even run on my pc, but I’m willing to chalk that up to my vast inexperience once again. I was told over reddit in a thread I had created asking about this very thing about the best way to do this, and I was introduced to pyInstaller, which puts everything you need into one exe that you can distribute without installing any other libraries, but when I tested it on a computer without Tcl, it crashed almost immediately. Still not sure why py2installer doesn’t include that.

Finally, I am considering expanding the tool and make it a public application that anyone can use. I’m not sure there’s a big demand for it, but I feel like I can find a subreddit that would definitely be able to find a use for it. In the very least a more capable programmer would be able to turn it into something a bit more usable.

Anyways this is longer and I’m too tired to proofread it, so might as well stop here. Til next time!

 

Some progress towards multithreading

Alright,

I’ve made some good progress today. I’ve got a super basic new/load title screen that loads…well so far it only loads one new thread, but it will handle the two threads that I can think of right now, the GUI and Logic thread.

It’s been tough going to get to this point because I was really having trouble figuring out the proper module structure, but what I’ve done is kept most everything in the global space of each of the 10 or so modules I’ve got, and just use a ludicrous amounts of module.attribute calls, which means I do a lot of imports over from module import. I can’t see that being a good thing in the future, but for now it’s what I’ve got.

The project doesn’t have shooting, GUI beyond pygame or enemies yet, because the modules haven’t been fully updated yet, but so far it just looks like I’ve gotta keep renaming certain objects, which Wing makes crazy easy. I’d really like to take the time here to outline all the positives, but I really don’t have anything to compare it to, other than notepad 1. It’s got just about everything you’d need

Anyways, like I mentioned I need to update those other parts before I can start making forward progress. I imagine I’ll need to learn how to use Queues to properly sync my threads, but I’ll have to leave that for another time.

So what I’ve learned today is that globals do not need to be at the start of a function, despite what I used to think, imports are sort of tough to get right, but fairly easy once you get the hang of it, and that it still feels really good to see what you’ve made work, despite little visible change.

Module Management

In this post, I’m going to try and plan out my module layout. As it currently stands I’m only using Squares.py and GUI2.py. This is going to become something quite different, as I’m hoping to solve the namespace issue I’ve been having.

It started when I started using the popular if __name__ == ‘main’: format I decided I wanted to clean up all the initialization stuff into a particular function init()but that was not as easy as I had hoped for. In fact it broke my code enough that I am writing a post about it.

The issue is probably obvious to anyone but me, but I forgot how namespaces worked. That is, I forgot that even if you put a function in the top level of a module, all variables created therein are scoped to that function. So what that left me with, was a global scope that was free of any variable I had created in the init() function. So I took to reddit, as usual, to solve all my issues.

Luckily, the ever present user, eryksun, was around, along with others, and informed me that multiprocessing worked best with the Queue module and my two modules split up into smaller ones.

I figure that that would my scope issue because instead of just calling player.name() for example to get his name, I could call objects.player.name() and get it, from any module that has imported objects. So this is going to mean for my code a slight rewrite, but more of a copy and paste sort of deal, with several changes to most calls in my entire two modules. Which aren’t that big, keep in mind. Maybe 1500 lines total, across Squares.py and GUI2.py.

Anyways, so far, my draft is this:

–          Main, which creates the two threads for logic and GUI2, which I’m going to drop the 2 from.

  • GUI is just going to be fed stats from logic and stats, but will also be able to change some of the stats it changes. I’m not sure how to do this just yet. I’m hoping someone will drop down from the heavens and show me.
  • Logic is going to be the main game logic behind most of everything. It’s going to draw on Tools, Objects, Items, Environment, and Stats so it’s going to import a few things.
    • Tools is going to be the module for most of the my math oriented stuff, also the function for handling images.
    • Objects is going to be the module for all the characters in the game. It will rely on AI for the NPCs. Have to decide whether the character components will be created there or not.
      • AI will be in charge of the AI patterns and such, when they get developed. Like I have previously written, I cannot get a handle on A* pathfinding. I’ve really tried though, it’s just not working.
    • Items is going to handle the items in the game. So all the drops and crap will be taken care of here.
    • Environment is will be where of the world information will be handled, so the world squares, backgrounds, that sort of thing.
    • Stats is going to be where the absolute plethora of statistics will be handled. This game will have an insane amount of stats, let me tell you what.

So there you go, a quick breakdown of what I’ve got in the works for now. It’s been a fun ride so far, for the most part. I hope it keeps going.

Looks like wordpress ate my formatting from msword which is a shame. I had all the module names styled as code.