Next page | Contents page |

Overall game structure

Some games, such as The Forest, simply use the structure we have seen so far: user mouse and key events end in draw() but some objects, such as an elevator, are animated for a limited time, calling draw() several times but then stopping.

Other games, such as The Green, have numerous objects continually moving (birds flying, shapes rotating and bouncing around). In this case the animation is a continual loop, never stopping. The loop calls draw() every time round so user events no longer need to use that function. The following pseudocode (just an English outline) shows the structure of this kind of program.


	const DATA = {};
	
	function run()
	{
	  get the canvas, set size
	  get the graphics context
	  DATA.n = numberOfImagesToLoad;
	  start images loading from files
	  // more on images in next section
	  build the world // data and functions
	  awaitLoading();
	}
	
	function awaitLoading()
	{
	  if (still loading) // DATA.n > 0
	  // im.onload must do DATA.n--;
	  {
	    setTimeout(awaitLoading, 10);
	    // just a few milliseconds
	  }
	  else // ready to run
	  {
	    add event listeners
	    animate();
	  }
	}
	
	function animate()
	{
	  move/change objects as necessary
	  draw();
	  requestAnimationFrame(animate);
	}
		
	function draw()
	{
	  //as shown before
	}
	
	function loadImage(filePath)
	{
	  // DATA.n--; when loaded
	  // more on this in the next section
	}
	
	// and the various mouse and key listeners,
	// NOT calling draw()
Next page | Contents page |