Building a Pacman Game With Bacon.js

Originally published at: http://www.sitepoint.com/building-pacman-with-bacon-js/

JavaScript embraces asynchronous programming. This can be a blessing and a curse that leads to the concept of “callback hell”. There are utility libraries that deal with organizing asynchronous code such as Async.js, but it’s still hard to follow the control flow and reason about asynchronous code effectively.

In this article, I’ll introduce you to the concept of reactive programming that helps dealing with the asynchronous nature of JavaScript, by using a library called Bacon.js.

Let’s Get Reactive

Reactive Programming is about asynchronous data streams. It replaces the Iterator Pattern with the Observable Pattern. This is different from imperative programming, where you actively iterate over data to handle stuff. In reactive programming, you subscribe to the data and react to events asynchronously.

Bart De Smet explains this shift in this talk. André Staltz covers Reactive Programming in depth in this article.

Once you become reactive, everything becomes an asynchronous data stream: database on the server, mouse events, promises, and server requests. This lets you avoid what’s known as “the callback hell”, and gives you better error handling. Another powerful feature of this approach is the ability to compose streams together, that gives you great control and flexibility. Jafar Husain explains these concepts in this talk.

Bacon.js is a reactive programming library and it’s an alternative to RxJS. In the next sections we’ll use Bacon.js to build a version of the well-known game “Pacman”.

Continue reading this article on SitePoint
2 Likes

Geeze that article was packed with a lot of great info. I started to bookmark all the links you posted but ended up just bookmarking the entire thing!

I’ve had RxJS bookmarked for a while, but their introductory paragraphs alone are super dense. Bacon.js is so much more digestible ba dum chhh

2 Likes

Great post, thanks! I was wondering one thing. How would you implement the logic if you wanted the ghosts to start arriving or moving faster as the game evolves? In that case you couldn’t make the Bacon interval streams static with 1000 and 800 millisecond intervals?

Ghosts have v properties that determine their speed. You could tweak that for dynamic speed, however, if you set it to 2, ghosts would start jumping by two squares. Another alternative is you set the Bacon interval to lowest value like 200 ms, and skip moving ghosts at some ticks. In any case you don’t have to dynamically update the Bacon interval, because it’s just a clock. Think about it like a cpu clock.

Thanks for your interest.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.