Interview: Scott Porter on JavaScript Games - WebReference Update - 020228 | WebReference

Interview: Scott Porter on JavaScript Games - WebReference Update - 020228

((((((((((((((((( WEBREFERENCE UPDATE NEWSLETTER ))))))))))))))))) February 28, 2002

___________________________ Sponsors ________________________________ This newsletter sponsored by: 802.11 Planet Spring 2002 _____________________________________________________________________

This week we interview Scott Porter, founder of Scott's new game JavaScript Pool, is making the rounds at virtual pool-halls around the Web. We ask Scott about his site and how his new game works. In other news don't miss Andrew Sullivan's blogger manifesto. *- link to us today *- newsletter home

New this week on and the Web:

1. INTERVIEW: Scott Porter of 2. OTHER VOICES: * A Blogger Manifesto * Google loves Blogs * Open Source Web Design 3. NET NEWS: * Security Flaws Found in PHP

Like what you see? Get our front page e-mailed to you every business day with our HTML newsletter. Just send an e-mail to:

or for this text newsletter:

Spread the word! Feel free to send a copy of this newsletter to your friends and colleagues, and while you're at it, snap a link to

/-------------------------------------------------------------------\ Coming to the East Coast! 802.11 Planet Spring 2002 Conf. & Expo --The Only Trade Show & Expo Focused on 802.11 Business-- June 10-12 Pennsylvania Conv. Ctr., Philadelphia, PA. Whether you're an expert in 802.11 or need to quickly get up to speed and profit from it, 802.11 Planet is the premier event for this exploding industry. Sign up today to receive the latest updates on this and future 802.11 Planet events!


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1. INTERVIEW: Scott Porter of

We were so impressed with the DHTML and XML-based JavaScript Pool game we reported on in the News Wednesday we decided to interview the author. Scott Porter is the founder of and the author of JavaScript Pool, an interactive network-ready pool game available at:

I asked Scott about how he got started with his JavaScript game site, how the game works, and his Gamelib API.

WEBREF: Give us an idea why you started this JavaScript game site?

SCOTT PORTER: The idea for the site came from a thread I was involved in on the comp.lang.javascript newsgroup a few years ago. I had written a few games by then, and my then ISP was warning me about excessive traffic to my free webspace. I asked whether anyone else would be interested in seeing a site devoted to JavaScript games and it seemed pretty popular, so I registered the name and decided to put something together.

A few other people I knew via the newsgroup and email had written games too, so I offered to host their games for free with links to their own sites, and since then I've had many many more submitted for inclusion by various authors from all over the world.

New games are announced via the mailing list, so they tend to get a lot of hits just after launch. The site has gone through a few major changes, but I like the current interface and it's easy for me to maintain. The site is all run using Perl scripts.

Apart from the site, I maintain the Gamelib library, which is an API for game developers using Javascript. I'm currently carrying out a major overhaul of the Interface module, for dynamic windows and other GUI elements. I'm also working on some games to run in Linux within the KDE desktop (C++). Truth be told, I'm a bit of a Linux advocate, and love the idea of open-source software - it's great for people who'd like to learn how things work.

I guess I must love games, I have 3 coin-op machines in my dining- room - only the classics though. Centipede, Pacman and R-Type2. I must do a JavaScript version of Centipede one day - as I've actually worked on the hardware and replaced chips on the board I should know how it plays with my eyes shut by now! :-)

WR: Your JavaScript game API, is it open source? Give us an URL.

SP: Yes, Gamelib is distributed under the GPL, so feel free to do with it as you will. It's a tad hard to read through the source though as I always remove white space from it to improve performance (I've found that unlike a compiled language, removal of white space in JS makes a real difference it terms of download time and CPU performance). I'm trying to keep a non-compressed version up to date, so it can be distributed along with it too, but I tend to forget to update both at the same time. I'm working on a Perl script to do this for me. Gamelib is always at:

You can download it as a zip - it has lots of documentation and some examples. Andy Harris has written a book for Javascript beginners that includes an older version of the library as well as some of my games - it's called "Javascript programming for the Absolute Beginner" and uses Gamelib for many of the examples.

WR: Are most games donated by users? I see many are yours.

Yes, most of the games are from other authors. You can search the site by author to find out who's written what. Some of the other guys have come up with some great stuff - for instance, Omar Wally's football game is great.

WR: I see you have the classics like Pacman and Frogger. Any legal problems replicating these?

SP: Not so far. The code is obviously completely different to the originals. The graphics are pretty similar in some of the games though (notably Donkey Kong, Galaxian, Frogger and IceBlox! (Pengo)) so if I receive a letter I guess I'll have to change them again. I don't make any money from the games though, so hopefully I won't attract any nasty letters.

WR: Your JavaScript Pool game. How does it work?

SP: Well, I've been playing with various methods of clientserver communication over the last couple of months since the I worked for took a nose-dive, and there appear to be four usable options for Javascript:

(a) Loading new content into hidden frames/iFrames. I've actually been using this method for a few years now, its advantage is that it works on just about anything, but is slow, and adds the data- request URLs to the browser's history object which can annoy visitors. It also makes IE5/6 emit a clicking sound after each download on the Windows platform.

(b) Using image src changes, and sending down the response from the server as cookie data. This method actually works quite well most of the time and I use it on the high-score chart loaders for a couple of my games (e.g. "Donkey Kong" at ). Its disadvantage is that Internet Explorer will occasionally fail to download an image or send a request to a CGI script, even if it exists on the server. I countered this by using a "watchdog" timer to give it a kick if there was no response for a few seconds. This seemed a bit of a hack though.

(c) Creating "persistent" connections. This requires a CGI script to send data back to the browser as it's available. To do this, I set up a Perl script, pointed at a hidden iFrame on the client. The script initially sends down the start of a page, then a large comment tag to cause the server-side output buffer to flush; after this, any data written using the print statement in Perl is sent straight to the client. After this, data is sent inside <script> </script> tags, so the client can use it immediately. New requests from the client are sent up using image source changes or using a second iFrame. During testing a connection could be maintained for up to 1/2hr on my server. This seemed too unreliable though.

(d) Using the XMLHttpRequest objects. This is a great method, as it allows minimal redundant data to be sent in each direction, and is very fast, and fairly reliable. I still use a watchdog timer, but it's better than the image src changes.

I ended up using (d). The data is actually sent up asynchronously in batches from an out-buffer as escaped strings, and data is returned as XML, with just one root node containing another escaped string. This saves bandwidth, and processing time, as it's just a matter of unescaping and splitting the data client-side before putting it into the in-buffer.

Anyway, I'd been wondering if any of this stuff had any practical application, then instead wondered if I could use it for a 2 player game! I love playing pool, and a turn-based game seemed to be the ideal choice. There is little data that needs to be transmitted (just the cue rotation and initial force on the cue ball for most turns), and plenty of time between turns as the balls roll around. The problem was the possibility of failed server requests and that the use of floating point math for ball positions could lead to the two players getting out of sync during the game. To stop this (most of the time anyway) once all the balls stop moving, their positions are rounded up to integer values ready for the next shot, and the JavaScript network object implemented client side uses sequence numbers to constantly rebroadcast the same data until it's received by the other client. This seems to work pretty well with the machines I have available for testing (I use Mozilla on Linux/Mac and IE5/6 on Mac and Windows). I threw in the chat-box too, as there's plenty of spare time between turns.

The hardest part of the game for me was trying to get the ball movement working semi-realistically. The difficult part is not working out the new trajectories, but exactly when and where the balls have collided. As this is JavaScript, I have to move the balls up to 30 pixels in either axis at a time due to the low framerate, which means a collision will normally occur inside another ball. So the game has to "back-up" until the balls are no longer intersecting - with multi-ball collisions this can be pretty complex!

WR: Method (d), how does this work? Is this a DOM-based technique? What browsers does this work on?

SP: Ok, this is a DOM based technique with Mozilla/NS6, with Explorer it uses the Msxml2.XMLHTTP or Microsoft.XMLHTTP ActiveX objects, depending upon which is available. If you're running a version of IE on a platform that doesn't have the ActiveX object available (such as IE5 on the Mac), it falls back to sending/ receiving data using a hidden iFrame. The requests are still sent to the same server-side script, which accepts only XML and returns either pure XML, or if fallback mode is in use returns the same data wrapped in JavaScript which pushes the data into a fake XMLHTTP object. The fallback mode incurs a slight overhead, so you'll notice the Windows version is much more responsive than the Mac version. I suggest using IE over Mozilla at the moment though, as Mozilla is very very slow at rendering animated Javascript content.

I've written a library for the network communication that will be added to the Gamelib library in due course. It's pretty simple to use, as you simply set your ID and the ID of the other machine (this is done for you by the "Wait for Challenger" screen), then just send whatever you like to the socket object as so:

socket.rawWrite('some more data');

and it'll end up on the other player's machine! Data is sent asynchronously, so whatever you send to the object is stored in an out-buffer until it can be sent up to the server. In the same vein, data from the server is stored in a FIFO in-buffer, so to read from it:

var data=socket.rawRead();

Once you read from the buffer, the data you've just read is removed - so the usual method is to read from it in a while loop until there's nothing more (it returns false when empty). Using the buffers means you shouldn't miss anything.

I believe this network code, and so the game, works with IE5+ on Windows and Mac, and Netscape 6/Mozilla 0.9.2+ on Windows, Mac, Linux and whatever else Moz runs on these days. I have Linux, OS-X and WinXP running here at home for testing. Most of my older games run on IE4/5/6 and Netscape 4 (and NS6 for the ones that use the Gamelib library). I'd love to support Konqueror under Linux, but it's not quite there yet with its DOM implementation. I'm moving away from supporting NS4 though, as although it's nice and fast for games (much faster than Mozilla) it's better for everyone if they move to more standards-compliant browsers - but hey, that's just my opinion.

WR: The ball movement, how did you simulate actual physics?

SP: Too much math! The balls in the game look reasonably realistic, but in actual fact I doubt their movement is all that close to their physical counterparts. The problem of using a scripting language with a math-heavy application is that it's a bit slow - you really need to try to keep it up to at least 20fps before it looks clunky. So I cut out a lot of variables; rolling resistance, gravity, true spin (you can apply spin to the cue-ball, but it's not "actual" spin).

The good thing about balls though, being spheres and all, is that it's simple to work out when they've collided using good old Pythagoras. Just get the distance between centers and if it's less than the diameter of the ball, it's a hit. The game does this for all moving balls (no need to check if a stationary ball is going to hit anything) and when it registers a collision (or more than one) it moves the current ball back to its previous position, then works out where the actual moment of contact occurred. Then the collision angle is worked out using the handy atan2 method - so for balls b and b2, you'd do something like:


to get the degrees. Then the velocities and angles are changed, for the new angles of the balls. I'm not sure if I use the "correct" method, but I always think that if you can make a game "look" realistic while doing the absolute minimum possible behind the scenes, then it's a good method.

WR: To set up your XML server, what is involved?

It will be distributed along with the next major version of Gamelib. I use Linux to run my servers, with the Apache web server, and it's as easy as putting the 2 CGI scripts in a directory, setting a few variables at the top for the directories they will use, and after that they look after themselves. They're just Perl scripts, so getting them to run on another OS shouldn't be a problem. The reason there are 2 scripts is that one is used for the Challenger waiting page, which must parse the input for people logging in, challenging and accepting games. The other script actually has the easiest job, as all it needs to do is pass the data back and forth during the game. It doesn't parse anything, just does the most basic security checking to ensure that ONLY the 2 players can communicate with each-other during a game. Sending back pure XML is actually easier for the server than having to construct all the headers and link in external pages for a normal web page. Consider sending back a variable to JavaScript in a hidden frame; you'd have to send something like:

<html> <head> <script language="Javascript"> parent.somePage.myVariable=1; </script> </head> <body> </body> </html>

Whereas the XML is:

<?xml version="1.0"?> <myVariable>1</myVariable>

WR: Why do you write games?

SP: I just love the thought that someone might enjoy playing my games (and the games of other authors I host on my site), the people who email me range from kids of all ages up to senior citizens. I make a Javascript library available to help others write games for free. The Web has given me a lot over the years, and I like to think I'm giving it something back.

WR: On my Mac, i can't seem to get a powerful break, any advice?

Have you tried using the spin control? The big cueball on the bottom right, you just click on it. If you give the cue loads of top-spin then it'll split the pack a bit better. I tend to hit the pack at an angle with top+side spin, which seems to work well.

# # # #

About the interviewee: Scott Porter is a Web developer and programmer, born, raised and currently living in the UK. He programs in x86 assembler, C/C++, Javascript, Java, Perl, PHP, shell and Actionscript. Scott loves to travel and spent time living and working in Belgium, Germany and Spain. He was educated at various institutions around UK. He can be reached at:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 2. OTHER VOICES: A Blogger Manifesto, Google loves Blogs, Open Source Web Design

* A Blogger Manifesto

Andrew Sullivan talks about the evolution of weblogs, and how his own blog has changed since the "early" days of 1999. Learn how he adapted business models to make money with his blog. Could blogs be the future of journalism? Hat tip to Andrew Sullivan, Feb. 24, 2002

* Google loves Blogs

John Hiler writes in response to the New York Times article on blogs. By their very nature, blogs have a big influence on millions of Google searches. Important backlinks, freshness, and frequency are all factored into Google's Pagerank algorithm., Feb. 26, 2002

* Open Source Web Design

Here's a neat idea. Provide free pre-designed templates for web site designs. Most of the designs are in tables, categorized and ranked. Now, if we could get the same thing for CSS layout designs. Anyone know of sources for free CSS-based layouts? Open Source Web Design, Feb. 2002

/-------------------------------------------------------------------\ ** When Face-to-Face is the Only Way ** The Internet is great for exchanging information and ideas, but nothing beats in-person learning and networking. Check out's upcoming Spring 2002 conferences and expositions including: ** Search Engine Strategies ** Nanotech Planet ** 802.11 Planet (Wireless) ** Instant Messaging Planet and more. Visit today!


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 3. NET NEWS: Security Flaws Found in PHP

* Security Flaws Found in PHP

CERT announced Wednesday a number of security flaws in PHP. Upgrading to version 4.12, or disabling fileupload fixes all the holes.,,10_982841,00.html, Feb. 28, 2002

That's it for this Thursday. See you next time.

Andrew King Newsletter Editor, aking at internet dot com ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

ARE YOU BABYSITTING YOUR EMAIL LIST SERVER SOFTWARE? Upgrade to Lyris ListManager From The Experts at SparkLIST, Save Money, and Remove Headaches With Our Free Installation Assistance Offer:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Advertising: If you are interested in advertising in our newsletters, call Claudia at 1-203-662-2863 or send email to ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For contact information on sales offices worldwide visit ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For details on becoming a Commerce Partner, contact David Arganbright on 1-203-662-2858 or ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To learn about other free newsletters offered by or to change your subscription visit ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'s network of more than 160 Web sites is organized into 16 channels: Internet Technology E-Commerce/Marketing Web Developer Windows Internet Technology Linux/Open Source Internet Resources ISP Resources Internet Lists Download International Internet News Internet Investing ASP Resources Wireless Internet Career Resources EarthWeb ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To find an answer - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Looking for a job? Filling an opening? - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This newsletter is published by Jupitermedia Corp - The Internet & IT Network Copyright (c) 2002 Jupitermedia Corp. All rights reserved. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For information on reprinting or linking to content: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~