import { _decorator, Component, instantiate, Node, Prefab, random, tween, Vec3,MathBase, Tween, EventTouch, TweenAction } from 'cc';
const { ccclass, property } = _decorator;
let XA = [];
let pr1; let X = 0, Y = 0;
@ccclass('main')
export class main extends Component {
@property(Prefab) P1: Prefab;
@property(Prefab) P2: Prefab;
@property(Prefab) P3: Prefab;
@property(Prefab) P4: Prefab;
@property(Node) N: Node;
start() {
let parr = [this.P1, this.P2, this.P3, this.P4];
let x1 = -240, y1 = 240;
for (let j = 0; j < 5; j++) {
let xa = []
for (let i = 0; i < 5; i++) {
let nu = (random() * 3).toFixed();
const p1 = instantiate(parr[nu]);
xa.push(p1);
this.N.addChild(p1);
p1.setPosition(x1+i*120, y1-j*120);
this.createpre(p1);}
XA.push(xa);
}
}
update(deltaTime: number) {
}
createpre(p1) {
setTimeout(() => {
p1.on(Node.EventType.TOUCH_START, (event: TouchEvent) => {
console.log(p1._siblingIndex, Math.floor((p1._siblingIndex - 1) / 5), ((p1._siblingIndex - 1) % 5));
if (pr1 == null ) {
pr1 = p1;
X = p1._lpos.x; Y = p1._lpos.y;
} else{
if (Math.abs(Math.floor((p1._siblingIndex - 1) / 5) - Math.floor((pr1._siblingIndex - 1) / 5)) <= 1 && Math.abs(((p1._siblingIndex - 1) % 5) - ((pr1._siblingIndex - 1) % 5)) <= 1) {
XA[Math.floor((p1._siblingIndex - 1) / 5)][((p1._siblingIndex - 1) % 5)] = pr1;
XA[Math.floor((pr1._siblingIndex - 1) / 5)][((pr1._siblingIndex - 1) % 5)] = p1;
p1._siblingIndex = p1._siblingIndex ^ pr1._siblingIndex;
pr1._siblingIndex = p1._siblingIndex ^ pr1._siblingIndex;
p1._siblingIndex = p1._siblingIndex ^ pr1._siblingIndex;
tween(pr1).to(0.5, { position: p1.position }).call(this.des).start();
tween(p1).to(0.5, { position: new Vec3(X, Y, 0) }).call(this.des).start();
X = 0, Y = 0; pr1 = null;
} else {
X = 0, Y = 0; pr1 = null;
}
}
}, this);
}, 2000);
}
dfs(x, y, no, book) {
let next = [[-1, 0], [1, 0], [0, -1], [0, 1]];
let tx, ty;
for (let i = 0; i < 4; i++) {
tx = x + next[i][0];
ty = y + next[i][1];
if (tx < 1 || ty < 1 || tx > 5 || ty > 5)
continue;
if (book[tx][ty] == 0 && XA[tx][ty]._name == no._name) {
book[tx][ty] = -1; //标记走过
this.dfs(tx, ty,no,book); //递归
book[tx][ty] = 0; //取消标记
}
}
}
des(event: TweenAction) {
let book = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]];
book[Math.floor((event._siblingIndex - 1) / 5)][((event._siblingIndex - 1) % 5)] = -1;
this.dfs(Math.floor((event._siblingIndex - 1) / 5), ((event._siblingIndex - 1) % 5), event, book);
}
}
des方法中调用dfs方法报错