30 December 2015

The tricks to a good HTML5 game - Part 2 - Clearing and Redrawing

Space Zombies v1.8.0 
     Making an HTML5 game has its own quirks, there are things that work , and things that seem like they should work sometimes just don't work.As I worked on Space Zombies ,I experienced this first hand, there were times i was frustrated after looking for days for a solution to some of the issues i faced. If you plan on making an HTML5 game and this is your first time , this series of posts will surely be of use to you.

Note: This is part 2 in a series of posts , read the first part about animations and game loop here..

25 December 2015

The tricks to a good HTML5 game - Part 1 - Animation and game loop

    Making a game in HTML 5 without using a game engine is perhaps not the easiest way to do things, but it definitely makes it much more of a learning experience.This series contains few of the things that I had to learn the hard way in the process of making my Space Zombies game .

This post is about getting fluid animations and proper game loop execution.

Always use requestAnimationFrame for animating 

       In a game, one of the most important things are the visuals and the animations , and requestAnimationFrame makes it not only easy to implement and manage but keeps your HTML5 game efficient.

Earlier method of animating would be to use setInterval for redrawing animations after x milliseconds , but the display would refresh at its own set rate, typically 60Hz , leading to unnecessary redrawing, which the user would not even see, as shown in the above image.

With raf the browser will automatically try to ensure you have a refresh rate equivalent to the monitor refresh rate, typically you should get close to 60fps , but that depends on multiple factors.But it will certainly reduce if not eliminate the unnecessary redraws.What's most important is that this method of animating makes your animations battery and CPU friendly, while also giving you performance improvements. The usage is pretty straight forward too.
function render() {
//your rendering code
you can read more about raf and why it's better  here , and for a polyfill visit here.

Use requestAnimationFrame only for rendering

     One easy to make mistake while using raf is to put all your update code and your rendering code in the same function that you are using with requestAnimationFrame , while this seems like a nice idea for repeatedly running your game logic , it's a bad idea for multiple reasons ,
  • Based on device resources, raf will have varying delays between subsequent calls to your function.Putting all your update logic here will mean that the game will run at unpredictable speeds,with speeds varying not just between devices, but even among different runs on the same device.For good user experience, you want there to be consistency in how fast your game runs.
  • Putting all your update logic in a function that you expect to be called every ~20ms , will usually mean that, you'll have a longer execution time for the function itself, leading to frame drops and choppy graphics.
  • Using raf only for rendering, will allow you to update the game at an almost constant rate using JavaScript timing functions, which you can control.
    Basically you get better control over your update speed.
See the above demo here ,in the demo the raf is running at a maximum of 60 updates per second , but the setInterval can be controlled to run at even 100 updates per second, leading to faster updates,the difference is much more easily seen on a mobile device,where sometimes the raf update rate goes well below 40 updates per second.

So we've seen how to get a consistent  game loop and  an efficient redraw method.In the next part , we will deal with improving the frame rate of your game. In the mean time, i would appreciate it , if you tried and rated my game Space Zombies on google play

Looking for a way to monetize your android or Ios app ? I've been using Startapp , and its fairly easy to integrate and they have bonus cash to earn based on your current earning , they support multiple platforms , from HTML5 to JAVA application to Unity  , give them a shot !

10 October 2015

Install OpenCV on Ubuntu for computer vision fun

      This is a guide i'm putting together for a friend , on setting up OpenCv for use in python on Ubuntu. Now , i'm sure there are other ways to do this , but this is the way i followed , and it worked for me .

17 September 2015

Blokky - A color matching game

A while back i read up on data structures like stacks , queues and graphs  and wanted to try them out as a mini project , in 7-8 hours spanning over 2 days , I had made Blokky .

 It's a simple game with simple mechanics , you click the group of a color and the group vanishes , the level ends when u have no valid moves left , if the number of blokky(the color blocks) left after u have no moves left is smaller than the level you're on , then u are allowed to progress to the next level.Each level adds another color to the palette , so the game gets progressively more challenging however there is the ability to undo your moves at the cost of half your current score , redo is free though.

19 July 2015

Making a Python game - Start and end screens - Part 4

Last time in this series, we got the game to the point , where it seems like it is finally playable.But as the game's programmer some things are obvious to to you and me that wouldn't be that obvious  to someone else , they might even have no idea what to do !
so we shall add a start screen , with instructions on how to play.
we also saw that the game quits too quickly after the player hits the obstacle , we don't even get to final score !,
so, we shall add an end screen to display this final score as well as the current game speed.

Let's begin by adding some constants and variables to store our game's instructions and states

The constant "STARTSCREEN_TEXT"  stores the entire instructions you want to display on the startscreen  , divided in multiple pages and lines, ready to be displayed on the screen.

The variable "startstate" stores the page number on the start screen.

Next, we will add the startscreen and endscreen functions to the game.

startscreen displays the first page of the "STARTSCREEN_TEXT" and waits for a key press , if "space" is pressed then it moves to the next page , else if "esc" is pressed it skips the start screen and directly enters the game

endscreen simply shows the score and the game speed and waits for the player to press "esc" , on doing so it will quit the game.

now that our functions have been defined , we will integrate them in our game.
we need to show the start screen , before our game loop and the endscreen after our game loop, so we call these functions in these respective positions.

now , try running the game , you will see something like this ,

The startscreen.
The game play , is exactly like the last version

The Score and speed displayed after crashing into an opponent

you will see that the game looks really good at this point , however , we still need to add an option to replay the game,instead of just quitting the game after the player loses. that will require some restructuring of the code. but we'll leave that for some other time
The code for this post can be found at the Git repo in the file "Cgame_part3.py"

14 July 2015

Making a Python game - Obstacles - Part 3

In the previous posts in this series , we have seen the following parts to making our game.
  1. Setting up our system
  2. Basic input and output
so far our game displays as such :

Now let's add the obstacles , so we need to keep in mind the following :
  • We need to move the screen so that the generated objects move towards the player.
  • We need our obstacles to generate randomly , but not block the player's route completely .
  • We need to give player points for dodging every obstacle, for the score.
  • We need to progressively increase the rate of the obstacle generation , and movement speed ,making the game harder to play as time goes on.
lets look at the additions to the code , now that we know our objectives ,

first of all , we need to import new modules, "time and random".

import mlcd,pygame,time,random

the "time" modules provides us timing functions so that the logic runs at a set "speed" and "random" module allows us to make random decisions.

next , we will add some more constants and variables.


"OBSTACLE_CHAR" stores our obstacles, again like the "PLAYER_CHAR" it can be changed ,just keep it a single character. "game" dictionary stores the movement speed, current level and obstacle count for the game."lasttime" and "curtime" , store the time to check if the game logic is running at a certain speed (not faster than human capability)

now we begin by adding the speed check for our game logic,inside the game loop,
we get the current time and see
if 1/speed time has passed,if yes then update 

variable for lasttime and then run the code for logic.

The above section of the code , checks if the player and the obstacle are at the same column, and if true , updates the values for score,level and speed being on the same line means from next cycle the obstacle cant cause any problems for the player , hence we also remove it from the count of current obstacles.

we now move every character (except for player) one position to the left,but you  will realize that once we do that, the leftmost characters are lost and the rightmost positions have no new values(the old ones are garbage for us). so now we need to add  new characters to the rightmost position , which will either be blank space(" ") or our "OBSTACLE_CHAR" in a random fashion, provided it doesn't block the path  completely.The code for doing this is here.
Now,all we are left to add is the obstacle collision,
#check for collision
if screenbuff[player["line"]][player["position"]]==OBSTACLE_CHAR:
done=True #player lost
after the "done=True" you may also add a "print" statement to display the final score in your console , however we will add a start screen , instructions and an endscreen which will display the code and instructions on how to play the game on the LCD itself, in a future post. Here are some screenshots of the game ,as it is now,
Code for this post is available on the git repo as the new file "Cgame_part2.py"

11 July 2015

Making a Python game -Basic I/O-Part 2

In the previous post , we setup our system and prepared our working directory , in this post we will begin with coding a few key components of the game , and see how they work.
  • Open the "Cgame_part1.py"  by right clicking and selecting "edit with IDLE" , or you may use notepad if you prefer , i just like using IDLE because u can run the programs directly.

  • You can download the code from my Git Repo directly , so focus on understanding what each bit does in this post.

Coding the basic components

  1. Begin by importing the modules needed for this part of the game.

    import mlcd,pygame

    This allows us to use the functions contained in these modules, so we can use them in our game
  2. Next we create a few constants and variables to store the state of our game, we will discuss them as they come up.

    This constant basically defines how our player is going to look on the screen, changing this will change the shape of our ship , you are free to play with this value, but remember to keep it a single character.
    screenbuff=[[" "," "," "," "," "," "," "," "," "," "," "," "], [" "," "," "," "," "," "," "," "," "," "," "," "]]

    This variable stores the state of that part of the screen where our obstacles and ship will be,think of it like a  virtual map of the playable area on the screen.
    These are two "dictionary" type variables to store the states of the pressed keys and the player's position and score.
  3. Now that we are done with creating the variables we need to use , we will create a function that will allow us to get the pressed keys using pygame.
    def keypress(): (refer to the code from git repo)

  4. The function first resets the keystates so that we don't get duplicate keypresses,
    then it checks the pygame key events and sets our keystate to true if the key is pressed and crosschecks it with a key up or key down event to ensure we don't send the keys if the key has been pressed and never released(which would cause the game to move things too fast).
  5. Now we can move on to the main part , the game loop,
         #initialize mlcd as 16x2 character lcd
         while not done:
             #add player to the buffer
             #ready the lines for drawing on lcd
             lines=[''.join(screenbuff[0]) + "|scr",
                       ''.join(screenbuff[1]) + "|"+str(player["score"])]
             #remove player from buffer
             screenbuff[player["line"]][player["position"]]=" "
             #get keypresses
             #modify player line (move the player) if space is pressed
             if keys["space"]:
                 if player["line"]==0:
             if keys["quit"]:
                 print("game quit")

Break down of the game loop

Before the loop begins,we set the control variable "done" to False , and initialize the mlcd display,

  1. first , we add the player to the screenbuff, so that the entire gameplay data is ready to be put on the screen ,we do this with the line

  2. with the next two lines , we create a list, containing the gameplay data , and the score , and display the entire data on to the screen.
                 lines=[''.join(screenbuff[0]) + "|scr",
                           ''.join(screenbuff[1]) + "|"+str(player["score"])]
  3. on the next line , we remove the player character from the gameplay data in the screenbuff, so that we don't end up putting the player character in it's last position.
                 #remove player from buffer

                 screenbuff[player["line"]][player["position"]]=" "
  4. Next , we get the keypresses and if space is pressed ,the player character switches lanes and if esc is pressed , we quit the loop by setting the loop condition "done" to true.this works because our looping condition is "while not done".
                 #get keypresses

                 #modify player line (move the player) if space is pressed
                 if keys["space"]:
                     if player["line"]==0:
                 if keys["quit"]:
                     print("game quit")
That ends the game loop , outside the loop block , we simply add one line to exit pygame after we are done executing everything.


Running this program displays a tiny 16x2 character lcd box like so,

and pressing the space key will switch the line of the player " > " and pressing the esc will quit the game. be sure to click the box , if your input doesn't respond , the window needs to be in focus for pygame to catch the key input.

so there you go, you have the basic Input and output of the game ready. now all we need to add are the obstacles and their movement across the screen,then we add a difficulty system and a few instructions on how to play, and our first game ,will be ready !
EDIT: added in part 3

if you are enjoying this series or have any questions , hit me up in the comments below , and i'll be glad to help

Making a Python game - Preparation -part 1

You've always wanted to make a game , but were too perplexed where to start ?  maybe you think you don't have the right tools or the knowledge to make a game ? well , i'll be honest , making a game is no simple task, but, its not impossible, i will divide the process into a series so that its digestible.

Through this series, we will see how to make a simple game for a 16x2 lcd screen and at the end of the series we will try to make an expanded version of the game for a pc or a bigger lcd display,we will not be going into the details of interfacing a lcd with your raspberry pi in this series, we will begin right on with the game, because that's the fun bit.

By the end of this series, your game will look (somewhat )like this:


Before we begin you need to set up your programming environment, we will be working with python,and some of its modules , download them and follow the installation instructions by the respective provider to install them on your system.

  1. Python 2.7.x - Python 3 may not be compatible, be sure to get 2.7.x
  2. Pygame - Install Pygame appropriate to your system for python 2.7
  3. mlcd - Download the module from Github link at the bottom of the page.

Prepare your working folder

  1. At a convenient location , on your computer, make a folder named "MyPygame"
    this is the folder that will contain all our working files for this game.
  2. Copy the mlcd module's folder in this directory , so that the module is accessible to our game.
  3. Create a file "Cgame_part1.py" , this is the file that will have all our game logic.
Now that we have downloaded all the dependencies and prepared our working folder,we can look into starting the work with our game.

The game is a simple obstacle avoidance game.we keep our ship in one of the two lanes on the screen, the randomly generated obstacles show up and the player needs to switch the lanes in time before they hit an obstacle,or it's "game over"

simple enough, right? perfect for a beginner or as a weekend project !.

Edit:Head over to the next part in this series , where we see the basic input and output of the game laid out.

07 July 2015

Prioritizing a uTorrent Download - The smarter way

So anyone who uses uTorrent knows this , at one point or the other , you end up downloading a lot of files on uTorrent and the bandwidth is shared between all those files , leading to slower download speeds for that one file you need urgently.
simplest solution is to stop all other downloads and let this one finish.However, this method has one shortcoming, u have to manually enable the next torrent you need , or your downloads will remain paused.surely,there must be some way to automate this process? Well,yes there is !

Prioritizing your downloads 

  • what we essentially want to do is get the torrent we want to download first, to the top of the list and pause all other torrents while it is downloading .Then,once that download is done , we want to download the immediate next torrent,  while pausing all the others , automatically,

but wait , uTorrent is a Peer-to-Peer download client (all torrent clients are) , meaning that instead of getting the files from some servers , it gets them from other people who have downloaded the file already and are uploading it , they are called seeders.In case there aren't any seeders available, the above configuration will lead to no torrent downloading at all.!..
There isn't a real solution to this issue, you can only hope you get enough seeders, but if you aren't getting to download your #1 file at the top speed allowed to you , you might as well download the next file in the list at the same time and so on.

so lets set up such a configuration on uTorrent , I'll be setting it up for the top 2 torrents in the list to be downloaded first , you can also use this guide to increase that number , if you have a high speed internet connection,

Setting Maximum Number of Downloads

  1. Start by opening Preferences by going into Options menu at the top
  2. In the Preferences box , click Queueing in the left panel
  3. set maximum number of active downloads to 2 , you may choose a higher number but it'll divide your bandwidth, leading to a slower ,speed per torrent.
  4. Click OK and you should see that all but two of your downloads will say "Queued" , this means they are waiting for their turn to be downloaded.
    Here ,I have a torrent "stopped" because I manually stopped it.
By default , uTorrent will select the torrent you added first as it's top priority and the next it's second and so on. if you want to override a torrent's position to make it the top priority , then you'll have to move it up the list , or to reduce its priority, move it down the list.

Changing Default Priorities

  1. Select the torrent ,whose priority you wish to change 
  2. Now move it up or down the list(Queue) by using the "move up queue" or "move down queue" buttons in the toolbar , they look like an upward arrow and a downward arrow respectively
  • Once you get all the torrents you have, downloading in the order of their priority , you can leave it unattended and it'll download sequentially,
  • The next time you add a new torrent it will be added to the bottom of this list,simply give it it's position in the queue by using the arrows and you're good to go.

05 July 2015

Writing a python module to simulate a LCD

            So recently I got a Raspberry pi and a 16x2 character LCD screen , I thought , lets make a simple game that can be played on the lcd. my first instinct was to code directly for the lcd on the pi , but as I started coding I realized that the clutter of having the lcd connected wasn't really necessary while i am programming the game's logic .

I decided to make a python module that gives me the lcd output on my monitor , this way i no longer need to work with my lcd connected and can even code the game on my laptop and test the results quickly . Moreover once im done with the coding , i can simply replace the module code , for the lcd control code , and my game is ready to deploy.

The game shall have a post for itself, for now , lets focus on the module.

Here's how to make a really simple python LCD simulator module.
  1. We begin by creating a folder , I shall name this folder "mlcd" (for mock lcd)
  2. Then we create a python file called "__init__.py" 
  3. The "__init__.py" is the file where our module code is going to be.
 so let us look at the code .

mlcd Module :
  1. import pygame
  2. def init(chars,lines):
  3.     global screen
  4.     global myfont
  5.     pygame.init()
  6.     size = [12*chars,20*lines]
  7.     screen= pygame.display.set_mode(size)
  8.     pygame.display.set_caption("Mock LCD")
  9.     myfont = pygame.font.SysFont("monospace", 20)

  10. def draw(args):
  11.     i=0;
  12.     global screen
  13.     global myfont
  14.     screen.fill((0,0,0))#erase screen contents
  15.     while(i < len(args)):
  16.         line= myfont.render(args[i], 2, (255,255,0))
  17.         screen.blit(line, (0, 20*i))
  18.         i+=1
  19.     pygame.display.flip()
The module works by using pygame to render the output , and simply has 2 functions
  1.  init(chars,lines)
    to initialize a display that is "chars" characters wide and "lines" lines in height
    this only needs to be run once.this code is designed to work with only one display
    ,however should one require multiple displays , the module can be modified to use classes
  2. draw(args)
    this is the function that draws the characters on to the screen , args is a python list (array)
    containing as many strings as there are lines . this function needs to be called again only if one wishes to update the  output.
to include this module in your python project , simply copy the mlcd folder , into your working directory and import the module

Usage example:
  1. import mlcd     #import the module
  2. mlcd.init(16,3) # initialize a 16x3 display
  3. #draw the three lines passed as a list
  4. mlcd.draw(["Hello",         
  5.            "     world",
  6.            "Mock LCD !!!"])
on running this script , we get the following output :

  •  Mono-space font is used because all characters must take equal amount of space on the screen , so changing the font might generate inaccurate results. 
  • The color of text and fontsize can be changed , however the size of the window must also be adjusted in line 6 of the mlcd module.

04 July 2015

Syncing the sound or the subtitles to the video

    Some times the sound or the subtitles on our videos just aren't properly synced with the video , basically they're either too early or too late , this takes away the entire fun from watching the Movie or the TV episode that we've waited for such a long time to watch..

Thankfully, there's an easy fix if you're using VLC media player(other players might have the feature as well) , we've already spoken about how we can download Subtitles easily using VLC media player , so let's see how we can fix the track sync as well .

  1. Open your video and click on tools in the menu bar at the top 

  2. Click on track synchronization , and you should see something like the picture below

  3. Now , depending on which track you need to sync with the video , the subtitles or the audio , use the appropriate input boxes' arrows to sync the tracks , hitting the up arrow will cause the track to be delayed and hitting the down arrow will cause it to be hastened 
  4. Keep a close eye at the video to properly sync the track with the video,you may have to wait a moment after you alter the value, to see the result in the playback window.
  5. Once you're happy with the sync , hit close and enjoy your Movie or Episode ....
if the subtitles are not staying on the screen long enough or are staying on too long , you can try playing around with the subtitle speed and duration factor to find the correct values and don't worry , should you mess up , you can always click the reset button in the upper right of the synchronization tab (the two blue arrows), to reset the tracks.


Download Subtitles Directly From Within VLC media player

      You just downloaded that latest episode of your favorite TV show on torrent, but it doesn't have any subtitles, well you have 2 options , either google for the subtitles and then try to download the right subs or use VLC media player's plugin VLSub, I'll show you how.

  1. Open the video file and pause it , on the menu bar at the top click on view .
  2. Hit "Download Subtitles" , you should see a dialog box like so 
  3. Okay , now all you need to do is search for the subs , there are two options here , "search by hash" and "search by name" , usually a search by hash will get you subs that are properly synced , but if that doesn't work , simply search by name and then correct the sync yourself (if it isn't already proper.)
    once the search is complete you should see a list of subs like this
  4. Now just select a subtitle file and hit download  , that's it ,enjoy your subs! 
The subs are downloaded and stored in the same folder as the video file , so this only needs to be done once. also u need atleast VLC media player  2.2 for VLSub to work ...

should u encounter any other issues , or if VLSub isnt installed by default , please check the VLSub plugin page

05 May 2015

Best of Logg | Coming back soon

Hey guys , I know I've been very inactive and that's because i hardly got any time from my college and studies but as more and more time passes i miss the blog more and more , so I've decided to start posting again , and what better way to kick that off , than with a list of the best and the handiest tips I've shared.

2.Google Chrome 
3.Reinstall windows silently

I will be back soon , with much more content. keep checking this space :)