我正在尝试用Python制作2048游戏,但是当这种情况发生在网格中时
0 0 0 0
0 0 4 0
0 0 2 0
0 0 2 0
我下移,发生这种情况
0 0 0 0
0 0 0 0
0 0 0 0
0 0 8 0
这应该发生的时间:
0 0 0 0
0 0 0 0
0 0 4 0
0 0 4 0
我正在使用递归函数在网格中移动数字。到目前为止,我一直在尝试以下方法:
import random, math
class Grid:
def __init__(self):
self.grid = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
def spawnRandom(self, num):
while True:
i = random.randint(0, 3)
j = random.randint(0, 3)
if not self.grid[i][j]: break
self.grid[i][j] = num
def moveUp(self):
def move(i, j):
if i == 0:
return
if self.grid[i-1][j] == self.grid[i][j]:
self.grid[i-1][j] *= 2
self.grid[i][j] = 0
return
if not self.grid[i-1][j]:
self.grid[i-1][j] = self.grid[i][j]
self.grid[i][j] = 0
move(i-1, j)
for i in range(1, 4):
for j in range(0, 4):
move(i, j)
def moveDown(self):
def move(i, j):
if i == 3:
return
if self.grid[i+1][j] == self.grid[i][j]:
self.grid[i+1][j] *= 2
self.grid[i][j] = 0
return
if not self.grid[i+1][j]:
self.grid[i+1][j] = self.grid[i][j]
self.grid[i][j] = 0
move(i+1, j)
for i in range(2, -1, -1):
for j in range(0, 4):
move(i, j)
def moveLeft(self):
def move(i, j):
if j == 0:
return
if self.grid[i][j-1] == self.grid[i][j]:
self.grid[i][j-1] *= 2
self.grid[i][j] = 0
return
if not self.grid[i][j-1]:
self.grid[i][j-1] = self.grid[i][j]
self.grid[i][j] = 0
move(i, j-1)
for j in range(1, 4):
for i in range(0, 4):
move(i, j)
def moveRight(self):
def move(i, j):
if j == 3:
return
if self.grid[i][j+1] == self.grid[i][j]:
self.grid[i][j+1] *= 2
self.grid[i][j] = 0
return
if not self.grid[i][j+1]:
self.grid[i][j+1] = self.grid[i][j]
self.grid[i][j] = 0
move(i, j+1)
for j in range(2, -1, -1):
for i in range(0, 4):
move(i, j)
def printGrid(self):
# formatting code
high = max([max(i) for i in self.grid])
numDig = int(math.log(high, 10)) + 1 if high else 1
strf = "{:" + str(numDig) + "}"
for i in self.grid:
for j in i:
print(strf.format(j), end=' ')
print()
def main():
g = Grid()
# 75% of spawning 2, 25% of spawning 4
g.spawnRandom(random.choice([2, 2, 2, 4]))
while True:
print()
g.spawnRandom(random.choice([2, 2, 2, 4]))
g.printGrid()
opt = input('move: ')
if opt == 'stop': break
elif opt == 'up': g.moveUp()
elif opt == 'down': g.moveDown()
elif opt == 'left': g.moveLeft()
elif opt == 'right': g.moveRight()
if __name__ == '__main__':
main()
提前谢谢!
我知道它是题外话,但是我觉得我应该为移动方法使用装饰器,以减少代码数量,但是我真的不知道如何实现这一点。任何想法都很棒!