我有一个项目,在其中我必须做一个2048年的游戏。
现在,我讨论的函数是,如果数字相等,它也应该把它们拉上来,如果数字之间有0。
基本上这就是我所做的:
'''tab creates the 2048 game board'''
def tab():
return ({
(1, 1): 0, (1, 2): 0, (1, 3): 0, (1, 4): 0,
(2, 1): 0, (2, 2): 0, (2, 3): 0, (2, 4): 0,
(3, 1): 0, (3, 2): 0, (3, 3): 0, (3, 4): 0,
(4, 1): 0, (4, 2): 0, (4, 3): 0, (4, 4): 0
})
#tab_reduc(t,d) gets a board(t) and a place to move as a string ('N','S','E','W') and moves the board as ordered
def tab_reduc(t,d):
for i in range(1,4):
for c in range(1,4):
if t[(i,c)] == t[(i,c+1)] and t[(i,c+1)] != 0:
t[(i,c)] = t[(i,c)] + t[(i,c+1)]
t[(i,c+1)] = 0
elif t[(i,c)] != t[(i,c+1)] and t[(i,c)] != 0:
t[(i,c)] = t[(i,c)]
t[(i,c+1)] = t[(i,c+1)]
elif t[(i,c)] == 0 and t[(i,c+1)] != 0:
t[(i,c)] = t[(i,c+1)]
t[(i,c+1)] = 0
return t例如,如果我有:
(1,1) = 4
(1,2) = 4
(1,3) = 8
(1,4) = 4当我运行"tab_reduc(t,'N')“时,游戏应该会上升,我确实得到了
(1,1) = 8
(1,2) = 8
(1,3) = 4
(1,4) = 0但如果我有
(1,1) = 4
(1,2) = 0
(1,3) = 0
(1,4) = 4我做北戏,我得到
(1,1) = 4
(1,2) = 0
(1,3) = 4
(1,4) = 0如果我再做一次,我会得到:
(1,1) = 4
(1,2) = 4
(1,3) = 0
(1,4) = 0又一次:
(1,1) = 8
(1,2) = 0
(1,3) = 0
(1,4) = 0问题是,这应该是在一个游戏,而不是几个剧本。
有人能帮我吗?
发布于 2014-12-03 17:57:34
思想..。
在移动N时,您可能想要向后迭代。
for i in range(1, 4):
for c in reversed(range(1, 4)):
...所以..。
如果你这样做了,你就会更接近你的解决方案。但是,在本例中仍然会有一个bug:
0 0 0 0
4 0 0 0
2 0 0 0
2 0 0 0然后,您的改进代码将生成:
8 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0当它应产生:
4 0 0 0
4 0 0 0
0 0 0 0
0 0 0 0我会把修正作为读者的练习。我想,解决这个问题的最简单的方法是,当您成功地完成一个积累时,就可以摆脱迭代。
还有一些最后的想法:
如果我要自己实现这一点,我会使用稍微不同的策略。这里的关键是把问题分解成几个步骤。让我们继续只谈北方。
步骤:
0。那就是,让我们把桌子向北摊平。所以这个:
0 0 0 1 1 0 1 0 0 0变成..。0 0 0 1 0 1 0 1 0 0 0现在。我们如何在代码中实现这样的东西呢?
def tab():
return ({
(1, 1): 0, (1, 2): 0, (1, 3): 0, (1, 4): 0,
(2, 1): 0, (2, 2): 0, (2, 3): 0, (2, 4): 0,
(3, 1): 0, (3, 2): 0, (3, 3): 0, (3, 4): 0,
(4, 1): 0, (4, 2): 0, (4, 3): 0, (4, 4): 0
})
def tab_reduc(t,d):
if d in ('n', 'N'):
# Merge whitespace
for _ in range(4): # FIXME: Massive hack...
for i in range(1,4):
for c in range(1,5):
if t[i+0, c] == 0 and t[i+1, c] != 0:
t[i+0, c] = t[i+1, c]
t[i+1, c] = 0
# Merge neighbors
for i in reversed(range(1, 4)):
for c in range(1,5):
if t[i+0, c] == t[i+1, c] and t[i, c] != 0:
t[i+0, c] *= 2
t[i+1, c] = 0
# Merge whitespace
for _ in range(4): # FIXME: Massive hack
for i in range(1,4):
for c in range(1,5):
if t[i+0, c] == 0 and t[i+1, c] != 0:
t[i+0, c] = t[i+1, c]
t[i+1, c] = 0
def tab_print(t):
for i in range(1, 5):
for c in range(1, 5):
print '{:2d}'.format(t[i,c]),
print
print
t = tab()
t[(1,4)] = 2
t[(2,4)] = 2
t[(3,4)] = 2
t[(4,4)] = 2
tab_print(t)
tab_reduc(t, 'N')
tab_print(t)运行时输出:
0 0 0 2
0 0 0 2
0 0 0 2
0 0 0 2
0 0 0 4
0 0 0 4
0 0 0 0
0 0 0 0我为了自己的理智改变了一些内心的东西。在这段代码中,(i, j)是向下的i-1行,j-1列在右边。
https://stackoverflow.com/questions/27278332
复制相似问题