private void MoveGrid(GridHolder[] gridHolders, List<IGridActionCommand> commands) { foreach (var gridHolder in gridHolders) { gridHolder.TempItem = gridHolder.GridItem; } int top = 0; for (int current = 1; current < gridHolders.Length;) { var currentGridHolder = gridHolders[current]; var topGridHolder = gridHolders[top]; if (currentGridHolder.IsTempNull) { ++current; continue; } var currentGridEntity = currentGridHolder.TempItem; if (topGridHolder.IsTempNull) { commands.Add(CreateMoveCommand(currentGridHolder, topGridHolder)); gridHolders[current].TempItem = null; gridHolders[top].TempItem = currentGridEntity; ++current; continue; } var topGridEntity = topGridHolder.TempItem; if (currentGridEntity.CanMerge(topGridEntity)) { // 删除被合并方格 commands.Add(CreateGridDeletionCommand(topGridHolder)); // 移动合并方格 commands.Add(CreateMoveCommand(currentGridHolder, topGridHolder)); // 删除移动后的方格 commands.Add(CreateGridDeletionCommand(topGridHolder)); GridItem newGridItem = currentGridEntity.Merge(topGridEntity); // 创建新的合并后的方块 commands.Add(CreateNewCreatedCommand(topGridHolder, newGridItem)); gridHolders[current].TempItem = null; gridHolders[top].TempItem = newGridItem; ++top; ++current; } else { ++top; if (current == top) { ++current; } } } }
private static GridNewCreatedCommand CreateNewCreatedCommand(GridHolder holder, GridItem newGridItem) { return new GridNewCreatedCommand() { Row = holder.Row, Col = holder.Col, NewGridItem = newGridItem }; }
private static GridMoveCommand CreateMoveCommand(GridHolder fromHolder, GridHolder toHolder) { return new GridMoveCommand { MoveInfo = new GridMoveInfo() { FromRow = fromHolder.Row, FromCol = fromHolder.Col, ToRow = toHolder.Row, ToCol = toHolder.Col } }; }
private static GridDeletionCommand CreateGridDeletionCommand(GridHolder holder) { return new GridDeletionCommand() { Row = holder.Row, Col = holder.Col }; }
public void MoveUp(List<IGridActionCommand> commands) { var gridHolders = new GridHolder[ROW_COUNT]; for (int col = 0; col < COL_COUNT; ++col) { int index = 0; for (int row = 0; row < ROW_COUNT; ++row) { gridHolders[index++] = GetGridHolder(row, col); } MoveGrid(gridHolders, commands); } }
public void InitGrid() { _gridData = new GridHolder[ROW_COUNT][]; for (int row = 0; row < ROW_COUNT; ++row) { _gridData[row] = new GridHolder[COL_COUNT]; for (int col = 0; col < COL_COUNT; ++col) { _gridData[row][col] = new GridHolder(row, col); } } List<IGridActionCommand> commands = new List<IGridActionCommand>(); AddRandomItems(2, commands); RunCommands(commands); }