The last few days I’ve been writing a 3D game.
- Not just a game, an online multiplayer game.
- Not just a 3D game, but one run in my browser.
- Not just in my browser, but only with CSS and HTML(and some JS and server side stuff of course).
- Not just AJAX, but Comet.
- Not just PHP+MySQL, but only ±30 lines of Bash.
Don’t believe me? Watch this:
It started out a few days back when I read about Comet. I found out about the new EventSource support in Webkit, but I was in doubt how to implement this on the server. My first thought was throwing some PHP+MySQL at it, but I decided otherwise.
Normal Ajax is pull data transfer. You push data to the server, but every time you need data you request it and PHP in turn requests it with the database.
Doing Comet with PHP+MySQL would make the server push data to the client, but the server still does pull transfer with the database.
Then I came up with named pipes, and because named pipes are the easiest in Bash I used that. Now every listening transfer creates a FIFO and all new data is just written to them. This system creates on big U-turn where everything submitted is instantly sent back to all the clients.
This is all the bash code I’m using:
#!/bin/bash echo "Content-type: text/plain" echo "" cd data echo -e "event:message\ndata:$QUERY_STRING\n" | tee -a $(ls -1)
#!/bin/bash cd data if [ $(ls -1 | wc -l) -lt 5 ] then echo "Content-type: text/event-stream" echo "" mkfifo data$$ trap rm\ data$$ SIGTERM SIGKILL EXIT while [ -p data$$ ] do cat data$$ done else echo "Content-type: text/plain" echo "Status: 503" echo "" echo "Sorry, server to busy!" fi
For the client side all I had to do is set up an AJAX form submitting player information and move players when an event occurred. The 3D part is done entirely with Webkit 3D transforms. The only downside about using EventSource and -webkit-transform is that you can only play my game with a nightly of Webkit(if you’re unsure if you have one you don’t).
I would love to share my game, but my host refuses to run it. It’s using gzip compression so all events are queued up until the request times out. You can however throw comet.zip from the box.net widget in your cgi-bin and try it yourself.