import { promptAction } from '@kit.ArkUI';

interface coordinates {
  x: number;
  y: number;
}

class Game2048 {
}

@Entry
@Component
struct Index {
  @State
  grid: number[][] = [
    [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]
  ]
  score: number = 0;

  aboutToAppear(): void {
    this.addRandomTile()
    this.addRandomTile()
  }

  addRandomTile() {
    let emptyCells: coordinates[] = [];
    for (let i = 0; i < 4; i++) {
      for (let j = 0; j < 4; j++) {
        if (this.grid[i][j] === 0) {
          emptyCells.push({ x: i, y: j });
        }
      }
    }
    if (emptyCells.length > 0) {
      const randomIndex = Math.floor(Math.random() * emptyCells.length);
      const randomCell = emptyCells[randomIndex];
      this.grid[randomCell.x][randomCell.y] = Math.random() < 0.9 ? 2 : 4;
    }
  }

  move(direction: string) {
    let newGrid: number[][] = [
      [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]
    ]
    let merged = false;

    switch (direction) {
      case 'up':
        for (let col = 0; col < 4; col++) {
          let mergedRow = 0;
          for (let row = 0; row < 4; row++) {
            if (this.grid[row][col]!== 0) {
              if (newGrid[mergedRow][col] === this.grid[row][col]) {
                // 如果相同且没有合并过
                if (!merged) {
                  newGrid[mergedRow][col] *= 2;
                  this.score += newGrid[mergedRow][col];
                  merged = true;
                } else {
                  // 如果已经合并过,则将当前数字放在下一行
                  mergedRow++;
                  newGrid[mergedRow][col] = this.grid[row][col];
                }
              } else {
                // 如果不相同
                if (newGrid[mergedRow][col]!== 0) {
                  mergedRow++;
                }
                newGrid[mergedRow][col] = this.grid[row][col];
              }
            }
          }
          merged = false;
        }
        break;
    // 其他方向的处理类似,以向左移动为例
      case 'left':
        for (let row = 0; row < 4; row++) {
          let mergedCol = 0;
          for (let col = 0; col < 4; col++) {
            if (this.grid[row][col]!== 0) {
              if (newGrid[row][mergedCol] === this.grid[row][col]) {
                if (!merged) {
                  newGrid[row][mergedCol] *= 2;
                  this.score += newGrid[row][mergedCol];
                  merged = true;
                } else {
                  mergedCol++;
                  newGrid[row][mergedCol] = this.grid[row][col];
                }
              } else {
                if (newGrid[row][mergedCol]!== 0) {
                  mergedCol++;
                }
                newGrid[row][mergedCol] = this.grid[row][col];
              }
            }
          }
          merged = false;
        }
        break;
    // 向右移动
      case 'right':
        for (let row = 0; row < 4; row++) {
          let mergedCol = 3;
          for (let col = 3; col >= 0; col--) {
            if (this.grid[row][col]!== 0) {
              if (newGrid[row][mergedCol] === this.grid[row][col]) {
                if (!merged) {
                  newGrid[row][mergedCol] *= 2;
                  this.score += newGrid[row][mergedCol];
                  merged = true;
                } else {
                  mergedCol--;
                  newGrid[row][mergedCol] = this.grid[row][col];
                }
              } else {
                if (newGrid[row][mergedCol]!== 0) {
                  mergedCol--;
                }
                newGrid[row][mergedCol] = this.grid[row][col];
              }
            }
          }
          merged = false;
        }
        break;
    // 向下移动
      case 'down':
        for (let col = 0; col < 4; col++) {
          let mergedRow = 3;
          for (let row = 3; row >= 0; row--) {
            if (this.grid[row][col]!== 0) {
              if (newGrid[mergedRow][col] === this.grid[row][col]) {
                if (!merged) {
                  newGrid[mergedRow][col] *= 2;
                  this.score += newGrid[mergedRow][col];
                  merged = true;
                } else {
                  mergedRow--;
                  newGrid[mergedRow][col] = this.grid[row][col];
                }
              } else {
                if (newGrid[mergedRow][col]!== 0) {
                  mergedRow--;
                }
                newGrid[mergedRow][col] = this.grid[row][col];
              }
            }
          }
          merged = false;
        }
        break;
    }

    if (!this.gridsEqual(this.grid, newGrid)) {
      this.grid = newGrid;
      this.addRandomTile();
    }
  }

  gridsEqual(grid1: number[][], grid2: number[][]): boolean {
    for (let i = 0; i < 4; i++) {
      for (let j = 0; j < 4; j++) {
        if (grid1[i][j] !== grid2[i][j]) {
          return false;
        }
      }
    }
    return true;
  }

  getBackColor(v:number){
    let backColor:ResourceColor
    switch (v) {
      case 2:
        backColor = '#eee4da';
        break;
      case 4:
        backColor = '#ede0c8';
        break;
      case 8:
        backColor = '#f2b179';
        break;
      case 16:
        backColor = '#f59563';
        break;
      case 32:
        backColor = '#f67c5f';
        break;
      case 64:
        backColor = '#f65e3b';
        break;
      case 128:
        backColor = '#edcf72';
        break;
      case 256:
        backColor = '#edcc61';
        break;
      case 512:
        backColor = '#edc850';
        break;
      case 1024:
        backColor = '#edc53f';
        break;
      case 2048:
        backColor = '#edc22e';
        break;
      default:
        backColor = '#ccc0b3';
    }
    return backColor
  }



  build() {
    Column() {
      Stack() {
        Grid() {
          ForEach([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 7, 7, 7,], () => {
            GridItem() {
            }.backgroundColor('#ccc0b3').borderRadius(10)

          })
        }
        .columnsTemplate('1fr 1fr 1fr 1fr')
        .rowsTemplate(' 1fr 1fr 1fr 1fr')
        .layoutDirection(GridDirection.Row)
        .width('100%')
        .aspectRatio(1)
        .backgroundColor('#bbada0')
        .margin(10)
        .borderRadius(10)
        .padding(10)
        .columnsGap(10)
        .rowsGap(10)

        //上层
        Grid() {

          ForEach(this.grid, (row: number[], i: number) => {
            ForEach(row, (col: number, j: number) => {
              GridItem() {
                if (this.grid[i][j]===0){
                  Text('')
                }else {
                  Text(this.grid[i][j].toString())
                    .fontColor('#776e65')
                    .fontSize(20)
                }

              }.backgroundColor(this.getBackColor(this.grid[i][j])).borderRadius(10)

            })
          })
        }
        .columnsTemplate('1fr 1fr 1fr 1fr')
        .rowsTemplate(' 1fr 1fr 1fr 1fr')
        .layoutDirection(GridDirection.Row)
        .width('100%')
        .aspectRatio(1)
        .margin(10)
        .borderRadius(10)
        .padding(10)
        .columnsGap(10)
        .rowsGap(10)
        .gesture(
          GestureGroup(GestureMode.Parallel, PanGesture({ direction: PanDirection.Up })
            .onActionEnd(() => {
              this.move('up');
            }),
            PanGesture({ direction: PanDirection.Down })
              .onActionEnd(() => {
                this.move('down');
                promptAction.showToast({
                  message: 'xia'
                })
              }),
        PanGesture({ direction: PanDirection.Left })
          .onActionEnd(() => {
            this.move('left');
            promptAction.showToast({
              message: 'Left'
            })
          }),PanGesture({ direction: PanDirection.Right })
          .onActionEnd(() => {
            this.move('right');
            promptAction.showToast({
              message: 'Right'
            })
          })
          )

        )
        .animation({
          duration: 2000,
          curve: Curve.EaseOut,
          iterations: 3,
          playMode: PlayMode.Normal
        })
      }
    }
    .height('100%')
    .width('100%')
  }
}

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐