Quantcast
Channel: sivasantosh
Viewing all articles
Browse latest Browse all 10

Handling resources in pygame

$
0
0

A resource should be loaded only once in a game and it should be when the resource was first needed.

Resources in a game typically are images, audio, font etc. Generally there is a heavy reusing of resources in games so you need to make sure this is how resource loading in done.

This is how it’s done.

  1. Declare a global variable, like all_resources_in_game, which keeps track of the resources loaded in the game. Make sure it is a Hash Table.
  2. Declare a global function, like get_resource(filename), which checks if the resource is loaded. If it’s not loaded then load the resource. Return the loaded resource’s reference.

Everytime you need to access an image resource we will use get_image_resource() method.

Here’s how it’s done in the code. Even though the below code doesn’t have a pygame related stuff it can be easily implemented in it.

all_resources_in_game = {}

def get_txt_resource(handle):
    global all_resources_in_game
    if (handle not in all_resources_in_game):
        print 'loading resource ...'
        all_resources_in_game[handle] = 'resource : '+handle
    return all_resources_in_game[handle]

print get_txt_resource('c')
print get_txt_resource('c++')
print get_txt_resource('java')
print get_txt_resource('java')
print get_txt_resource('c')

The get_txt_resource() can be a get_image_resource() or get_audio_resource() or get_font_resource() depending on the type of resource you are handling.

I am guessing that this is how you avoid long loading times at start of a game. And unless your game is hogging the computer you won’t see any lag in gameplay with this technique.



Viewing all articles
Browse latest Browse all 10

Latest Images

Trending Articles





Latest Images