鸿蒙开发案例:黑白棋_旋转角度

黑白棋,又叫翻转棋(Reversi)、奥赛罗棋(Othello)、苹果棋或正反棋(Anti reversi)。黑白棋在西方和日本很流行。游戏通过相互翻转对方的棋子,最后以棋盘上谁的棋子多来判断胜负。它的游戏规则简单,因此上手很容易,但是它的变化又非常复杂。有一种说法是:只需要几分钟学会它,却需要一生的时间去精通它。

此代码基于API 12编写,包含了游戏的基本逻辑,包括初始化棋盘、处理玩家和AI的走法、检查游戏状态、以及动画展示等部分。以下是具体的功能和使用的算法分析:

【实现的功能】

1. 棋盘初始化:创建了一个8×8的棋盘,并在中心位置放置了四个棋子作为初始布局,遵循了翻转棋的标准规则。

2. 棋子展示与翻转:定义了ChessCell类来表示棋盘上的每个单元格,支持显示黑色或白色棋子,并且能够翻转棋子,即从黑色变为白色或反之亦然。此过程伴随有动画效果。

3. 有效走法检测:通过findReversible方法来查找某个位置放置新棋子后可翻转的棋子集合。此方法考虑了八个方向上的可能走法。

4. 玩家切换:currentPlayerIsBlackChanged方法用于切换当前玩家,并检查当前玩家是否有有效的走法。如果没有,就检查对手是否有走法,如果没有则判定游戏结束并显示胜利者。

5. AI走法:在单人模式下,AI会选择一个随机的有效走法进行下棋。6. 游戏结束判定:当没有任何一方可以走棋时,游戏结束并显示胜利信息。

【使用的算法】

1. 有效走法检测算法

有效走法检测是通过findReversible函数实现的。该函数接收行号、列号和当前玩家的颜色作为参数,并返回一个数组,该数组包含所有可以在指定方向上翻转的棋子对象。

findReversible(row: number, col: number, color: number): ChessCell[] {
          
          
    let reversibleTiles: ChessCell[] = [];
    const directions = [
        [-1, -1], // 左上
        [-1, 0], // 正上
        [-1, 1], // 右上
        [0, -1], // 左
        [0, 1], // 右
        [1, -1], // 左下
        [1, 0], // 正下
        [1, 1]  // 右下
    ];
    for (const direction of directions) {
          
          
        let foundOpposite = false;
        let x = row;
        let y = col;
        do {
          
          
            x += direction[0];
            y += direction[1];
            if (x < 0 || y < 0 || x >= this.chessBoardSize || y >= this.chessBoardSize) {
          
          
                break;
            }
            const cell = this.chessBoard[x][y];
            if (cell.frontVisibility === 0) {
          
          
                break;
            }
            if (cell.frontVisibility === color) {
          
          
                if (foundOpposite) {
          
          
                    let tempX: number = x - direction[0];
                    let tempY: number = y - direction[1];
                    while (tempX !== row || tempY !== col) {
          
          
                        reversibleTiles.push(this.chessBoard[tempX][tempY]);
                        tempX -= direction[0];
                        tempY -= direction[1];
                    }
                }
                break;
            } else {
          
          
                foundOpposite = true;
            }
        } while (true);
    }
    return reversibleTiles;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.

该算法首先定义了所有可能的方向,然后逐一检查这些方向上是否存在有效的可翻转棋子序列。对于每一个方向,它会尝试移动到下一个位置,并检查那个位置上的棋子状态,如果遇到空位则停止搜索;如果遇到同色棋子,那么在这之前的所有异色棋子都可以被翻转;否则继续搜索直到边界或同色棋子出现。

2. AI随机下棋策略

AI的随机下棋策略是在aiPlaceRandom函数中实现的。该函数首先收集所有当前玩家可以下棋的位置,然后从中随机选择一个位置进行下棋。

aiPlaceRandom() {
          
          
    let validMoves: [number, number][] = [];
    for (let i = 0; i < this.validMoveIndicators.length; i++) {
          
          
        for (let j = 0; j < this.validMoveIndicators[i].length; j++) {
          
          
            if (this.validMoveIndicators[i][j].isValidMove) {
          
          
                validMoves.push([i, j]);
            }
        }
    }
    if (validMoves.length > 0) {
          
          
        const randomMove = validMoves[Math.floor(Math.random() * validMoves.length)];
        let chessCell = this.chessBoard[randomMove[0]][randomMove[1]];
        this.placeChessPiece(randomMove[0], randomMove[1], chessCell)
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.

这里通过双重循环遍历所有的validMoveIndicators数组,找到所有标记为有效走法的位置,将其坐标存储在一个数组中。之后,从中随机选取一个坐标,调用placeChessPiece函数进行下棋。

3. 棋子翻转动画

棋子的翻转动画是由ChessCell类中的flip方法控制的。根据当前棋子的状态,调用相应颜色的展示方法(如showBlack或showWhite),并根据传入的时间参数来决定是否启用动画。

flip(time: number) {
          
          
    if (this.frontVisibility === 1) {
          
           // 当前是黑子,要翻转成白子
        this.showWhite(time);
    } else if (this.frontVisibility === 2) {
          
           // 当前是白子,要翻转成黑子
        this.showBlack(time);
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

翻转操作会触发动画效果,通过旋转和透明度的变化来模拟棋子的翻转动作。这些算法共同作用,使得该游戏具有了基础的棋子翻转、有效走法检测和AI下棋的能力。

【完整代码】

import {
          
           promptAction } from '@kit.ArkUI'; // 导入用于弹出对话框的工具

@ObservedV2
class ChessCell {
          
           // 定义棋盘上的单元格类
  @Trace frontVisibility: number = 0; // 单元格上的棋子状态:0表示无子, 1表示黑子,2表示白子
  @Trace rotationAngle: number = 0; // 单元格卡片的旋转角度
  @Trace opacity: number = 1; // 透明度
  isAnimationRunning: boolean = false; // 标记动画是否正在运行

  flip(time: number) {
          
           // 翻转棋子的方法
    if (this.frontVisibility === 1) {
          
           // 当前是黑子,要翻转成白子
      this.showWhite(time);
    } else if (this.frontVisibility === 2) {
          
           // 当前是白子,要翻转成黑子
      this.showBlack(time);
    }
  }

  showBlack(animationTime: number, callback?: () => void) {
          
           // 展示黑色棋子
    if (this.isAnimationRunning) {
          
           // 如果已经有动画在运行,则返回
      return;
    }
    this.isAnimationRunning = true; // 设置动画状态为运行中
    if (animationTime == 0) {
          
           // 如果不需要动画
      this.rotationAngle = 0; // 设置旋转角度为0
      this.frontVisibility = 1; // 黑子
      this.isAnimationRunning = false; // 设置动画状态为停止
      if (callback) {
          
           // 如果有回调函数,则执行
        callback();
      }
    }

    animateToImmediately({
          
          
      // 开始动画
      duration: animationTime, // 动画持续时间
      iterations: 1, // 动画迭代次数
      curve: Curve.Linear, // 动画曲线类型
      onFinish: () => {
          
           // 动画完成后的回调
        animateToImmediately({
          
          
          // 再次开始动画
          duration: animationTime, // 动画持续时间
          iterations: 1, // 动画迭代次数