使用room.clientCount来作为房间是否已满的判断依据

This commit is contained in:
zhl 2021-03-16 13:54:22 +08:00
parent de3839004c
commit bc54b7c590
7 changed files with 164 additions and 143 deletions

21
src/global.d.ts vendored
View File

@ -34,6 +34,10 @@ declare module 'colyseus' {
robotCount: number; robotCount: number;
match: string | undefined; match: string | undefined;
score: number; score: number;
/**
* room的client数量
*/
clientCount: number;
/** /**
* sessionId获取client * sessionId获取client
@ -41,10 +45,6 @@ declare module 'colyseus' {
*/ */
getClient(player: string | Player): Client; getClient(player: string | Player): Client;
/**
* room的client数量
*/
clientCount(): number;
// >>>>>>>>> Begin of extend send message <<<<<<<<<<<<< // >>>>>>>>> Begin of extend send message <<<<<<<<<<<<<
/** /**
@ -167,7 +167,7 @@ declare module 'colyseus' {
* @param data * @param data
* @param options * @param options
*/ */
bPlayerDead(data: any, options?: any) : void; bPlayerDead(data: any, options?: any): void;
/** /**
* 广 * 广
@ -245,14 +245,23 @@ declare module 'colyseus' {
*/ */
beginSchedule(millisecond: number, handler: Function, name: string): void; beginSchedule(millisecond: number, handler: Function, name: string): void;
/**
* active
* @param {string} name
* @return {boolean}
*/
scheduleActive(name: string): boolean;
/** /**
* *
*/ */
stopSchedule(name: string): number; stopSchedule(name: string): number;
/** /**
* *
*/ */
pauseSchedule(name: string): number; pauseSchedule(name: string): number;
/** /**
* *
*/ */
@ -312,7 +321,7 @@ declare module 'colyseus' {
* @param exPlayer * @param exPlayer
* @return {Player[]} * @return {Player[]}
*/ */
getOtherTeamPlayers(srcPlayer: string, exPlayer?: string ): Player[]; getOtherTeamPlayers(srcPlayer: string, exPlayer?: string): Player[];
/** /**
* index获取玩家 * index获取玩家

View File

@ -246,7 +246,7 @@ export class GeneralRoom extends Room {
* client数量 * client数量
* @return {number} * @return {number}
*/ */
clientCount(): number { get clientCount(): number {
return this.clients.length return this.clients.length
} }
@ -288,7 +288,9 @@ export class GeneralRoom extends Room {
this.gameClock.delete(name) this.gameClock.delete(name)
return time return time
} }
scheduleActive(name: string): boolean {
return this.gameClock.has(name) && this.gameClock.get(name).active
}
/** /**
* , * ,
* @param {string} name * @param {string} name

View File

@ -65,7 +65,7 @@ export class GMCommand extends Command<CardGameState, {client: Client, message:
*/ */
addRobot(msg:string) { addRobot(msg:string) {
let count = msg ? parseInt(msg) : 1; let count = msg ? parseInt(msg) : 1;
let count2 = this.room.maxClients - this.room.clientCount(); let count2 = this.room.maxClients - this.room.clientCount;
for (let i = 0; i< Math.min(count, count2); i++) { for (let i = 0; i< Math.min(count, count2); i++) {
this.room.addRobot(); this.room.addRobot();
} }

View File

@ -178,7 +178,7 @@ export class GameResultCommand extends Command<CardGameState, {}> {
await self.room.setPrivate(false) await self.room.setPrivate(false)
//开启匹配定时, 长时间没匹配到人的话, 添加机器人 //开启匹配定时, 长时间没匹配到人的话, 添加机器人
let timeOutWaitingPlayer = async function () { let timeOutWaitingPlayer = async function () {
let count = self.room.maxClients - self.room.clientCount() let count = self.room.maxClients - self.room.clientCount
if (count > 0) { if (count > 0) {
for (let i = 0; i < count; i++) { for (let i = 0; i < count; i++) {
await self.room.addRobot() await self.room.addRobot()

View File

@ -1,12 +1,13 @@
import { Command } from '@colyseus/command' import { Command } from '@colyseus/command'
import { CardGameState } from '../schema/CardGameState' import { CardGameState } from '../schema/CardGameState'
import { Player } from '../schema/Player' import { Player } from '../schema/Player'
import { Client } from 'colyseus' import { Client, Room } from 'colyseus'
import { GameStateConst } from '../../constants/GameStateConst' import { GameStateConst } from '../../constants/GameStateConst'
import { GameEnv } from '../../cfg/GameEnv' import { GameEnv } from '../../cfg/GameEnv'
import { BaseConst } from '../../constants/BaseConst' import { BaseConst } from '../../constants/BaseConst'
import { getUserInfo, randomUserInfo } from '../../common/WebApi' import { getUserInfo, randomUserInfo } from '../../common/WebApi'
import { ClockNameConst } from '../../constants/ClockNameConst' import { ClockNameConst } from '../../constants/ClockNameConst'
import { debugRoom } from '../../common/Debug'
/** /**
* *
@ -18,12 +19,12 @@ export class OnJoinCommand extends Command<CardGameState, {
score?: number score?: number
}> { }> {
async execute({ client, accountId, seat, score } = this.payload) { async execute({ client, accountId, seat, score } = this.payload) {
let count = this.state.players.size const count = this.room.clientCount
if (count >= this.room.maxClients) { if (count >= this.room.maxClients) {
return return
} }
// begin of set seat and team // begin of set seat and team
let idx = count let idx: number
let seatSet = new Set([0, 1, 2, 3]) let seatSet = new Set([0, 1, 2, 3])
let accounts: string[] = [] let accounts: string[] = []
for (let [, p] of this.state.players) { for (let [, p] of this.state.players) {
@ -70,16 +71,19 @@ export class OnJoinCommand extends Command<CardGameState, {
this.room.addAssistClient(client.sessionId) this.room.addAssistClient(client.sessionId)
let self = this let self = this
if (!this.room.match && !this.room.robotCount) { if (!this.room.match && !this.room.robotCount) {
if (this.state.players.size >= this.room.maxClients) { /**
this.room.lock().then(() => { * , (),
}) * maxClients,
this.state.updateGameState(GameStateConst.STATE_WAIT_PREPARE) */
if (this.room.clientCount >= this.room.maxClients) {
beginWaitingPrepare(this.room)
} }
} else { } else {
if (this.room.clientCount() == 1) { if (this.room.clientCount == 1) {
// 正常的匹配逻辑进入的第一个玩家, 开启定时, 超过设定时间人没齐的话, 添加机器人 // 正常的匹配逻辑进入的第一个玩家, 开启定时, 超过设定时间人没齐的话, 添加机器人
let timeOutWaitingPlayer = async function () { let timeOutWaitingPlayer = async function () {
let count = self.room.maxClients - self.room.clientCount() let count = self.room.maxClients - self.room.clientCount
debugRoom(`waiting_player time over, add ${ count } robot`)
if (count > 0) { if (count > 0) {
for (let i = 0; i < count; i++) { for (let i = 0; i < count; i++) {
await self.room.addRobot() await self.room.addRobot()
@ -88,17 +92,14 @@ export class OnJoinCommand extends Command<CardGameState, {
} }
let time = new GameEnv().waitingPlayerTime * 1000 let time = new GameEnv().waitingPlayerTime * 1000
self.room.beginSchedule(time, timeOutWaitingPlayer, ClockNameConst.WAITING_PLAYER) self.room.beginSchedule(time, timeOutWaitingPlayer, ClockNameConst.WAITING_PLAYER)
} else if (this.room.clientCount() > 1 && this.room.clientCount() < this.room.maxClients) { } else if (this.room.clientCount > 1 && this.room.clientCount < this.room.maxClients) {
let moreTime = new GameEnv().waitingPlayerOnePlus * 1000 let moreTime = new GameEnv().waitingPlayerOnePlus * 1000
self.room.addScheduleTime(moreTime, 'play_join', ClockNameConst.WAITING_PLAYER) self.room.addScheduleTime(moreTime, 'play_join', ClockNameConst.WAITING_PLAYER)
} }
if (this.state.players.size >= this.room.maxClients) { if (this.room.clientCount >= this.room.maxClients) {
this.room.stopSchedule(ClockNameConst.WAITING_PLAYER) beginWaitingPrepare(this.room)
this.room.lock().then(() => { } else if (this.room.clientCount < this.room.maxClients
}) && this.room.clientCount >= this.room.maxClients - this.room.robotCount) {
this.state.updateGameState(GameStateConst.STATE_WAIT_PREPARE)
} else if (this.state.players.size < this.room.maxClients
&& this.state.players.size >= this.room.maxClients - this.room.robotCount) {
for (let i = 0; i < this.room.robotCount; i++) { for (let i = 0; i < this.room.robotCount; i++) {
this.room.robotCount-- this.room.robotCount--
await self.room.addRobot() await self.room.addRobot()
@ -106,8 +107,14 @@ export class OnJoinCommand extends Command<CardGameState, {
} }
} }
this.room.bUserJoin(`${ client.sessionId }`, { except: client }) this.room.bUserJoin(`${ client.sessionId }`, { except: client })
} }
} }
const beginWaitingPrepare = function (room: Room) {
room.stopSchedule(ClockNameConst.WAITING_PLAYER)
room.lock().then(() => {
})
room.state.updateGameState(GameStateConst.STATE_WAIT_PREPARE)
}

View File

@ -1,68 +1,71 @@
import {Command} from "@colyseus/command"; import { Command } from '@colyseus/command'
import {CardGameState} from "../schema/CardGameState"; import { CardGameState } from '../schema/CardGameState'
import {Client} from "colyseus"; import { Client } from 'colyseus'
import {PlayerStateConst} from "../../constants/PlayerStateConst"; import { PlayerStateConst } from '../../constants/PlayerStateConst'
import {GameStateConst} from "../../constants/GameStateConst"; import { GameStateConst } from '../../constants/GameStateConst'
import {GameEnv} from "../../cfg/GameEnv"; import { GameEnv } from '../../cfg/GameEnv'
import {SelectHeroCommand} from "./SelectHeroCommand"; import { SelectHeroCommand } from './SelectHeroCommand'
import {HeroCfg} from "../../cfg/parsers/HeroCfg"; import { HeroCfg } from '../../cfg/parsers/HeroCfg'
import {BaseConst} from "../../constants/BaseConst"; import { BaseConst } from '../../constants/BaseConst'
import { ClockNameConst } from '../../constants/ClockNameConst' import { ClockNameConst } from '../../constants/ClockNameConst'
/** /**
* *
*/ */
export class PlayReadyCommand extends Command<CardGameState, { export class PlayReadyCommand extends Command<CardGameState, {
client: Client client: Client
}> { }> {
async execute({client}: { client: Client }) { async execute({ client }: { client: Client }) {
this.state.players.get(client.sessionId).state = PlayerStateConst.PLAYER_READY; this.state.players.get(client.sessionId).state = PlayerStateConst.PLAYER_READY
this.room.broadcast("player_ready_s2c", {player: client.sessionId}, {except: client}); this.room.broadcast('player_ready_s2c', { player: client.sessionId }, { except: client })
let readyCount = 0; let readyCount = 0
for (let [, player] of this.state.players) { for (let [, player] of this.state.players) {
if (player.state === PlayerStateConst.PLAYER_READY) { if (player.state === PlayerStateConst.PLAYER_READY) {
readyCount++; readyCount++
}
}
// 如果所有人的状态都为已准备状态, 则开始发牌
if (readyCount >= this.room.maxClients) {
this.room.stopSchedule(ClockNameConst.RESTART_SCHEDULE)
this.room.stopSchedule(ClockNameConst.WAITING_PLAYER)
// 比大小, 确定先手
// return [new PrepareCommand()];
// let i = 0;
// for (let [,player] of this.state.players) {
// player.team = (i == 1 || i == 2) ? 1 : 0;
// i += 1;
// }
await this.room.setPrivate(true)
this.room.state.updateGameState(GameStateConst.CHANGE_HERO)
let self = this
/**
*
*/
let pickHeroTimeOut = function () {
for (let [, curPlayer] of self.state.players) {
if (curPlayer.state == PlayerStateConst.PLAYER_READY) {
let heroId: number
if (curPlayer.heros) {
heroId = curPlayer.heros.randomOne()
} else {
let heroMap: Map<number, HeroCfg> = global.$cfg.get(BaseConst.HERO)
let heroArr: HeroCfg[] = [...heroMap.values()]
let hero: HeroCfg = heroArr.randomOne()
heroId = hero.id
} }
let targetClient = self.room.getClient(curPlayer)
self.room.dispatcher.dispatch(new SelectHeroCommand(), {
client: targetClient,
heroId
})
}
} }
// 如果所有人的状态都为已准备状态, 则开始发牌 }
if (readyCount >= this.room.maxClients) { let time = new GameEnv().pickHeroTime * 1000
this.room.stopSchedule(ClockNameConst.RESTART_SCHEDULE); this.room.beginSchedule(time, pickHeroTimeOut, ClockNameConst.PICK_HERO)
this.room.stopSchedule(ClockNameConst.WAITING_PLAYER);
// 比大小, 确定先手
// return [new PrepareCommand()];
// let i = 0;
// for (let [,player] of this.state.players) {
// player.team = (i == 1 || i == 2) ? 1 : 0;
// i += 1;
// }
await this.room.setPrivate(true);
this.room.state.updateGameState(GameStateConst.CHANGE_HERO);
let self = this;
/**
*
*/
let pickHeroTimeOut = function () {
for (let [, curPlayer] of self.state.players) {
if (curPlayer.state == PlayerStateConst.PLAYER_READY ) {
let heroId: number
if (curPlayer.heros) {
heroId = curPlayer.heros.randomOne()
} else {
let heroMap: Map<number, HeroCfg> = global.$cfg.get(BaseConst.HERO);
let heroArr: HeroCfg[] = [...heroMap.values()];
let hero: HeroCfg = heroArr.randomOne();
heroId = hero.id
}
let targetClient = self.room.getClient(curPlayer);
self.room.dispatcher.dispatch(new SelectHeroCommand(), {client: targetClient, heroId});
}
}
}
let time = new GameEnv().pickHeroTime * 1000;
this.room.beginSchedule(time, pickHeroTimeOut, ClockNameConst.PICK_HERO);
}
} }
}
} }

View File

@ -5,58 +5,58 @@ import {
Schema, Schema,
SetSchema, SetSchema,
type type
} from "@colyseus/schema"; } from '@colyseus/schema'
import {Pet} from "./Pet"; import { Pet } from './Pet'
import {Card} from "./Card"; import { Card } from './Card'
import {GameEnv} from "../../cfg/GameEnv"; import { GameEnv } from '../../cfg/GameEnv'
import {PlayerStateConst} from "../../constants/PlayerStateConst"; import { PlayerStateConst } from '../../constants/PlayerStateConst'
import {StateTypeEnum} from "../enums/StateTypeEnum"; import { StateTypeEnum } from '../enums/StateTypeEnum'
export class Player extends Schema { export class Player extends Schema {
@type("string") @type('string')
id: string; id: string
accountId: string; accountId: string
/** /**
* *
* @type {number} * @type {number}
*/ */
@type("number") @type('number')
score: number; score: number
/** /**
* *
* @type {string} * @type {string}
*/ */
group?: string; group?: string
@type("number") @type('number')
heroId: number; heroId: number
/** /**
* *
*/ */
@filter(function (this: Player, client, value, root) { @filter(function (this: Player, client, value, root) {
return (client.sessionId == this.id); return (client.sessionId == this.id)
}) })
@type({map: Card}) @type({ map: Card })
cards = new MapSchema<Card>(); cards = new MapSchema<Card>()
/** /**
* *
* @type {SetSchema<string>} * @type {SetSchema<string>}
*/ */
@type({set: "string"}) @type({ set: 'string' })
cardSet = new SetSchema<string>(); cardSet = new SetSchema<string>()
/** /**
* *
*/ */
@type([Card]) @type([Card])
cardQueue = new ArraySchema<Card>(); cardQueue = new ArraySchema<Card>()
/** /**
* hp * hp
*/ */
@type("number") @type('number')
hp: number; hp: number
/** /**
* *
@ -66,81 +66,81 @@ export class Player extends Schema {
* 3: 已换完牌 * 3: 已换完牌
* 4: 玩家已选择英雄 * 4: 玩家已选择英雄
*/ */
@type("number") @type('number')
state: number; state: number
online: boolean = true; online: boolean = true
/** /**
* *
*/ */
@type({map: Pet}) @type({ map: Pet })
pets = new MapSchema<Pet>(); pets = new MapSchema<Pet>()
/** /**
* *
*/ */
@type("number") @type('number')
team: number; team: number
@type("number") @type('number')
idx: number; idx: number
/** /**
* , , * , ,
*/ */
@type("number") @type('number')
extraTime: number; extraTime: number
@type("string") @type('string')
nickname: string; nickname: string
@type("string") @type('string')
avatar: string; avatar: string
/** /**
* *
*/ */
countTotal: number; countTotal: number
/** /**
* *
*/ */
countPresent: number; countPresent: number
/** /**
* *
*/ */
statData: Map<StateTypeEnum, number> = new Map(); statData: Map<StateTypeEnum, number> = new Map()
/** /**
* pet值, * pet值,
*/ */
petData: Map<number, number> = new Map(); petData: Map<number, number> = new Map()
heros: number[]; heros: number[]
// 是否是机器人 // 是否是机器人
robot: boolean; robot: boolean
// 十场胜率 // 十场胜率
winRate: number; winRate: number
/** /**
* , , () * , , ()
* key = id * key = id
* val = weight * val = weight
*/ */
@type({map: "number"}) @type({ map: 'number' })
unitCfgs = new MapSchema<number>(); unitCfgs = new MapSchema<number>()
constructor(id: string, idx: number, team: number) { constructor(id: string, idx: number, team: number) {
super(); super()
this.id = id; this.id = id
this.state = PlayerStateConst.PLAYER_NORMAL; this.state = PlayerStateConst.PLAYER_NORMAL
this.hp = 0; this.hp = 0
this.idx = idx; this.idx = idx
this.heroId = 0; this.heroId = 0
this.team = team; this.team = team
this.countTotal = 0; this.countTotal = 0
this.countPresent = 0; this.countPresent = 0
this.online = true; this.online = true
for (let i = 0; i < new GameEnv().maxPlayerPetCount + 1; i++) { for (let i = 0; i < new GameEnv().maxPlayerPetCount + 1; i++) {
let pet = new Pet(i); let pet = new Pet(i)
pet.state = 0; pet.state = 0
pet.isHero = i === 0; pet.isHero = i === 0
this.pets.set(i + '', pet); this.pets.set(i + '', pet)
} }
} }