大家好,我是 V 哥。首先要公布一个好消息,V 哥原创的《鸿蒙HarmonyOS NEXT 开发之路 卷1:ArkTS 语言篇》图书终于出版了,有正在学习鸿蒙的兄弟可以关注一下,写书真是磨人,耗时半年之久,感概一下,希望可以帮助到正在入门鸿蒙开发的小伙伴,一书在手 ArkTS无优。
今天要给大家分享一个 ArkTS小游戏的开发,五子棋游戏,通过这个小游戏的学习,可以帮助小伙伴们快速开发出自己的第一款纯血鸿蒙应用,先上图:
五子棋游戏介绍
1. 这个五子棋游戏包含以下功能:
- 使用15x15的标准棋盘
- 支持双人轮流下棋(黑棋先手)
- 自动判断胜负(任意方向五连即胜)
- 游戏结束提示
- 重新开始功能
- 触摸交互支持
2. 视觉反馈:
- 黑色棋子代表玩家1
- 白色棋子代表玩家2
- 棕色(#CBA)棋盘背景
3. 使用方法:
- 点击棋盘格子下棋
- 当一方达成五连时弹出胜利提示
- 点击"重新开始"按钮重置游戏
4. 游戏规则:
5. 该代码使用了HarmonyOS的ArkUI框架,主要特性包括:
- 使用Grid布局实现棋盘
- @State管理游戏状态
- TouchTarget处理触摸事件
- AlertDialog显示胜利提示
- Flex布局实现整体界面
- 二维数组存储棋盘状态
注意:V哥在测试时使用的是模拟器,在真实设备运行时可能需要根据屏幕尺寸调整单元格大小(修改.width(30)和.height(30)的数值)以获得最佳显示效果。
下面是详细代码实现及解释,按照以下思路即可完美实现。
五子棋游戏代码分析
这段代码实现了一个简单的五子棋游戏,使用了ArkTS(Ark TypeScript)语言。下面我将详细解释每个部分的功能,帮助你理解代码。
1. 导入和声明
@Entry
@Component
struct GobangGame {
@Entry
和@Component
是装饰器,用于标记这是一个页面组件。struct GobangGame
定义了一个名为GobangGame
的结构体,表示五子棋游戏的主界面。
2. 状态变量
@State board: number[][] = Array(15).fill(null).map(() => Array(15).fill(0))@State currentPlayer: number = 1 // 1: 黑棋, 2: 白棋@State gameOver: boolean = false
@State
表示这些变量是可变的状态。board
是一个15x15的二维数组,表示棋盘,初始值为0(空位),1表示黑棋,2表示白棋。currentPlayer
表示当前玩家,1为黑棋,2为白棋。gameOver
表示游戏是否结束。
3. 构建UI
build() {Column() {// 游戏标题Text(this.gameOver ? '游戏结束' : `当前玩家: ${this.currentPlayer === 1 ? '黑棋' : '白棋'}`).fontSize(20).margin(10)// 重新开始按钮Button('重新开始').onClick(() => this.resetGame()).margin(5)// 棋盘Column() {ForEach(this.board, (row: number[], rowIndex: number) => {Row() {ForEach(row, (cell: number, colIndex: number) => {Column().width(30).height(30).border({ width: 1, color: '#999' }).backgroundColor(this.getCellColor(cell)).onTouch((event: TouchEvent) => {if (event.type === TouchType.Down) {this.handleClick(rowIndex, colIndex)}})}, (colIndex: number) => colIndex.toString())}}, (rowIndex: number) => rowIndex.toString())}.margin(10)}.width('100%').height('100%').justifyContent(FlexAlign.Center)}
build()
方法用于构建页面的UI。- 使用
Column
和Row
布局容器来排列元素。 - 显示当前玩家或游戏结束信息。
- 提供一个“重新开始”按钮,点击后调用
resetGame()
方法重置游戏。 - 使用
ForEach
循环渲染棋盘,每个单元格是一个Column
,设置了宽度、高度、边框和背景颜色,并绑定了触摸事件。
4. 获取单元格颜色
private getCellColor(value: number): ResourceColor {return value === 1 ? '#000' : value === 2 ? '#fff' : '#CBA'}
getCellColor
方法根据单元格的值返回相应的颜色:- 1(黑棋)返回黑色 (
#000
) - 2(白棋)返回白色 (
#fff
) - 0(空位)返回浅灰色 (
#CBA
)
- 1(黑棋)返回黑色 (
5. 处理点击事件
private handleClick(row: number, col: number) {if (this.gameOver || this.board[row][col] !== 0) returnlet newBoard = [...this.board]newBoard[row][col] = this.currentPlayerthis.board = newBoardif (this.checkWin(row, col)) {this.gameOver = trueAlertDialog.show({ message: `${this.currentPlayer === 1 ? '黑棋' : '白棋'}获胜!` })} else {this.currentPlayer = this.currentPlayer === 1 ? 2 : 1}}
handleClick
方法处理玩家点击棋盘的动作:
6. 检查胜利条件
private checkWin(row: number, col: number): boolean {const directions = [[[-1, 0], [1, 0]], // 垂直[[0, -1], [0, 1]], // 水平[[-1, -1], [1, 1]], // 主对角线[[-1, 1], [1, -1]] // 副对角线]for (let direction of directions) {let count = 1for (let i = 0; i < direction.length; i++) {let dx = direction[i][0]let dy = direction[i][1]let x = row + dxlet y = col + dywhile (x >= 0 && x < 15 && y >= 0 && y < 15 &&this.board[x][y] === this.currentPlayer) {count++x += dxy += dy}}if (count >= 5) return true}return false}
checkWin
方法检查当前玩家是否在某个方向上连成五子:- 定义了四个方向:垂直、水平、主对角线和副对角线。
- 对每个方向进行检查,统计连续相同棋子的数量。
- 如果任意方向上有五个或更多相同的棋子,则返回
true
,表示当前玩家获胜。
7. 重置游戏
private resetGame() {this.board = Array(15).fill(null).map(() => Array(15).fill(0))this.currentPlayer = 1this.gameOver = false}
最后小结
这段代码实现了一个完整的五子棋游戏,包括棋盘绘制、玩家交互、胜负判断和游戏重置功能。通过理解每个部分的功能,你可以更好地掌握如何使用ArkTS开发类似的游戏应用。最后需要游戏源码的伙伴,可以到 Gitee 下载,V 哥已经把源代码上传到 Gitee(https://gitee.com/wgjava/GobangGame),欢迎一起交流鸿蒙原生开发。关注威哥爱编程,鸿蒙开发共前行。