corgi-ws/src/rooms/PuzzleMathRoom.ts

116 lines
2.8 KiB
TypeScript

import { Client, Room } from 'colyseus'
import { Dispatcher } from '@colyseus/command'
import { IncomingMessage } from 'http'
import { debugRoom, msgLog } from '../common/Debug'
import { OnJoinCommand } from './commands/OnJoinCommand'
import { Player } from './schema/Player'
import { BeginGameCommand } from './commands/BeginGameCommand'
import { PuzzleGameState } from './schema/PuzzleGameState'
import { EndGameCommand } from './commands/EndGameCommand'
export class PuzzleMathRoom extends Room {
dispatcher = new Dispatcher(this)
async onAuth(client: Client, options: any, request: IncomingMessage) {
debugRoom(options)
// TODO: 验证用户信息
return true
}
onCreate(options: any) {
let cs = new PuzzleGameState()
this.setState(cs)
this.onMessage('*', (client, type, message) => {
msgLog(client.sessionId, 'sent', type, JSON.stringify(message))
})
}
onJoin(client: Client, options: any) {
const data = {client, accountId: options.accountid,}
this.dispatcher.dispatch(new OnJoinCommand(), data)
}
async onLeave(client: Client, consented: boolean) {
}
onDispose() {
this.dispatcher.stop()
}
/**
* 获取指定player的client实例, 如果玩家已掉线, 则获取该玩家的assist client
* @param {string | Player} player
* @return {Client}
*/
getRemoteClient(player: string | Player): Client {
let result: Client
if (typeof player == 'string') {
result = this.clients.find(client => client.sessionId == player)
} else {
result = this.clients.find(client => client.sessionId == player.id)
}
return result
}
/**
* 发送私信给玩家
* @param {string} clientId
* @param {string} type
* @param {string} msg
*/
smsg(clientId: string, type: string, msg: string) {
msgLog(`sendMsg to: ${clientId}, type: ${type}, msg: ${msg}`);
const client = this.getRemoteClient(clientId)
if (client) {
client.send(type, msg);
}
}
/**
* 加入当前房间的client数量
* @return {number}
*/
get clientCount(): number {
return this.clients.length
}
/**
* 开始游戏
*/
beginGame() {
console.log(`admin send begin game cmd`)
this.dispatcher.dispatch(new BeginGameCommand() )
}
/**
* 游戏结束
*/
endGame() {
console.log(`admin send end game cmd`)
this.dispatcher.dispatch(new EndGameCommand() )
}
updateScore(datas: any) {
console.log(`admin updateScore: ${JSON.stringify(datas)}`)
for (let data of datas) {
for (let [,player] of this.state.players) {
if (player.accountId == data.accountid) {
player.score += data.score
break
}
}
}
}
/**
* 更新论数
* @param {number} round
*/
updateRound(round: number) {
this.state.round = round
}
}