public Board() { // Allocate board space _Board = new Cell[_NumRows][]; for (int row = 0; row < _NumRows; row++) _Board[row] = new Cell[_NumColumns]; // Initialize board space for (int row = 0; row < _NumRows; row++) for (int col = 0; col < _NumColumns; col++) _Board[row][col] = new Cell(_Empty, row, col); _Random = new Random(); _WorkArray = new int[Math.Max(_NumRows, _NumColumns)]; }
// Shift assumes that the cells are in the reverse order of the current MoveDirection private bool Shift(Cell[] line) { bool movedOrMerged = false; int w = 0; // An iterator for the workArray ClearWorkArray(); // Puts cell values from line in the appropriate index in workArray for (int i = 0; i < line.Length; i++) { if (!line[i].Empty) { if (_WorkArray[w] == _Empty) { _WorkArray[w] = line[i].Value; } else if (_WorkArray[w] == line[i].Value) { _WorkArray[w] *= 2; line[w++].Merged = true; } else { _WorkArray[++w] = line[i].Value; } } } // Determine if any cells merged or moved while copying the work array for (int i = 0; i < line.Length; i++) { if (line[i].Value != _WorkArray[i]) movedOrMerged = true; line[i].Value = _WorkArray[i]; } return movedOrMerged; }
// CanShift assumes that the cells are in order of the current MoveDirection private bool CanShift(Cell[] line) { // Check for an empty cell a non-empty cell can move into. bool foundNumber = false; for (int i = 0; i < line.Length; i++) { if (foundNumber && line[i].Empty) return true; if (!line[i].Empty) foundNumber = true; } // Check for non-empty adjacent cells with same value for (int i = 0; i < line.Length - 1; i++) if (!line[i].Empty) if (line[i].Value == line[i + 1].Value) return true; return false; }