Tag Archives: python

Particle Simulator

Back from the break.

I decided to downgrade my project once again, because I guess my steps weren’t of a baby sized variation. In case you’re keeping track, it’s gone from the world’s best Python Roguelike, to a top down shooter, to a pong clone, and now finally, a particle simulator! I’m pretty sure this is a normal progression, because all it means is I’m learning what I’m capable of.

So anyways, I’m looking to create a simple physics simulator to fool around with, and I got stuck on what was a simple case of not using the right variables. Typical stuff, and then tonight I got stuck on inter-particle collisions, because once I got the wall collisions working I felt pretty good about it. Little did I know, life was going to get more complicated.

Pretty much we’re back to the beginning with the endless wall bouncing, and I’m not sure why exactly. The thing that seemed to cause it, is I’m resetting the list that contains all the rects of the particles, but as far as I know, the only thing that needs to use that list is the collision functions. The reason I wanted to reset that list every frame was just because I wasn’t updating the rects in it, so every collision test was testing against the original positions of the particles. Empyting and re-filling it every frame seemed to do the trick at first, but in the end, it seems like it didn’t really help at all.

Oh well, another night I’ll work through it and get it nice and functioning.

On another note, I’m going to try to write at least 200 words 3 times a week in order to build up my writing chops, and hopefully get a bit of a helping crowd going.

Talk to you Thursday!

Pygame Rotation Tutorial

Hey there,

So what I was recently having some trouble with was with Python’s PyGame Rotate function. I was having trouble understanding what some of from the comments found here meant, or were trying to illustrate, let alone the documentation given, so I resolved to figure it out , once and for all, so hopefully this post will be enough to get someone else on track. I think I was getting caught up on the different ways to deal with blitting and surfaces and rects.

Continue reading Pygame Rotation Tutorial

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!