2016-12-16 55 views
2

我最近做了一個連接四個遊戲,並且我有問題來編程對角線贏錢支票。我只是無法弄清楚如何獲得勝利檢查....在Javascript中連接四個對角線贏得支票

我的水平的代碼如下所示:

var winMoveSpalte = function() { 
 
    var rowDummy = 3; 
 
    var count = 0; 
 
    for (var i_row = 0; i_row < 6; i_row++) { 
 
    rowDummy = 3; 
 
    count = 0; 
 
    for (var i_col = 0; i_col < 7; i_col++) { 
 
     if (rowDummy == 3 && settings.fieldSet[i_col][i_row] != 0) { 
 
     winnerMove[count]['col'] = i_col; //x 
 
     winnerMove[count]['row'] = i_row; //y 
 
     count++; 
 
     } else if (settings.fieldSet[i_col][i_row] != 0 && (rowDummy == settings.fieldSet[i_col][i_row])) { 
 
     if (count < 4) { 
 
      winnerMove[count]['col'] = i_col; //x 
 
      winnerMove[count]['row'] = i_row; //y 
 
      count++; 
 
      if (count == 4) { 
 
      for (var w = 0; w <= 3; w++) { 
 
       $('div#feld .col_' + winnerMove[w]["col"] + '.row_' + winnerMove[w]['row']).addClass('winnerStone' + settings.activePlayer); 
 
      } 
 
      return settings.fieldSet[i_col][i_row]; 
 
      } 
 
     } 
 
     } else { 
 
     count = 0; 
 
     if (settings.fieldSet[i_col][i_row] != 0) { 
 
      winnerMove[count]['col'] = i_col; //x 
 
      winnerMove[count]['row'] = i_row; //y 
 
      count++; 
 
     } 
 
     } 
 
     rowDummy = settings.fieldSet[i_col][i_row]; 
 
    } 
 
    } 
 
}

+1

要檢查對角線,您只需增加數組的每個維度並檢查狀態:例如'arr [n] [n]','arr [n + 1] [n + 1]','arr [n + 2] [n + 2]'... –

+0

@RoryMcCrossan'arr [n] [n]','arr [n + 1] [n-1]','arr [n + 2] [n-2]',...也是對角線 –

+0

@ MarcCompte是的,好點。 –

回答

0

這將返回你所需要的結果:

boolean hasDiagonalWin(int[][] board, int row, int column) { 
    boolean result = false; 

    if(board[row][column] != 0) { 
     // there are four possible directions of a win 
     // if the top right contains a possible win 
     if(row - 3 > -1 && column + 3 < numColumns) { 
      result = board[row][column] == board[row - 1][column + 1] && 
        board[row][column] == board[row - 2][column + 2] && 
        board[row][column] == board[row - 3][column + 3]; 
     } 
     // if the bottom right contains possible win 
     if(row + 3 < numRows && column + 3 < numColumns) { 
      result = board[row][column] == board[row + 1][column + 1] && 
        board[row][column] == board[row + 2][column + 2] && 
        board[row][column] == board[row + 3][column + 3]; 
     } 
     // if the bottom left contains possible win 
     if(row + 3 < numRows && column - 3 > -1) { 
      result = board[row][column] == board[row + 1][column - 1] && 
        board[row][column] == board[row + 2][column - 2] && 
        board[row][column] == board[row + 3][column - 3]; 
     } 
     // if the top left contains a possible win 
     if(row - 3 > -1 && column - 3 > -1) { 
      result = board[row][column] == board[row - 1][column - 1] && 
        board[row][column] == board[row - 2][column - 2] && 
        board[row][column] == board[row - 3][column - 3]; 
     } 
    } 

    return result; 
}