与矩阵--2048游戏一起制作得分作为元组

时间:2015-12-05 10:38:08

标签: python

我正致力于为流行的2048游戏编程。目前我正在编写连续搜索可能匹配项的函数。匹配是指两个相同的元素彼此相邻或仅由None分隔。找到匹配项后,将进行匹配,并将总和放在匹配项中最左侧的元素上。例如,我们有这个董事会:

board = [[2.0, None, 2.0, 2.0],
     [2.0, 2.0, None, None],
     [2.0, None, 2.0, 2.0],
     [2.0, None, 2.0, None]

我编写了以下代码,它可以正确匹配部分。但我也希望将分数作为额外元素添加到我的列表元组中。我有:

for i in range(4):
    for j in range(2):
        score = 0
        if (board[i][j] != None and board[i][j] == board[i][j+1]):
            board[i][j] = board[i][j] + board[i][j+1]
            board[i][j+1] = None
            score = score + board[i][j]

        if board[i][j] != board[i][j+1] and board[i][j] == board[i][j+2]:
            board[i][j] = board[i][j] + board[i][j+2]
            board[i][j+2] = None
            score = score + board[i][j]

        if board[i][j+1] != None and board[i][j+1] == board[i][j+2]:
            board[i][j+1] = board[i][j+1] + board[i][j+2]
            board[i][j+2] = None
            score = score + board[i][j+1]

这会产生以下部分正确的输出:

[[4.0, None, None, 2.0],
[4.0, None, None, None],
[4.0, None, None, 2.0],
[4.0, None, None, None]], 0)

但请注意分数是0,这显然是假的。得分应该是每行中所有比赛的总和。例如,在这种情况下,在所有行中我们都有4.0,因此得分应为4 x 4.0 = 16.0。对此的帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

score保持在循环之外会使其停止重置为0:

score = 0
for i in range(4):
    for j in range(2):
        if (board[i][j] != None and board[i][j] == board[i][j+1]):
            board[i][j] = board[i][j] + board[i][j+1]
            board[i][j+1] = None
            score = score + board[i][j]

        if board[i][j] != board[i][j+1] and board[i][j] == board[i][j+2]:
            board[i][j] = board[i][j] + board[i][j+2]
            board[i][j+2] = None
            score = score + board[i][j]

        if board[i][j+1] != None and board[i][j+1] == board[i][j+2]:
            board[i][j+1] = board[i][j+1] + board[i][j+2]
            board[i][j+2] = None
            score = score + board[i][j+1]