The Station Manager game with Realtime Tube data
I’ve been learning a lot recently about using realtime data streams and how and why one might use them in an app. In order to better understand the differences between realtime streaming data and REST APIs (which I’ve had more experience with), I decided to build a game, the mechanic of which uses realtime train arrival data. As trains arrive into the station in real life, effects are triggered in the game which the user has to manage.
All of the code for the game is on Glitch. This means that you can see the code, ‘remix’ it and make it your own. There is a thorough readme file in the repo and I’ll also go over some of the methods used in this blog post.
Ably has a Hub of realtime data streams for developers to try out and build apps with. I used the London Tube Schedule stream, which provides a stream of various data from TFL; including arrivals at a given station. For the tamagotchi game, I wanted to find out the arrivals at a busy station, so that I would have lots of trains arriving in close succession. I chose King’s Cross station for this reason. The data stream uses the station NAPTAN code rather than it’s name to get the correct data, so I had to look up the correct code for King’s Cross (you can look up station codes here), which is 940GZZLUKSX
.
The stream I’ll therefore be using is:
[product:ably-tfl/tube]tube:940GZZLUKSX:arrivals
Every time the data from TFL is updated, this channel will publish a message with the new arrival times of trains into Kings Cross. The joy of the data being a realtime stream means that I don’t have to poll for the data, as I would with a REST API, instead, I establish a connection once and data is published to the channel as and when updates happen.
In order to connect to the data stream I used the Ably Javascript SDK. To do so, I need an Ably API key which comes with a free account. To keep my API key safe, I also used Token Authentication which makes a Token Request on the server side which is handed to the Ably realtime client to authenticate. There is a brilliant walkthrough of how to implement Token Authentication here:
#realtime #javascript #trains #gamedev #pixel-art #programming