powerfun-new-net/Unility/GameRoomHelper.cs
2022-05-18 10:39:35 +08:00

105 lines
3.0 KiB
C#

using Newtonsoft.Json;
using OnlineUserPool.Model;
using Serilog;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace OnlineUserPool.Unility
{
public class GameRoomHelper
{
public static string GameRoomFilePath { get; set; }
public static string GameRoomIdPath { get; set; }
public static object _lockobj = new object();
public static object _lockMaxId = new object();
static GameRoomHelper()
{
GameRoomFilePath = AppDomain.CurrentDomain.BaseDirectory + "\\GameRoom.txt";
GameRoomIdPath = AppDomain.CurrentDomain.BaseDirectory + "\\GameRoomId.txt";
if (!File.Exists(GameRoomFilePath))
{
File.Create(GameRoomFilePath);
}
if (!File.Exists(GameRoomIdPath))
{
File.Create(GameRoomIdPath);
}
}
public static int GetMaxId()
{
try
{
if (!File.Exists(GameRoomIdPath))
{
return 0;
}
var content = File.ReadAllText(GameRoomIdPath);
if (string.IsNullOrEmpty(content))
{
return 0;
}
return Convert.ToInt32(content);
}
catch (Exception e)
{
Log.Error($"本地读取对战信息房间号出错:{e}");
return 0;
}
}
public static void SetMaxId(int id)
{
try
{
lock (_lockMaxId)
{
File.WriteAllText(GameRoomIdPath, $"{id}");
}
}
catch (Exception e)
{
Log.Error($"本地存储对战信息房间号出错:{e}");
}
}
public static List<RoomModel> Get()
{
var list = new List<RoomModel>();
try
{
if (!File.Exists(GameRoomFilePath))
{
return list;
}
var content = File.ReadAllText(GameRoomFilePath);
if (string.IsNullOrEmpty(content))
{
return list;
}
return JsonConvert.DeserializeObject<List<RoomModel>>(content);
}
catch (Exception e)
{
Log.Error($"读取本地存储对战信息出错:{e}");
}
return list;
}
public static void Set(List<RoomModel> list)
{
try
{
lock (_lockobj)
{
var str = JsonConvert.SerializeObject(list);
File.WriteAllText(GameRoomFilePath, str);
}
}
catch (Exception e) { Log.Error($"本地存储对战信息出错:{e}"); }
}
}
}