HarmonyOS鸿蒙Next学习例程3.1 数字华容道 v0.2.20241230

HarmonyOS鸿蒙Next学习例程3.1 数字华容道 v0.2.20241230 看了些课程、资料,对【数字华容道】做了优化。

整理优化了类定义、页面布局,完善了注释,增加可读性。

图不变:

图像

优化后代码如下:

//行列
interface RowCol {
  Row: number
  Col: number
}

//【华容道】类
class HuaRongdao {
  rowCol: RowCol = { Row: 3, Col: 3 } //总行列数
  EmptyRowCol: RowCol = { Row: 2, Col: 2 } //空格子的位置
  cells: HRDCell[][] = [] //单元格二维数组
  YouWin: boolean = false //是否成功排序

  //【华容道】构造函数
  constructor(rows: number, cols: number) {
    this.init(rows, cols)
  }

  //初始化
  init(rows: number, cols: number) {
    this.YouWin = false
    this.rowCol.Row = rows
    this.rowCol.Col = cols
    this.cells.length = 0
    this.EmptyRowCol.Row = rows - 1
    this.EmptyRowCol.Col = cols - 1
    for (let _row = 0; _row < rows; _row++) {
      this.cells[_row] = [];
      for (let _col = 0; _col < cols; _col++) {
        this.cells[_row][_col] = new HRDCell(_row, _col, _row * cols + _col + 1)
      }
    }
    this.cells[rows-1][cols-1].num = -1
    this.orderRandom()
  }

  //随机交换【空格子】与它的【相邻格子】,形成谜题
  orderRandom(): void {
    let times = this.rowCol.Row * this.rowCol.Col * 40 //设置随机交换的次数,次数越多越复杂
    for (let i = 0; i < times; i++) {
      let isGood: Boolean = false //标志:待交换位是否合理
      let trc: RowCol = { Row: 0, Col: 0 } //待交换位
      let tx = 0 //横向偏移
      let ty = 0 //纵向偏移
      do {
        tx = this.GetRandomNum(-1, 1) //随机横向偏移
        ty = this.GetRandomNum(-1, 1) //随机纵向偏移
        trc = { Row: this.EmptyRowCol.Row + ty, Col: this.EmptyRowCol.Col + tx } //新的位置
        //新的位置在棋盘范围内,才是合理位置
        isGood = (trc.Row >= 0) && (trc.Row < this.rowCol.Row) && (trc.Col >= 0) && (trc.Col < this.rowCol.Col)
      } while ((!isGood) || (Math.abs(tx) + Math.abs(ty) != 1)) //待交换位置不合理,或者不是上下左右位置,则重新生成随机位置

      this.exchangeCell(trc, this.EmptyRowCol) //交换【空格子】与它的【相邻格子】
      this.EmptyRowCol = trc //记载新的【空格子】位置
    }
  }

  //交换两个【格子】的数字
  exchangeCell(a: RowCol, b: RowCol): void {
    let cellA = this.getCell(a)
    let cellB = this.getCell(b)
    let oldNum = cellA.num
    cellA.num = cellB.num
    cellB.num = oldNum
  }

  //尝试交换 【输入位置】与【空格子】的位置
  tryMove(a: RowCol): boolean {
    if (this.adjoin(a, this.EmptyRowCol)) //与空格子相邻
    {
      this.exchangeCell(a, this.EmptyRowCol)
      this.EmptyRowCol = a;
      return true
    }
    return false
  }

  //判断两个位置是否相邻(正上、正下、正左、正右)
  adjoin(a: RowCol, b: RowCol): boolean {
    if (Math.abs(a.Row - b.Row) + Math.abs(a.Col - b.Col) == 1) {
      return true
    }
    return false
  }

  //判断是否排序正确
  win(): boolean {
    let oldNum: number = this.cells[0][0].num - 1
    for (let _row = 0; _row < this.rowCol.Row; _row++) {
      for (let _col = 0; _col < this.rowCol.Col; _col++) {
        if (_row == this.rowCol.Row - 1 && _col == this.rowCol.Col - 1) {
          break //最后一格不用比较
        }
        if (this.cells[_row][_col].num != oldNum + 1) {
          return false //下一格的数字不是刚刚好比上一格多一,则必定未排序正确
        }
        oldNum++
      }
    }
    return true
  }

  //获取定界随机数
  GetRandomNum(Min: number, Max: number): number {
    return (Min + Math.round(Math.random() * (Max - Min)));
  }

  //根据位置返回 HRDCell 对象
  getCell(rowCol: RowCol): HRDCell {
    return this.cells[rowCol.Row][rowCol.Col]
  }
}

//【华容道】单元格类
class HRDCell {
  rowCol: RowCol = { Row: 0, Col: 0 } //格子在【华容道】棋盘中的位置
  num: number = 0 //格子记载的数字

  //构造函数
  constructor(row: number, col: number, faceNum: number) {
    this.rowCol.Row = row
    this.rowCol.Col = col
    this.num = faceNum
  }

  //格子显示的字符串
  show() {
    return this.num == -1 ? '' : this.num.toString()
  }

  toString() {
    return "【华容道】单元格" + "[" + this.rowCol.Col.toString() + "," + this.rowCol.Row.toString() + "]:" +
    this.num.toString()
  }
}

[@Entry](/user/Entry)
[@Component](/user/Component)
struct Index {
  [@State](/user/State) topMessage: string = '鸿蒙开发初探 → 数字华容道'
  [@State](/user/State) version: string = "v0.2.20241230"
  [@State](/user/State) huaRongdao: HuaRongdao = new HuaRongdao(3, 3) //定义【华容道】,指定棋盘大小
  [@State](/user/State) RowTempString: string = "" //记载 Grid控件 行模版字符串
  [@State](/user/State) ColTempString: string = "" //记载 Grid控件 列模版字符串

  //生成显示界面前调用
  aboutToAppear(): void {
    //初始化【华容道】题面
    this.huaRongdao.init(this.huaRongdao.rowCol.Row, this.huaRongdao.rowCol.Col)
    this.RowTempString = ""
    for (let i = 0; i < this.huaRongdao.rowCol.Row; i++) {
      this.RowTempString += "1fr "
    }
    this.ColTempString = ""
    for (let i = 0; i < this.huaRongdao.rowCol.Col; i++) {
      this.ColTempString += "1fr "
    }
  }

  //构造显示界面
  build() {
    Column() { //列布局
      Text(this.topMessage)//文本组件,显示顶行信息
        .fontSize(20)
        .fontWeight(FontWeight.Bold)
        .fontColor('#080888')
        .width('100%')
        .textAlign(TextAlign.Start)
        .padding({ top: 5, left: 15 })
      Text(this.version)//文本组件,显示版本号
        .fontSize(10)
        .fontColor('#222222')
        .width('100%')
        .textAlign(TextAlign.End)
        .padding({ top: 5, left: 15 })
      //网格组件,显示【华容道】棋盘
      Grid() {
        ForEach(this.huaRongdao.cells, (line: HRDCell[], idxLine: number) => {
          ForEach(line, (_cell: HRDCell, idxCell: number) => {
            GridItem() {
              GridButton({
                parentHRD: this.huaRongdao,
                cellRowCol: _cell.rowCol
              })
                .borderRadius(15)
                .align(Alignment.Center)
            }
          },)
        },)
      }
      .columnsTemplate(this.ColTempString)
      .rowsTemplate(this.ColTempString)
      .columnsGap(10)
      .rowsGap(10)
      .height(300)
      .margin({ top: 10, left: 10, right: 10 })

      Text('新局')//文本组件,点击后生成新的【华容道】题面
        .width('50%')
        .height('50')
        .backgroundColor(0x444444)
        .fontColor(0xffffff)
        .margin({ top: 30 })
        .padding(5)
        .borderRadius(5)
        .textAlign(TextAlign.Center)
        .onClick((event: ClickEvent) => {
          this.aboutToAppear() //生成新的【华容道】题面
        })
    }
    .height('100%')
    .width('100%')
    .backgroundColor('#F1F3F5')
  }
}

//自定义组件,显示【华容道】单元格内容
[@Component](/user/Component)
struct GridButton {
  [@Link](/user/Link) parentHRD: HuaRongdao //记载【华容道】对象。修饰符用 [@Link](/user/Link) ,以便数据更新时自动更新界面
  [@State](/user/State) cellRowCol: RowCol = { Row: 0, Col: 0 } //记载此【单元格】在【华容道】中的位置

  build() {
    //文本组件;如果排序正确,且此为【空格子】,则显示“赢了”;否则显示【单元格】的数字
    Text(this.parentHRD.YouWin && this.parentHRD.getCell(this.cellRowCol).num == -1 ? '赢了' :
    this.parentHRD.getCell(this.cellRowCol).show())
      .fontColor(0xffffff)
      .backgroundColor(this.parentHRD.getCell(this.cellRowCol).num == -1 ? (this.parentHRD.YouWin ? 0xff0000 : 0x0) :
        0x4444ff)//根据不同情况调整控件背景色
      .borderRadius(15)
      .fontSize(20)
      .fontWeight(FontWeight.Bolder)
      .textAlign(TextAlign.Center)
      .width('100%')
      .height('100%')
      .onClick((event: ClickEvent) => {
        //赢了,则不做其他动作,直接返回
        if (this.parentHRD.YouWin) {
          return
        }
        //未成功排序,则尝试交换 被点击的【单元格】与【空格子】
        if (this.parentHRD.tryMove(this.cellRowCol)) {
          //成功交换,则判断是否赢了
          if (this.parentHRD.win()) {
            console.log("大胜!")
            this.parentHRD.YouWin = true //设定【华容道】中的 赢 标志
          }
        }
      })
  }
}

更多关于HarmonyOS鸿蒙Next学习例程3.1 数字华容道 v0.2.20241230的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

HarmonyOS鸿蒙Next学习例程3.1 数字华容道 v0.2.20241230 是一个基于鸿蒙操作系统的数字华容道游戏示例程序。该例程展示了如何在鸿蒙系统上开发一个简单的数字拼图游戏,适用于初学者学习鸿蒙应用开发的基础知识。

在鸿蒙系统中,数字华容道的实现主要依赖于ArkUI框架,使用TypeScript或JavaScript进行开发。ArkUI是鸿蒙系统提供的一套UI开发框架,支持声明式UI编程,开发者可以通过简洁的代码快速构建用户界面。

该例程的核心功能包括:

  1. 界面布局:使用ArkUI的Flex布局或Grid布局来排列数字方块,实现华容道的棋盘。
  2. 交互逻辑:通过触摸事件处理用户的操作,实现数字方块的移动。
  3. 游戏逻辑:检测数字方块的排列顺序,判断游戏是否完成。
  4. 状态管理:使用鸿蒙系统的状态管理机制,保存和恢复游戏进度。

开发者在学习该例程时,可以掌握鸿蒙应用开发的基本流程,包括项目创建、界面设计、事件处理和数据管理等方面的知识。通过这个例程,开发者可以进一步熟悉鸿蒙系统的开发工具和API,为开发更复杂的应用打下基础。

更多关于HarmonyOS鸿蒙Next学习例程3.1 数字华容道 v0.2.20241230的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中开发数字华容道v0.2.20241230版本,首先需要设计UI布局,使用ArkUI组件构建游戏界面。通过JavaScript或TypeScript实现游戏逻辑,包括数字块的初始化、移动规则及胜利条件判断。利用HarmonyOS的事件处理机制响应用户点击操作,更新数字块位置。最后,通过状态管理维护游戏状态,确保界面与数据同步。

建议参考HarmonyOS官方文档,掌握ArkUI、事件处理及状态管理等核心技术,以高效完成开发。

回到顶部