Skip to content

December 10, 2012

How to write a simple ajax game loop in Javascript

by e1ven

A friend of mine from the Java world has been trying to get into JS lately.

He understood the basics of how JS works – Functions look (on the outside) superficially similar to Java, it has standard loops/variables, etc.
Canvas functions are very straight forward- The part that confused him was “How do I create a game loop”, and “How do I update the page based on JSON responses from my server?”

Luckily, both of those are REALLY easy in Javascript!

I’m certainly not a Javascript expert, but I put together a simple demonstration, with an over-the-top number of comments.
GameShot

We’ll start with our very simple HTML page.
Anyone who’s done even “Hello World” should understand most of what we’re doing here.

We’re loading our JS, then three divs – Header, Game, and Footer.

<html>
<head>
    <title>This is an example</title>

    <!-- 
         Include are our JS scripts. The "defer" line just tells it to run this after the page loads.
         It's not actually needed, but it makes the initial load faster 
         We're loading in jQuery via a CDN, but copying it locally would work just as well.
         This is just one less file to deal with.
     -->

    <script defer src="http://code.jquery.com/jquery.js"></script>
    <script defer src="exampleCode.js"></script>
</head>

    <!-- 
        In the body (below), define the game however you want it to look.
        I'm using 3 divs, just for the sake of showing we're only showing/changing the game div.
        There's nothing special about this setup.
     -->

<body>
    <div id="Intro">
        This is the beginning of the game.
    </div>
    <div id="Game">
        The GAME GOES HERE.
    </div>
    <div id="Footer">
        This is the bottom.
    </div>
</body>

Now this is calling our JS, exampleCode.js –
That’s also very simple. We’re just going to do two “game loops” to update the page.
One of which updates the color, and the other uses an AJAX request


// This function does the logic of updating our game div.
// Obviously, in a real game, this would be more interesting.
function ChangeColor()
{ 

  // in jQuery, the $ character gives you the root jQuery object.
  // You can use the $(FOO) notation gives you a reference to any element
  // Any element you want. It's just like a CSS selector.
  // So-
  // $('#foo') gives you a HTML element with id="foo"
  // $('.foo') gives you every element with the class="foo" (loop through them)

  // The next line creates an array of random colors.
  bgcolorlist= Array("#DFDFFF", "#FFFFBF", "#80FF80", "#EAEAFF", "#C9FFA8", "#F7F7F7", "#FFFFFF", "#DDDD00");

  // Now, Randomly choose one, by picking a random number (between 1 and arraysize), and then get that array element.
  randombgcolor = bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)];

  // Now, in jQuery, you can set a CSS property, by using the .css function.
  // I'm using it to set the background for the HTML element #Game.

  $("#Game").css('background',randombgcolor);

}

// Let's try a slightly more interesting function. We'll add an external call.
function UpdateTime()
{ 

  // Now, let's do something Ajaxy-
  // There is a URL endpoint for Tavern that gives us the server status, including the time.
  // We can use that to display the current time on our page.

  // The $.ajax() function doesn't return the JSON.. It RUNS the success value as a function.
  // That function will save the variable for us.

  // Normally, we could use $.get(), or $.getJSON(), but these just call $.ajax() under the hood.
  // By calling $.ajax() directly, we can set more options.

  // set the result variable ahead of time, so it's scope isn't only inside the function.
  var result;


  // make the AJAX call
  $.ajax({
    // async defaults to True- This means that the result will wait for a return before running anything else.
    async: false,
    // Setting the dataType to JSON is a convenience. It automatically parses it into a JSON object for us.
    dataType:"json",
    // This is the URL we're pulling from. I set this up to be accessible from any domain.
    // Normally, you can only make requests to the SAME DOMAIN as the HTML runs from.
    // But you can bypass this with a header (Access-Control-Allow-Origin), which I've set for you.
    url: "http://gettavern.com:8090/status",

    // This is just our super-simple function that gets called on success.
    // ALL it's doing is setting the result back to that variable we declared before.

    // Normally, in JS, you'd just do whatever it is you actually needed with your drawing/etc, right in the inline function..
    // Or have it call a longer function, that's defined normally (like the one we're in!)
    // But in this case, I wanted to a) illustrate Inline functions.
    //                           and b) make it short ;)
    success: function(data) {
        result = data;
    }
  });




  // Now, make that into something printable. Notice how we pull values out of the JS call as if it were a dictionary/hashmap?
  timeStampString = "The current timestamp is " + result['timestamp'] + ".";

  // Now, let's DO something with this data-
  // create a new javascript Date object based on the timestamp
  // multiplied by 1000 so that the argument is in milliseconds, not seconds
  var date = new Date(result['timestamp']*1000);
  // hours part from the timestamp
  var hours = date.getHours();
  // minutes part from the timestamp
  var minutes = date.getMinutes();
  // seconds part from the timestamp
  var seconds = date.getSeconds();

  // will display time in 10:30:23 format
  var formattedTime = "
This is equal to " + hours + ":" + minutes + ":" + seconds; // This redefines the HTML inside the game object to whatever we pass it. In this case, it's the time. // Get the Game's DOM object // This gets the instance of the Game, just like we were in the first function. game = $("#Game"); // Replace the Game's HTML. // Just like used the background function in the first example (above), here we're overwriting the HTML that's in the Game object. // Everytime this runs, everthing that is in the game div is erased, and replaced with whatever string we pass. // In this case, we're passing in our two time-based strings we just created. game.html(timeStampString + formattedTime); } // Run the code above, every 500ms self.setInterval("ChangeColor()",500); self.setInterval("UpdateTime()",1000);

You can see this in action at jsfiddle.

It’s all very very straightforward code, but it occured to me that it might be useful to others, so I’ve archived it here for anyone who finds it 😉

Advertisements
Read more from Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments

%d bloggers like this: