Section 3: Silverlight Game
Table of Contents
3.1.2Game loop
Typical Windows forms applications work in an event-driven fashion. That is, the application sits idle until an event comes which triggers some logic inside the application. Games, on the other hand, need to perform many tasks all the time, such as drawing screen, animating objects, performing AI operations, etc. Therefore, the default functionality of Windows forms applications doesn't work for games. Games need what is called "Game Loop" to let the game take control of its events and program flow.
Whether there’s a player’s input or there isn’t, the “game loop” makes the game run smoothly; any game must continue to run regardless of the player’s input, thanks to “game loop.” A generic “game loop” will look like the following pseudo-code:
while(true)
{
// 1. check for player input
// 2. execute game logic
// 3. animate sprites
// 4. resolve collisions
// 5. draw graphics
// 6. play sounds
}
This approach doesn’t work properly with the modern multi-tasking operating systems, because the game will not respond to OS events. Therefore, it will appear as “Not Responding.” In Silverlight a game loop can be implemented using the JavaScript setTimeout function. The setTimeout function takes two parameters: the first is the name of the method to be invoked after the timeout interval expires and the second parameter is the timeout interval in milliseconds. The game loop should look like the following code:
function gameLoop(){
//Perform game operations
var t = setTimeout("gameLoop()", 17);
}
The second parameter sets the game frame rate; the frame rate controls how many times per second the game screen will be redrawn. For a smooth experience most games set the frame rate to 60 FPS. The 17 millisecond timeout will approximately produce the desired frame rate.
NAVIGATION
Silverlight Resources
Program Silverlight™ apps faster and more efficiently with these free resources.

