77 lines
2.5 KiB
TypeScript
Raw Normal View History

2022-12-01 22:26:41 +08:00
import { _decorator, Component, Node, Prefab, director, instantiate } from 'cc';
2022-12-03 20:06:57 +08:00
import { ApiMsgEnum, IMsgGameStart, IMsgRoom } from '../Common';
2022-12-07 22:24:46 +08:00
import { SceneEnum } from '../Enum';
2022-12-01 22:26:41 +08:00
import DataManager from '../Global/DataManager';
2022-12-03 20:06:57 +08:00
import NetworkManager from '../Global/NetworkManager';
import { PlayerManager } from '../UI/PlayerManager';
2022-12-01 22:26:41 +08:00
const { ccclass, property } = _decorator;
@ccclass('RoomManager')
export class RoomManager extends Component {
@property(Node)
playerContainer: Node = null;
@property(Prefab)
2022-12-03 20:06:57 +08:00
playerPrefab: Prefab = null;
2022-12-01 22:26:41 +08:00
onLoad() {
director.preloadScene(SceneEnum.Battle);
2022-12-07 22:24:46 +08:00
NetworkManager.Instance.listenMsg(ApiMsgEnum.MsgRoom, this.renderPlayers, this);
NetworkManager.Instance.listenMsg(ApiMsgEnum.MsgGameStart, this.handleGameStart, this);
2022-12-01 22:26:41 +08:00
}
onDestroy() {
2022-12-07 22:24:46 +08:00
NetworkManager.Instance.unlistenMsg(ApiMsgEnum.MsgRoom, this.renderPlayers, this);
NetworkManager.Instance.unlistenMsg(ApiMsgEnum.MsgGameStart, this.handleGameStart, this);
2022-12-01 22:26:41 +08:00
}
async start() {
2022-12-03 20:06:57 +08:00
this.renderPlayers({
room: DataManager.Instance.roomInfo
})
2022-12-01 22:26:41 +08:00
}
2022-12-07 22:24:46 +08:00
renderPlayers({ room: { players: list } }: IMsgRoom) {
2022-12-01 22:26:41 +08:00
for (const item of this.playerContainer.children) {
item.active = false
}
while (this.playerContainer.children.length < list.length) {
2022-12-03 20:06:57 +08:00
const playerItem = instantiate(this.playerPrefab);
2022-12-01 22:26:41 +08:00
playerItem.active = false
playerItem.setParent(this.playerContainer)
}
for (let i = 0; i < list.length; i++) {
const data = list[i];
const node = this.playerContainer.children[i]
2022-12-03 20:06:57 +08:00
const playerItemManager = node.getComponent(PlayerManager)
2022-12-01 22:26:41 +08:00
playerItemManager.init(data)
}
}
async handleLeave() {
const { success, res, error } = await NetworkManager.Instance.callApi(ApiMsgEnum.ApiRoomLeave, {});
if (!success) {
console.log(error)
return;
}
DataManager.Instance.roomInfo = null
director.loadScene(SceneEnum.Hall);
}
2022-12-03 20:06:57 +08:00
async handleStart() {
const { success, res, error } = await NetworkManager.Instance.callApi(ApiMsgEnum.ApiGameStart, { rid: DataManager.Instance.roomInfo.id });
if (!success) {
console.log(error)
return;
}
}
2022-12-07 22:24:46 +08:00
handleGameStart({ state }: IMsgGameStart) {
2022-12-03 20:06:57 +08:00
DataManager.Instance.state = state
director.loadScene(SceneEnum.Battle);
2022-12-01 22:26:41 +08:00
}
}