HumanBreak/src/core/main/game.ts

99 lines
3.1 KiB
TypeScript
Raw Normal View History

2023-08-05 12:12:02 +08:00
import { EmitableEvent, EventEmitter } from '../common/eventEmitter';
2023-11-12 19:41:07 +08:00
import { loading } from '../loader/load';
2023-08-05 12:12:02 +08:00
export interface GameEvent extends EmitableEvent {
2023-10-29 22:13:37 +08:00
/** Emitted in events.prototype.resetGame. */
2023-08-05 12:12:02 +08:00
reset: () => void;
2023-10-29 22:13:37 +08:00
/** Emitted in src/App.vue setup. */
mounted: () => void;
2023-08-05 12:12:02 +08:00
}
export const hook = new EventEmitter<GameEvent>();
2023-11-12 19:41:07 +08:00
interface ListenerEvent extends EmitableEvent {
hoverBlock: (block: Block) => void;
leaveBlock: (block: Block) => void;
2023-11-12 20:47:46 +08:00
clickBlock: (block: Block) => void;
2023-11-12 19:41:07 +08:00
}
class GameListener extends EventEmitter<ListenerEvent> {
static num: number = 0;
num: number = GameListener.num++;
constructor() {
super();
loading.once('coreInit', () => {
this.init();
});
}
private init() {
// block
let lastHoverX = -1;
let lastHoverY = -1;
2023-11-12 20:47:46 +08:00
const getBlockLoc = (px: number, py: number) => {
return [
Math.floor((px - core.bigmap.offsetX) / 32),
Math.floor((py - core.bigmap.offsetY) / 32)
];
};
2023-11-12 19:41:07 +08:00
core.registerAction(
'onmove',
`@GameListener_${this.num}_block`,
(x, y, px, py) => {
if (core.status.lockControl || !core.isPlaying()) return false;
2023-11-12 20:47:46 +08:00
const [bx, by] = getBlockLoc(px, py);
2023-11-12 19:41:07 +08:00
const blocks = core.getMapBlocksObj();
if (lastHoverX !== bx || lastHoverY !== by) {
const lastBlock = blocks[`${lastHoverX},${lastHoverY}`];
const block = blocks[`${bx},${by}`];
if (!!lastBlock) {
this.emit('leaveBlock', lastBlock);
}
if (!!block) {
this.emit('hoverBlock', block);
lastHoverX = bx;
lastHoverY = by;
} else {
lastHoverX = -1;
lastHoverY = -1;
}
}
return false;
},
50
);
core.canvas.data.canvas.addEventListener('mouseleave', () => {
if (core.status.lockControl || !core.isPlaying()) return;
const blocks = core.getMapBlocksObj();
const lastBlock = blocks[`${lastHoverX},${lastHoverY}`];
if (!!lastBlock) {
this.emit('leaveBlock', lastBlock);
}
lastHoverX = -1;
lastHoverY = -1;
});
2023-11-12 20:47:46 +08:00
core.registerAction(
'onup',
`@GameListener_${this.num}_block`,
(x, y, px, py) => {
if (core.status.lockControl || !core.isPlaying()) return false;
const [bx, by] = getBlockLoc(px, py);
const blocks = core.getMapBlocksObj();
const block = blocks[`${bx},${by}`];
if (!!block) {
this.emit('clickBlock', block);
}
return false;
},
50
);
2023-11-12 19:41:07 +08:00
}
}
export const gameListener = new GameListener();