Every now and then a viral game shows up. It is difficult to name a particular quality which makes a game popular, but most people would probably describe it as addictive. 2048 is just that, despite its remarkable simplicity.
Soon, I started wondering how many lines of code would it take to write it and what are the bare essentials of the game, and tried writing my own version. To keep things short, movements are implemented in a single direction only. For the rest of the moves to work you have to rotate the matrix a few times first, perform the move and rotate it some more to return to your starting point. Not ideal, but simple it is. Game over detect simply checks if movement in any direction affects the board.
Tile creation needed to be short, so a list of zero-valued matrix elements’ coordinates was made, one picked out at random and a 2 or 4 placed there. To color the backgrounds differently, its background color is derived from its value. A dictionary could have been used as well, but it would be slightly longer.
That’s pretty much it - no score, no menu, no restart, no keypress error handling… just the bare essentials, but - it works. And it’s kind of fun, too!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
…and it looks like this: