Frame/Assets/Scripts/Room/Room.cs

131 lines
3.8 KiB
C#

using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Cysharp.Threading.Tasks;
using Game.Player;
using UnityEngine;
namespace Game.Room
{
public interface IRoom
{
string roomName { get; }
RoomData roomData { get; }
RoomInfo roomInfo { get; }
IReadOnlyList<IPlayer> players { get; }
RoomType roomType { get; }
UniTask<bool> JoinAsync(IPlayer player, CancellationToken token);
UniTask<bool> Quit(IPlayer player);
void SetIsCanReturnJinBei(bool isCan);
List<IPlayer> QuitAndClearAll();
// float ClearAll();
void Dispose();
bool InvestmentJinBei(IPlayer player, float jinbei);
}
[System.Serializable]
public class Room : IRoom
{
private GameObject self;
private RoomInfo _roomInfo;
private RoomData _roomData;
private string _roomName;
private bool _isCanReturnJinBei;
public RoomType roomType => this._roomData.roomType;
public string roomName => this._roomName;
public RoomData roomData => this._roomData;
public RoomInfo roomInfo => this._roomInfo;
public IReadOnlyList<IPlayer> players => this._roomData.players;
public Room(RoomType roomType, GameObject roomGo)
{
this._roomData = new RoomData(roomType);
_roomName = roomType.ToString();
// view
this._roomInfo = roomGo.GetComponent<RoomInfo>();
this._roomInfo.SetRoom(this);
this.self = roomGo;
this._roomData.jinBeiCallback += this._roomInfo.UpdateNumber;
}
public void Dispose()
{
this._roomData.jinBeiCallback -= this._roomInfo.UpdateNumber;
this._roomData.Reset();
this.self = null;
this._roomInfo = null;
this._roomData = null;
this._roomName = null;
}
public async UniTask<bool> JoinAsync(IPlayer player, CancellationToken token)
{
if (this.players.Contains(player))
return false;
// Debug.Log($"{player.playerName} join {roomType} !!");
bool res = await player.WaitMoveRoomAsync(this, token);
this._roomData.AddPlayer(player);
return true;
}
public async UniTask<bool> Quit(IPlayer player)
{
if (!this.players.Contains(player))
return false;
Debug.Log($"{player.playerName} quit {roomType} !!");
var f = this._roomData.RemovePlayer(player);
EventManager.Instance.FireNow(this, new ReturnPlayerJinBeiEventArgs(player, f));
await UniTask.Yield();
return true;
}
public void SetIsCanReturnJinBei(bool isCan)
{
this._isCanReturnJinBei = isCan;
}
public List<IPlayer> QuitAndClearAll()
{
if (this._isCanReturnJinBei)
{
// 归还金贝
var dictionary = this._roomData.ReturnPlayerAndJinBei();
foreach (var player in dictionary.Keys)
{
Debug.Log($"return player {player.playerName} jinBei : {dictionary[player]}");
EventManager.Instance.FireNow(this, new ReturnPlayerJinBeiEventArgs(player, dictionary[player]));
}
}
var list = new List<IPlayer>(_roomData.players);
this._roomData.Reset();
return list;
}
public bool InvestmentJinBei(IPlayer player, float jinBei)
{
if (!this.players.Contains(player))
{
Debug.LogWarning($"{roomType} dont have {player.playerName}");
return false;
}
this._roomData.AddJinBei(player, jinBei);
return true;
}
}
}