2048 is the newest game to really go viral. No one even remembers Flappy Bird anymore, now it's all 2048 all day long. So what is 2048? It's a sliding puzzle game you can play here. And it's open source and up on Github. It can be summed up as this: you have a 4x4 grid of numbers and empty spaces. Slide all the tiles in any direction and any times of the same value that touch combine into a single tile. Your objective is to make larger and larger tiles, all the way up to (and beyond) 2048. Spend a few minutes playing the game and you'll see, it's a simple game.
Cloning 2048 in Ruby is a bit of a challenge though. Like all puzzle games, there's some data jugging to do, and unlike action or arcade games, you can't just "feel" your way through the gameplay. It's all based on an exacting algorithm. Get that algorithm wrong and the entire game won't play right.
Over the following six articles, we'll walk through creating an complete clone of 2048 in Ruby. There's not much of an interface, but all the core elements are there. If you just want to cut to the chase and see the code, see it here on GitHub.
- The Algorithm - Before we start coding we really need to take a close look at the game. We need to see exactly how it's doing what it's doing. If we go off half cocked with assumptions on how it works and we're wrong, we'll just waste a whole lot of time.
- Two Dimensional Arrays in Ruby - While this might sound straightforward, it's a bit tricky in Ruby. We'll look at how to create and manipulate two dimensional arrays in Ruby (which we'll need to represent the board in 2048) as well as how not to implement two dimensional arrays in Ruby.
- Rotating Two Dimensional Arrays in Ruby - This is the last "background" article before we get onto implementing the game. In order to cleanly implement our algorithm, we need to implement it once for sliding the puzzle to the left, then rotate the entire puzzle to get the other directions. This sounds a bit silly, but most of the code is in sliding the puzzle to the left, adding a bit of extra code to rotate the puzzle is much easier, not to mention DRY.
- The Board Class - The Board class houses all of this code and in this article we take a look at the overall structure of the class and its attributes. We'll also go over the code used to convert the board to a string so it can easily be printed on a command line window.
- The Rotate and Slide Methods - The core methods of this whole project are discussed here. The rotate method is almost verbatim from the previous article, and the slide method implements the core algorithm. The slide method is easily the densest and most intricate method in the whole project.
- The Final Few Methods - This last article talks about a few methods that don't really fit anywhere else. One method checks of the game over condition is met, and the other two get a list of empty cells and spawn random new numbers in those empty cells.