@老师_咖啡 文件没上传成功,贴了一下game的代码;里面是有一些按照自己逻辑写的,没有完全按照视频写
import { _decorator, AudioClip, AudioSource, Component, instantiate, LabelComponent, Node, NodeEventType, Prefab, Sprite, sys, tween, UITransform, v2, v3, Vec2 } from 'cc';
import { Tile } from './Tile';
const { ccclass, property } = _decorator;
// 定义移动方向枚举
enum MOVE_DIRECTION {UP, DOWN, LEFT, RIGHT};
@ccclass('Game')
export class Game extends Component {
@property(Node)
startPanel:Node = null!;
@property(Node)
gamePanel:Node = null!;
@property(Node)
overPanel:Node = null!;
// 游戏等级
@property(LabelComponent)
txtLevel:LabelComponent = null!;
// 当前分数
@property(LabelComponent)
txtScore:LabelComponent = null!;
// 最高分数
@property(LabelComponent)
txtMaxScore:LabelComponent = null!;
// 撤回
@property(LabelComponent)
txtBack:LabelComponent = null!;
// 格子的父容器
@property(Node)
ndCellParent:Node = null!;
// 格子父容器的UI,宽高
@property(UITransform)
nodeParentUITransform:UITransform = null!;
// 格子整体背景
@property(Prefab)
cellBg:Prefab = null!;
// 单个格子
@property(Prefab)
cell:Prefab = null!;
@property(AudioClip)
soundMove:AudioClip = null!;
@property(AudioClip)
soundGetScore:AudioClip = null!;
// 用户数据
private userData:any = null;
// 格子间隔,默认5
private cellPadding:number = 15;
// 单个格子宽高
private cellChildWH:number = 0;
// 格子父容器宽高
private cellParentWH:number = 0;
// 游戏内的二位数组
private gameArrayData = [];
// 记录移动事件的起始位置,从而判断[上下左右]移动
private touchStartPos = null;
private touchEndPos = null;
// 移动一次的得分
private moveOnceScore = 0;
start() {
this.initPanel();
this.startPanel.active = true;
}
update(deltaTime: number) {
}
private init() {
this.getUserData();
this.updateView();
this.addTouchEvent();
}
// 添加触碰事件
private addTouchEvent() {
this.ndCellParent.on(NodeEventType.TOUCH_START, this.onTouchStart, this);
this.ndCellParent.on(NodeEventType.TOUCH_END, this.onTouchEnd, this);
this.ndCellParent.on(NodeEventType.TOUCH_MOVE, this.onTouchMove, this);
this.ndCellParent.on(NodeEventType.TOUCH_CANCEL, this.onTouchCancle, this);
}
// 触碰事件开始
private onTouchStart(event) {
this.touchStartPos = event.getLocation();
}
// 触碰事件结束
private onTouchEnd(event) {
this.touchEndPos = event.getLocation();
let moveDirection:MOVE_DIRECTION = this.calMoveDirection();
this.move(moveDirection);
}
// 计算移动方向
private calMoveDirection () : MOVE_DIRECTION {
// 计算横向和纵向移动的距离
let xDistance:number = this.touchEndPos.x - this.touchStartPos.x;
let yDistance:number = this.touchEndPos.y - this.touchStartPos.y;
if (Math.abs(xDistance) > Math.abs(yDistance)) {
// 说明是横向移动大,当做横向移动
return xDistance > 0 ? MOVE_DIRECTION.RIGHT : MOVE_DIRECTION.LEFT;
} else {
return yDistance > 0 ? MOVE_DIRECTION.UP : MOVE_DIRECTION.DOWN;
}
}
// 移动逻辑
private move(moveDirection:MOVE_DIRECTION) {
switch (moveDirection) {
// 目前上下是反的 不清楚啥问题先这样处理
case MOVE_DIRECTION.UP:
this.moveAndMergeDown();
//this.moveAndMergeUp();
break;
case MOVE_DIRECTION.DOWN:
this.moveAndMergeUp();
//this.moveAndMergeDown();
break;
case MOVE_DIRECTION.LEFT:
this.moveAndMergeLeft();
break;
case MOVE_DIRECTION.RIGHT:
this.moveAndMergeRight();
break;
}
}
/** 右移动 start */
private moveAndMergeRight() {
let gameArrayData = this.gameArrayData;
// 记录是否有移动
let hasMoved = false;
// 记录是否可以得分,只要merge了就可以得分
let canGetScore = false;
for (let row = 0; row < gameArrayData.length; row++) {
// 向右移动数字
let rowValues = gameArrayData[row];
let movedThisTime = this.moveRight(rowValues);
if (movedThisTime) {
hasMoved = true;
}
// 合并相同的数字
let mergedThisTime = this.mergeRight(rowValues);
if (mergedThisTime) {
hasMoved = true;
canGetScore = true;
}
}
this.processAfterMove(hasMoved, canGetScore);
}
// 向右移动,返回是否有移动动作
private moveRight(rowValues):boolean {
let hasMove = false;
for (let i = rowValues.length - 1; i > 0; i--) {
if (rowValues[i] == 0) {
// 如果当前位置为0,则该位置左侧第一个非零数字移到当前位置
for (let j = i - 1; j >= 0; j--) {
if (rowValues[j] != 0) {
rowValues[i] = rowValues[j];
rowValues[j] = 0;
hasMove = true;
break;
}
}
}
}
return hasMove;
}
private mergeRight(rowValues):boolean {
let hasMerged = false;
for (let i = rowValues.length - 1; i > 0; i--) {
if (rowValues[i] == rowValues[i - 1] && rowValues[i] != 0) {
// 如果相邻两个数字相等,则合并并将结果放入当前位置
rowValues[i] *= 2;
rowValues[i - 1] = 0;
this.moveOnceScore += rowValues[i];
hasMerged = true;
}
}
// 再次进行向右移动,确保合并后的数字仍然靠右
this.moveRight(rowValues);
return hasMerged;
}
/** 右移动 end */
/** 左移动 start */
private moveAndMergeLeft() {
let gameArrayData = this.gameArrayData;
// 记录是否有移动
let hasMoved = false;
// 记录是否可以得分,只要merge了就可以得分
let canGetScore = false;
for (let row = 0; row < gameArrayData.length; row++) {
// 向左移动数字
let rowValues = gameArrayData[row];
let movedThisTime = this.moveLeft(rowValues);
if (movedThisTime) {
hasMoved = true;
}
// 合并相同的数字
let mergedThisTime = this.mergeLeft(rowValues);
if (mergedThisTime) {
hasMoved = true;
canGetScore = true;
}
}
this.processAfterMove(hasMoved, canGetScore);
}
// 向左移动,返回是否有移动动作
private moveLeft(rowValues):boolean {
let hasMove = false;
for (let i = 0; i < rowValues.length; i++) {
if (rowValues[i] == 0) {
// 如果当前位置为0,则该位置右侧第一个非零数字移到当前位置
for (let j = i + 1; j < rowValues.length; j++) {
if (rowValues[j] != 0) {
rowValues[i] = rowValues[j];
rowValues[j] = 0;
hasMove = true;
break;
}
}
}
}
return hasMove;
}
private mergeLeft(rowValues):boolean {
let hasMerged = false;
for (let i = 0; i < rowValues.length - 1; i++) {
if (rowValues[i] == rowValues[i + 1] && rowValues[i] != 0) {
// 如果相邻两个数字相等,则合并并将结果放入当前位置
rowValues[i] *= 2;
rowValues[i + 1] = 0;
this.moveOnceScore += rowValues[i];
hasMerged = true;
}
}
// 再次进行向右移动,确保合并后的数字仍然靠右
this.moveLeft(rowValues);
return hasMerged;
}
/** 左移动 end */
/** 上移动 start */
private moveAndMergeUp() {
let gameArrayData = this.gameArrayData;
let cols = gameArrayData[0].length;
// 记录是否有移动
let hasMoved = false;
// 记录是否可以得分,只要merge了就可以得分
let canGetScore = false;
for (let col = 0; col < cols; col++) {
// 向上移动数字
let movedThisTime = this.moveUp(col);
if (movedThisTime) {
hasMoved = true;
}
// 合并相同的数字
let mergedThisTime = this.mergeUp(col);
if (mergedThisTime) {
hasMoved = true;
canGetScore = true;
}
}
this.processAfterMove(hasMoved, canGetScore);
}
// 入参是操作的第几列
private moveUp(col:number):boolean {
let hasMove = false;
for (let i = 0; i < this.gameArrayData.length; i++) {
if (this.gameArrayData[i][col] == 0) {
// 如果当前位置为0,则该位置下方第一个非零数字移到当前位置
for (let j = i + 1; j < this.gameArrayData.length; j++) {
if (this.gameArrayData[j][col] != 0) {
this.gameArrayData[i][col] = this.gameArrayData[j][col];
this.gameArrayData[j][col] = 0;
hasMove = true;
break;
}
}
}
}
return hasMove;
}
// 入参是操作的第几列
private mergeUp(col:number):boolean {
let hasMerged = false;
for (let i = 0; i < this.gameArrayData.length - 1; i++) {
if (this.gameArrayData[i][col] == this.gameArrayData[i + 1][col] && this.gameArrayData[i][col] != 0) {
// 如果相邻两个数字相等,则合并并将结果放入当前位置
this.gameArrayData[i][col] *= 2;
this.gameArrayData[i + 1][col] = 0;
this.moveOnceScore += this.gameArrayData[i][col];
hasMerged = true;
}
}
// 再次进行向上移动,确保合并后的数字仍然靠上
this.moveUp(col);
return hasMerged;
}
/** 上移动 end */
/** 下移动 start */
private moveAndMergeDown() {
let gameArrayData = this.gameArrayData;
let cols = gameArrayData[0].length;
// 记录是否有移动
let hasMoved = false;
// 记录是否可以得分,只要merge了就可以得分
let canGetScore = false;
for (let col = 0; col < cols; col++) {
// 向上移动数字
let movedThisTime = this.moveDown(col);
if (movedThisTime) {
hasMoved = true;
}
// 合并相同的数字
let mergedThisTime = this.mergeDown(col);
if (mergedThisTime) {
hasMoved = true;
canGetScore = true;
}
}
this.processAfterMove(hasMoved, canGetScore);
}
// 入参是操作的第几列
private moveDown(col:number):boolean {
let hasMove = false;
for (let i = this.gameArrayData.length - 1; i > 0; i--) {
if (this.gameArrayData[i][col] == 0) {
// 如果当前位置为0,则该位置上方第一个非零数字移到当前位置
for (let j = i - 1; j >= 0; j--) {
if (this.gameArrayData[j][col] != 0) {
this.gameArrayData[i][col] = this.gameArrayData[j][col];
this.gameArrayData[j][col] = 0;
hasMove = true;
break;
}
}
}
}
return hasMove;
}
// 入参是操作的第几列
private mergeDown(col:number):boolean {
let hasMerged = false;
for (let i = this.gameArrayData.length - 1; i > 0; i--) {
if (this.gameArrayData[i][col] == this.gameArrayData[i - 1][col] && this.gameArrayData[i][col] != 0) {
// 如果相邻两个数字相等,则合并并将结果放入当前位置
this.gameArrayData[i][col] *= 2;
this.gameArrayData[i - 1][col] = 0;
this.moveOnceScore += this.gameArrayData[i][col];
hasMerged = true;
}
}
// 再次进行向下移动,确保合并后的数字仍然靠下
this.moveDown(col);
return hasMerged;
}
/** 下移动 end */
/**
* 移动之后的动作
* 1. 清除之前的格子
* 2. 遍历数据生成新格子
* 3. 更新分数
* 4. 再随机生成1个格子
*/
private processAfterMove(hasMoved:boolean, canGetScore:boolean) {
if (!hasMoved) {
console.log('本次不能移动');
return;
}
let audioSource:AudioSource = new AudioSource();
if (canGetScore) {
audioSource.playOneShot(this.soundGetScore);
} else {
audioSource.playOneShot(this.soundMove);
}
// 1. 清楚之前的格子
this.cleanAllItem();
// 2. 生成新格子
for (let i = 0; i < this.gameArrayData.length; i++) {
for (let j = 0; j < this.gameArrayData[i].length; j++) {
if (this.gameArrayData[i][j] > 0) {
this.createItem(v2(i, j), this.gameArrayData[i][j], true);
}
}
}
// 3.计算分数
this.userData.score += this.moveOnceScore;
this.moveOnceScore = 0; // 使用完需要清空
if (this.userData.score > this.userData.maxScore) {
this.userData.maxScore = this.userData.score;
}
this.txtScore.string = this.userData.score;
this.txtMaxScore.string = this.userData.maxScore;
// 4. 随机生成1个格子
this.randomArray();
}
private cleanAllItem() {
let children = this.ndCellParent.children;
for(let i = children.length-1;i>=0;i--){
let tile =children[i].getComponent(Tile);
if(tile) {
this.ndCellParent.removeChild(children[i]);
}
}
}
// 触碰事件移动
private onTouchMove(event) {
}
// 触碰事件取消
private onTouchCancle(event) {
}
// 获取用户信息
private getUserData() {
//this.userData = JSON.parse(sys.localStorage.getItem("userData"));
this.userData = null;
if (this.userData == null) {
// 初始化数据
this.userData = {
level: 5,
score: 0,
maxScore: 0,
array: [],
arrHistory: [],
backNum: 3
};
}
this.saveUserData();
}
private saveUserData() {
//sys.localStorage.setItem("userData", JSON.stringify(this.userData));
}
// 更新页面视图
private updateView() {
let level = this.userData.level;
this.txtLevel.string = level + "x" + level;
this.txtScore.string = this.userData.score.toString();
this.txtMaxScore.string = this.userData.maxScore.toString();
this.txtBack.string = "撤回(" + this.userData.backNum + ")";
// 计算每个格子以及父容器的大小
this.cellChildWH = Math.round((640 - (level + 1) * this.cellPadding) / level);
this.cellParentWH = 640;
this.nodeParentUITransform.width = this.cellParentWH;
this.nodeParentUITransform.height = this.cellParentWH;
// 初始化格子背景
this.addCellBg(level);
// 初始化游戏数据
this.initGameArrayData(level);
// 产生一个随机数
this.randomArray();
}
// 初始化游戏数据, 每个格子都初始化成0
private initGameArrayData(level:number) {
this.gameArrayData = [];
for (let i = 0; i < level; i++) {
this.gameArrayData[i] = [];
}
for (let i = 0; i < level; i++) {
for (let j = 0; j < level; j++) {
this.gameArrayData[i][j] = 0;
}
}
}
// 在空格子随机添加数字创建一个随机数组
private randomArray() {
// 找到所有空格子
let emptyCells = [];
for (let i = 0; i < this.gameArrayData.length; i++) {
for (let j = 0; j < this.gameArrayData[i].length; j++) {
if (this.gameArrayData[i][j] == 0) {
emptyCells.push(v2(i, j));
}
}
}
if (emptyCells.length > 0) {
// 在所有空格子里面随机找一个格子
let randomCell = emptyCells[Math.floor(Math.random() * emptyCells.length)];
// 格子的位置
let i = randomCell.x;
let j = randomCell.y;
// 生成随机数字
let randomNum = Math.random() * 10 <= 4 ? 4 : 2;
this.gameArrayData[i][j] = randomNum;
// 创建格子
this.createItem(randomCell, randomNum, true);
// 校验是否结束
this.checkGameOver();
}
}
// 创建一个格子
private createItem(cellPos:Vec2, num:number, isAction = false) {
// 计算初始化位置
let pos = -this.cellParentWH / 2 + this.cellChildWH / 2 + this.cellPadding;
let posStart = v2(pos, pos);
let cell = instantiate(this.cell);
let cellTile = cell.getComponent(Tile);
if (cellTile) {
cellTile.init(num);
}
cell.parent = this.ndCellParent;
let cellUI:UITransform = cell.getComponent(UITransform);
cellUI.width = this.cellChildWH;
cellUI.height = this.cellChildWH;
// 计算该格子的位置
let posX = posStart.x + (cellUI.width + this.cellPadding) * cellPos.y;
let posY = posStart.y + (cellUI.height + this.cellPadding) * cellPos.x;
cell.position = v3(posX, posY, 0);
// 动画
if (isAction) {
cell.scale = v3(0, 0, 0);
tween(cell).to(0.15, {scale:v3(1, 1, 1)}, {easing: "sineInOut"}).start();
}
}
// 格子背景
private addCellBg(level:number) {
let pos = -this.cellParentWH / 2 + this.cellChildWH / 2 + this.cellPadding;
let posStart = v2(pos, pos);
for (let i = 0; i < level; i++) {
for (let j = 0; j < level; j++) {
let cellBg = instantiate(this.cellBg);
cellBg.parent = this.ndCellParent;
let cellBgTf: UITransform = cellBg.getComponent(UITransform);
cellBgTf.width = this.cellChildWH;
cellBgTf.height = this.cellChildWH;
// 计算该格子的位置
let posX = posStart.x + (cellBgTf.width + this.cellPadding) * j;
let posY = posStart.y + (cellBgTf.height + this.cellPadding) * i;
cellBg.position = v3(posX, posY, 0);
}
}
}
// 初始化面板
private initPanel() {
this.startPanel.active = false;
this.gamePanel.active = false;
this.overPanel.active = false;
}
private activeOverPanel() {
this.startPanel.active = false;
this.gamePanel.active = true;
this.overPanel.active = true;
}
// 点击开始游戏
private onBtnStartClick() {
this.initPanel();
this.gamePanel.active = true;
this.init();
}
// 点击重玩
private onBtnReplayClick() {
}
// 点击撤回
private onBtnBackClick() {
}
// 回主页面
private onBtnHomeClick() {
this.initPanel();
this.startPanel.active = true;
}
// 判断是否游戏结束
private checkGameOver() {
// 没有空格子,并且不存在可以合并的清空,说明结束了
let isOver = !this.hasEmptyCell() && !this.canMerge();
if (isOver) {
this.saveUserData();
this.activeOverPanel();
} else {
}
}
// 判断是否存在空格子
private hasEmptyCell():boolean {
for (let i = 0; i < this.gameArrayData.length; i++) {
for (let j = 0; j < this.gameArrayData[i].length; j++) {
if (this.gameArrayData[i][j] == 0) {
return true;
}
}
}
return false;
}
// 判断是否可以合并
private canMerge():boolean {
let level = this.gameArrayData.length;
// 看每一行的前后是否存在相等的数值
for (let i = 0; i < level; i++) {
for (let j = 0; j < level - 1; j++) {
if (this.gameArrayData[i][j] == this.gameArrayData[i][j+1]) {
return true;
}
}
}
// 看每一列的上下是否存在相等的数值
for (let i = 0; i < level - 1; i++) {
for (let j = 0; j < level; j++) {
if (this.gameArrayData[j][i] == this.gameArrayData[j][i+1]) {
return true;
}
}
}
return false;
}
}