Search This Blog

Monday, September 17, 2012

Challenges faced

My application's modules,

  1. Race game
  2. Cows and Bulls
  3. Bubble break
Challenges faced:

1.Race game:
  • Animation done using setInterval is not optimized. It lead to slower processing. Overcome by using animation frames, an option provided by all major browsers to optimize animations in canvas.
  • Cross browser compatibility in event handling . Used jquery initially to overcome this problem. But then I knew that using external libraries is always an overhead. So used addEventListener function which works well in all major browsers.
  • What to render? Every object in the game world if rendered may pull down the game speed. Overcome by writing a function to find objects which are in current canvas view.
  • Realism: to bring realism to the game, lot of factors like acceleration, top-speed, lateral steering movement, aftermath of collision have to be considered which is challenging.  
  • Event queue maintenance: the very idea of processing events is challenging. Improper way to process may bog down the performance. Event queue is maintained to overcome this problem. 
  • Collision detection: For every loop detection algorithm has to be run in optimized way to find any collisions.
  • Gamestate and dashboard: Since pausing the game was also included the gamestate to be maintained became complex. In addition to this, when displaying time in dashboard these game states had to be kept in mind which was really a challenge.

2.Cows and bulls:
  • Dictionary words only: The guesses have to be validated against dictionary words. But the dictionary words should be loaded into the application dynamically. Overcome by using AJAX request to local dictionary file.
3.Bubble break:
  • Writing event driven code: Since i was using nowjs and nodejs everything needs to be written in a event driven way. Using callbacks and stuff which was really challenging initially.

Friday, September 14, 2012

Bubble breaker game

1.Game description:
Its a multiplayer game played over network. It keeps track of number of bubbles popped by each user. The scoreboard shows scores of every player to every other player playing the game.

2.Rules:
Bubbles are automatically generated at the rate of one bubble per 2 seconds.
On clicking a bubble it pops/breaks. One point is added for popping one bubble.

3.Implementation:
Server is written using node.js
Event driven programming approach is used.
Now.js library is also used. It allows calling of server side functions from clients and vice versa.

Cows and bulls description

1.Game description:
Aim of user is to find the target word set by the computer by guessing. Each guess will be responded by number of cows and bulls.
If an alphabet in your guess is present in the target but not in the current position then you get a cow.
If the position also matches exactly you get a bull.

2.Game rules:
There are three difficulty levels/word length (3,4 and 5).
For word length ,
3 --> no of guesses allowed is 10
4 --> 15
5 --> 20
Only dictionary words are allowed. Alphabets cannot repeat in target or guess.

3.Implementation:
Main process is,

  • get word from user
  • validate
  • display number of cows and bulls
Validation involves,
checking for character repetition, checking for correct length and checking if the word exists in dictionary.
I load dictionary into my application using AJAX request and then use it rest of the time.



My race game description

1.Race game description :
Aim of user is to take his car to finish line in least time/position possible .

Controls:
up --> accelerates the car
down --> brake
left -->steer left
right --> steer right
space --> pause the game

Rules:

  • User car starts always at last position
  • Car has a health of 100. Each collision reduces health by 25
  • On health becoming 0 user car explodes and game finishes
  • Collision with other cars result in explosion of those cars. This also reduces user car speed by half.

Other details:

  • Steering left and right is free when speed of car is low. It becomes more constrained at higher speeds
  • Car cannot accelerate beyond top speed.
  • Steering away from road is not possible.
  • Braking produces drastic speed reduction when compared to stopping acceleration

2.Main parts of Source code:

Classes:
Car , road divider, trees are all functions , which acts as classes to generate objects

set functions:
The set functions initialize attributes of objects and other elements.
eg: setCanvas function initializes canvas, gets context etc...

draw functions:
The draw functions are called during rendering part of game loop. 
eg: drawObstacles will draw other cars in the updated position.

event handlers:
Interaction with the game is only possible because of these event handlers.
window. addEventListener() function is used to add event handlers for key down , key up events.
Then in the handlers, the events are just pushed to the event queue. No state change or drawing is done here.

process events:
Brain of the game ! For each instance of gameloop one event is popped out and is processed. For example, if key down is the event and the key pressed is right arrow , then the flag which says the car is moving right is set to true and that's it. Drawing is not done here too! draw function sees this variable/state change and moves car position to right accordingly.

state variables:
Game state is maintained and updated using variables. For eg, gamestate = "paused" 

The Game Loop:
Here lies the heart of the game. This loop runs at the rate of 60 fps. Its done using setInterval. For optimization requestAnimFrame is used.
Game loop does the following,
  • process events
  • updates state variables
  • clears the canvas
  • draws objects
3.The dash board:
Apart from canvas there is a table showing game details , pretty much like dash board.
Contents of dashboard are,

  • Distance covered -> based on pixels , updated for every gameloop
  • Position --> based on how many cars have been overtaken. Updated for every gameloop.
  • Speed --> based on car speed. Updated for every game loop.
  • Health --> based on number of collisions. Updated once a collision is detected.
  • Time --> updated every second.


Monday, September 10, 2012

The racing game

In today's post i will tell about the racing game i am creating. The game is almost complete. I will now explain what are the features i added and how it came out. 

Objects everywhere !
If you wanna learn Object oriented programming, start developing a game. It comes naturally. Its always easy to identify objects in game. For example in my game, car,obstacles,trees,road dividers are objects. It's easy to implement this way instead of having global variables for every thing(its almost impossible to do it that way!). So most of the time my refactoring process would include making the code more object oriented and reusable. Main advantage of doing that is the flexibility you gain. In games many times you need to scale up and down variables. Unless you go for a modular , object oriented approach you would certainly fail.

Event Handling --> look out for cross browser compatibility
In any game human computer interaction is done using some event handling mechanisms. In Javascript you can perform event handling in lot of ways. Most of the times it will not work in all browsers in the same way you expected.
-->One simple solution is to use jquery library to handle events. The compatibility issues are taken care by jquery function itself.
-->Next solution is make your event handlers work somehow. For me adding event listeners in the following way worked like a charm in all browsers,

window.addEventListener('keydown',doKeyDown,true);

then you write doKeyDown function as,

function doKeyDown(event)
{}

To find the key which has been pressed down you do,

event.which

it gives the keycode of the key pressed.
For example,
if(event.which==32)
{
    alert("you pressed spacebar");
}

Processing events
Handling events is just the beginning of a very important job called processing events. After a key is pressed you may wish to do something. For example, after pressing left arrow you may wish to turn your car left.
What beginners mostly do is( i say this because that's what i did quite a few times before knowing the right way to do it) do all the processing inside the event handle function itself. Games doesn't work that way at all !!
The correct way to process events is to, 

  • add events to an event queue 
  • in every instance of gameloop remove an event from the event queue and process it
Unless you do this kind of implementation, some events wont be caught and it may ultimately affect the performance of the game.

The canvas 
Canvas is the place where you will show your game. That's where you can draw stuffs , put images etc... While developing the game i developed it using constant height of 500px. I used 500 in my calculations everywhere. But after the game came out well, it looked small. 
The way to proceed is to expand the canvas in CSS. You give more height to the canvas in CSS it automatically expands the canvas to that size. However number of pixels still remain the same.
In this way you can save processing power too :P
Some browsers do anti-aliasing themselves when we expand canvas like this.

More concepts in posts to come ! see you in next post.


Thursday, September 6, 2012

HTML 5 gaming

Few people around me were working with HTML 5. After seeing those cool stuffs it was irresistible to start working in it. Canvas element is the most attractive part of HTML5 according to me. Using it we can develop very cool stuffs like animations and games!
I decided to develop a game. I was playing Road Fighter ( classic nes game, which makes me nostalgic whenever i play it now ) yesterday night. So i thought of developing a similar game.
Games require lot of intelligent coding. I was introduced to game development basics by a colleague. So i don't use while(1) for looping infinitely anymore.
I started of with a simple gameloop for which i set an interval of 1000/60 . Which means the loop runs again and again after 1000/60 milliseconds. (ie)  1/60th of a second. This gives us 60 frames per second speed in which our game runs.
Inside the game loop i called functions to drawlines and then clear the canvas.
By drawing lines vertically and moving it down for every loop i had a road movement like effect.
Next i placed mycar at the bottom of the canvas.
Used jquery to capture key press and moved the car left and right based on keys i press.
Finally made another car to come in opposite direction.
Still lot of things left to be complete, but before moving any further i thought of refactoring my code.
At this point i came across requestAnimFrame function which gives smooth animations in html5.
It took some time to figure out how to use the Animation frame. It works like this, our gameloop has to be given as a callback function to the requestAnimFrame event of windows. Inside the function which gets called when we request a animation frame, we setInterval of 60fps and call our gameloop after getting a new animation frame each time. I don't know how exactly it speeds up my animation/game. But i will research and tell you soon.
Stay in touch. See you in next blog.

Cows and Bulls : back to JavaScript

No ROR today. My aim for the day was to develop cows and bulls game. Sadly many friends of mine didn't know about the game! Its a very popular time pass game in school.

http://en.wikipedia.org/wiki/Bulls_and_cows

check this link to know the rules of the game :)

What i did is basically a word game. The word to be guessed correctly can be a 3 or 4 or 5 letter word . User's can adjust word length.
So the major problem here is , the words chosen by computer and words given by users as guess should be all proper English words.
To solve this problem,

  • i downloaded a text file containing all dictionary words
  • made a new file containing words of length only from 3 to 6 using grep command
  • from inside the webpage sent a xmlhttp request (AJAX request) to the local file
  • fetched the words and loaded them into array
  • used this array to check if the word entered by user is a proper english word
The solution worked perfectly on Firefox. Chrome didn't allow AJAX request to be sent to some local file. Seems like they are strict with security issues associated with accessing resources in local system.
I have to find some workaround for making the game work in Chrome.

To add more spice to the game, i implemented a scratch pad kind of thing ( using tables) which has all 26 English alphabets. Users can mark them red/green so that they can easily track what alphabets are rejected(red) and what alphabets are present(green).

It looked like a small application when i started coding. But it took one full day to fix all bugs and make it work smoothly in a user friendly way.Wrote the game from scratch using pure JS and html.
I shall share the code with you soon.
See you in next post with more interesting applications :)

Tuesday, September 4, 2012

ROR strong and steady


My experience:
Today opened my project again and decided to do a bit of refactoring. The command
rake routes
was very helpful. I saw the route name there and modified my redirect to statements. Code became more readable and clear.
Then came the devise problem. Controller of devise was nowhere to be seen ! After sign out i wanted users to be redirected to home page. But how do i do it without the controllers of devise. (for those who don't know devise,.. its a gem which helps in implementing authentication in your application) After a bit of googling i found that everything i needed to know about devise is in wiki page of devise in github itself!
by implementing the following private method in application_controller i was able to control the redirection.


  def after_sign_out_path_for(users)
    home_path
  end


in routes i have written this,
 get "/home/index", :to=>"home#index", :as=>"home" 
so everything works nicely as expected !
after the user signs out , action: index of controller: home is called.




Monday, September 3, 2012

ROR more concepts

Control over caching:
ActiveRecord comes in handy for doing lot of operations on associated tables and models.
For example, consider the following scenario

class Person <ActiveRecord::Base

    has_many: accounts
end

class Account <ActiveRecord::Base

   belongs_to: person
end

in the above case , the following association is made,

a person has many accounts and each account belongs to one person.

This association creates many methods automatically with the help of meta programming!
one such method is 'accounts',a instance method for Person class.
we can do,
@person1.accounts
this will fetch all accounts of person1.
next we do,
@person1.accounts.size
this will tell number of accounts of person1. Normally people would expect that the above statement will run some query again to find the size. But its not the case. During first statement itself @person.accounts is cached. Next time when we do, @person.accounts.size the cached copy is only used, thus saving lot of time !
What if we specifically require to fire a new query for finding size (since some other application could have changed the database in meantime). There is a way to achieve it.
@person.accounts(true).size
will fetch the current size after executing a new query instead of using cached version of orders.

My experience today:
Probably many might not have heard about collaborative story writing . There are few websites for the purpose though. It means user's registered in the website can start writing a story and also contribute to  stories written by other users. I took up this application for learning Rails. Today is my first day. I implemented sign up,sign in and other authentication stuffs using devise gem.
Its a very neat and efficient gem for doing all sort of functionality like "forgot password" , "remember me" etc..
I designed the basic schema of my application and started coding.
I implemented "edit profile" functionality for users. It would seem very less for a day. But as i mentioned in my previous post learning curve of rails is very steep. I will be able to speed up once i get hold of Rails :)
See you in next post with more interesting stuffs! stay in touch.