2048 Design
The first step is to make a playable game of 2048. This makes sure we have correctly implemented all of the internal logic.
Representation
I suggest you use a list of 16 numbers: [0]*16
to start out.
So that everyone in the class talks about the same repesentation,
number the squares like this:
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
Rules
Make sure you know the rules of 2048. Write them down and make test
cases that demonstrate that your program follows them. For example,
what happens when you have a row [2,2,4,4]
? How about [0,4,4,4]
?
Does it matter if you slide these examples left or right?
Possible Class Design
A Board2048
class could have the following methods.
- An instance variable
self.board
for the list of 16 numbers. - A constant
DIRECTIONS
and definitions for numbers to representUP
,DOWN
,LEFT
, andRIGHT
. - A method
slide(direction)
to shift the board. - Helper methods
left()
,right()
,up()
,down()
to let you work step by step on getting them all right. - An
empty_squares()
method returning a list of all empty squares. - A
legal_moves()
method returning the directions in which the tiles can be slid. - Possibly a
spawn()
method which returns a new object containing one additional, randomly placed, tile. The standard game is reported to produce a “2” tile 90% of the time, and a “4” tile 10% of the time. I make every empty square equally likely to contain the spawned tile. - A
game_over()
method is needed somewhere. A game can continue when either (i) there is an empty space; or (ii) two adjacent tiles have the same value.