2015-08-20 56 views
0

我試圖重新創建遊戲2048作爲一個項目,我無法操作2d數組。我試圖移動二維數組中的元素,並且不讓它們離開屏幕。移動項目在二維數組python

def move(self, direction): 

    if (self.d == UP): 
     for i in range(3): 
      for j in range(3): 
       if(self.line[i][j]!= self.line[0][0]): 
        self.line[i][j] = self.line[i + 1][j] 
        self.line[i + 1][j] = self.line[i + 2][j] 
        self.line[i + 2][j] = self.line[i + 3][j] 

這是我現在只是讓他們向上移動,他們似乎總是消失或失敗。

+0

你需要設置一個限制 - 你讓指數高於3. – mauve

+0

我想我設置了第二個if語句的限制。我將如何正確地做到這一點? – pingtar

回答

0

我做了,這可能是你在找什麼,它是在JavaScript中,因爲我不是目前我自己的電腦上,但在這裏它是:

function up(tbl) { 
    var x = 0; 
    while (x < tbl[0].length) { 
     do { 
      var move = 0; 
      var y = 0; 
      while (y < tbl.length - 1) { 
       if (tbl[y][x] == 0 && tbl[y + 1][x] != 0) { 
        tbl[y][x] = tbl[y + 1][x]; 
        tbl[y + 1][x] = 0; 
        move = 1; 
       } 
       else if (tbl[y][x] != 0 && tbl[y][x] == tbl[y + 1][x]) { 
        tbl[y][x] += tbl[y + 1][x]; 
        tbl[y + 1][x] = 0; 
        move = 1; 
       } 
       y++; 
      } 
     } while (move == 1) 
     x++; 
    } 
    return tbl; 
} 

/* Just a testing table */ 
var t = [[1, 1, 0, 1], 
     [0, 2, 2, 8], 
     [0, 128, 1, 1], 
     [2, 0, 1, 4]]; 

up(t); 

它所做的是通過柱走柱,用從上到下,並檢查:

  • 如果有一個間隙,且在它的小區不是,它移動單元向上
  • 否則如果兩個小區是相同的數目,它們被添加了如果沒有
  • 如果一個循環(從上到下)後,無論是上面發生的條件下,它移動到下一列

此外,如果你想申請這對其他三個方向,我建議旋轉桌子而不是再做3個以上的功能。如果您在將它轉換爲Python時遇到困難,我將在今晚晚些時候爲您提供幫助。

編輯:

在這裏你去,同樣的事情,但在Python:

def up(tbl): 
    x = 0 
    while (x < len(tbl[0])): 
     while True: 
      move = 0 
      y = 0 
      while (y < (len(tbl) - 1)): 
       if (tbl[y][x] == 0 and tbl[y + 1][x] != 0): 
        tbl[y][x] = tbl[y + 1][x] 
        tbl[y + 1][x] = 0 
        move = 1 
       elif (tbl[y][x] != 0 and tbl[y][x] == tbl[y + 1][x]): 
        tbl[y][x] += tbl[y + 1][x] 
        tbl[y + 1][x] = 0 
        move = 1 
       y = y + 1 
      if (move == 0): 
       break 
     x = x + 1 
    return tbl 

t = [[1, 1, 0, 1], 
    [0, 2, 2, 8], 
    [0, 128, 1, 1], 
    [2, 0, 1, 4]]; 

up(t) 

print('\n'.join([''.join(['{:5}'.format(item) for item in row]) for row in t])) 

哦,原來2048不允許平鋪到同一回合中兩次合併,所以你可能想要調整elif來適應這種情況,因爲它將它們合併,直到它不再。

+0

這將非常感謝,謝謝! – pingtar