From ef61e7a56876a06d8542721881dbcc88a86e85c3 Mon Sep 17 00:00:00 2001 From: Hajime Hoshi Date: Fri, 29 Jul 2016 03:41:55 +0900 Subject: [PATCH] examples/2048: Bug fix: Should not add a new tile when no tiles are moved --- examples/2048/2048/board.go | 13 ++++++++++--- examples/2048/2048/board_test.go | 3 ++- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/examples/2048/2048/board.go b/examples/2048/2048/board.go index 1207f4669..fe0032656 100644 --- a/examples/2048/2048/board.go +++ b/examples/2048/2048/board.go @@ -81,7 +81,7 @@ func (b *Board) tileAt(x, y int) *Tile { return tileAt(b.tiles, x, y) } -func MoveTiles(tiles map[*Tile]struct{}, size int, dir Dir) map[*Tile]struct{} { +func MoveTiles(tiles map[*Tile]struct{}, size int, dir Dir) (map[*Tile]struct{}, bool) { vx, vy := dir.Vector() tx := []int{} ty := []int{} @@ -98,6 +98,7 @@ func MoveTiles(tiles map[*Tile]struct{}, size int, dir Dir) map[*Tile]struct{} { nextTiles := map[*Tile]struct{}{} merged := map[*Tile]bool{} + moved := false for _, j := range ty { for _, i := range tx { t := tileAt(tiles, i, j) @@ -116,6 +117,7 @@ func MoveTiles(tiles map[*Tile]struct{}, size int, dir Dir) map[*Tile]struct{} { if tt == nil { ii = ni jj = nj + moved = true continue } if t.value != tt.value { @@ -124,6 +126,7 @@ func MoveTiles(tiles map[*Tile]struct{}, size int, dir Dir) map[*Tile]struct{} { if !merged[tt] { ii = ni jj = nj + moved = true } break } @@ -137,11 +140,15 @@ func MoveTiles(tiles map[*Tile]struct{}, size int, dir Dir) map[*Tile]struct{} { nextTiles[t] = struct{}{} } } - return nextTiles + return nextTiles, moved } func (b *Board) Move(dir Dir) { - b.tiles = MoveTiles(b.tiles, b.size, dir) + moved := false + b.tiles, moved = MoveTiles(b.tiles, b.size, dir) + if !moved { + return + } b.addRandomTile() } diff --git a/examples/2048/2048/board_test.go b/examples/2048/2048/board_test.go index 07f93f446..5a3c1c3c0 100644 --- a/examples/2048/2048/board_test.go +++ b/examples/2048/2048/board_test.go @@ -191,7 +191,8 @@ func TestMoveTiles(t *testing.T) { for _, test := range testCases { tiles := cellsToTiles(test.Input, size) want := tilesToCells(cellsToTiles(test.Want, size), size) - got := tilesToCells(MoveTiles(tiles, size, test.Dir), size) + gotTiles, _ := MoveTiles(tiles, size, test.Dir) + got := tilesToCells(gotTiles, size) if fmt.Sprint(got) != fmt.Sprint(want) { t.Errorf("dir: %s, input: %v, got %v; want %v", test.Dir.String(), test.Input, got, want) }