Monthly Archives: January 2012

some random musings (part 2)


what now? currently my task at work is to populate the database with flood maps of places all over the country. for those who are into programming, the task involves parsing a KML file, creating objects from it, then saving it to the database. i already got a script for it, the only thing is, i can only upload one flood map file at a time to the server. yeah, i know, i can do multiple uploads. but considering that the machine takes at least 5 minutes to store all coordinates of one file to the database. multiple uploading no longer appear appealing to me. it will most certainly cripple the machine. so i’m doing it one by one. which in turn gives me ample time to write something and update this pretty neglected blog.

so what’s for today. i figured i better not write something that involves a lot of thinking since i will need to keep focus on my work so i chose to continue sharing my random musings. as i’ve said before, i keep a record of random musings. i write it in a little journal that i never fail to carry in my bag. here’s another set of them and some short elaborations.

April 6, 2011
if you talk shit about other people when they’re not around, how can i trust you not to do the same with me?

this one’s pretty straightforward. this is maybe one of those questions that people tend to ask others the most even just in their heads. no, i won’t say that i’ve never talk bad of others behind their back before, but i think i can say that i’m always ready to utter the same words in front of them if i have to. that’s how i live my life. you may not call me kind or a good person but i know how to be responsible with whatever i do. but don’t get it wrong, even though it’s like that for me i of course still know how and when to be careful with what i say. it pays to always think things over before saying it.

April 8, 2011
sometimes we feel extraordinarily clever that we fail to see that by natural standards, we are actually acting foolish. oh what an irony.

i remember writing this after a moment of reflection and finding out that i often over-analyze things which ironically leads me far from the right thing. unfortunately it is not very easy to tell from one’s point of view when they are just giving things a good analysis and when they are over-analyzing and confusing themselves further. it would be good to have someone who can tell you to stop once in a while.

the following entry is a mix of English and Filipino because i talk a lot that way. but i’m offering a rough translation for those who cannot understand Filipino but would like to know it.

April 13, 2011
one of my best rules in life: to survive victoriously hindi mo kailangang mang-iwan. for once, h’wag nateng i-base ang achievements naten sa narating ng iba. it is way greater to know even just by yourself, na hindi ka basta basta mapag-iiwanan. self-respect above all praises.

[Translation]
one of my best rules in life: to survive victoriously you don’t need to leave others behind. for once, let us not base our achievements from what others have reached. it is way greater to know even just by ourselves, that we’re not someone who can be easily left behind. self-respect above all praises.

i remember writing this down when i encountered another person who simply won’t settle for a position because someone else occupies a higher one and they want to be just like that. i think it’s perfectly fine to desire something. but what’s disagreeable about it is when one does it out of envy. i strongly believe that self-respect should be above all praises and titles. what’s being able to snatch a place when one has to lose self-respect for it? when i do good that’s because i’m simply good or enjoying things. it is certainly not because i want to be better than someone. i prefer it that way. it keeps my conscience clean.

April 30, 2011
in every relationship, together with knowing that there is something wrong is knowing that there’s something that needs to be fixed. and knowing that there’s a problem that must be solved and working on it is way better than pretending that everything is doing well.

i posted it on a radio station’s Facebook page for it to be read to listeners. the DJ was asking for random lessons and i figured i should share it since a lot of listeners talk about love. by now you must have had the idea that the truth matters to me a lot no matter how painful or horrible it may be. that’s right, i’m like that. i just believe that the more we hide a problem, the more we make it complicated. the more we ignore it, the more it becomes painful to bear when the time comes that we had no other choice but to face it.

in life, i always try to keep things simple. like most of us, if not all, i don’t want to have a lot of “what-ifs” in life. so whenever i got the chance to think ahead and avoid complications, i make sure that i use it well. there are certain situations in life that once we’re in it will no longer be easy to think clearly. so if we got the chance to think things over at the beginning or while it is early, i think we better grab it. we may shed a tear or two but we just know it will be better that way.

May 3, 2011
it pays great to know humility. that’s why it’s one of the most difficult things to learn and re-learn.

i wrote this after observing my own attitude towards people especially those who are younger and inexperienced compared to me at work. they may have not noticed it but being very self-critical i knew there was a trace of arrogance on my actions and i didn’t like it. there are always things to learn from other people and one could miss it if he will only pay attention to himself. this not to mention how difficult it is to swallow one’s pride once he was proven wrong by someone he considers inferior. setting aside the things one knows definitely clears his mind and makes him more open and agreeable to others. sadly, this realization added to my paranoia but i guess i’m dealing with it well lately haha.

i may be right or wrong about these things but either way i think people could always get something from somebody’s musings. for now let me just wish you well.

Tagged , , , , , , , ,

rendering background image using PyGame in Python 2.7


it has been quite a while since i last posted anything regarding my endeavors in game programming. the past weeks have been quite busy for i was working on the backend of another mobile application. anyway, i was able to continue studying python this weekend and inspired by Final Fantasy III which I’ve been playing using an emulator lately, I decided working on rendering more visually pleasing backgrounds. yes, you read that right, Final Fantasy III. why am i playing such an old game? i’m quite into light weight games. and i figured it would be better to start with 2D games.

this is a short tutorial on rendering backgrounds using a single image source. here’s a sample of the perfectly symmetric background i was able to produce.

Background Demo

the sample background of a 2D game

the codes are available HERE.

the source image

since i’m only working on a demo, i simply copied the source image from a game installed in my computer. that game is Deadly Sin. if we are going to create more maps just for practice, we can find good resource from the games already installed in our machines like this one.

Tile Set

the tile set from Deadly Sin

it is a 512px X 480px image composed of different tiles used in the game to create the various stages and maps.

the map

i decided to put all details of a particular place in one file and call it map. this way i can produce as many different maps as i want completely independent of the game.

import pygame
from pygame import *

# fills a 16 X 14 map with rectangles representing tiles to be rendered from the
# source images to the game display

#assigns source image
SOURCE = pygame.image.load('images/TileA4.png')

p = pygame.Rect(288, 0, 32, 32) #area of source image containing pavement
g = pygame.Rect(416, 0, 32, 32) #area of source image containing grass
s = pygame.Rect(288, 160, 32, 32) #area of source image containing sand/dirt
b = pygame.Rect(288, 320, 32, 32) #area of source image containing bush

#matrix containing the pattern of tiles to be rendered
MAP = [[p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p],\
       [p,b,b,b,b,b,p,p,p,p,b,b,b,b,b,p],\
       [p,b,b,g,g,g,g,p,p,g,g,g,g,b,b,p],\
       [p,b,g,g,g,g,g,p,p,g,g,g,g,g,b,p],\
       [p,b,g,g,g,p,p,p,p,p,p,g,g,g,b,p],\
       [p,b,g,s,g,p,s,s,s,s,p,g,s,g,b,p],\
       [s,s,s,s,s,s,s,g,g,s,s,s,s,s,s,s],\
       [s,s,s,s,s,s,s,g,g,s,s,s,s,s,s,s],\
       [p,b,g,s,g,p,s,s,s,s,p,g,s,g,b,p],\
       [p,b,g,g,g,p,p,p,p,p,p,g,g,g,b,p],\
       [p,b,g,g,g,g,g,p,p,g,g,g,g,g,b,p],\
       [p,b,b,g,g,g,g,p,p,g,g,g,g,b,b,p],\
       [p,b,b,b,b,b,p,p,p,p,b,b,b,b,b,p],\
       [p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p]]

as shown, we first loaded the image that will be used by the map and set it as its SOURCE. next we defined the areas from the source image that we would like to be rendered on our game screen as tiles p, g, s, and b. lastly, we created a 16 X 14 matrix that will contain the tiles we created. there could have been a better way of creating the matrix that is less space complex, but i intended it to be that way so we can directly compare the matrix with the pattern we have in mind just by looking at it.

the game

unlike the previous tutorials, this game file will not make use of any user input.

import pygame
from pygame import *
import map1

DEFAULT_SCREENSIZE = [512, 448] #16 X 14 grid with 32px X 32px cell

pygame.init()

screen = pygame.display.set_mode(DEFAULT_SCREENSIZE)
display.set_caption('Background Rendering Demo')

#loops through map to set background
for y in range(len(map1.MAP)):
    for x in range(len(map1.MAP[y])):
        location = (x*32, y*32)
        screen.blit(map1.SOURCE, location, map1.MAP[y][x])

updated = False
going = True

while going:
    if updated == False:
        pygame.display.update()
        updated = True

    for e in event.get():
        if e.type == QUIT: #checks if close button was clicked
            going = False

pygame.quit()

to discuss it in detail, first we import the modules we need including the map we created named map1.py.

import pygame
from pygame import *
import map1

next, we initialize our screen and display.

DEFAULT_SCREENSIZE = [512, 448] #16 X 14 grid with 32px X 32px cell

pygame.init()

screen = pygame.display.set_mode(DEFAULT_SCREENSIZE)
display.set_caption('Background Rendering Demo')

then we go to the most essential part of this tutorial where we need to loop through our map and assign the tiles to our screen.

#loops through map to set background
for y in range(len(map1.MAP)):
    for x in range(len(map1.MAP[y])):
        location = (x*32, y*32)
        screen.blit(map1.SOURCE, location, map1.MAP[y][x])

lastly, we perform the loop that will keep the game running. note that checking if the display was updated was only done to reduce overhead.

updated = False
going = True

while going:
    if updated == False:
        pygame.display.update()
        updated = True

    for e in event.get():
        if e.type == QUIT: #checks if close button was clicked
            going = False

pygame.quit()

that’s it for this week. hope you find this useful folks!

Tagged , , , , ,

Metro Manila Flood App (MMFA)


screenshot 1 a good news came today. after months of training, the team finally got to upload its first app in the app store. i was not part of its development but i’m breaking the news just the same because i’m proud of our three people working on iOS, namely Elbert Yagaya, Lei Montas, and Pope Abella.

the team has been around for more than a year now but there weren’t much activities in the past so i can say we are pretty much still starting. and this is a good start so far. it only took an hour or so before the app got approved. well maybe that was because it’s not very complex. but it’s doubtlessly useful.

you can get the app for free at iTunes. basically it’s an app that can monitor flood prone areas around Metro Manila and send real time notifications to its users regarding the current flood situation.

screenshot 2 screenshot 3
Tagged , , , , ,

Simple Sprite Animation in Python 2.7


a picture of the simple animation

a picture of the simple animation

the codes for this simple animation can be downloaded here.

last time i posted my sample of the snake game written in Python 2.7 using PyGame. like what i already said it was supposed to be a part of my self training on python game programming and it went pretty well. i have one comment though, i was trying to accomplish a lot in one sample project. so i decided that from this week on i’ll take it one step at a time by creating tiny projects that i could use as a template when i finally have something big to code. well not really big for i’m only programming games for leisure, the more approriate term would be complex, something more complex to code. and so for my first tiny project i’m going to have simple sprite animation.

anyway, since i’m a lover OOP i decided i’ll try creating a collection of modules that will function as a class library or, if lucky, a personal framework for creating my type of python games. my plan is to build this collection in the weeks to come. so let us begin.

THE UTILITIES LIBRARY

this library will contain classes that could be useful to most if not all other classes. classes that are not part of the game design but useful in carrying out particular tasks common to most other classes. i named the file ‘lib_utils.py’ the prefix ‘lib_’ is supposed to tell which of my python files function as libraries and which are not. it currently contains only one class which is the StaticFunction class that i use for creating static methods on my classes.

#used for creating static functions
class StaticFunction():
    def __init__(self, function):
        self.__call__ = function

THE SPRITES BASE LIBRARY

the sprites base library which i named ‘lib_spritesbase.py’ will contain classes that are essential to sprite animation. currently it contains classes such as Direction, ImageSet, and SimpleSprite

Direction class

#class enumerating valid directions
class Direction():
    UP, DOWN, RIGHT, LEFT, UPRIGHT, UPLEFT, DOWNRIGHT, DOWNLEFT = \
        'Y+', 'Y-', 'X+', 'X-', 'X+Y+', 'X-Y+', 'X+Y-', 'X-Y-'

    #checks if a given direction is valid
    def is_direction(direction):

        #compares direction to provided direction values
        if direction == Direction.UP:
            return True
        elif direction == Direction.DOWN:
            return True
        elif direction == Direction.RIGHT:
            return True
        elif direction == Direction.LEFT:
            return True
        elif direction == Direction.UPRIGHT:
            return True
        elif direction == Direction.UPLEFT:
            return True
        elif direction == Direction.DOWNRIGHT:
            return True
        elif direction == Direction.DOWNLEFT:
            return True

        #no match was found
        return False

    #makes the function 'is_direction' static to Direction class
    is_direction = StaticFunction(is_direction)

if you checked out my last post, this class and the SnakeMove class mentioned there are basically the same. the only thing i did was to give it a name that is not tied into any game and add other possible directions of movement in a game like the up right, up left, down right, and down left.

ImageSet class

#stores a collection of images to be used by a sprite
class ImageSet():
    def __init__(self, img_up=None, img_down=None, img_right=None \
                , img_left=None , img_upright=None, img_upleft=None \
                , img_dowright=None, img_downleft=None):

        #direction was used as key assuring that one direction corresponds to
        #one image
        self.images = {Direction.UP:img_up, Direction.DOWN:img_down \
            , Direction.RIGHT:img_right, Direction.LEFT:img_left \
            , Direction.UPRIGHT:img_upright, Direction.UPLEFT:img_upleft \
            , Direction.DOWNRIGHT:img_dowright, Direction.DOWNLEFT:img_downleft}

    #gets the image for a given direction
    def get_image(self, direction=None):
        #parameter validation
        if direction == None:
            raise Exception('Direction cannot be null.')
        if Direction.is_direction(direction) != True:
            raise Exception('Invalid direction.')

        return self.images[direction]

it’s not that i perfectly adhere to coding standards but we know how difficult it is whenever we don’t know the right parameters to a particular function provided in a third party class library, especially when working with weakly typed languages like python. because of this i always try to come up with a form of enumeration of valid values and provide some sort of validation no matter how shallow they maybe sometimes.

the ImageSet will be used as a container of all images that a simple sprite will use. since there could be a lot of ways to pass the filenames of images to a sprite class i made it a point that the my sprite classes will only accept an instance of ImageSet.

SimpleSprite class

class SimpleSprite(pygame.sprite.Sprite):
    def __init__(self, direction=None, position=None, images=None):

        #parameter validation
        if None in [direction, position, images]:
            raise Exception('None of the parameters could be equal to "None"')
        if Direction.is_direction(direction) != True:
            raise Exception('Invalid direction.')
        if isinstance(images, ImageSet) != True:
            raise Exception('Images assigned not of type ImageSet.')

        self.imageset = images
        self.position = position
        self.change_direction(direction)

    def change_direction(self, direction):
        #parameter validation
        if Direction.is_direction(direction) != True:
            raise Exception('Invalid direction.')
        if self.imageset.images[direction] == None:
            raise Exception('No image set for given direction.')

        self.image = image.load(self.imageset.get_image(direction))
        self.size = self.image.get_size()
        self.rect = self.image.get_rect()
        self.rect.topleft = self.position
        self.direction = direction

    #must be overridden in a sub-class
    def move(self):
        pass

SimpleSprite will be the base class of my simple sprites, meaning those sprites that has only one image per direction. as shown in the code it has a change_direction function and a stub of move function. i included change_direction since a change of direction doesn’t necessarily entail moving away from one’s position. the move function on the other hand may be omitted but i chose to include it to make it appear more like a base class.

THE SPRITES

i decided to put all my sprites in one file which i named ‘sprites.py’. currently it only has one class which is the Arrow class. the Arrow class is simply a sprite with an arrow for an image. since the whole point of this mini-project is to be able to move around a surface using a sprite that changes its appearance accordingly, i simply downloaded an image of an arrow here and rotated it to point to different directions.

class Arrow(SimpleSprite):
    def __init__(self, direction, position, images):
        super(Arrow, self).__init__(direction, position, images)

    def change_direction(self, direction):
        super(Arrow, self).change_direction(direction)

    def move(self, direction=None, limits=None):
        #parameter validation
        if Direction.is_direction(direction) != True:
            raise Exception('Invalid direction.')
        if limits == None:
            raise Exception('Limits must not be empty.')

        #gets size of step and creates new position
        newposition = self.position
        if direction in [Direction.UP, Direction.DOWN]:
            stepsize = self.size[1]
            if direction == Direction.UP:
                newposition = [self.position[0], (self.position[1]-stepsize)%limits[1]]
            else:
                newposition = [self.position[0], (self.position[1]+stepsize)%limits[1]]
        elif direction in [Direction.RIGHT, Direction.LEFT]:
            stepsize = self.size[0]
            if direction == Direction.RIGHT:
                newposition = [(self.position[0]+stepsize)%limits[0], self.position[1]]
            else:
                newposition = [(self.position[0]-stepsize)%limits[0], self.position[1]]

        self.position = newposition
        self.rect.topleft = newposition

as shown, initialization of this sub-class as well as the change_direction function simply calls that of the parent class or super class. also notice that the move function was overridden here. i intended the move function to be overridden because characters in game would not probably always move in the same way. once in a while we introduce characters that behave differently.

in the case of the Arrow class movement simply means moving to the next cell specified by a direction if we are going to take the whole surface as a grid.

THE CONFIGURATION FILE

i decided to have a separate file for configuration which i named ‘conf_arrow.py’. it isn’t really necessary but i decided to come up with it anyway. this will be loaded by the main game module everytime the game starts. this way, i can have multiple configurations with minimal modification to the main game module. with different configuration files i’ll be able to test different settings by simply changing a line in the main game module which loads the configuration to be used.

import lib_spritesbase
from lib_spritesbase import Direction, ImageSet, StaticFunction

class ArrowConfig:
    SCREENSIZE = [640, 480]
    INITIAL_DIRECTION = Direction.LEFT
    UPDATE_SPEED = 50
    INITIAL_POSITION = [0, 0]
    IMAGES = None
    BACKGROUND = 0

    def init():
        ArrowConfig.IMAGES = ImageSet('sprites/up2.png', 'sprites/down2.png' \
                , 'sprites/right2.png' , 'sprites/left2.png')

    init = StaticFunction(init)

in this file we set the size of the screen, the initial direction of the sprite, the speed by which the display is updated, the starting position of our sprite, the color of the background, and the set of images to be used. the ArrowConfig class will hold the configuration.

THE GAME MODULE

i named the main game module ‘arrow.py’. the filename of the module is not very crucial, i just figured i would name it after the sprite that i’m going to use in the game in it.

import pygame
from pygame import *

import sprites
from sprites import Arrow, Direction

import conf_arrow
from conf_arrow import ArrowConfig

pygame.init()
ArrowConfig.init()

#global variable initialization
updatetime = pygame.time.get_ticks() + ArrowConfig.UPDATE_SPEED
screen = pygame.display.set_mode(ArrowConfig.SCREENSIZE)
isdone = False

#sprite initialization
arrow = Arrow(ArrowConfig.INITIAL_DIRECTION, ArrowConfig.INITIAL_POSITION \
            , ArrowConfig.IMAGES)

while isdone == False:
    screen.fill(ArrowConfig.BACKGROUND) #color screen with default color
    direction = None
    for e in event.get():
        #checks key press and sets direction or end game
        if e.type == KEYUP:
            if e.key == K_ESCAPE:
                isdone = True
            elif e.key == K_UP:
                direction = Direction.UP
            elif e.key == K_DOWN:
                direction = Direction.DOWN
            elif e.key == K_RIGHT:
                direction = Direction.RIGHT
            elif e.key == K_LEFT:
                direction = Direction.LEFT

            #if sprite is facing wrong direction replace with appropriate sprite
            #else move sprite by one step to specified direction
            if arrow.direction != direction:
                arrow.change_direction(direction)
            else:
                arrow.move(direction, ArrowConfig.SCREENSIZE)

    currenttime = pygame.time.get_ticks()
    global updatetime
    if currenttime >= updatetime:
        screen.blit(arrow.image, arrow.rect)
        pygame.display.update()
        updatetime = currenttime + ArrowConfig.UPDATE_SPEED

since the contents of this module is pretty long. let’s try to take it few lines at a time.

import pygame
from pygame import *

import sprites
from sprites import Arrow, Direction

import conf_arrow
from conf_arrow import ArrowConfig

the first few lines are used for importing classes from the other modules mentioned earlier. observing the import lines, it is noticeable that i used * when importing from pygame. to be honest here i still don’t know the classes i need for a game by their names so i simply included all. however the following import lines are generally preferred since it specify the classes to be used from one class library and/or module. it will reduce ambiguity and possible overhead.

pygame.init()
ArrowConfig.init()

what follows is the initialization for pygame and our configuration.

#global variable initialization
updatetime = pygame.time.get_ticks() + ArrowConfig.UPDATE_SPEED
screen = pygame.display.set_mode(ArrowConfig.SCREENSIZE)
isdone = False

#sprite initialization
arrow = Arrow(ArrowConfig.INITIAL_DIRECTION, ArrowConfig.INITIAL_POSITION \
            , ArrowConfig.IMAGES)

next we initialize some variables to be used in the game. ‘updatetime’ holds the next time by which the display will update, the ‘screen’ represents the game screen, while ‘isdone’ states whether the game is over or not. ‘arrow’ on the other hand represents our sprite.

the implementation of the game flow is just a little simpler than the sample snake game.

    screen.fill(ArrowConfig.BACKGROUND) #color screen with default color
    direction = None
    for e in event.get():
        #checks key press and sets direction or end game
        if e.type == KEYUP:
            if e.key == K_ESCAPE:
                isdone = True
            elif e.key == K_UP:
                direction = Direction.UP
            elif e.key == K_DOWN:
                direction = Direction.DOWN
            elif e.key == K_RIGHT:
                direction = Direction.RIGHT
            elif e.key == K_LEFT:
                direction = Direction.LEFT

            #if sprite is facing wrong direction replace with appropriate sprite
            #else move sprite by one step to specified direction
            if arrow.direction != direction:
                arrow.change_direction(direction)
            else:
                arrow.move(direction, ArrowConfig.SCREENSIZE)

first, the screen will be filled by the set background color in our configuration file. next, we are going to check if any key was pressed. if ‘esc’ was pressed, we need to end the game by setting the ‘isdone’ variable to True. Otherwise, we get the direction then change a sprites direction or move it.

	
    currenttime = pygame.time.get_ticks()
    global updatetime
    if currenttime >= updatetime:
        screen.blit(arrow.image, arrow.rect)
        pygame.display.update()
        updatetime = currenttime + ArrowConfig.UPDATE_SPEED

we then check if it’s already time to update the screen. if it is, we update the screen and set the next update time. else we’re going to do nothing.

if you got Python2.7 installed with PyGame. you can try running this game template by downloading the code here. by default .py files open with python so you can just double click on ‘arrow.py’. or you can open console, redirect to the folder where you saved the files then type ‘python arrow.py’.

feel free to comment on this post. have a nice day everyone!

Tagged , , , , , , ,
Follow

Get every new post delivered to your Inbox.

Join 39 other followers