Shift[list_]:=PadRight[Cases[list,Except[0]],4];

Merge[list_]:=Flatten[list//.{x___,c_,c_,y___}->{x,{2*c},y}];

SlideRow[list_]:=Shift[Merge[Shift[list]]];

Slide[list_,l]:=Table[SlideRow[list[[j]]],{j,1,4}];

Slide[list_,r]:=Table[Reverse[SlideRow[Reverse[list[[j]]]]],{j,1,4}];

Slide[list_,u]:=Transpose[Table[SlideRow[Transpose[list][[j]]],{j,1,4}]];

Slide[list_,d]:=Transpose[Table[Reverse[SlideRow[Reverse[Transpose[list][[j]]]]],{j,1,4}]];

RandInsert[list_]:=ReplacePart[list,RandomChoice[Position[list,0]]->RandomChoice[{2,4}]]

(*these functions slide each row in the given direction,combine like terms,and add one random number to an empty tile*)



Col[n_]:=Graphics[{Blend[{Yellow,Cyan,Purple,Red},((Log[n+1]/Log[2]))/11],Rectangle[]}];

Visual[list_]:=ImageCompose[GraphicsGrid[Table[Table[Col[list[[j,i]]],{i,1,4}],{j,1,4}]],GraphicsGrid[list,Frame->All]]

(*the tiles,with colors and numbers*)



Nex[list_,move_]:=If[FreeQ[list,0],ConstantArray[Infinity,{4,4}],RandInsert[Slide[list,move]]]

(*the update rule*)



(*the game itself.input from {u,d,l,r} to move*)

game=ConstantArray[0,{4,4}];Print[Dynamic[Visual[game]]];While[game!=ConstantArray[Infinity,{4,4}],game=Nex[game,Input[]]]



Nex[list_, move_] := Piecewise[{{RandInsert[list], Total[Flatten[list]] == 0}, {Total[Flatten[list]], Slide[list, u] == Slide[list, d] == Slide[list, l] == Slide[list, r] == list}, {list, Slide[list, move] == list}}, RandInsert[Slide[list, move]]]

Hey all, I'm a student and am just starting to get the hang of Mathematica. I tried to make a Mathematica version of the. My program works now, so I thought I'd share. I'd love to hear if there are any better ways to do it, or any suggestions you have to make it better.I originally wanted to see the distribution of how many moves a random game would last. So, now you can use all the normal Mathematica tools to discover cool patterns in 2048.Thanks, hope you enjoy!Edit: When I compared my results with the excellent artent article below, I noticed two important bugs. A random tile was added even after moves that didn't change anything. And the game ended after the board was full, even if further moves were possible. To fix this, I changed the Nex update rule. It's a little clunky, but should work. Uh, right now for the sake of analysis I have the final state be the total score instead of the grid, but you can change it easily enough. Thanks everyone for the comments!