# 玩一个完美的2048游戏

18

``````Input:
-------
0 0 0 0
0 0 0 0
0 0 0 0
0 0 8 8

Output:
-------
0 0 0 0
0 0 0 0
0 0 0 0
0 4 8 8

0 0 0 0
0 0 0 0
0 0 0 0
0 0 4 16
``````

@undergroundmonorail与这个问题不同。这个问题允许产生自己的瓷砖，并且在数学上要尽可能地发展，而不仅仅是达到2048。–
Kendall Frey

1
@TheDoctor 68是2的幂的总和，并且如果你得到你的分数会是什么2，4，8，16
user12205

2

1
@Quincunx这确实会产生次优游戏。

4

Rainbolt

4

## Ruby，进入角落，得分：3340

``````def slide board, dir
case dir
when 'U'
i0 = 0
i_stride = 1
i_dist = 4
when 'D'
i0 = 15
i_stride = -1
i_dist = -4
when 'L'
i0 = 0
i_stride = 4
i_dist = 1
when 'R'
i0 = 15
i_stride = -4
i_dist = -1
end

4.times do |x|
column = []
top_merged = false
4.times do |y|
tile = board[i0 + x*i_stride + y*i_dist]
next if tile == 0
if top_merged || tile != column.last
column.push tile
top_merged = false
else
column[-1] *= 2
top_merged = true
end
end

4.times do |y|
board[i0 + x*i_stride + y*i_dist] = column[y] || 0
end
end

board
end

if board.reduce(:*) > 0
return board, board
end

16.times do |i|
if board[15-i] == 0
board[15-i] = 4
break
end
end

spawned = board.clone

# Attention, dirty dirty hand-tweaked edge cases to avoid
# the inevitable for a bit longer. NSFS!
if board[11] == 8 && (board[12..15] == [32, 16, 4, 4] ||
board[12..15] == [16, 16, 4, 4] && board[8..10] == [256,64,32]) ||
board[11] == 16 && (board[12..15] == [32, 8, 4, 4] ||
board[12..15] == [4, 32, 8, 8] ||
board[12..15] == [4, 32, 0, 4])

dir = 'R'
elsif board[11] == 16 && board[12..15] == [4, 4, 32, 4] ||
board[11] == 8 && board[12..15] == [0, 4, 32, 8]
dir = 'U'
else
dir = (board.reduce(:+)/4).even? ? 'U' : 'L'
end

board = slide(board, dir)

if board == spawned
dir = dir == 'U' ? 'L' : 'U'
board = slide(board, dir)
end
return spawned, board
end
``````

`advance`功能是您所要求的。它以棋盘为一维数组，并在生成瓦片并进行移动后返回棋盘。

``````board = [0]*16
loop do
board.each_slice(4) {|row| puts row*' '}
puts
break if board[15] > 0
end

puts "Score: #{board.reduce :+}"
``````

``````1024 512 256 128
512 256 128  16
256 128  64   8
8  32   8   4
``````

BrunoJ 2014年

@BrunoJ此挑战的分数只是作为末尾所有图块的总和来计算，而不是您在实际游戏中得到的分数。但是，如果是这样，您当然是对的。;）...尽管我认为我的策略不会有什么不同，因为我只会得到128而不是256。
Martin Ender 2014年

BrunoJ 2014年