examples/2048: Refactoring

This commit is contained in:
Hajime Hoshi 2016-07-31 14:57:42 +09:00
parent b59649336a
commit c44f2819af
2 changed files with 25 additions and 11 deletions

View File

@ -84,9 +84,15 @@ func tileAt(tiles map[*Tile]struct{}, x, y int) *Tile {
func nextTileAt(tiles map[*Tile]struct{}, x, y int) *Tile {
var result *Tile
for t := range tiles {
if 0 < t.animationCount {
if t.next.x != x || t.next.y != y || t.next.value == 0 {
continue
}
} else {
if t.current.x != x || t.current.y != y {
continue
}
}
if result != nil {
panic("not reach")
}
@ -142,10 +148,10 @@ func MoveTiles(tiles map[*Tile]struct{}, size int, dir Dir) bool {
moved = true
continue
}
if t.current.value != tt.next.value {
if t.current.value != tt.current.value {
break
}
if tt.current.value != tt.next.value {
if 0 < tt.animationCount && tt.current.value != tt.next.value {
// already merged
break
}
@ -157,16 +163,20 @@ func MoveTiles(tiles map[*Tile]struct{}, size int, dir Dir) bool {
next := TileData{}
next.value = t.current.value
if tt := nextTileAt(tiles, ii, jj); tt != t && tt != nil {
next.value = t.current.value + tt.next.value
next.value = t.current.value + tt.current.value
tt.next.value = 0
tt.next.x = ii
tt.next.y = jj
tt.animationCount = maxAnimationCount
}
next.x = ii
next.y = jj
if t.current != next {
t.next = next
t.animationCount = maxAnimationCount
}
}
}
if !moved {
for t := range tiles {
t.next = TileData{}

View File

@ -42,11 +42,15 @@ func tilesToCells(tiles map[*Tile]struct{}, size int) ([]int, []int) {
for t := range tiles {
x, y := t.Pos()
cells[x+y*size] = t.Value()
if t.IsAnimating() {
if t.NextValue() == 0 {
continue
}
nx, ny := t.NextPos()
nextCells[nx+ny*size] = t.NextValue()
} else {
nextCells[x+y*size] = t.Value()
}
}
return cells, nextCells
}