From d2544487014644027138985454fcc59d5097426a Mon Sep 17 00:00:00 2001 From: 964293341 Date: Thu, 25 Apr 2024 12:39:31 +0800 Subject: [PATCH 01/11] feat: :sparkles: a more powerful logger --- logic/Preparation/Utility/Logger.cs | 93 +++++++++++++++++++++++++---- playback/Playback/MessageWriter.cs | 6 +- 2 files changed, 86 insertions(+), 13 deletions(-) diff --git a/logic/Preparation/Utility/Logger.cs b/logic/Preparation/Utility/Logger.cs index 84c1e976..b47b34dd 100755 --- a/logic/Preparation/Utility/Logger.cs +++ b/logic/Preparation/Utility/Logger.cs @@ -1,21 +1,90 @@ using System; +using System.Collections.Generic; using System.IO; +using System.Threading; +using System.Threading.Tasks; +using Timothy.FrameRateTask; -namespace Preparation.Utility +namespace Preparation.Utility.Logging; + +public struct LogInfo { - public class Logger + public string FileName; + public string Info; +} + +public class LogQueue +{ + public static LogQueue Global { get; } = new(); + private static readonly object queueLock = new(); + + private readonly Queue logInfoQueue = new(); + + public async Task Commit(LogInfo logInfo) { - static public void Writelog(object current, string str) + await Task.Run(() => { - string path = "log.txt"; - string log = $"[{DateTime.Now}] {current.GetType()} {current} {str}"; - File.AppendAllText(path, log + Environment.NewLine); - } - static public void Writelog(string str) + lock (queueLock) logInfoQueue.Enqueue(logInfo); + }); + } + + private LogQueue() + { + new Thread(() => { - string path = "log.txt"; - string log = $"[{DateTime.Now}] {str}"; - File.AppendAllText(path, log + Environment.NewLine); - } + new FrameRateTaskExecutor( + loopCondition: () => Global != null, + loopToDo: () => + { + lock (queueLock) + { + while (logInfoQueue.Count != 0) + { + var logInfo = logInfoQueue.Dequeue(); + File.AppendAllText(logInfo.FileName, logInfo.Info + Environment.NewLine); + } + } + }, + timeInterval: 200, + finallyReturn: () => 0 + ).Start(); + }) + { IsBackground = true }.Start(); + } +} + +public class Logger(string module, string file) +{ + public void ConsoleLog(string msg, bool Duplicate = false) + { + var info = $"[{module}]{msg}"; + Console.WriteLine(info); + if (Duplicate) + _ = LogQueue.Global.Commit(new() + { + FileName = file, + Info = info + }); + } + public void ConsoleLogDebug(string msg, bool Duplicate = false) + { +#if DEBUG + var info = $"[{module}]{msg}"; + Console.WriteLine(info); + if (Duplicate) + _ = LogQueue.Global.Commit(new() + { + FileName = file, + Info = info + }); +#endif + } + public static string TypeName(object obj) + { + return obj.GetType().Name; + } + public static string ObjInfo(object obj, string msg) + { + return $"<{TypeName(obj)} {msg}>"; } } diff --git a/playback/Playback/MessageWriter.cs b/playback/Playback/MessageWriter.cs index 57fd44b0..61a2bb97 100755 --- a/playback/Playback/MessageWriter.cs +++ b/playback/Playback/MessageWriter.cs @@ -36,7 +36,11 @@ public void WriteOne(MessageToClient msg) if (Disposed) return; cos.WriteMessage(msg); WrittenNum++; - if (WrittenNum % FlushNum == 0) Flush(); + if (WrittenNum % FlushNum == 0) + { + Flush(); + WrittenNum = 0; + } } public void Flush() From 648668110f9bb09b24c4f7d12213bb1be174afa5 Mon Sep 17 00:00:00 2001 From: 964293341 Date: Thu, 25 Apr 2024 12:41:48 +0800 Subject: [PATCH 02/11] feat(Preparation): introduce FrameRateTask in Preparation --- logic/Preparation/Preparation.csproj | 1 + 1 file changed, 1 insertion(+) diff --git a/logic/Preparation/Preparation.csproj b/logic/Preparation/Preparation.csproj index ecdec7a6..954ef09f 100755 --- a/logic/Preparation/Preparation.csproj +++ b/logic/Preparation/Preparation.csproj @@ -9,6 +9,7 @@ + From 0d2ef3285e1ff7a4998e2a62174e3a4440f1f778 Mon Sep 17 00:00:00 2001 From: 964293341 Date: Thu, 25 Apr 2024 14:17:00 +0800 Subject: [PATCH 03/11] refactor: introduce some namespaces - Preparation.Utility.Value - Preparation.Utility.Value.SafeValue - Preparation.Utility.Value.SafeValue.Atomic - Preparation.Utility.Value.SafeValue.LockedValue - Preparation.Utility.Value.SafeValue.SafeMethod --- logic/GameClass/GameObj/Areas/AreaFactory.cs | 1 + logic/GameClass/GameObj/Areas/Asteroid.cs | 1 + logic/GameClass/GameObj/Areas/Construction.cs | 3 ++ logic/GameClass/GameObj/Areas/Home.cs | 2 + logic/GameClass/GameObj/Areas/NullArea.cs | 1 + .../GameObj/Areas/OutOfBoundBlock.cs | 1 + logic/GameClass/GameObj/Areas/Resource.cs | 3 ++ logic/GameClass/GameObj/Areas/Ruin.cs | 1 + logic/GameClass/GameObj/Areas/Shadow.cs | 1 + logic/GameClass/GameObj/Areas/Wormhole.cs | 5 +- logic/GameClass/GameObj/Areas/WormholeCell.cs | 5 +- logic/GameClass/GameObj/Base.cs | 3 ++ logic/GameClass/GameObj/BombedBullet.cs | 1 + logic/GameClass/GameObj/Bullet.cs | 2 + logic/GameClass/GameObj/Bullets/Arc.cs | 1 + .../GameObj/Bullets/BulletFactory.cs | 1 + logic/GameClass/GameObj/Bullets/Laser.cs | 1 + logic/GameClass/GameObj/Bullets/Missile.cs | 1 + logic/GameClass/GameObj/Bullets/NullBullet.cs | 1 + logic/GameClass/GameObj/Bullets/Plasma.cs | 1 + logic/GameClass/GameObj/Bullets/Shell.cs | 1 + logic/GameClass/GameObj/GameObj.cs | 2 + logic/GameClass/GameObj/Immovable.cs | 1 + logic/GameClass/GameObj/Map/Map.cs | 4 +- logic/GameClass/GameObj/Map/MapGameTimer.cs | 2 +- logic/GameClass/GameObj/MoneyPool.cs | 3 +- logic/GameClass/GameObj/Movable.cs | 2 + logic/GameClass/GameObj/ObjOfShip.cs | 1 + logic/GameClass/GameObj/Ship.cs | 5 +- logic/GameEngine/CollisionChecker.cs | 2 + logic/GameEngine/MoveEngine.cs | 1 + logic/Gaming/AttackManager.cs | 1 + logic/Gaming/Game.cs | 1 + logic/Gaming/ShipManager.cs | 1 + logic/Preparation/Interface/IGameObj.cs | 2 + logic/Preparation/Interface/IHome.cs | 2 +- logic/Preparation/Interface/IMap.cs | 2 + logic/Preparation/Interface/IMoneyPool.cs | 3 +- logic/Preparation/Interface/IMovable.cs | 2 + logic/Preparation/Interface/IPlayer.cs | 2 +- logic/Preparation/Interface/IShip.cs | 2 + logic/Preparation/Interface/ITimer.cs | 2 +- logic/Preparation/Utility/GameData.cs | 3 +- .../Utility/Value/SafeValue/Atomic.cs | 14 ++--- .../Utility/Value/SafeValue/AtomicInt.cs | 33 ++++++------ .../Utility/Value/SafeValue/ListLocked.cs | 2 +- .../SafeValue/LockedValue/InRangeTimeBased.cs | 16 +++--- .../Value/SafeValue/LockedValue/InTheRange.cs | 25 ++++----- .../SafeValue/LockedValue/LockedDouble.cs | 5 +- .../SafeValue/LockedValue/LockedValue.cs | 11 ++-- .../Value/SafeValue/LockedValue/PositiveV.cs | 8 +-- .../Utility/Value/SafeValue/ObjPool.cs | 2 +- .../SafeValue/SafeMethod/InterlockedEx.cs | 12 ++--- .../Utility/Value/SafeValue/TimeBased.cs | 31 +++++------ .../Utility/Value/ValueInterface/IAddable.cs | 2 +- .../Utility/Value/ValueInterface/IDouble.cs | 4 +- logic/Preparation/Utility/Value/XY.cs | 54 +++++++++---------- 57 files changed, 179 insertions(+), 123 deletions(-) diff --git a/logic/GameClass/GameObj/Areas/AreaFactory.cs b/logic/GameClass/GameObj/Areas/AreaFactory.cs index 49e93de3..11400498 100755 --- a/logic/GameClass/GameObj/Areas/AreaFactory.cs +++ b/logic/GameClass/GameObj/Areas/AreaFactory.cs @@ -1,4 +1,5 @@ using Preparation.Utility; +using Preparation.Utility.Value; namespace GameClass.GameObj.Areas; diff --git a/logic/GameClass/GameObj/Areas/Asteroid.cs b/logic/GameClass/GameObj/Areas/Asteroid.cs index 841c0966..8dca4053 100755 --- a/logic/GameClass/GameObj/Areas/Asteroid.cs +++ b/logic/GameClass/GameObj/Areas/Asteroid.cs @@ -1,4 +1,5 @@ using Preparation.Utility; +using Preparation.Utility.Value; namespace GameClass.GameObj.Areas; diff --git a/logic/GameClass/GameObj/Areas/Construction.cs b/logic/GameClass/GameObj/Areas/Construction.cs index 28a8595b..1161c235 100755 --- a/logic/GameClass/GameObj/Areas/Construction.cs +++ b/logic/GameClass/GameObj/Areas/Construction.cs @@ -1,4 +1,7 @@ using Preparation.Utility; +using Preparation.Utility.Value; +using Preparation.Utility.Value.SafeValue.Atomic; +using Preparation.Utility.Value.SafeValue.LockedValue; namespace GameClass.GameObj.Areas; diff --git a/logic/GameClass/GameObj/Areas/Home.cs b/logic/GameClass/GameObj/Areas/Home.cs index 0ddc1e9c..dbd6da49 100755 --- a/logic/GameClass/GameObj/Areas/Home.cs +++ b/logic/GameClass/GameObj/Areas/Home.cs @@ -1,5 +1,7 @@ using Preparation.Interface; using Preparation.Utility; +using Preparation.Utility.Value; +using Preparation.Utility.Value.SafeValue.LockedValue; namespace GameClass.GameObj.Areas; diff --git a/logic/GameClass/GameObj/Areas/NullArea.cs b/logic/GameClass/GameObj/Areas/NullArea.cs index 674b9f3f..3baeea51 100755 --- a/logic/GameClass/GameObj/Areas/NullArea.cs +++ b/logic/GameClass/GameObj/Areas/NullArea.cs @@ -1,4 +1,5 @@ using Preparation.Utility; +using Preparation.Utility.Value; namespace GameClass.GameObj.Areas; diff --git a/logic/GameClass/GameObj/Areas/OutOfBoundBlock.cs b/logic/GameClass/GameObj/Areas/OutOfBoundBlock.cs index dfbcf758..c5f600a4 100755 --- a/logic/GameClass/GameObj/Areas/OutOfBoundBlock.cs +++ b/logic/GameClass/GameObj/Areas/OutOfBoundBlock.cs @@ -1,5 +1,6 @@ using Preparation.Interface; using Preparation.Utility; +using Preparation.Utility.Value; namespace GameClass.GameObj.Areas; diff --git a/logic/GameClass/GameObj/Areas/Resource.cs b/logic/GameClass/GameObj/Areas/Resource.cs index 62d4c465..8edc43a8 100755 --- a/logic/GameClass/GameObj/Areas/Resource.cs +++ b/logic/GameClass/GameObj/Areas/Resource.cs @@ -1,4 +1,7 @@ using Preparation.Utility; +using Preparation.Utility.Value; +using Preparation.Utility.Value.SafeValue.Atomic; +using Preparation.Utility.Value.SafeValue.LockedValue; namespace GameClass.GameObj.Areas; diff --git a/logic/GameClass/GameObj/Areas/Ruin.cs b/logic/GameClass/GameObj/Areas/Ruin.cs index fcb32017..c4a96790 100755 --- a/logic/GameClass/GameObj/Areas/Ruin.cs +++ b/logic/GameClass/GameObj/Areas/Ruin.cs @@ -1,4 +1,5 @@ using Preparation.Utility; +using Preparation.Utility.Value; namespace GameClass.GameObj.Areas; diff --git a/logic/GameClass/GameObj/Areas/Shadow.cs b/logic/GameClass/GameObj/Areas/Shadow.cs index 36f1e3e4..3d35a9b3 100755 --- a/logic/GameClass/GameObj/Areas/Shadow.cs +++ b/logic/GameClass/GameObj/Areas/Shadow.cs @@ -1,4 +1,5 @@ using Preparation.Utility; +using Preparation.Utility.Value; namespace GameClass.GameObj.Areas; diff --git a/logic/GameClass/GameObj/Areas/Wormhole.cs b/logic/GameClass/GameObj/Areas/Wormhole.cs index d94f9ee7..f92035c6 100755 --- a/logic/GameClass/GameObj/Areas/Wormhole.cs +++ b/logic/GameClass/GameObj/Areas/Wormhole.cs @@ -1,5 +1,6 @@ -using Preparation.Interface; -using Preparation.Utility; +using Preparation.Utility; +using Preparation.Utility.Value.SafeValue.Atomic; +using Preparation.Utility.Value.SafeValue.LockedValue; using System.Collections.Generic; namespace GameClass.GameObj.Areas; diff --git a/logic/GameClass/GameObj/Areas/WormholeCell.cs b/logic/GameClass/GameObj/Areas/WormholeCell.cs index 90cd9b08..0f1726ed 100644 --- a/logic/GameClass/GameObj/Areas/WormholeCell.cs +++ b/logic/GameClass/GameObj/Areas/WormholeCell.cs @@ -1,6 +1,5 @@ -using Preparation.Interface; -using Preparation.Utility; -using System.Collections.Generic; +using Preparation.Utility; +using Preparation.Utility.Value; namespace GameClass.GameObj.Areas; diff --git a/logic/GameClass/GameObj/Base.cs b/logic/GameClass/GameObj/Base.cs index dd79ba25..adc208e9 100644 --- a/logic/GameClass/GameObj/Base.cs +++ b/logic/GameClass/GameObj/Base.cs @@ -1,6 +1,9 @@ using GameClass.GameObj.Areas; using Preparation.Interface; using Preparation.Utility; +using Preparation.Utility.Value; +using Preparation.Utility.Value.SafeValue; +using Preparation.Utility.Value.SafeValue.Atomic; using System.Collections.Generic; namespace GameClass.GameObj diff --git a/logic/GameClass/GameObj/BombedBullet.cs b/logic/GameClass/GameObj/BombedBullet.cs index 6e628038..0d89bc29 100755 --- a/logic/GameClass/GameObj/BombedBullet.cs +++ b/logic/GameClass/GameObj/BombedBullet.cs @@ -1,4 +1,5 @@ using Preparation.Utility; +using Preparation.Utility.Value; namespace GameClass.GameObj { diff --git a/logic/GameClass/GameObj/Bullet.cs b/logic/GameClass/GameObj/Bullet.cs index b93d9523..b2d9bd60 100755 --- a/logic/GameClass/GameObj/Bullet.cs +++ b/logic/GameClass/GameObj/Bullet.cs @@ -1,5 +1,7 @@ using Preparation.Interface; using Preparation.Utility; +using Preparation.Utility.Value; +using Preparation.Utility.Value.SafeValue.Atomic; namespace GameClass.GameObj; diff --git a/logic/GameClass/GameObj/Bullets/Arc.cs b/logic/GameClass/GameObj/Bullets/Arc.cs index dcdea31d..2dda6fb4 100755 --- a/logic/GameClass/GameObj/Bullets/Arc.cs +++ b/logic/GameClass/GameObj/Bullets/Arc.cs @@ -1,4 +1,5 @@ using Preparation.Utility; +using Preparation.Utility.Value; using System; namespace GameClass.GameObj.Bullets; diff --git a/logic/GameClass/GameObj/Bullets/BulletFactory.cs b/logic/GameClass/GameObj/Bullets/BulletFactory.cs index 53cf207e..cea76b02 100755 --- a/logic/GameClass/GameObj/Bullets/BulletFactory.cs +++ b/logic/GameClass/GameObj/Bullets/BulletFactory.cs @@ -1,4 +1,5 @@ using Preparation.Utility; +using Preparation.Utility.Value; namespace GameClass.GameObj.Bullets; diff --git a/logic/GameClass/GameObj/Bullets/Laser.cs b/logic/GameClass/GameObj/Bullets/Laser.cs index fb20bea9..5911e166 100755 --- a/logic/GameClass/GameObj/Bullets/Laser.cs +++ b/logic/GameClass/GameObj/Bullets/Laser.cs @@ -1,4 +1,5 @@ using Preparation.Utility; +using Preparation.Utility.Value; namespace GameClass.GameObj.Bullets; diff --git a/logic/GameClass/GameObj/Bullets/Missile.cs b/logic/GameClass/GameObj/Bullets/Missile.cs index c1d4895d..6296313b 100755 --- a/logic/GameClass/GameObj/Bullets/Missile.cs +++ b/logic/GameClass/GameObj/Bullets/Missile.cs @@ -1,4 +1,5 @@ using Preparation.Utility; +using Preparation.Utility.Value; using System; namespace GameClass.GameObj.Bullets; diff --git a/logic/GameClass/GameObj/Bullets/NullBullet.cs b/logic/GameClass/GameObj/Bullets/NullBullet.cs index 12de9476..eddd8d6f 100755 --- a/logic/GameClass/GameObj/Bullets/NullBullet.cs +++ b/logic/GameClass/GameObj/Bullets/NullBullet.cs @@ -1,4 +1,5 @@ using Preparation.Utility; +using Preparation.Utility.Value; namespace GameClass.GameObj.Bullets; diff --git a/logic/GameClass/GameObj/Bullets/Plasma.cs b/logic/GameClass/GameObj/Bullets/Plasma.cs index 3eea5fc2..2e719bf6 100755 --- a/logic/GameClass/GameObj/Bullets/Plasma.cs +++ b/logic/GameClass/GameObj/Bullets/Plasma.cs @@ -1,4 +1,5 @@ using Preparation.Utility; +using Preparation.Utility.Value; namespace GameClass.GameObj.Bullets; diff --git a/logic/GameClass/GameObj/Bullets/Shell.cs b/logic/GameClass/GameObj/Bullets/Shell.cs index 5d538caa..24189948 100755 --- a/logic/GameClass/GameObj/Bullets/Shell.cs +++ b/logic/GameClass/GameObj/Bullets/Shell.cs @@ -1,4 +1,5 @@ using Preparation.Utility; +using Preparation.Utility.Value; namespace GameClass.GameObj.Bullets; diff --git a/logic/GameClass/GameObj/GameObj.cs b/logic/GameClass/GameObj/GameObj.cs index 8754ab9c..95a419ee 100755 --- a/logic/GameClass/GameObj/GameObj.cs +++ b/logic/GameClass/GameObj/GameObj.cs @@ -1,5 +1,7 @@ using Preparation.Interface; using Preparation.Utility; +using Preparation.Utility.Value; +using Preparation.Utility.Value.SafeValue.Atomic; using System.Threading; namespace GameClass.GameObj diff --git a/logic/GameClass/GameObj/Immovable.cs b/logic/GameClass/GameObj/Immovable.cs index 314e7063..6d371518 100755 --- a/logic/GameClass/GameObj/Immovable.cs +++ b/logic/GameClass/GameObj/Immovable.cs @@ -1,4 +1,5 @@ using Preparation.Utility; +using Preparation.Utility.Value; namespace GameClass.GameObj; diff --git a/logic/GameClass/GameObj/Map/Map.cs b/logic/GameClass/GameObj/Map/Map.cs index 201b0b21..96f9ed13 100755 --- a/logic/GameClass/GameObj/Map/Map.cs +++ b/logic/GameClass/GameObj/Map/Map.cs @@ -2,6 +2,8 @@ using GameClass.MapGenerator; using Preparation.Interface; using Preparation.Utility; +using Preparation.Utility.Value; +using Preparation.Utility.Value.SafeValue; using System; using System.Collections.Generic; @@ -11,7 +13,7 @@ public partial class Map : IMap { private readonly Dictionary> gameObjDict; public Dictionary> GameObjDict => gameObjDict; - private readonly List wormholes = new(); + private readonly List wormholes = []; private readonly uint height; public uint Height => height; private readonly uint width; diff --git a/logic/GameClass/GameObj/Map/MapGameTimer.cs b/logic/GameClass/GameObj/Map/MapGameTimer.cs index f9a92db6..ac4e0841 100755 --- a/logic/GameClass/GameObj/Map/MapGameTimer.cs +++ b/logic/GameClass/GameObj/Map/MapGameTimer.cs @@ -1,4 +1,4 @@ -using Preparation.Utility; +using Preparation.Utility.Value.SafeValue.Atomic; using System; using System.Threading; using ITimer = Preparation.Interface.ITimer; diff --git a/logic/GameClass/GameObj/MoneyPool.cs b/logic/GameClass/GameObj/MoneyPool.cs index 515d8856..d7b3d6c5 100644 --- a/logic/GameClass/GameObj/MoneyPool.cs +++ b/logic/GameClass/GameObj/MoneyPool.cs @@ -1,5 +1,6 @@ using Preparation.Interface; -using Preparation.Utility; +using Preparation.Utility.Value.SafeValue.Atomic; +using Preparation.Utility.Value.SafeValue.LockedValue; namespace GameClass.GameObj; diff --git a/logic/GameClass/GameObj/Movable.cs b/logic/GameClass/GameObj/Movable.cs index cc22edef..0c1a4ddc 100755 --- a/logic/GameClass/GameObj/Movable.cs +++ b/logic/GameClass/GameObj/Movable.cs @@ -1,5 +1,7 @@ using Preparation.Interface; using Preparation.Utility; +using Preparation.Utility.Value; +using Preparation.Utility.Value.SafeValue.Atomic; using System.Threading; namespace GameClass.GameObj diff --git a/logic/GameClass/GameObj/ObjOfShip.cs b/logic/GameClass/GameObj/ObjOfShip.cs index 716b2fb0..5519080d 100755 --- a/logic/GameClass/GameObj/ObjOfShip.cs +++ b/logic/GameClass/GameObj/ObjOfShip.cs @@ -1,5 +1,6 @@ using Preparation.Interface; using Preparation.Utility; +using Preparation.Utility.Value; using System.Threading; namespace GameClass.GameObj diff --git a/logic/GameClass/GameObj/Ship.cs b/logic/GameClass/GameObj/Ship.cs index a0bf7fd8..ec851c07 100755 --- a/logic/GameClass/GameObj/Ship.cs +++ b/logic/GameClass/GameObj/Ship.cs @@ -3,7 +3,10 @@ using GameClass.GameObj.Occupations; using Preparation.Interface; using Preparation.Utility; -using System.Threading; +using Preparation.Utility.Value; +using Preparation.Utility.Value.SafeValue; +using Preparation.Utility.Value.SafeValue.Atomic; +using Preparation.Utility.Value.SafeValue.LockedValue; namespace GameClass.GameObj; diff --git a/logic/GameEngine/CollisionChecker.cs b/logic/GameEngine/CollisionChecker.cs index 6494c228..eb079554 100755 --- a/logic/GameEngine/CollisionChecker.cs +++ b/logic/GameEngine/CollisionChecker.cs @@ -1,5 +1,7 @@ using Preparation.Interface; using Preparation.Utility; +using Preparation.Utility.Value; +using Preparation.Utility.Value.SafeValue; using System; namespace GameEngine diff --git a/logic/GameEngine/MoveEngine.cs b/logic/GameEngine/MoveEngine.cs index 8d43c19b..2945f976 100755 --- a/logic/GameEngine/MoveEngine.cs +++ b/logic/GameEngine/MoveEngine.cs @@ -1,5 +1,6 @@ using Preparation.Interface; using Preparation.Utility; +using Preparation.Utility.Value; using System; using System.Threading; using Timothy.FrameRateTask; diff --git a/logic/Gaming/AttackManager.cs b/logic/Gaming/AttackManager.cs index 4693d74c..38c494ee 100755 --- a/logic/Gaming/AttackManager.cs +++ b/logic/Gaming/AttackManager.cs @@ -4,6 +4,7 @@ using GameEngine; using Preparation.Interface; using Preparation.Utility; +using Preparation.Utility.Value; using System; using System.Collections.Generic; using System.Linq; diff --git a/logic/Gaming/Game.cs b/logic/Gaming/Game.cs index be2506dc..0e79f3dd 100755 --- a/logic/Gaming/Game.cs +++ b/logic/Gaming/Game.cs @@ -3,6 +3,7 @@ using GameClass.MapGenerator; using Preparation.Interface; using Preparation.Utility; +using Preparation.Utility.Value; using System; using System.Collections.Generic; using System.Linq; diff --git a/logic/Gaming/ShipManager.cs b/logic/Gaming/ShipManager.cs index 36f041ae..a9a4165b 100755 --- a/logic/Gaming/ShipManager.cs +++ b/logic/Gaming/ShipManager.cs @@ -1,5 +1,6 @@ using GameClass.GameObj; using Preparation.Utility; +using Preparation.Utility.Value; using System.Threading; namespace Gaming diff --git a/logic/Preparation/Interface/IGameObj.cs b/logic/Preparation/Interface/IGameObj.cs index f7cac913..427dcc0f 100755 --- a/logic/Preparation/Interface/IGameObj.cs +++ b/logic/Preparation/Interface/IGameObj.cs @@ -1,4 +1,6 @@ using Preparation.Utility; +using Preparation.Utility.Value; +using Preparation.Utility.Value.SafeValue.Atomic; namespace Preparation.Interface { diff --git a/logic/Preparation/Interface/IHome.cs b/logic/Preparation/Interface/IHome.cs index 996fa847..74851b20 100755 --- a/logic/Preparation/Interface/IHome.cs +++ b/logic/Preparation/Interface/IHome.cs @@ -1,4 +1,4 @@ -using Preparation.Utility; +using Preparation.Utility.Value.SafeValue.LockedValue; namespace Preparation.Interface { diff --git a/logic/Preparation/Interface/IMap.cs b/logic/Preparation/Interface/IMap.cs index 6a4cf884..3b6ee174 100755 --- a/logic/Preparation/Interface/IMap.cs +++ b/logic/Preparation/Interface/IMap.cs @@ -1,4 +1,6 @@ using Preparation.Utility; +using Preparation.Utility.Value; +using Preparation.Utility.Value.SafeValue; using System.Collections.Generic; namespace Preparation.Interface diff --git a/logic/Preparation/Interface/IMoneyPool.cs b/logic/Preparation/Interface/IMoneyPool.cs index 5269caae..335ccef4 100644 --- a/logic/Preparation/Interface/IMoneyPool.cs +++ b/logic/Preparation/Interface/IMoneyPool.cs @@ -1,4 +1,5 @@ -using Preparation.Utility; +using Preparation.Utility.Value.SafeValue.Atomic; +using Preparation.Utility.Value.SafeValue.LockedValue; namespace Preparation.Interface { diff --git a/logic/Preparation/Interface/IMovable.cs b/logic/Preparation/Interface/IMovable.cs index 1a636b7f..0392235d 100755 --- a/logic/Preparation/Interface/IMovable.cs +++ b/logic/Preparation/Interface/IMovable.cs @@ -1,4 +1,6 @@ using Preparation.Utility; +using Preparation.Utility.Value; +using Preparation.Utility.Value.SafeValue.Atomic; using System; using System.Threading; diff --git a/logic/Preparation/Interface/IPlayer.cs b/logic/Preparation/Interface/IPlayer.cs index c4d336fb..a0f3a2d0 100644 --- a/logic/Preparation/Interface/IPlayer.cs +++ b/logic/Preparation/Interface/IPlayer.cs @@ -1,4 +1,4 @@ -using Preparation.Utility; +using Preparation.Utility.Value.SafeValue.Atomic; namespace Preparation.Interface { diff --git a/logic/Preparation/Interface/IShip.cs b/logic/Preparation/Interface/IShip.cs index de261198..b5a7858e 100755 --- a/logic/Preparation/Interface/IShip.cs +++ b/logic/Preparation/Interface/IShip.cs @@ -1,4 +1,6 @@ using Preparation.Utility; +using Preparation.Utility.Value.SafeValue; +using Preparation.Utility.Value.SafeValue.LockedValue; namespace Preparation.Interface { diff --git a/logic/Preparation/Interface/ITimer.cs b/logic/Preparation/Interface/ITimer.cs index bbcaee20..a9e54dfd 100755 --- a/logic/Preparation/Interface/ITimer.cs +++ b/logic/Preparation/Interface/ITimer.cs @@ -1,4 +1,4 @@ -using Preparation.Utility; +using Preparation.Utility.Value.SafeValue.Atomic; namespace Preparation.Interface { diff --git a/logic/Preparation/Utility/GameData.cs b/logic/Preparation/Utility/GameData.cs index 0b625fec..3931b5b3 100755 --- a/logic/Preparation/Utility/GameData.cs +++ b/logic/Preparation/Utility/GameData.cs @@ -1,4 +1,5 @@ -using System; +using Preparation.Utility.Value; +using System; namespace Preparation.Utility diff --git a/logic/Preparation/Utility/Value/SafeValue/Atomic.cs b/logic/Preparation/Utility/Value/SafeValue/Atomic.cs index c8dcbda1..d62daaba 100644 --- a/logic/Preparation/Utility/Value/SafeValue/Atomic.cs +++ b/logic/Preparation/Utility/Value/SafeValue/Atomic.cs @@ -1,6 +1,8 @@ -using System.Threading; +using Preparation.Interface; +using Preparation.Utility.Value.SafeValue.SafeMethod; +using System.Threading; -namespace Preparation.Utility +namespace Preparation.Utility.Value.SafeValue.Atomic { //其对应属性不应当有set访问器,避免不安全的=赋值 public abstract class Atomic @@ -53,18 +55,18 @@ public class AtomicBool(bool x) : Atomic, IAddable { private int v = x ? 1 : 0;//v&1==0为false,v&1==1为true - public override string ToString() => ((Interlocked.CompareExchange(ref v, -2, -2) & 1) == 0) ? "false" : "true"; - public bool Get() => ((Interlocked.CompareExchange(ref v, -2, -2) & 1) == 1); + public override string ToString() => (Interlocked.CompareExchange(ref v, -2, -2) & 1) == 0 ? "false" : "true"; + public bool Get() => (Interlocked.CompareExchange(ref v, -2, -2) & 1) == 1; public static implicit operator bool(AtomicBool abool) => abool.Get(); /// 返回操作前的值 - public bool SetROri(bool value) => ((Interlocked.Exchange(ref v, value ? 1 : 0) & 1) == 1); + public bool SetROri(bool value) => (Interlocked.Exchange(ref v, value ? 1 : 0) & 1) == 1; public void Set(bool value) => Interlocked.Exchange(ref v, value ? 1 : 0); /// 赋值前的值是否与将赋予的值不相同 public bool TrySet(bool value) { - return ((Interlocked.Exchange(ref v, value ? 1 : 0) & 1) != (value ? 1 : 0)); + return (Interlocked.Exchange(ref v, value ? 1 : 0) & 1) != (value ? 1 : 0); } public bool And(bool x) => (Interlocked.And(ref v, x ? 1 : 0) & 1) == 1; diff --git a/logic/Preparation/Utility/Value/SafeValue/AtomicInt.cs b/logic/Preparation/Utility/Value/SafeValue/AtomicInt.cs index 56eba021..17370e22 100644 --- a/logic/Preparation/Utility/Value/SafeValue/AtomicInt.cs +++ b/logic/Preparation/Utility/Value/SafeValue/AtomicInt.cs @@ -1,7 +1,8 @@ -using System; +using Preparation.Interface; +using System; using System.Threading; -namespace Preparation.Utility +namespace Preparation.Utility.Value.SafeValue.Atomic { //其对应属性不应当有set访问器,避免不安全的=赋值 @@ -123,12 +124,12 @@ public override int AddPositiveRNow(int x) public override int SubRNow(int x) { - if (x < 0) Score.Add(Convert.ToInt32((-x) * speed.ToDouble())); + if (x < 0) Score.Add(Convert.ToInt32(-x * speed.ToDouble())); return Interlocked.Add(ref v, -x); } public override void Sub(int x) { - if (x < 0) Score.Add(Convert.ToInt32((-x) * speed.ToDouble())); + if (x < 0) Score.Add(Convert.ToInt32(-x * speed.ToDouble())); Interlocked.Add(ref v, -x); } public int SubRNowNotAddScore(int x) @@ -200,12 +201,12 @@ public int SetROriNotAddScore(int value) public override void Add(int x) { - Score.Add(Convert.ToInt32((x) * speed)); + Score.Add(Convert.ToInt32(x * speed)); Interlocked.Add(ref v, x); } public override int AddRNow(int x) { - Score.Add(Convert.ToInt32((x) * speed)); + Score.Add(Convert.ToInt32(x * speed)); return Interlocked.Add(ref v, x); } public void AddNotAddScore(int x) => Interlocked.Add(ref v, x); @@ -214,7 +215,7 @@ public override int AddRNow(int x) /// public override void AddPositive(int x) { - Score.Add(Convert.ToInt32((x) * speed)); + Score.Add(Convert.ToInt32(x * speed)); Interlocked.Add(ref v, x); } /// @@ -222,18 +223,18 @@ public override void AddPositive(int x) /// public override int AddPositiveRNow(int x) { - Score.Add(Convert.ToInt32((x) * speed)); + Score.Add(Convert.ToInt32(x * speed)); return Interlocked.Add(ref v, x); } public override void Sub(int x) { - Score.Add(Convert.ToInt32((-x) * speed)); + Score.Add(Convert.ToInt32(-x * speed)); Interlocked.Add(ref v, -x); } public override int SubRNow(int x) { - Score.Add(Convert.ToInt32((-x) * speed)); + Score.Add(Convert.ToInt32(-x * speed)); return Interlocked.Add(ref v, -x); } public void SubNotAddScore(int x) => Interlocked.Add(ref v, -x); @@ -242,7 +243,7 @@ public override int SubRNow(int x) /// public override void SubPositive(int x) { - Score.Add(Convert.ToInt32((-x) * speed)); + Score.Add(Convert.ToInt32(-x * speed)); Interlocked.Add(ref v, -x); } public override int Inc() @@ -288,7 +289,7 @@ public class AtomicLong(long x) : Atomic, IIntAddable, IAddable /// 返回操作前的值 public virtual long SetROri(long value) => Interlocked.Exchange(ref v, value); public virtual void Add(long x) => Interlocked.Add(ref v, x); - public virtual void Add(int x) => Interlocked.Add(ref v, (long)x); + public virtual void Add(int x) => Interlocked.Add(ref v, x); public virtual long AddRNow(long x) => Interlocked.Add(ref v, x); public virtual void Sub(long x) => Interlocked.Add(ref v, -x); @@ -337,12 +338,12 @@ public long SetROriNotAddScore(long value) } public override void Add(long x) { - if (x > 0) Score.Add(Convert.ToInt32((x) * speed)); + if (x > 0) Score.Add(Convert.ToInt32(x * speed)); Interlocked.Add(ref v, x); } public override long AddRNow(long x) { - if (x > 0) Score.Add(Convert.ToInt32((x) * speed)); + if (x > 0) Score.Add(Convert.ToInt32(x * speed)); return Interlocked.Add(ref v, x); } public void AddNotAddScore(long x) @@ -352,12 +353,12 @@ public void AddNotAddScore(long x) public override void Sub(long x) { - if (x < 0) Score.Add(Convert.ToInt32((-x) * speed)); + if (x < 0) Score.Add(Convert.ToInt32(-x * speed)); Interlocked.Add(ref v, -x); } public override long SubRNow(long x) { - if (x < 0) Score.Add(Convert.ToInt32((-x) * speed)); + if (x < 0) Score.Add(Convert.ToInt32(-x * speed)); return Interlocked.Add(ref v, -x); } public void SubNotAddScore(long x) diff --git a/logic/Preparation/Utility/Value/SafeValue/ListLocked.cs b/logic/Preparation/Utility/Value/SafeValue/ListLocked.cs index 18ee9fcc..d742444c 100644 --- a/logic/Preparation/Utility/Value/SafeValue/ListLocked.cs +++ b/logic/Preparation/Utility/Value/SafeValue/ListLocked.cs @@ -3,7 +3,7 @@ using System.Linq; using System.Threading; -namespace Preparation.Utility +namespace Preparation.Utility.Value.SafeValue { public class LockedClassList where T : class? { diff --git a/logic/Preparation/Utility/Value/SafeValue/LockedValue/InRangeTimeBased.cs b/logic/Preparation/Utility/Value/SafeValue/LockedValue/InRangeTimeBased.cs index 8e421f84..ae9dff5d 100644 --- a/logic/Preparation/Utility/Value/SafeValue/LockedValue/InRangeTimeBased.cs +++ b/logic/Preparation/Utility/Value/SafeValue/LockedValue/InRangeTimeBased.cs @@ -1,9 +1,9 @@ -using Preparation.Utility; -using System; -using System.Numerics; +using System; using System.Threading; +using Preparation.Interface; +using Preparation.Utility.Value.SafeValue.Atomic; -namespace Preparation.Utility +namespace Preparation.Utility.Value.SafeValue.LockedValue { //其对应属性不应当有set访问器,避免不安全的=赋值 @@ -52,7 +52,7 @@ public long AddStartTime(double speed = 1.0) return WriteNeed(() => { long previousV = v; - long addV = (Environment.TickCount64 - startTime.Stop()); + long addV = Environment.TickCount64 - startTime.Stop(); if (addV > 0) v += (long)(addV * speed); else return 0; if (v > maxV) v = maxV; @@ -91,7 +91,7 @@ public void SetAndStop(long value = 0) { WriteNeed(() => { - this.v = value; + v = value; startTime.Stop(); }); } @@ -126,7 +126,7 @@ public TimeBasedProgressAtVariableSpeed(long needProgress, double speed = 1.0) public TimeBasedProgressAtVariableSpeed() { progress = new LongInVariableRangeWithStartTime(0, 0); - this.speed = new AtomicDouble(1.0); + speed = new AtomicDouble(1.0); } #endregion @@ -155,7 +155,7 @@ public bool IsProgressing() { long progressNow, needTime, startT; (progressNow, needTime, startT) = progress.AddStartTimeToMaxV(speed.ToDouble()); - return (startT != long.MaxValue && progressNow != needTime); + return startT != long.MaxValue && progressNow != needTime; } #endregion diff --git a/logic/Preparation/Utility/Value/SafeValue/LockedValue/InTheRange.cs b/logic/Preparation/Utility/Value/SafeValue/LockedValue/InTheRange.cs index cf66e4f7..be5228f5 100644 --- a/logic/Preparation/Utility/Value/SafeValue/LockedValue/InTheRange.cs +++ b/logic/Preparation/Utility/Value/SafeValue/LockedValue/InTheRange.cs @@ -1,9 +1,10 @@ -using Preparation.Utility; +using Preparation.Interface; using System; using System.Numerics; using System.Threading; +using Preparation.Utility.Value.SafeValue.Atomic; -namespace Preparation.Utility +namespace Preparation.Utility.Value.SafeValue.LockedValue { //其对应属性不应当有set访问器,避免不安全的=赋值 @@ -30,7 +31,7 @@ public InVariableRange(T value, T maxValue) : base() maxValue = T.Zero; } v = value.CompareTo(maxValue) < 0 ? value : maxValue; - this.maxV = maxValue; + maxV = maxValue; } /// /// 默认使Value=maxValue @@ -42,7 +43,7 @@ public InVariableRange(T maxValue) : base() Debugger.Output("Warning:Try to set IntInTheVariableRange.maxValue to " + maxValue.ToString() + "."); maxValue = T.Zero; } - v = this.maxV = maxValue; + v = maxV = maxValue; } public override string ToString() @@ -60,10 +61,10 @@ public T GetMaxV() { return ReadNeed(() => (v, maxV)); } - public T GetDifference() => ReadNeed(() => (maxV - v)); + public T GetDifference() => ReadNeed(() => maxV - v); public double GetDivideValueByMaxV() { - return ReadNeed(() => (v.ToDouble(null) / maxV.ToDouble(null))); + return ReadNeed(() => v.ToDouble(null) / maxV.ToDouble(null)); } #endregion @@ -132,7 +133,7 @@ public T SetRNow(T value) } else { - return WriteNeed(() => v = (value > maxV) ? maxV : value); + return WriteNeed(() => v = value > maxV ? maxV : value); } } @@ -143,7 +144,7 @@ public void Set(double value) WriteNeed(() => v = T.Zero); } T va = T.CreateChecked(value); - WriteNeed(() => v = (va > maxV) ? maxV : va); + WriteNeed(() => v = va > maxV ? maxV : va); } /// @@ -151,7 +152,7 @@ public void Set(double value) /// public T SetPositiveVRNow(T value) { - return WriteNeed(() => v = (value > maxV) ? maxV : value); + return WriteNeed(() => v = value > maxV ? maxV : value); } #endregion @@ -263,7 +264,7 @@ public T AddPositiveVRChange(T addPositiveV) { WriteNeed(() => { - addPositiveV = (addPositiveV < maxV - v) ? addPositiveV : maxV - v; + addPositiveV = addPositiveV < maxV - v ? addPositiveV : maxV - v; v += addPositiveV; }); return addPositiveV; @@ -363,7 +364,7 @@ public T SubPositiveVRChange(T subPositiveV) { WriteNeed(() => { - subPositiveV = (subPositiveV < v) ? subPositiveV : v; + subPositiveV = subPositiveV < v ? subPositiveV : v; v -= subPositiveV; }); return subPositiveV; @@ -375,7 +376,7 @@ public void SubPositiveV(T subPositiveV) { WriteNeed(() => { - v = (subPositiveV < v) ? v - subPositiveV : T.Zero; + v = subPositiveV < v ? v - subPositiveV : T.Zero; }); } #endregion diff --git a/logic/Preparation/Utility/Value/SafeValue/LockedValue/LockedDouble.cs b/logic/Preparation/Utility/Value/SafeValue/LockedValue/LockedDouble.cs index 97b4e8a9..9b3163cd 100644 --- a/logic/Preparation/Utility/Value/SafeValue/LockedValue/LockedDouble.cs +++ b/logic/Preparation/Utility/Value/SafeValue/LockedValue/LockedDouble.cs @@ -1,7 +1,6 @@ -using System; -using System.Threading; +using Preparation.Interface; -namespace Preparation.Utility +namespace Preparation.Utility.Value.SafeValue.LockedValue { public class LockedDouble(double x) : LockedValue, IDouble { diff --git a/logic/Preparation/Utility/Value/SafeValue/LockedValue/LockedValue.cs b/logic/Preparation/Utility/Value/SafeValue/LockedValue/LockedValue.cs index 19deef10..a59234c5 100644 --- a/logic/Preparation/Utility/Value/SafeValue/LockedValue/LockedValue.cs +++ b/logic/Preparation/Utility/Value/SafeValue/LockedValue/LockedValue.cs @@ -1,10 +1,9 @@ using System; -using System.Collections; using System.Threading; using System.Collections.Generic; using System.Linq; -namespace Preparation.Utility +namespace Preparation.Utility.Value.SafeValue.LockedValue { public abstract class LockedValue { @@ -55,12 +54,12 @@ public LockedValue() public TResult? EnterOtherLock(LockedValue a, Func func) { - if (this.idInClass == a.idInClass) return default(TResult?); + if (idInClass == a.idInClass) return default; bool thisLock = false; bool thatLock = false; try { - if (this.idInClass < a.idInClass) + if (idInClass < a.idInClass) { Monitor.Enter(vLock, ref thisLock); Monitor.Enter(a.VLock, ref thatLock); @@ -80,12 +79,12 @@ public LockedValue() } public void EnterOtherLock(LockedValue a, Action func) { - if (this.idInClass == a.idInClass) return; + if (idInClass == a.idInClass) return; bool thisLock = false; bool thatLock = false; try { - if (this.idInClass < a.idInClass) + if (idInClass < a.idInClass) { Monitor.Enter(vLock, ref thisLock); Monitor.Enter(a.VLock, ref thatLock); diff --git a/logic/Preparation/Utility/Value/SafeValue/LockedValue/PositiveV.cs b/logic/Preparation/Utility/Value/SafeValue/LockedValue/PositiveV.cs index 849bb680..c0819c4d 100644 --- a/logic/Preparation/Utility/Value/SafeValue/LockedValue/PositiveV.cs +++ b/logic/Preparation/Utility/Value/SafeValue/LockedValue/PositiveV.cs @@ -1,8 +1,8 @@ -using System; +using Preparation.Interface; +using System; using System.Numerics; -using System.Threading; -namespace Preparation.Utility +namespace Preparation.Utility.Value.SafeValue.LockedValue { /// /// 一个保证大于0的可变值 @@ -151,7 +151,7 @@ public T SubRChange(T subV) { WriteNeed(() => { - subV = (subV.CompareTo(v) > 0) ? v : subV; + subV = subV.CompareTo(v) > 0 ? v : subV; v -= subV; }); return subV; diff --git a/logic/Preparation/Utility/Value/SafeValue/ObjPool.cs b/logic/Preparation/Utility/Value/SafeValue/ObjPool.cs index e91fcea6..a0109cee 100644 --- a/logic/Preparation/Utility/Value/SafeValue/ObjPool.cs +++ b/logic/Preparation/Utility/Value/SafeValue/ObjPool.cs @@ -2,7 +2,7 @@ using System; using System.Collections.Generic; -namespace Preparation.Utility; +namespace Preparation.Utility.Value.SafeValue; public class ObjPool(Func classfier, Func idleChecker, diff --git a/logic/Preparation/Utility/Value/SafeValue/SafeMethod/InterlockedEx.cs b/logic/Preparation/Utility/Value/SafeValue/SafeMethod/InterlockedEx.cs index 3393e5ad..0f5e89f3 100644 --- a/logic/Preparation/Utility/Value/SafeValue/SafeMethod/InterlockedEx.cs +++ b/logic/Preparation/Utility/Value/SafeValue/SafeMethod/InterlockedEx.cs @@ -3,7 +3,7 @@ using System.Reflection.Emit; using System.Threading; -namespace Preparation.Utility +namespace Preparation.Utility.Value.SafeValue.SafeMethod { static class CompareExchangeEnumImpl { @@ -13,7 +13,7 @@ static class CompareExchangeEnumImpl static dImpl CreateCompareExchangeImpl() { var underlyingType = Enum.GetUnderlyingType(typeof(T)); - var dynamicMethod = new DynamicMethod(string.Empty, typeof(T), new[] { typeof(T).MakeByRefType(), typeof(T), typeof(T) }); + var dynamicMethod = new DynamicMethod(string.Empty, typeof(T), [typeof(T).MakeByRefType(), typeof(T), typeof(T)]); var ilGenerator = dynamicMethod.GetILGenerator(); ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldarg_1); @@ -24,7 +24,7 @@ static dImpl CreateCompareExchangeImpl() "CompareExchange", BindingFlags.Static | BindingFlags.Public, null, - new[] { underlyingType.MakeByRefType(), underlyingType, underlyingType }, + [underlyingType.MakeByRefType(), underlyingType, underlyingType], null)); ilGenerator.Emit(OpCodes.Ret); return (dImpl)dynamicMethod.CreateDelegate(typeof(dImpl)); @@ -39,7 +39,7 @@ static class ExchangeEnumImpl static dImpl CreateExchangeImpl() { var underlyingType = Enum.GetUnderlyingType(typeof(T)); - var dynamicMethod = new DynamicMethod(string.Empty, typeof(T), new[] { typeof(T).MakeByRefType(), typeof(T) }); + var dynamicMethod = new DynamicMethod(string.Empty, typeof(T), [typeof(T).MakeByRefType(), typeof(T)]); var ilGenerator = dynamicMethod.GetILGenerator(); ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldarg_1); @@ -49,7 +49,7 @@ static dImpl CreateExchangeImpl() "Exchange", BindingFlags.Static | BindingFlags.Public, null, - new[] { underlyingType.MakeByRefType(), underlyingType }, + [underlyingType.MakeByRefType(), underlyingType], null)); ilGenerator.Emit(OpCodes.Ret); return (dImpl)dynamicMethod.CreateDelegate(typeof(dImpl)); @@ -70,7 +70,7 @@ public static T ExchangeEnum(ref T location, T value) public static T ReadEnum(ref T location) { - T dummy = default(T); + T dummy = default; return CompareExchangeEnum(ref location!, dummy, dummy)!; } } diff --git a/logic/Preparation/Utility/Value/SafeValue/TimeBased.cs b/logic/Preparation/Utility/Value/SafeValue/TimeBased.cs index f96b0e5e..fcd08bb7 100644 --- a/logic/Preparation/Utility/Value/SafeValue/TimeBased.cs +++ b/logic/Preparation/Utility/Value/SafeValue/TimeBased.cs @@ -1,7 +1,8 @@ -using System; +using Preparation.Utility.Value.SafeValue.Atomic; +using System; using System.Threading; -namespace Preparation.Utility +namespace Preparation.Utility.Value.SafeValue { //其对应属性不应当有set访问器,避免不安全的=赋值 @@ -49,11 +50,11 @@ public class TimeBasedProgressOptimizedForInterrupting public TimeBasedProgressOptimizedForInterrupting(long needTime) { if (needTime <= 0) Debugger.Output("Bug:TimeBasedProgressOptimizedForInterrupting.needProgress (" + needTime.ToString() + ") is less than 0."); - this.needT = needTime; + needT = needTime; } public TimeBasedProgressOptimizedForInterrupting() { - this.needT = 0; + needT = 0; } public long GetEndTime() => Interlocked.CompareExchange(ref endT, -2, -2); public long GetNeedTime() => Interlocked.CompareExchange(ref needT, -2, -2); @@ -109,7 +110,7 @@ public double GetProgressDouble() if (cutime <= 0) return 1; long needTime = Interlocked.CompareExchange(ref needT, -2, -2); if (needTime == 0) return 0; - return 1.0 - ((double)cutime / needTime); + return 1.0 - (double)cutime / needTime; } public double GetNonNegativeProgressDouble(long time) { @@ -117,7 +118,7 @@ public double GetNonNegativeProgressDouble(long time) if (cutime <= 0) return 1; long needTime = Interlocked.CompareExchange(ref needT, -2, -2); if (needTime <= cutime) return 0; - return 1.0 - ((double)cutime / needTime); + return 1.0 - (double)cutime / needTime; } public bool Start(long needTime) @@ -179,7 +180,7 @@ public BoolUpdateEachCD(long cd, long startTime) { if (cd <= 1) Debugger.Output("Bug:BoolUpdateEachCD.cd (" + cd.ToString() + ") is less than 1."); this.cd = cd; - this.nextUpdateTime = startTime; + nextUpdateTime = startTime; } public long GetCD() => Interlocked.Read(ref cd); @@ -224,7 +225,7 @@ public LongProgressUpdateEachCD(long cd, long startTime) { if (cd <= 1) Debugger.Output("Bug:LongProgressUpdateEachCD.cd (" + cd.ToString() + ") is less than 1."); this.cd = cd; - this.nextUpdateTime = startTime; + nextUpdateTime = startTime; } public long GetRemainingTime() @@ -269,10 +270,10 @@ public IntNumUpdateEachCD(int num, int maxNum, int cd) if (num < 0) Debugger.Output("Bug:IntNumUpdateEachCD.num (" + num.ToString() + ") is less than 0."); if (maxNum < 0) Debugger.Output("Bug:IntNumUpdateEachCD.maxNum (" + maxNum.ToString() + ") is less than 0."); if (cd <= 0) Debugger.Output("Bug:IntNumUpdateEachCD.cd (" + cd.ToString() + ") is less than 0."); - this.num = (num < maxNum) ? num : maxNum; + this.num = num < maxNum ? num : maxNum; this.maxNum = maxNum; CD.Set(cd); - this.updateTime = Environment.TickCount64; + updateTime = Environment.TickCount64; } /// /// 默认使num=maxNum @@ -281,12 +282,12 @@ public IntNumUpdateEachCD(int maxNum, int cd) { if (maxNum < 0) Debugger.Output("Bug:IntNumUpdateEachCD.maxNum (" + maxNum.ToString() + ") is less than 0."); if (cd <= 0) Debugger.Output("Bug:IntNumUpdateEachCD.cd (" + cd.ToString() + ") is less than 0."); - this.num = this.maxNum = maxNum; + num = this.maxNum = maxNum; CD.Set(cd); } public IntNumUpdateEachCD() { - this.num = this.maxNum = 0; + num = maxNum = 0; } public int GetMaxNum() { lock (numLock) return maxNum; } @@ -299,7 +300,7 @@ public int GetNum(long time) { int add = (int)Math.Min(maxNum - num, (time - updateTime) / CD); updateTime += add * CD; - return (num += add); + return num += add; } return num; } @@ -345,7 +346,7 @@ public bool SetMaxNumAndNum(int maxNum) if (maxNum < 0) maxNum = 0; lock (numLock) { - this.num = this.maxNum = maxNum; + num = this.maxNum = maxNum; } return maxNum > 0; } @@ -356,7 +357,7 @@ public void SetPositiveMaxNumAndNum(int maxNum) { lock (numLock) { - this.num = this.maxNum = maxNum; + num = this.maxNum = maxNum; } } /// diff --git a/logic/Preparation/Utility/Value/ValueInterface/IAddable.cs b/logic/Preparation/Utility/Value/ValueInterface/IAddable.cs index 175eb6d8..81c125cc 100644 --- a/logic/Preparation/Utility/Value/ValueInterface/IAddable.cs +++ b/logic/Preparation/Utility/Value/ValueInterface/IAddable.cs @@ -1,4 +1,4 @@ -namespace Preparation.Utility +namespace Preparation.Interface { public interface IAddable { diff --git a/logic/Preparation/Utility/Value/ValueInterface/IDouble.cs b/logic/Preparation/Utility/Value/ValueInterface/IDouble.cs index e2f3b32b..f6ca8639 100644 --- a/logic/Preparation/Utility/Value/ValueInterface/IDouble.cs +++ b/logic/Preparation/Utility/Value/ValueInterface/IDouble.cs @@ -1,6 +1,4 @@ -using System; - -namespace Preparation.Utility +namespace Preparation.Interface { public interface IDouble { diff --git a/logic/Preparation/Utility/Value/XY.cs b/logic/Preparation/Utility/Value/XY.cs index 5a2a1e89..313126a8 100644 --- a/logic/Preparation/Utility/Value/XY.cs +++ b/logic/Preparation/Utility/Value/XY.cs @@ -1,6 +1,6 @@ using System; -namespace Preparation.Utility; +namespace Preparation.Utility.Value; public readonly struct XY { @@ -15,40 +15,40 @@ public XY(int x, int y) } public XY(double angle, double length) { - this.x = (int)(length * Math.Cos(angle)); - this.y = (int)(length * Math.Sin(angle)); + x = (int)(length * Math.Cos(angle)); + y = (int)(length * Math.Sin(angle)); } public XY(XY Direction, double length) { if (Direction.x == 0 && Direction.y == 0) { - this.x = 0; - this.y = 0; + x = 0; + y = 0; } else { - this.x = (int)(length * Math.Cos(Direction.Angle())); - this.y = (int)(length * Math.Sin(Direction.Angle())); + x = (int)(length * Math.Cos(Direction.Angle())); + y = (int)(length * Math.Sin(Direction.Angle())); } } #endregion public override string ToString() => $"({x}, {y})"; /// 数量积 - public static int operator *(XY v1, XY v2) => (v1.x * v2.x) + (v1.y * v2.y); + public static int operator *(XY v1, XY v2) => v1.x * v2.x + v1.y * v2.y; /// 左数乘 public static XY operator *(int a, XY v2) => new(a * v2.x, a * v2.y); /// 右数乘 public static XY operator *(XY v2, int a) => new(a * v2.x, a * v2.y); public static XY operator +(XY v1, XY v2) => new(v1.x + v2.x, v1.y + v2.y); public static XY operator -(XY v1, XY v2) => new(v1.x - v2.x, v1.y - v2.y); - public static bool operator ==(XY v1, XY v2) => (v1.x == v2.x) && (v1.y == v2.y); - public static bool operator !=(XY v1, XY v2) => (v1.x != v2.x) || (v1.y != v2.y); + public static bool operator ==(XY v1, XY v2) => v1.x == v2.x && v1.y == v2.y; + public static bool operator !=(XY v1, XY v2) => v1.x != v2.x || v1.y != v2.y; #region Distance public static double DistanceFloor3(XY p1, XY p2) { - long c = (((long)(p1.x - p2.x) * (p1.x - p2.x)) + ((long)(p1.y - p2.y) * (p1.y - p2.y))) * 1000000; + long c = ((long)(p1.x - p2.x) * (p1.x - p2.x) + (long)(p1.y - p2.y) * (p1.y - p2.y)) * 1000000; long t = c / 2 + 1; while (t * t > c || (t + 1) * (t + 1) <= c) t = (c / t + t) / 2; @@ -56,7 +56,7 @@ public static double DistanceFloor3(XY p1, XY p2) } public static double DistanceCeil3(XY p1, XY p2) { - long c = (((long)(p1.x - p2.x) * (p1.x - p2.x)) + ((long)(p1.y - p2.y) * (p1.y - p2.y))) * 1000000; + long c = ((long)(p1.x - p2.x) * (p1.x - p2.x) + (long)(p1.y - p2.y) * (p1.y - p2.y)) * 1000000; long t = c / 2 + 1; while (t * t > c || (t + 1) * (t + 1) <= c) t = (c / t + t) / 2; @@ -65,7 +65,7 @@ public static double DistanceCeil3(XY p1, XY p2) } #endregion - public double Length() => Math.Sqrt(((long)x * x) + ((long)y * y)); + public double Length() => Math.Sqrt((long)x * x + (long)y * y); public double Angle() => Math.Atan2(y, x); /// @@ -73,7 +73,7 @@ public static double DistanceCeil3(XY p1, XY p2) /// public XY Perpendicular() => new(-y, x); - public override bool Equals(object? obj) => (obj is not null) && (obj is XY xy) && (this == xy); + public override bool Equals(object? obj) => obj is not null && obj is XY xy && this == xy; public override int GetHashCode() => x.GetHashCode() ^ y.GetHashCode(); /// @@ -98,40 +98,40 @@ public CellXY(int x, int y) } public CellXY(double angle, double length) { - this.x = (int)(length * Math.Cos(angle)); - this.y = (int)(length * Math.Sin(angle)); + x = (int)(length * Math.Cos(angle)); + y = (int)(length * Math.Sin(angle)); } public CellXY(XY Direction, double length) { if (Direction.x == 0 && Direction.y == 0) { - this.x = 0; - this.y = 0; + x = 0; + y = 0; } else { - this.x = (int)(length * Math.Cos(Direction.Angle())); - this.y = (int)(length * Math.Sin(Direction.Angle())); + x = (int)(length * Math.Cos(Direction.Angle())); + y = (int)(length * Math.Sin(Direction.Angle())); } } #endregion public override string ToString() => $"({x}, {y})"; /// 数量积 - public static int operator *(CellXY v1, CellXY v2) => (v1.x * v2.x) + (v1.y * v2.y); + public static int operator *(CellXY v1, CellXY v2) => v1.x * v2.x + v1.y * v2.y; /// 左数乘 public static CellXY operator *(int a, CellXY v2) => new(a * v2.x, a * v2.y); /// 右数乘 public static CellXY operator *(CellXY v2, int a) => new(a * v2.x, a * v2.y); public static CellXY operator +(CellXY v1, CellXY v2) => new(v1.x + v2.x, v1.y + v2.y); public static CellXY operator -(CellXY v1, CellXY v2) => new(v1.x - v2.x, v1.y - v2.y); - public static bool operator ==(CellXY v1, CellXY v2) => (v1.x == v2.x) && (v1.y == v2.y); - public static bool operator !=(CellXY v1, CellXY v2) => (v1.x != v2.x) || (v1.y != v2.y); + public static bool operator ==(CellXY v1, CellXY v2) => v1.x == v2.x && v1.y == v2.y; + public static bool operator !=(CellXY v1, CellXY v2) => v1.x != v2.x || v1.y != v2.y; #region Distance public static double DistanceFloor3(CellXY p1, CellXY p2) { - long c = (((long)(p1.x - p2.x) * (p1.x - p2.x)) + ((long)(p1.y - p2.y) * (p1.y - p2.y))) * 1000000; + long c = ((long)(p1.x - p2.x) * (p1.x - p2.x) + (long)(p1.y - p2.y) * (p1.y - p2.y)) * 1000000; long t = c / 2 + 1; while (t * t > c || (t + 1) * (t + 1) <= c) t = (c / t + t) / 2; @@ -139,7 +139,7 @@ public static double DistanceFloor3(CellXY p1, CellXY p2) } public static double DistanceCeil3(CellXY p1, CellXY p2) { - long c = (((long)(p1.x - p2.x) * (p1.x - p2.x)) + ((long)(p1.y - p2.y) * (p1.y - p2.y))) * 1000000; + long c = ((long)(p1.x - p2.x) * (p1.x - p2.x) + (long)(p1.y - p2.y) * (p1.y - p2.y)) * 1000000; long t = c / 2 + 1; while (t * t > c || (t + 1) * (t + 1) <= c) t = (c / t + t) / 2; @@ -148,7 +148,7 @@ public static double DistanceCeil3(CellXY p1, CellXY p2) } #endregion - public double Length() => Math.Sqrt(((long)x * x) + ((long)y * y)); + public double Length() => Math.Sqrt((long)x * x + (long)y * y); public double Angle() => Math.Atan2(y, x); /// @@ -156,7 +156,7 @@ public static double DistanceCeil3(CellXY p1, CellXY p2) /// public CellXY Perpendicular() => new(-y, x); - public override bool Equals(object? obj) => (obj is not null) && (obj is CellXY xy) && (this == xy); + public override bool Equals(object? obj) => obj is not null && obj is CellXY xy && this == xy; public override int GetHashCode() => x.GetHashCode() ^ y.GetHashCode(); /// From 734b549334726d6c5ad2c07dc927d6aca7d41362 Mon Sep 17 00:00:00 2001 From: 964293341 Date: Thu, 25 Apr 2024 14:20:04 +0800 Subject: [PATCH 04/11] refactor: introduce namespace Preparation.Utility.Value.SafeValue.TimeBased --- logic/GameClass/GameObj/Ship.cs | 2 +- logic/Preparation/Interface/IShip.cs | 2 +- .../Utility/Value/SafeValue/LockedValue/InRangeTimeBased.cs | 1 + .../Utility/Value/SafeValue/LockedValue/InTheRange.cs | 1 + .../Utility/Value/SafeValue/LockedValue/PositiveV.cs | 1 + logic/Preparation/Utility/Value/SafeValue/TimeBased.cs | 2 +- 6 files changed, 6 insertions(+), 3 deletions(-) diff --git a/logic/GameClass/GameObj/Ship.cs b/logic/GameClass/GameObj/Ship.cs index ec851c07..6e128af9 100755 --- a/logic/GameClass/GameObj/Ship.cs +++ b/logic/GameClass/GameObj/Ship.cs @@ -4,9 +4,9 @@ using Preparation.Interface; using Preparation.Utility; using Preparation.Utility.Value; -using Preparation.Utility.Value.SafeValue; using Preparation.Utility.Value.SafeValue.Atomic; using Preparation.Utility.Value.SafeValue.LockedValue; +using Preparation.Utility.Value.SafeValue.TimeBased; namespace GameClass.GameObj; diff --git a/logic/Preparation/Interface/IShip.cs b/logic/Preparation/Interface/IShip.cs index b5a7858e..1568d4a8 100755 --- a/logic/Preparation/Interface/IShip.cs +++ b/logic/Preparation/Interface/IShip.cs @@ -1,6 +1,6 @@ using Preparation.Utility; -using Preparation.Utility.Value.SafeValue; using Preparation.Utility.Value.SafeValue.LockedValue; +using Preparation.Utility.Value.SafeValue.TimeBased; namespace Preparation.Interface { diff --git a/logic/Preparation/Utility/Value/SafeValue/LockedValue/InRangeTimeBased.cs b/logic/Preparation/Utility/Value/SafeValue/LockedValue/InRangeTimeBased.cs index ae9dff5d..8cfb79cf 100644 --- a/logic/Preparation/Utility/Value/SafeValue/LockedValue/InRangeTimeBased.cs +++ b/logic/Preparation/Utility/Value/SafeValue/LockedValue/InRangeTimeBased.cs @@ -2,6 +2,7 @@ using System.Threading; using Preparation.Interface; using Preparation.Utility.Value.SafeValue.Atomic; +using Preparation.Utility.Value.SafeValue.TimeBased; namespace Preparation.Utility.Value.SafeValue.LockedValue { diff --git a/logic/Preparation/Utility/Value/SafeValue/LockedValue/InTheRange.cs b/logic/Preparation/Utility/Value/SafeValue/LockedValue/InTheRange.cs index be5228f5..b4f11147 100644 --- a/logic/Preparation/Utility/Value/SafeValue/LockedValue/InTheRange.cs +++ b/logic/Preparation/Utility/Value/SafeValue/LockedValue/InTheRange.cs @@ -3,6 +3,7 @@ using System.Numerics; using System.Threading; using Preparation.Utility.Value.SafeValue.Atomic; +using Preparation.Utility.Value.SafeValue.TimeBased; namespace Preparation.Utility.Value.SafeValue.LockedValue { diff --git a/logic/Preparation/Utility/Value/SafeValue/LockedValue/PositiveV.cs b/logic/Preparation/Utility/Value/SafeValue/LockedValue/PositiveV.cs index c0819c4d..f7f4e9a3 100644 --- a/logic/Preparation/Utility/Value/SafeValue/LockedValue/PositiveV.cs +++ b/logic/Preparation/Utility/Value/SafeValue/LockedValue/PositiveV.cs @@ -1,4 +1,5 @@ using Preparation.Interface; +using Preparation.Utility.Value.SafeValue.TimeBased; using System; using System.Numerics; diff --git a/logic/Preparation/Utility/Value/SafeValue/TimeBased.cs b/logic/Preparation/Utility/Value/SafeValue/TimeBased.cs index fcd08bb7..78d01719 100644 --- a/logic/Preparation/Utility/Value/SafeValue/TimeBased.cs +++ b/logic/Preparation/Utility/Value/SafeValue/TimeBased.cs @@ -2,7 +2,7 @@ using System; using System.Threading; -namespace Preparation.Utility.Value.SafeValue +namespace Preparation.Utility.Value.SafeValue.TimeBased { //其对应属性不应当有set访问器,避免不安全的=赋值 From fb9d85fa96371c64940fc0cfb1d6c6ba18b8549e Mon Sep 17 00:00:00 2001 From: 964293341 Date: Thu, 25 Apr 2024 21:53:57 +0800 Subject: [PATCH 05/11] feat: replace `Debugger` with `Logger` --- logic/GameClass/GameObj/Map/Map.cs | 9 +- logic/GameClass/GameObj/Map/MapGameTimer.cs | 2 +- logic/GameClass/GameObj/Map/MapInfo.cs | 2 +- logic/GameClass/GameObj/Ship.cs | 34 +++++- logic/GameEngine/MoveEngine.cs | 27 ++++- logic/Gaming/ActionManager.cs | 10 +- logic/Gaming/AttackManager.cs | 63 ++++++++--- logic/Gaming/Game.cs | 24 +++- logic/Gaming/ShipManager.cs | 99 ++++++++++++---- logic/Preparation/Utility/Debugger.cs | 20 ---- logic/Preparation/Utility/Logger.cs | 73 ++++++------ .../SafeValue/LockedValue/InRangeTimeBased.cs | 39 ++++--- .../Value/SafeValue/LockedValue/InTheRange.cs | 29 +++-- .../SafeValue/LockedValue/LockedValue.cs | 5 + .../Value/SafeValue/LockedValue/PositiveV.cs | 2 +- .../Utility/Value/SafeValue/TimeBased.cs | 107 ++++++++++++------ logic/Server/GameServer.cs | 1 + 17 files changed, 376 insertions(+), 170 deletions(-) delete mode 100755 logic/Preparation/Utility/Debugger.cs diff --git a/logic/GameClass/GameObj/Map/Map.cs b/logic/GameClass/GameObj/Map/Map.cs index 96f9ed13..6f964690 100755 --- a/logic/GameClass/GameObj/Map/Map.cs +++ b/logic/GameClass/GameObj/Map/Map.cs @@ -2,13 +2,18 @@ using GameClass.MapGenerator; using Preparation.Interface; using Preparation.Utility; +using Preparation.Utility.Logging; using Preparation.Utility.Value; using Preparation.Utility.Value.SafeValue; using System; using System.Collections.Generic; -namespace GameClass.GameObj +namespace GameClass.GameObj.Map { + public static class MapLogging + { + public static readonly Logger logger = new("Map"); + } public partial class Map : IMap { private readonly Dictionary> gameObjDict; @@ -207,7 +212,7 @@ public bool RemoveJustFromMap(GameObj gameObj) public void Add(IGameObj gameObj) { GameObjDict[gameObj.Type].Add(gameObj); - Debugger.Output($"Found a {gameObj.Type} at {gameObj.Position}"); + MapLogging.logger.ConsoleLogDebug($"Add {gameObj.Type} at {gameObj.Position}"); } public Map(MapStruct mapResource) { diff --git a/logic/GameClass/GameObj/Map/MapGameTimer.cs b/logic/GameClass/GameObj/Map/MapGameTimer.cs index ac4e0841..126e6914 100755 --- a/logic/GameClass/GameObj/Map/MapGameTimer.cs +++ b/logic/GameClass/GameObj/Map/MapGameTimer.cs @@ -3,7 +3,7 @@ using System.Threading; using ITimer = Preparation.Interface.ITimer; -namespace GameClass.GameObj +namespace GameClass.GameObj.Map { public partial class Map { diff --git a/logic/GameClass/GameObj/Map/MapInfo.cs b/logic/GameClass/GameObj/Map/MapInfo.cs index 9578cb23..2a2e7935 100755 --- a/logic/GameClass/GameObj/Map/MapInfo.cs +++ b/logic/GameClass/GameObj/Map/MapInfo.cs @@ -1,6 +1,6 @@ using GameClass.MapGenerator; -namespace GameClass.GameObj +namespace GameClass.GameObj.Map { public static class MapInfo { diff --git a/logic/GameClass/GameObj/Ship.cs b/logic/GameClass/GameObj/Ship.cs index 6e128af9..569eaac8 100755 --- a/logic/GameClass/GameObj/Ship.cs +++ b/logic/GameClass/GameObj/Ship.cs @@ -3,6 +3,7 @@ using GameClass.GameObj.Occupations; using Preparation.Interface; using Preparation.Utility; +using Preparation.Utility.Logging; using Preparation.Utility.Value; using Preparation.Utility.Value.SafeValue.Atomic; using Preparation.Utility.Value.SafeValue.LockedValue; @@ -10,6 +11,15 @@ namespace GameClass.GameObj; +public static class ShipLogging +{ + public static Logger logger = new("Ship"); + public static string ShipLogInfo(Ship ship) + => Logger.ObjInfo(typeof(Ship), $"{ship.TeamID} {ship.PlayerID}"); + public static string ShipLogInfo(long teamId, long shipId) + => Logger.ObjInfo(typeof(Ship), $"{teamId} {shipId}"); +} + public class Ship : Movable, IShip { public AtomicLong TeamID { get; } = new(long.MaxValue); @@ -318,7 +328,9 @@ public long SetShipState(RunningStateType running, ShipStateType value = ShipSta lock (actionLock) { ShipStateType nowShipState = shipState; - Debugger.Output(this, "SetShipState from " + nowShipState + " to " + value); + ShipLogging.logger.ConsoleLogDebug( + ShipLogging.ShipLogInfo(this) + + $"SetShipState from {nowShipState} to {value}"); if (nowShipState == value) return -1; GameObj? lastObj = whatInteractingWith; switch (nowShipState) @@ -360,14 +372,18 @@ public bool ResetShipState(long state, RunningStateType running = RunningStateTy { if (state != stateNum) { - Debugger.Output(this, "ResetShipState failed"); + ShipLogging.logger.ConsoleLogDebug( + ShipLogging.ShipLogInfo(this) + + "ResetShipState failed"); return false; } runningState = running; whatInteractingWith = (GameObj?)obj; shipState = value; ++stateNum; - Debugger.Output(this, "ResetShipState succeeded" + stateNum); + ShipLogging.logger.ConsoleLogDebug( + ShipLogging.ShipLogInfo(this) + + $"ResetShipState succeeded {stateNum}"); return true; } } @@ -388,12 +404,16 @@ public bool StartThread(long stateNum, RunningStateType runningState) { if (StateNum == stateNum) { - Debugger.Output(this, "StartThread succeeded"); + ShipLogging.logger.ConsoleLogDebug( + ShipLogging.ShipLogInfo(this) + + "StartThread succeeded"); this.runningState = runningState; return true; } } - Debugger.Output(this, "StartThread failed"); + ShipLogging.logger.ConsoleLogDebug( + ShipLogging.ShipLogInfo(this) + + "StartThread failed"); return false; } public bool TryToRemoveFromGame(ShipStateType shipStateType) @@ -456,6 +476,8 @@ public Ship(int initRadius, ShipType shipType, MoneyPool moneyPool) : ArmorModule.SetROri(ModuleFactory.FindIArmor(ShipType, ArmorType.Null)); ShieldModule.SetROri(ModuleFactory.FindIShield(ShipType, ShieldType.Null)); WeaponModule.SetROri(ModuleFactory.FindIWeapon(ShipType, weaponType)); - Debugger.Output(this, "Ship created"); + ShipLogging.logger.ConsoleLogDebug( + ShipLogging.ShipLogInfo(this) + + "Ship created"); } } diff --git a/logic/GameEngine/MoveEngine.cs b/logic/GameEngine/MoveEngine.cs index 2945f976..7c861de0 100755 --- a/logic/GameEngine/MoveEngine.cs +++ b/logic/GameEngine/MoveEngine.cs @@ -1,5 +1,6 @@ using Preparation.Interface; using Preparation.Utility; +using Preparation.Utility.Logging; using Preparation.Utility.Value; using System; using System.Threading; @@ -8,6 +9,10 @@ namespace GameEngine { + public static class GameEngineLogging + { + public static readonly Logger logger = new("GameEngine"); + } /// /// Constrctor /// @@ -112,7 +117,11 @@ private bool LoopDo(IMovable obj, double direction, ref double deltaLen, long st flag = true; break; case AfterCollision.Destroyed: - Debugger.Output(obj, $"collide with {collisionObj} and has been removed from the game."); + GameEngineLogging.logger.ConsoleLogDebug( + Logger.ObjInfo(obj) + + " collide with " + + Logger.ObjInfo(collisionObj) + + " and has been removed from the game"); return false; case AfterCollision.MoveMax: if (!MoveMax(obj, res, stateNum)) return false; @@ -130,7 +139,9 @@ private bool LoopDo(IMovable obj, double direction, ref double deltaLen, long st public void MoveObj(IMovable obj, int moveTime, double direction, long stateNum) { - Debugger.Output(obj, $"Position {obj.Position}, Start moving in direction {direction}."); + GameEngineLogging.logger.ConsoleLogDebug( + Logger.ObjInfo(obj) + + $" position {obj.Position}, start moving in direction {direction}"); if (!gameTimer.IsGaming) return; lock (obj.ActionLock) { @@ -162,7 +173,11 @@ public void MoveObj(IMovable obj, int moveTime, double direction, long stateNum) flag = true; break; case AfterCollision.Destroyed: - Debugger.Output(obj, $"collide with {collisionObj} and has been removed from the game."); + GameEngineLogging.logger.ConsoleLogDebug( + Logger.ObjInfo(obj) + + " collide with " + + Logger.ObjInfo(collisionObj) + + " and has been removed from the game"); isEnded = true; break; case AfterCollision.MoveMax: @@ -244,7 +259,11 @@ public void MoveObj(IMovable obj, int moveTime, double direction, long stateNum) flag = true; break; case AfterCollision.Destroyed: - Debugger.Output(obj, $"collide with {collisionObj} and has been removed from the game."); + GameEngineLogging.logger.ConsoleLogDebug( + Logger.ObjInfo(obj) + + " collide with " + + Logger.ObjInfo(collisionObj) + + " and has been removed from the game"); isEnded = true; break; case AfterCollision.MoveMax: diff --git a/logic/Gaming/ActionManager.cs b/logic/Gaming/ActionManager.cs index 7fa2daec..72468343 100755 --- a/logic/Gaming/ActionManager.cs +++ b/logic/Gaming/ActionManager.cs @@ -1,13 +1,19 @@ using GameClass.GameObj; +using GameClass.GameObj.Map; using GameClass.GameObj.Areas; using GameEngine; using Preparation.Utility; using System; using System.Threading; using Timothy.FrameRateTask; +using Preparation.Utility.Logging; namespace Gaming { + public static class ActionManagerLogging + { + public static readonly Logger logger = new("ActionManager"); + } public partial class Game { private readonly ActionManager actionManager; @@ -46,13 +52,13 @@ public bool MoveShip(Ship shipToMove, int moveTimeInMilliseconds, double moveDir { if (moveTimeInMilliseconds < 5) { - Debugger.Output("Move time is too short."); + ActionManagerLogging.logger.ConsoleLogDebug("Move time is too short"); return false; } long stateNum = shipToMove.SetShipState(RunningStateType.Waiting, ShipStateType.Moving); if (stateNum == -1) { - Debugger.Output("Ship is not commandable."); + ActionManagerLogging.logger.ConsoleLogDebug("Ship is not commandable"); return false; } new Thread diff --git a/logic/Gaming/AttackManager.cs b/logic/Gaming/AttackManager.cs index 38c494ee..056488a0 100755 --- a/logic/Gaming/AttackManager.cs +++ b/logic/Gaming/AttackManager.cs @@ -1,4 +1,5 @@ using GameClass.GameObj; +using GameClass.GameObj.Map; using GameClass.GameObj.Areas; using GameClass.GameObj.Bullets; using GameEngine; @@ -10,9 +11,14 @@ using System.Linq; using System.Threading; using Timothy.FrameRateTask; +using Preparation.Utility.Logging; namespace Gaming { + public static class AttackManagerLogging + { + public static readonly Logger logger = new("AttackManager"); + } public partial class Game { private readonly AttackManager attackManager; @@ -36,7 +42,9 @@ public AttackManager(Game game, Map gameMap, ShipManager shipManager) }, EndMove: obj => { - Debugger.Output(obj, " end move at " + obj.Position.ToString() + " At time: " + Environment.TickCount64); + AttackManagerLogging.logger.ConsoleLogDebug( + Logger.ObjInfo(obj) + + $" end move at {obj.Position} Time: {Environment.TickCount64}"); if (obj.CanMove) { BulletBomb((Bullet)obj, null); @@ -52,13 +60,22 @@ public void ProduceBulletNaturally(BulletType bulletType, Ship ship, double angl if (bulletType == BulletType.Null) return; Bullet? bullet = BulletFactory.GetBullet(ship, pos, bulletType); if (bullet == null) return; - Debugger.Output(bullet, "Attack in " + pos.ToString()); + AttackManagerLogging.logger.ConsoleLogDebug( + Logger.TypeName(bullet) + + $" attack in {pos}"); gameMap.Add(bullet); - moveEngine.MoveObj(bullet, (int)(bullet.AttackDistance * 1000 / bullet.MoveSpeed), angle, ++bullet.StateNum); // 这里时间参数除出来的单位要是ms + moveEngine.MoveObj( + bullet, + (int)(bullet.AttackDistance * 1000 / bullet.MoveSpeed), + angle, + ++bullet.StateNum); // 这里时间参数除出来的单位要是ms } private void BombObj(Bullet bullet, GameObj objBeingShot) { - Debugger.Output(bullet, "bombed " + objBeingShot.ToString()); + AttackManagerLogging.logger.ConsoleLogDebug( + Logger.TypeName(bullet) + + " bombed " + + Logger.ObjInfo(objBeingShot)); switch (objBeingShot.Type) { case GameObjType.Ship: @@ -67,8 +84,12 @@ private void BombObj(Bullet bullet, GameObj objBeingShot) case GameObjType.Construction: var constructionType = ((Construction)objBeingShot).ConstructionType; var flag = ((Construction)objBeingShot).BeAttacked(bullet); - if (constructionType == ConstructionType.Community && flag) game.RemoveBirthPoint(((Construction)objBeingShot).TeamID, ((Construction)objBeingShot).Position); - else if (constructionType == ConstructionType.Factory && flag) game.RemoveFactory(((Construction)objBeingShot).TeamID); + if (constructionType == ConstructionType.Community && flag) + game.RemoveBirthPoint( + ((Construction)objBeingShot).TeamID, + ((Construction)objBeingShot).Position); + else if (constructionType == ConstructionType.Factory && flag) + game.RemoveFactory(((Construction)objBeingShot).TeamID); break; case GameObjType.Wormhole: ((WormholeCell)objBeingShot).Wormhole.BeAttacked(bullet); @@ -79,10 +100,15 @@ private void BombObj(Bullet bullet, GameObj objBeingShot) { foreach (Ship ship in shipList) { - Debugger.Output(ship, " is destroyed!"); + AttackManagerLogging.logger.ConsoleLogDebug( + ShipLogging.ShipLogInfo(ship) + + " is destroyed!"); var money = ship.GetCost(); bullet.Parent!.AddMoney(money); - Debugger.Output(bullet.Parent, " get " + money.ToString() + " money because of destroying " + ship); + AttackManagerLogging.logger.ConsoleLogDebug( + ShipLogging.ShipLogInfo((Ship)bullet.Parent) + + $" get {money} money because of destroying " + + ShipLogging.ShipLogInfo(ship)); shipManager.Remove(ship); } } @@ -120,9 +146,14 @@ public bool TryRemoveBullet(Bullet bullet) private void BulletBomb(Bullet bullet, GameObj? objBeingShot) { if (objBeingShot != null) - Debugger.Output(bullet, "bombed with" + objBeingShot.ToString()); + AttackManagerLogging.logger.ConsoleLogDebug( + Logger.TypeName(bullet) + + " bombed with" + + Logger.ObjInfo(objBeingShot)); else - Debugger.Output(bullet, "bombed without objBeingShot"); + AttackManagerLogging.logger.ConsoleLogDebug( + Logger.TypeName(bullet) + + " bombed without objBeingShot"); if (!TryRemoveBullet(bullet)) { @@ -167,7 +198,9 @@ public bool Attack(Ship ship, double angle) Bullet? bullet = ship.Attack(angle); if (bullet != null) { - Debugger.Output(bullet, "Attack in " + bullet.Position.ToString()); + AttackManagerLogging.logger.ConsoleLogDebug( + Logger.TypeName(bullet) + + $" attack in {bullet.Position}"); gameMap.Add(bullet); moveEngine.MoveObj(bullet, (int)(bullet.AttackDistance * 1000 / bullet.MoveSpeed), angle, ++bullet.StateNum); // 这里时间参数除出来的单位要是ms if (bullet.CastTime > 0) @@ -210,12 +243,16 @@ public bool Attack(Ship ship, double angle) } if (bullet != null) { - Debugger.Output($"Player {ship.PlayerID} from Team {ship.TeamID} successfully attacked!"); + AttackManagerLogging.logger.ConsoleLogDebug( + ShipLogging.ShipLogInfo(ship) + + " successfully attacked!"); return true; } else { - Debugger.Output($"Player {ship.PlayerID} from Team {ship.TeamID} failed to attack!"); + AttackManagerLogging.logger.ConsoleLogDebug( + ShipLogging.ShipLogInfo(ship) + + " failed to attack!"); return false; } } diff --git a/logic/Gaming/Game.cs b/logic/Gaming/Game.cs index 0e79f3dd..76084961 100755 --- a/logic/Gaming/Game.cs +++ b/logic/Gaming/Game.cs @@ -1,8 +1,10 @@ using GameClass.GameObj; +using GameClass.GameObj.Map; using GameClass.GameObj.Areas; using GameClass.MapGenerator; using Preparation.Interface; using Preparation.Utility; +using Preparation.Utility.Logging; using Preparation.Utility.Value; using System; using System.Collections.Generic; @@ -11,6 +13,10 @@ namespace Gaming { + public static class GameLogging + { + public static readonly Logger logger = new("Game"); + } public partial class Game { public struct PlayerInitInfo(long teamID, long playerID, ShipType shipType) @@ -81,11 +87,11 @@ public long AddPlayer(PlayerInitInfo playerInitInfo) } public long ActivateShip(long teamID, ShipType shipType, int birthPointIndex = 0) { - Debugger.Output($"Trying to activate: {teamID} {shipType} at {birthPointIndex}"); + GameLogging.logger.ConsoleLogDebug($"Try to activate {teamID} {shipType} at birthpoint {birthPointIndex}"); Ship? ship = teamList[(int)teamID].ShipPool.GetObj(shipType); if (ship == null) { - Debugger.Output($"Failed to activate: {teamID} {shipType}, no ship available"); + GameLogging.logger.ConsoleLogDebug($"Fail to activate {teamID} {shipType}, no ship available"); return GameObj.invalidID; } if (birthPointIndex < 0) @@ -96,13 +102,13 @@ public long ActivateShip(long teamID, ShipType shipType, int birthPointIndex = 0 pos += new XY(((random.Next() & 2) - 1) * 1000, ((random.Next() & 2) - 1) * 1000); if (ShipManager.ActivateShip(ship, pos)) { - Debugger.Output($"Successfully activated: {teamID} {shipType} at {pos}"); + GameLogging.logger.ConsoleLogDebug($"Successfully activated {teamID} {shipType} at {pos}"); return ship.PlayerID; } else { teamList[(int)teamID].ShipPool.ReturnObj(ship); - Debugger.Output($"Failed to activate: {teamID} {shipType} at {pos}, rule not permitted"); + GameLogging.logger.ConsoleLogDebug($"Fail to activate {teamID} {shipType} at {pos}, rule not permitted"); return GameObj.invalidID; } } @@ -138,12 +144,18 @@ public bool MoveShip(long teamID, long shipID, int moveTimeInMilliseconds, doubl Ship? ship = gameMap.FindShipInPlayerID(teamID, shipID); if (ship != null && ship.IsRemoved == false) { - Debugger.Output("Trying to move: " + teamID + " " + shipID + " " + moveTimeInMilliseconds + " " + angle); + GameLogging.logger.ConsoleLogDebug( + "Try to move " + + ShipLogging.ShipLogInfo(ship) + + $" {moveTimeInMilliseconds} {angle}"); return actionManager.MoveShip(ship, moveTimeInMilliseconds, angle); } else { - Debugger.Output("Failed to move: " + teamID + " " + shipID + ", no ship found"); + GameLogging.logger.ConsoleLogDebug( + "Fail to move " + + ShipLogging.ShipLogInfo(teamID, shipID) + + ", not found"); return false; } } diff --git a/logic/Gaming/ShipManager.cs b/logic/Gaming/ShipManager.cs index a9a4165b..fc702efd 100755 --- a/logic/Gaming/ShipManager.cs +++ b/logic/Gaming/ShipManager.cs @@ -1,10 +1,16 @@ using GameClass.GameObj; +using GameClass.GameObj.Map; using Preparation.Utility; +using Preparation.Utility.Logging; using Preparation.Utility.Value; using System.Threading; namespace Gaming { + public static class ShipManagerLogging + { + public static readonly Logger logger = new("ShipManager"); + } public partial class Game { private readonly ShipManager shipManager; @@ -18,14 +24,14 @@ private class ShipManager(Game game, Map gameMap) gameMap.Add(newShip); newShip.TeamID.SetROri(teamID); newShip.PlayerID.SetROri(playerID); - Debugger.Output( + ShipManagerLogging.logger.ConsoleLogDebug( "Added ship: " + newShip.ShipType + " with " + newShip.ProducerModuleType + ", " + newShip.ConstructorModuleType + ", " + newShip.ArmorModuleType + ", " + newShip.ShieldModuleType + ", " + newShip.WeaponModuleType - ); + ); return newShip; } public static bool ActivateShip(Ship ship, XY pos) @@ -36,13 +42,22 @@ public static bool ActivateShip(Ship ship, XY pos) } ship.ReSetPos(pos); ship.SetShipState(RunningStateType.Null, ShipStateType.Null); - Debugger.Output(ship, " is activated!"); + ShipManagerLogging.logger.ConsoleLogDebug( + ShipLogging.ShipLogInfo(ship) + + " is activated!" + ); return true; } public void BeAttacked(Ship ship, Bullet bullet) { - Debugger.Output(ship, " is attacked!"); - Debugger.Output(bullet, $" 's AP is {bullet.AP}"); + ShipManagerLogging.logger.ConsoleLogDebug( + ShipLogging.ShipLogInfo(ship) + + " is attacked!" + ); + ShipManagerLogging.logger.ConsoleLogDebug( + Logger.TypeName(bullet) + + $" 's AP is {bullet.AP}" + ); if (bullet!.Parent!.TeamID == ship.TeamID) { return; @@ -51,31 +66,47 @@ public void BeAttacked(Ship ship, Bullet bullet) if (bullet.TypeOfBullet != BulletType.Missile && ship.Shield > 0) { ship.Shield.SubPositiveV((long)(subHP * bullet.ShieldModifier)); - Debugger.Output(ship, $" 's shield is {ship.Shield}"); + ShipManagerLogging.logger.ConsoleLogDebug( + ShipLogging.ShipLogInfo(ship) + + $" 's shield is {ship.Shield}" + ); } else if (ship.Armor > 0) { ship.Armor.SubPositiveV((long)(subHP * bullet.ArmorModifier)); - Debugger.Output(ship, $" 's armor is {ship.Armor}"); + ShipManagerLogging.logger.ConsoleLogDebug( + ShipLogging.ShipLogInfo(ship) + + $" 's armor is {ship.Armor}" + ); } else { ship.HP.SubPositiveV(subHP); - Debugger.Output(ship, $" 's HP is {ship.HP}"); + ShipManagerLogging.logger.ConsoleLogDebug( + ShipLogging.ShipLogInfo(ship) + + $" 's HP is {ship.HP}" + ); } if (ship.HP == 0) { - Debugger.Output(ship, " is destroyed!"); + ShipManagerLogging.logger.ConsoleLogDebug( + ShipLogging.ShipLogInfo(ship) + + " is destroyed!"); var money = ship.GetCost(); bullet.Parent.AddMoney(money); - Debugger.Output(bullet.Parent, $" get {money} money because of destroying {ship}"); + ShipManagerLogging.logger.ConsoleLogDebug( + ShipLogging.ShipLogInfo((Ship)bullet.Parent) + + $" get {money} money because of destroying " + + ShipLogging.ShipLogInfo(ship)); Remove(ship); } } public void BeAttacked(Ship ship, long AP, long teamID) { - Debugger.Output(ship, " is attacked!"); - Debugger.Output($"AP is {AP}"); + ShipManagerLogging.logger.ConsoleLogDebug( + ShipLogging.ShipLogInfo(ship) + + " is attacked!"); + ShipManagerLogging.logger.ConsoleLogDebug($"AP is {AP}"); if (AP <= 0) { return; @@ -83,19 +114,29 @@ public void BeAttacked(Ship ship, long AP, long teamID) if (ship.Armor > 0) { ship.Armor.SubPositiveV(AP); - Debugger.Output(ship, $" 's armor is {ship.Armor}"); + ShipManagerLogging.logger.ConsoleLogDebug( + ShipLogging.ShipLogInfo(ship) + + $" 's armor is {ship.Armor}"); } else { ship.HP.SubPositiveV(AP); - Debugger.Output(ship, $" 's HP is {ship.HP}"); + ShipManagerLogging.logger.ConsoleLogDebug( + ShipLogging.ShipLogInfo(ship) + + $" 's HP is {ship.HP}"); } if (ship.HP == 0) { - Debugger.Output(ship, " is destroyed!"); + ShipManagerLogging.logger.ConsoleLogDebug( + ShipLogging.ShipLogInfo(ship) + + " is destroyed!"); var money = ship.GetCost(); - game.TeamList[(int)teamID].AddMoney(money); - Debugger.Output(ship, $" get {money} money because of destroying {ship}"); + var team = game.TeamList[(int)teamID]; + team.AddMoney(money); + ShipManagerLogging.logger.ConsoleLogDebug( + Logger.ObjInfo(typeof(Base), teamID.ToString()) + + $" get {money} money because of destroying " + + ShipLogging.ShipLogInfo(ship)); Remove(ship); } } @@ -109,7 +150,9 @@ public static long BeStunned(Ship ship, int time) new Thread (() => { - Debugger.Output(ship, $" is stunned for {time} ms"); + ShipManagerLogging.logger.ConsoleLogDebug( + ShipLogging.ShipLogInfo(ship) + + $" is stunned for {time} ms"); Thread.Sleep(time); ship.ResetShipState(stateNum); } @@ -131,7 +174,9 @@ public static bool BackSwing(Ship ship, int time) new Thread (() => { - Debugger.Output(ship, $" is swinging for {time} ms"); + ShipManagerLogging.logger.ConsoleLogDebug( + ShipLogging.ShipLogInfo(ship) + + $" is swinging for {time} ms"); Thread.Sleep(time); ship.ResetShipState(stateNum); } @@ -166,9 +211,13 @@ public bool Recycle(Ship ship) default: return false; } - Debugger.Output(ship, $" 's value is {shipValue}"); + ShipManagerLogging.logger.ConsoleLogDebug( + ShipLogging.ShipLogInfo(ship) + + $" 's value is {shipValue}"); ship.AddMoney((long)(shipValue * 0.5 * ship.HP.GetDivideValueByMaxV())); - Debugger.Output(ship, " is recycled!"); + ShipManagerLogging.logger.ConsoleLogDebug( + ShipLogging.ShipLogInfo(ship) + + " is recycled!"); Remove(ship); return false; } @@ -176,10 +225,14 @@ public void Remove(Ship ship) { if (!ship.TryToRemoveFromGame(ShipStateType.Deceased)) { - Debugger.Output(ship, " is not removed from game!"); + ShipManagerLogging.logger.ConsoleLogDebug( + ShipLogging.ShipLogInfo(ship) + + " hasn't been removed from game!"); return; } - Debugger.Output(ship, " is removed from game!"); + ShipManagerLogging.logger.ConsoleLogDebug( + ShipLogging.ShipLogInfo(ship) + + " hasn been removed from game!"); gameMap.Remove(ship); } } diff --git a/logic/Preparation/Utility/Debugger.cs b/logic/Preparation/Utility/Debugger.cs deleted file mode 100755 index 94ca944b..00000000 --- a/logic/Preparation/Utility/Debugger.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; - -namespace Preparation.Utility -{ - public class Debugger - { - static public void Output(object current, string str) - { -#if DEBUG - Console.WriteLine($"{current.GetType()} {current} {str}"); -#endif - } - static public void Output(string str) - { -#if DEBUG - Console.WriteLine(str); -#endif - } - } -} diff --git a/logic/Preparation/Utility/Logger.cs b/logic/Preparation/Utility/Logger.cs index b47b34dd..45fd36a5 100755 --- a/logic/Preparation/Utility/Logger.cs +++ b/logic/Preparation/Utility/Logger.cs @@ -7,24 +7,20 @@ namespace Preparation.Utility.Logging; -public struct LogInfo -{ - public string FileName; - public string Info; -} - public class LogQueue { public static LogQueue Global { get; } = new(); + private static uint logNum = 0; + private static uint logCopyNum = 0; private static readonly object queueLock = new(); - private readonly Queue logInfoQueue = new(); + private readonly Queue logInfoQueue = new(); - public async Task Commit(LogInfo logInfo) + public async Task Commit(string info) { await Task.Run(() => { - lock (queueLock) logInfoQueue.Enqueue(logInfo); + lock (queueLock) logInfoQueue.Enqueue(info); }); } @@ -40,8 +36,17 @@ private LogQueue() { while (logInfoQueue.Count != 0) { - var logInfo = logInfoQueue.Dequeue(); - File.AppendAllText(logInfo.FileName, logInfo.Info + Environment.NewLine); + var info = logInfoQueue.Dequeue(); + File.AppendAllText(LoggingData.ServerLogPath, info + Environment.NewLine); + logNum++; + if (logNum >= LoggingData.MaxLogNum) + { + File.Copy(LoggingData.ServerLogPath, + $"{LoggingData.ServerLogPath}-copy{logCopyNum}.txt"); + logCopyNum++; + File.Delete(LoggingData.ServerLogPath); + logNum = 0; + } } } }, @@ -53,38 +58,40 @@ private LogQueue() } } -public class Logger(string module, string file) +public class Logger(string module) { - public void ConsoleLog(string msg, bool Duplicate = false) + public readonly string Module = module; + + public void ConsoleLog(string msg, bool Duplicate = true) { - var info = $"[{module}]{msg}"; + var info = $"[{Module}]{msg}"; Console.WriteLine(info); if (Duplicate) - _ = LogQueue.Global.Commit(new() - { - FileName = file, - Info = info - }); + _ = LogQueue.Global.Commit(info); } - public void ConsoleLogDebug(string msg, bool Duplicate = false) + public void ConsoleLogDebug(string msg, bool Duplicate = true) { #if DEBUG - var info = $"[{module}]{msg}"; + var info = $"[{Module}]{msg}"; Console.WriteLine(info); if (Duplicate) - _ = LogQueue.Global.Commit(new() - { - FileName = file, - Info = info - }); + _ = LogQueue.Global.Commit(info); #endif } public static string TypeName(object obj) - { - return obj.GetType().Name; - } - public static string ObjInfo(object obj, string msg) - { - return $"<{TypeName(obj)} {msg}>"; - } + => obj.GetType().Name; + public static string TypeName(Type tp) + => tp.Name; + public static string ObjInfo(object obj, string msg = "") + => msg == "" ? $"<{TypeName(obj)}>" + : $"<{TypeName(obj)} {msg}>"; + public static string ObjInfo(Type tp, string msg = "") + => msg == "" ? $"<{TypeName(tp)}>" + : $"<{TypeName(tp)} {msg}>"; +} + +public static class LoggingData +{ + public const string ServerLogPath = "log.txt"; + public const uint MaxLogNum = 5000; } diff --git a/logic/Preparation/Utility/Value/SafeValue/LockedValue/InRangeTimeBased.cs b/logic/Preparation/Utility/Value/SafeValue/LockedValue/InRangeTimeBased.cs index 8cfb79cf..57efaeae 100644 --- a/logic/Preparation/Utility/Value/SafeValue/LockedValue/InRangeTimeBased.cs +++ b/logic/Preparation/Utility/Value/SafeValue/LockedValue/InRangeTimeBased.cs @@ -38,8 +38,10 @@ public LongInVariableRangeWithStartTime(long maxValue) : base(maxValue) { } return WriteNeed(() => { long addV = (long)(startTime.StopIfPassing(maxV - v) * speed); - if (addV < 0) return (v, maxV, startTime.Get()); - if (maxV - v < addV) return (v = maxV, maxV, startTime.Get()); + if (addV < 0) + return (v, maxV, startTime.Get()); + if (maxV - v < addV) + return (v = maxV, maxV, startTime.Get()); return (v + addV, maxV, startTime.Get()); }); } @@ -121,7 +123,9 @@ public IDouble Speed public TimeBasedProgressAtVariableSpeed(long needProgress, double speed = 1.0) { progress = new LongInVariableRangeWithStartTime(0, needProgress); - if (needProgress <= 0) Debugger.Output("Bug:TimeBasedProgressAtVariableSpeed.needProgress (" + needProgress.ToString() + ") is less than 0."); + if (needProgress <= 0) + LockedValueLogging.logger.ConsoleLogDebug( + $"Bug: TimeBasedProgressAtVariableSpeed.needProgress({needProgress}) is less than 0"); this.speed = new AtomicDouble(speed); } public TimeBasedProgressAtVariableSpeed() @@ -136,15 +140,20 @@ public override string ToString() { long progressStored, lastStartTime; (progressStored, lastStartTime) = progress.GetValueWithStartTime(); - return "ProgressStored: " + progressStored.ToString() - + " ; LastStartTime: " + lastStartTime.ToString() + "ms" - + " ; Speed: " + speed.ToString(); - } - public long GetProgressNow() => progress.AddStartTimeToMaxV(speed.ToDouble()).Item1; - public (long, long, long) GetProgressNowAndNeedTimeAndLastStartTime() => progress.AddStartTimeToMaxV(speed.ToDouble()); - public long GetProgressStored() => progress.GetValue(); - public (long, long) GetProgressStoredAndNeedTime() => progress.GetValueAndMaxV(); - public (long, long, long) GetProgressStoredAndNeedTimeAndLastStartTime() => progress.GetValueAndMaxVWithStartTime(); + return $"ProgressStored: {progressStored}; " + + $"LastStartTime: {lastStartTime} ms; " + + $"Speed: {speed}"; + } + public long GetProgressNow() + => progress.AddStartTimeToMaxV(speed.ToDouble()).Item1; + public (long, long, long) GetProgressNowAndNeedTimeAndLastStartTime() + => progress.AddStartTimeToMaxV(speed.ToDouble()); + public long GetProgressStored() + => progress.GetValue(); + public (long, long) GetProgressStoredAndNeedTime() + => progress.GetValueAndMaxV(); + public (long, long, long) GetProgressStoredAndNeedTimeAndLastStartTime() + => progress.GetValueAndMaxVWithStartTime(); public bool IsFinished() { @@ -164,10 +173,12 @@ public bool Start(long needTime) { if (needTime <= 2) { - Debugger.Output("Warning:Start TimeBasedProgressAtVariableSpeed with the needProgress (" + needTime.ToString() + ") which is less than 0."); + LockedValueLogging.logger.ConsoleLogDebug( + $"Warning: Start TimeBasedProgressAtVariableSpeed with the needProgress({needTime}) which is less than 0"); return false; } - if (progress.startTime.Start() != long.MaxValue) return false; + if (progress.startTime.Start() != long.MaxValue) + return false; progress.SetMaxV(needTime); return true; } diff --git a/logic/Preparation/Utility/Value/SafeValue/LockedValue/InTheRange.cs b/logic/Preparation/Utility/Value/SafeValue/LockedValue/InTheRange.cs index b4f11147..c5a0be08 100644 --- a/logic/Preparation/Utility/Value/SafeValue/LockedValue/InTheRange.cs +++ b/logic/Preparation/Utility/Value/SafeValue/LockedValue/InTheRange.cs @@ -23,12 +23,14 @@ public InVariableRange(T value, T maxValue) : base() { if (value < T.Zero) { - Debugger.Output("Warning:Try to set IntInTheVariableRange to " + value.ToString() + "."); + LockedValueLogging.logger.ConsoleLogDebug( + $"Warning: Try to set IntInTheVariableRange to {value}"); value = T.Zero; } if (maxValue < T.Zero) { - Debugger.Output("Warning:Try to set IntInTheVariableRange.maxValue to " + maxValue.ToString() + "."); + LockedValueLogging.logger.ConsoleLogDebug( + $"Warning: Try to set IntInTheVariableRange.maxValue to {maxValue}"); maxValue = T.Zero; } v = value.CompareTo(maxValue) < 0 ? value : maxValue; @@ -41,7 +43,8 @@ public InVariableRange(T maxValue) : base() { if (maxValue < T.Zero) { - Debugger.Output("Warning:Try to set IntInTheVariableRange.maxValue to " + maxValue.ToString() + "."); + LockedValueLogging.logger.ConsoleLogDebug( + $"Warning: Try to set IntInTheVariableRange.maxValue to {maxValue}"); maxValue = T.Zero; } v = maxV = maxValue; @@ -49,7 +52,7 @@ public InVariableRange(T maxValue) : base() public override string ToString() { - return ReadNeed(() => "value:" + v.ToString() + " , maxValue:" + maxV.ToString()); + return ReadNeed(() => $"value: {v} , maxValue: {maxV}"); } public T GetValue() { return ReadNeed(() => v); } public double ToDouble() => GetValue().ToDouble(null); @@ -419,7 +422,8 @@ public T VAddPartMaxVRChange(double ratio) #endregion #region 与InVariableRange类的运算,运算会影响该对象的值 - public T AddRChange(InVariableRange a, double speed = 1.0) where TA : IConvertible, IComparable, INumber + public T AddRChange(InVariableRange a, double speed = 1.0) + where TA : IConvertible, IComparable, INumber { return EnterOtherLock(a, () => WriteNeed(() => { @@ -430,7 +434,8 @@ public T AddRChange(InVariableRange a, double speed = 1.0) where TA : IC return v - previousV; }))!; } - public T AddVUseOtherRChange(T value, InVariableRange other, double speed = 1.0) where TA : IConvertible, IComparable, INumber + public T AddVUseOtherRChange(T value, InVariableRange other, double speed = 1.0) + where TA : IConvertible, IComparable, INumber { return EnterOtherLock(other, () => WriteNeed(() => { @@ -443,7 +448,8 @@ public T AddVUseOtherRChange(T value, InVariableRange other, double spee return v - previousV; }))!; } - public T SubVLimitedByAddingOtherRChange(T value, InVariableRange other, double speed = 1.0) where TA : IConvertible, IComparable, INumber + public T SubVLimitedByAddingOtherRChange(T value, InVariableRange other, double speed = 1.0) + where TA : IConvertible, IComparable, INumber { return EnterOtherLock(other, () => WriteNeed(() => { @@ -457,7 +463,8 @@ public T SubVLimitedByAddingOtherRChange(T value, InVariableRange other, return value; }))!; } - public T SubRChange(InVariableRange a) where TA : IConvertible, IComparable, IComparable, INumber + public T SubRChange(InVariableRange a) + where TA : IConvertible, IComparable, IComparable, INumber { return EnterOtherLock(a, () => WriteNeed(() => { @@ -481,8 +488,10 @@ public T SubRChange(InVariableRange a) where TA : IConvertible, ICompara return WriteNeed(() => { long addV = (long)(startTime.StopIfPassing((maxV - v).ToInt64(null)) * speed); - if (addV < 0) return (v, maxV, startTime.Get()); - if (maxV - v < T.CreateChecked(addV)) return (v = maxV, maxV, startTime.Get()); + if (addV < 0) + return (v, maxV, startTime.Get()); + if (maxV - v < T.CreateChecked(addV)) + return (v = maxV, maxV, startTime.Get()); return (v, maxV, startTime.Get()); }); } diff --git a/logic/Preparation/Utility/Value/SafeValue/LockedValue/LockedValue.cs b/logic/Preparation/Utility/Value/SafeValue/LockedValue/LockedValue.cs index a59234c5..c3d6de4f 100644 --- a/logic/Preparation/Utility/Value/SafeValue/LockedValue/LockedValue.cs +++ b/logic/Preparation/Utility/Value/SafeValue/LockedValue/LockedValue.cs @@ -2,9 +2,14 @@ using System.Threading; using System.Collections.Generic; using System.Linq; +using Preparation.Utility.Logging; namespace Preparation.Utility.Value.SafeValue.LockedValue { + public static class LockedValueLogging + { + public static readonly Logger logger = new("LockedValue"); + } public abstract class LockedValue { protected readonly object vLock = new(); diff --git a/logic/Preparation/Utility/Value/SafeValue/LockedValue/PositiveV.cs b/logic/Preparation/Utility/Value/SafeValue/LockedValue/PositiveV.cs index f7f4e9a3..001cc5da 100644 --- a/logic/Preparation/Utility/Value/SafeValue/LockedValue/PositiveV.cs +++ b/logic/Preparation/Utility/Value/SafeValue/LockedValue/PositiveV.cs @@ -19,7 +19,7 @@ public PositiveValue(T value) : base() { if (value < T.Zero) { - Debugger.Output("Warning:Try to set PositiveValue to " + value.ToString() + "."); + LockedValueLogging.logger.ConsoleLogDebug($"Warning: Try to set PositiveValue to {value}"); value = T.Zero; } v = value; diff --git a/logic/Preparation/Utility/Value/SafeValue/TimeBased.cs b/logic/Preparation/Utility/Value/SafeValue/TimeBased.cs index 78d01719..9b4d955e 100644 --- a/logic/Preparation/Utility/Value/SafeValue/TimeBased.cs +++ b/logic/Preparation/Utility/Value/SafeValue/TimeBased.cs @@ -1,9 +1,15 @@ -using Preparation.Utility.Value.SafeValue.Atomic; +using Preparation.Utility.Logging; +using Preparation.Utility.Value.SafeValue.Atomic; using System; using System.Threading; namespace Preparation.Utility.Value.SafeValue.TimeBased { + public static class TimeBasedLogging + { + public static readonly Logger logger = new("TimeBased"); + } + //其对应属性不应当有set访问器,避免不安全的=赋值 /// @@ -49,7 +55,9 @@ public class TimeBasedProgressOptimizedForInterrupting public TimeBasedProgressOptimizedForInterrupting(long needTime) { - if (needTime <= 0) Debugger.Output("Bug:TimeBasedProgressOptimizedForInterrupting.needProgress (" + needTime.ToString() + ") is less than 0."); + if (needTime <= 0) + TimeBasedLogging.logger.ConsoleLogDebug( + $"Bug: TimeBasedProgressOptimizedForInterrupting.needProgress({needTime}) is less than 0"); needT = needTime; } public TimeBasedProgressOptimizedForInterrupting() @@ -58,7 +66,8 @@ public TimeBasedProgressOptimizedForInterrupting() } public long GetEndTime() => Interlocked.CompareExchange(ref endT, -2, -2); public long GetNeedTime() => Interlocked.CompareExchange(ref needT, -2, -2); - public override string ToString() => "EndTime:" + Interlocked.CompareExchange(ref endT, -2, -2).ToString() + " ms, NeedTime:" + Interlocked.CompareExchange(ref needT, -2, -2).ToString() + " ms"; + public override string ToString() + => $"EndTime: {Interlocked.CompareExchange(ref endT, -2, -2)} ms, NeedTime: {Interlocked.CompareExchange(ref needT, -2, -2)} ms"; public bool IsFinished() { return Interlocked.CompareExchange(ref endT, -2, -2) <= Environment.TickCount64; @@ -70,13 +79,15 @@ public bool IsFinished() public long GetProgress() { long cutime = Interlocked.CompareExchange(ref endT, -2, -2) - Environment.TickCount64; - if (cutime <= 0) return Interlocked.CompareExchange(ref needT, -2, -2); + if (cutime <= 0) + return Interlocked.CompareExchange(ref needT, -2, -2); return Interlocked.CompareExchange(ref needT, -2, -2) - cutime; } public long GetNonNegativeProgress() { long cutime = Interlocked.CompareExchange(ref endT, -2, -2) - Environment.TickCount64; - if (cutime <= 0) return Interlocked.CompareExchange(ref needT, -2, -2); + if (cutime <= 0) + return Interlocked.CompareExchange(ref needT, -2, -2); long progress = Interlocked.CompareExchange(ref needT, -2, -2) - cutime; return progress < 0 ? 0 : progress; } @@ -86,38 +97,45 @@ public long GetNonNegativeProgress() public long GetProgress(long time) { long cutime = Interlocked.CompareExchange(ref endT, -2, -2) - time; - if (cutime <= 0) return Interlocked.CompareExchange(ref needT, -2, -2); + if (cutime <= 0) + return Interlocked.CompareExchange(ref needT, -2, -2); return Interlocked.CompareExchange(ref needT, -2, -2) - cutime; } public long GetNonNegativeProgress(long time) { long cutime = Interlocked.Read(ref endT) - time; - if (cutime <= 0) return Interlocked.CompareExchange(ref needT, -2, -2); + if (cutime <= 0) + return Interlocked.CompareExchange(ref needT, -2, -2); long progress = Interlocked.CompareExchange(ref needT, -2, -2) - cutime; return progress < 0 ? 0 : progress; } /// - /// <0则表明未开始 + /// 小于0则表明未开始 /// - public static implicit operator long(TimeBasedProgressOptimizedForInterrupting pLong) => pLong.GetProgress(); + public static implicit operator long(TimeBasedProgressOptimizedForInterrupting pLong) + => pLong.GetProgress(); /// - /// GetProgressDouble<0则表明未开始 + /// GetProgressDouble < 0则表明未开始 /// public double GetProgressDouble() { long cutime = Interlocked.CompareExchange(ref endT, -2, -2) - Environment.TickCount64; - if (cutime <= 0) return 1; + if (cutime <= 0) + return 1; long needTime = Interlocked.CompareExchange(ref needT, -2, -2); - if (needTime == 0) return 0; + if (needTime == 0) + return 0; return 1.0 - (double)cutime / needTime; } public double GetNonNegativeProgressDouble(long time) { long cutime = Interlocked.Read(ref endT) - time; - if (cutime <= 0) return 1; + if (cutime <= 0) + return 1; long needTime = Interlocked.CompareExchange(ref needT, -2, -2); - if (needTime <= cutime) return 0; + if (needTime <= cutime) + return 0; return 1.0 - (double)cutime / needTime; } @@ -125,19 +143,24 @@ public bool Start(long needTime) { if (needTime <= 0) { - Debugger.Output("Warning:Start TimeBasedProgressOptimizedForInterrupting with the needProgress (" + needTime.ToString() + ") which is less than 0."); + TimeBasedLogging.logger.ConsoleLogDebug( + $"Warning: Start TimeBasedProgressOptimizedForInterrupting with the needProgress({needTime}) which is less than 0"); return false; } //规定只有Start可以修改needT,且需要先访问endTime,从而避免锁(某种程度上endTime可以认为是needTime的锁) - if (Interlocked.CompareExchange(ref endT, Environment.TickCount64 + needTime, long.MaxValue) != long.MaxValue) return false; - if (needTime <= 2) Debugger.Output("Warning:the field of TimeBasedProgressOptimizedForInterrupting is " + needTime.ToString() + ",which is too small."); + if (Interlocked.CompareExchange(ref endT, Environment.TickCount64 + needTime, long.MaxValue) != long.MaxValue) + return false; + if (needTime <= 2) + TimeBasedLogging.logger.ConsoleLogDebug( + $"Warning: The field of TimeBasedProgressOptimizedForInterrupting is {needTime},which is too small"); Interlocked.Exchange(ref needT, needTime); return true; } public bool Start() { long needTime = Interlocked.CompareExchange(ref needT, -2, -2); - if (Interlocked.CompareExchange(ref endT, Environment.TickCount64 + needTime, long.MaxValue) != long.MaxValue) return false; + if (Interlocked.CompareExchange(ref endT, Environment.TickCount64 + needTime, long.MaxValue) != long.MaxValue) + return false; return true; } /// @@ -168,17 +191,20 @@ public class BoolUpdateEachCD private long nextUpdateTime = 0; public BoolUpdateEachCD(int cd) { - if (cd <= 1) Debugger.Output("Bug:BoolUpdateEachCD.cd (" + cd.ToString() + ") is less than 1."); + if (cd <= 1) + TimeBasedLogging.logger.ConsoleLogDebug($"Bug: BoolUpdateEachCD.cd({cd}) is less than 1"); this.cd = cd; } public BoolUpdateEachCD(long cd) { - if (cd <= 1) Debugger.Output("Bug:BoolUpdateEachCD.cd (" + cd.ToString() + ") is less than 1."); + if (cd <= 1) + TimeBasedLogging.logger.ConsoleLogDebug($"Bug: BoolUpdateEachCD.cd({cd}) is less than 1"); this.cd = cd; } public BoolUpdateEachCD(long cd, long startTime) { - if (cd <= 1) Debugger.Output("Bug:BoolUpdateEachCD.cd (" + cd.ToString() + ") is less than 1."); + if (cd <= 1) + TimeBasedLogging.logger.ConsoleLogDebug($"Bug: BoolUpdateEachCD.cd({cd}) is less than 1"); this.cd = cd; nextUpdateTime = startTime; } @@ -198,7 +224,8 @@ public bool TryUse() } public void SetCD(int cd) { - if (cd <= 1) Debugger.Output("Bug:BoolUpdateEachCD.cd to " + cd.ToString() + "."); + if (cd <= 1) + TimeBasedLogging.logger.ConsoleLogDebug($"Bug: BoolUpdateEachCD.cd to {cd}"); Interlocked.Exchange(ref this.cd, cd); } } @@ -213,17 +240,20 @@ public class LongProgressUpdateEachCD private long nextUpdateTime = 0; public LongProgressUpdateEachCD(int cd) { - if (cd <= 1) Debugger.Output("Bug:LongProgressUpdateEachCD.cd (" + cd.ToString() + ") is less than 1."); + if (cd <= 1) + TimeBasedLogging.logger.ConsoleLogDebug($"Bug: LongProgressUpdateEachCD.cd({cd}) is less than 1"); this.cd = cd; } public LongProgressUpdateEachCD(long cd) { - if (cd <= 1) Debugger.Output("Bug:LongProgressUpdateEachCD.cd (" + cd.ToString() + ") is less than 1."); + if (cd <= 1) + TimeBasedLogging.logger.ConsoleLogDebug($"Bug: LongProgressUpdateEachCD.cd({cd}) is less than 1"); this.cd = cd; } public LongProgressUpdateEachCD(long cd, long startTime) { - if (cd <= 1) Debugger.Output("Bug:LongProgressUpdateEachCD.cd (" + cd.ToString() + ") is less than 1."); + if (cd <= 1) + TimeBasedLogging.logger.ConsoleLogDebug($"Bug: LongProgressUpdateEachCD.cd({cd}) is less than 1"); this.cd = cd; nextUpdateTime = startTime; } @@ -250,7 +280,8 @@ public bool TryUse() } public void SetCD(int cd) { - if (cd <= 1) Debugger.Output("Bug:Set LongProgressUpdateEachCD.cd to " + cd.ToString() + "."); + if (cd <= 1) + TimeBasedLogging.logger.ConsoleLogDebug($"Bug: Set LongProgressUpdateEachCD.cd to {cd}"); Interlocked.Exchange(ref this.cd, cd); } } @@ -267,9 +298,12 @@ public class IntNumUpdateEachCD private readonly object numLock = new(); public IntNumUpdateEachCD(int num, int maxNum, int cd) { - if (num < 0) Debugger.Output("Bug:IntNumUpdateEachCD.num (" + num.ToString() + ") is less than 0."); - if (maxNum < 0) Debugger.Output("Bug:IntNumUpdateEachCD.maxNum (" + maxNum.ToString() + ") is less than 0."); - if (cd <= 0) Debugger.Output("Bug:IntNumUpdateEachCD.cd (" + cd.ToString() + ") is less than 0."); + if (num < 0) + TimeBasedLogging.logger.ConsoleLogDebug($"Bug: IntNumUpdateEachCD.num({num}) is less than 0"); + if (maxNum < 0) + TimeBasedLogging.logger.ConsoleLogDebug($"Bug: IntNumUpdateEachCD.maxNum({maxNum}) is less than 0"); + if (cd <= 0) + TimeBasedLogging.logger.ConsoleLogDebug($"Bug: IntNumUpdateEachCD.cd({cd}) is less than 0"); this.num = num < maxNum ? num : maxNum; this.maxNum = maxNum; CD.Set(cd); @@ -280,8 +314,10 @@ public IntNumUpdateEachCD(int num, int maxNum, int cd) /// public IntNumUpdateEachCD(int maxNum, int cd) { - if (maxNum < 0) Debugger.Output("Bug:IntNumUpdateEachCD.maxNum (" + maxNum.ToString() + ") is less than 0."); - if (cd <= 0) Debugger.Output("Bug:IntNumUpdateEachCD.cd (" + cd.ToString() + ") is less than 0."); + if (maxNum < 0) + TimeBasedLogging.logger.ConsoleLogDebug($"Bug: IntNumUpdateEachCD.maxNum({maxNum}) is less than 0"); + if (cd <= 0) + TimeBasedLogging.logger.ConsoleLogDebug($"Bug: IntNumUpdateEachCD.cd({cd}) is less than 0"); num = this.maxNum = maxNum; CD.Set(cd); } @@ -312,7 +348,8 @@ public int GetNum(long time) /// public int TrySub(int subV) { - if (subV < 0) Debugger.Output("Bug:IntNumUpdateEachCD Try to sub " + subV.ToString() + ", which is less than 0."); + if (subV < 0) + TimeBasedLogging.logger.ConsoleLogDebug($"Bug: IntNumUpdateEachCD Try to sub {subV}, which is less than 0"); long time = Environment.TickCount64; lock (numLock) { @@ -332,7 +369,8 @@ public int TrySub(int subV) /// public void TryAdd(int addV) { - if (addV < 0) Debugger.Output("Bug:IntNumUpdateEachCD Try to add " + addV.ToString() + ", which is less than 0."); + if (addV < 0) + TimeBasedLogging.logger.ConsoleLogDebug($"Bug: IntNumUpdateEachCD Try to add {addV}, which is less than 0"); lock (numLock) { num += Math.Min(addV, maxNum - num); @@ -423,7 +461,8 @@ public void SetPositiveNum(int num) } public void SetCD(int cd) { - if (cd <= 0) Debugger.Output("Bug:Set IntNumUpdateEachCD.cd to " + cd.ToString() + "."); + if (cd <= 0) + TimeBasedLogging.logger.ConsoleLogDebug($"Bug: Set IntNumUpdateEachCD.cd to {cd}"); CD.Set(cd); } } diff --git a/logic/Server/GameServer.cs b/logic/Server/GameServer.cs index 4ee277b8..6be67b90 100755 --- a/logic/Server/GameServer.cs +++ b/logic/Server/GameServer.cs @@ -1,4 +1,5 @@ using GameClass.GameObj; +using GameClass.GameObj.Map; using GameClass.MapGenerator; using Gaming; using Newtonsoft.Json; From f377a8bb4b149a4255d435f3870f7bee011d792f Mon Sep 17 00:00:00 2001 From: 964293341 Date: Thu, 25 Apr 2024 22:29:00 +0800 Subject: [PATCH 06/11] perf(Client): dispose some outdated codes --- installer/Data/ConfigFileData.cs | 32 ++-- installer/Model/Logger.cs | 17 +- logic/Client/Interact/CommandLineProcess.cs | 11 +- logic/Client/Model/Player.cs | 10 +- logic/Client/Old/PlayerStatusBar.xaml.cs | 25 ++- logic/Client/PlaybackClient.cs | 6 +- logic/Client/Util/UtilInfo.cs | 24 ++- logic/Client/View/MainPage.xaml.cs | 8 +- logic/Client/ViewModel/GeneralViewModel.cs | 162 ++++++++++++-------- logic/Client/ViewModel/MapViewModel.cs | 30 ++-- logic/GameClass/GameObj/Map/MapGameTimer.cs | 2 +- logic/Preparation/Interface/ITimer.cs | 2 +- logic/Server/GameServer.cs | 2 +- 13 files changed, 164 insertions(+), 167 deletions(-) diff --git a/installer/Data/ConfigFileData.cs b/installer/Data/ConfigFileData.cs index 1e8ff595..1e28730d 100644 --- a/installer/Data/ConfigFileData.cs +++ b/installer/Data/ConfigFileData.cs @@ -1,15 +1,9 @@ //using installer.ViewModel; -using System; -using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; -using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Runtime.CompilerServices; -using System.Text; using System.Text.Json; using System.Text.Json.Serialization; -using System.Threading.Tasks; namespace installer.Data { @@ -135,13 +129,13 @@ public record ConfigDataFile public string UserName { get; set; } = string.Empty; public string Password { get; set; } = string.Empty; public bool Remembered { get; set; } = false; - public CommandFile Commands { get; set; } = new CommandFile(); - public List Players { get; set; } = new List(); + public CommandFile Commands { get; set; } = new(); + public List Players { get; set; } = []; } public class Command { - public Command(CommandFile? f = null) => file = f ?? new CommandFile(); + public Command(CommandFile? f = null) => file = f ?? new(); public event EventHandler? OnMemoryChanged; public CommandFile file; public bool Enabled @@ -299,7 +293,7 @@ public ConfigData(string? p = null, bool autoSave = true) path = string.IsNullOrEmpty(p) ? Path.Combine(dataDir, "config.json") : p; file = new ConfigDataFile(); com = new Command(file.Commands); - Players = new ObservableCollection(); + Players = []; Players.CollectionChanged += (sender, args) => { if (args.NewItems is not null) @@ -321,14 +315,12 @@ public void ReadFile() { try { - using (FileStream s = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)) - using (StreamReader r = new StreamReader(s)) - { - var f = JsonSerializer.Deserialize(r.ReadToEnd()); - if (f is null) - throw new JsonException(); - else file = f; - } + using FileStream s = new(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); + using StreamReader r = new(s); + var f = JsonSerializer.Deserialize(r.ReadToEnd()); + if (f is null) + throw new JsonException(); + else file = f; } catch (Exception) { @@ -344,8 +336,8 @@ public void SaveFile() { file.Commands = com.file; file.Players = new List(Players); - using FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); - using StreamWriter sw = new StreamWriter(fs); + using FileStream fs = new(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); + using StreamWriter sw = new(fs); fs.SetLength(0); sw.Write(JsonSerializer.Serialize(file)); sw.Flush(); diff --git a/installer/Model/Logger.cs b/installer/Model/Logger.cs index 17d23282..e6d4c083 100644 --- a/installer/Model/Logger.cs +++ b/installer/Model/Logger.cs @@ -1,12 +1,7 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; +using System.Collections.Concurrent; using System.Collections.ObjectModel; using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Linq; using System.Text; -using System.Threading.Tasks; #pragma warning disable CA1416 @@ -52,9 +47,9 @@ public string Color public abstract class Logger : IDisposable { private int jobID = 0; - public List Partner = new List(); + public List Partner = []; public string PartnerInfo = string.Empty; - public Dictionary CountDict = new Dictionary + public Dictionary CountDict = new() { { LogLevel.Trace, 0 }, { LogLevel.Debug, 1 }, { LogLevel.Information, 2 }, { LogLevel.Warning, 3 }, @@ -202,7 +197,7 @@ public class FileLogger : Logger { private DateTime time = DateTime.MinValue; private string path; - private Mutex mutex = new Mutex(); + private readonly Mutex mutex = new(); public string Path { get => path; set @@ -341,8 +336,8 @@ protected override void Log(LogLevel logLevel, string message) } public class ListLogger : Logger { - protected ConcurrentQueue Queue = new ConcurrentQueue(); - public ObservableCollection List = new ObservableCollection(); + protected ConcurrentQueue Queue = new(); + public ObservableCollection List = []; public override DateTime LastRecordTime => DateTime.Now; private Timer timer; private DateTime time; diff --git a/logic/Client/Interact/CommandLineProcess.cs b/logic/Client/Interact/CommandLineProcess.cs index b4151dc9..d7165974 100644 --- a/logic/Client/Interact/CommandLineProcess.cs +++ b/logic/Client/Interact/CommandLineProcess.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Diagnostics; +using System.Diagnostics; namespace Client.Interact { @@ -11,7 +6,7 @@ public static class CommandLineProcess { public static void StartProcess() { - ProcessStartInfo startInfo = new ProcessStartInfo + ProcessStartInfo startInfo = new() { FileName = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe", RedirectStandardInput = true, @@ -19,7 +14,7 @@ public static void StartProcess() UseShellExecute = false }; - Process process = new Process { StartInfo = startInfo }; + Process process = new() { StartInfo = startInfo }; process.Start(); // 写入命令行 diff --git a/logic/Client/Model/Player.cs b/logic/Client/Model/Player.cs index d13ce135..b69ee99b 100644 --- a/logic/Client/Model/Player.cs +++ b/logic/Client/Model/Player.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Collections.ObjectModel; namespace Client.Model { @@ -58,7 +52,7 @@ public ObservableCollection Ships { get { - return ships ?? (ships = new ObservableCollection()); + return ships ??= []; } set { diff --git a/logic/Client/Old/PlayerStatusBar.xaml.cs b/logic/Client/Old/PlayerStatusBar.xaml.cs index 69c03f78..e72e3091 100644 --- a/logic/Client/Old/PlayerStatusBar.xaml.cs +++ b/logic/Client/Old/PlayerStatusBar.xaml.cs @@ -1,4 +1,3 @@ -using System; using Client.Util; using Protobuf; @@ -12,9 +11,9 @@ enum PlayerRole Red, //the down player Blue //the up player }; - PlayerRole myRole; + readonly PlayerRole myRole; private double lengthOfHpSlide = 240; - List shipLabels = new List(); + readonly List shipLabels = []; public PlayerStatusBar(Grid parent, int Row, int Column, int role) { InitializeComponent(); @@ -116,7 +115,7 @@ public void SetShipValue(MessageOfShip ship) { if (ship.TeamId == (long)PlayerTeam.Red && myRole == PlayerRole.Red || ship.TeamId == (long)PlayerTeam.Blue && myRole == PlayerRole.Blue) { - ShipLabel shipLabel = new ShipLabel(); + ShipLabel shipLabel = new(); shipLabel.name.Text = ship.ShipType.ToString() + ship.PlayerId.ToString(); shipLabel.producer.Text = ship.ProducerType.ToString(); shipLabel.armor.Text = ship.ArmorType.ToString(); @@ -140,15 +139,15 @@ public void SlideLengthSet() } public class ShipLabel { - public Label name = new Label() { Text = "name" }; - public Label producer = new Label() { Text = "producer" }; - public Label constructor = new Label() { Text = "constructor" }; - public Label armor = new Label() { Text = "armor" }; - public Label shield = new Label() { Text = "shield" }; - public Label weapon = new Label() { Text = "weapon" }; - public Label status = new Label() { Text = "IDLE" }; + public Label name = new() { Text = "name" }; + public Label producer = new() { Text = "producer" }; + public Label constructor = new() { Text = "constructor" }; + public Label armor = new() { Text = "armor" }; + public Label shield = new() { Text = "shield" }; + public Label weapon = new() { Text = "weapon" }; + public Label status = new() { Text = "IDLE" }; public double lengthOfShipHpSlide = 80; - public BoxView hpSlide = new BoxView() { Color = Colors.Red, WidthRequest = 80, HeightRequest = 3, HorizontalOptions = LayoutOptions.Start, VerticalOptions = LayoutOptions.End }; - public Grid shipStatusGrid = new Grid(); + public BoxView hpSlide = new() { Color = Colors.Red, WidthRequest = 80, HeightRequest = 3, HorizontalOptions = LayoutOptions.Start, VerticalOptions = LayoutOptions.End }; + public Grid shipStatusGrid = new(); }; } \ No newline at end of file diff --git a/logic/Client/PlaybackClient.cs b/logic/Client/PlaybackClient.cs index 2bb70f1a..1bb7a9b4 100644 --- a/logic/Client/PlaybackClient.cs +++ b/logic/Client/PlaybackClient.cs @@ -21,7 +21,7 @@ public class PlaybackClient private readonly double playbackSpeed; private readonly int frameTimeInMilliseconds; public MessageReader? Reader; - private SemaphoreSlim sema; + private readonly SemaphoreSlim sema; public SemaphoreSlim Sema => sema; public PlaybackClient(string fileName, double playbackSpeed = 1.0, int frameTimeInMilliseconds = 50) { @@ -63,8 +63,8 @@ public PlaybackClient(string fileName, double playbackSpeed = 1.0, int frameTime bool endFile = false; bool mapFlag = false; // 是否获取了地图 int[,] map = new int[50, 50]; - long frame = (long)(this.frameTimeInMilliseconds / this.playbackSpeed); - var mapCollecter = new MessageReader(this.fileName); + long frame = (long)(frameTimeInMilliseconds / playbackSpeed); + var mapCollecter = new MessageReader(fileName); while (!mapFlag) { var msg = mapCollecter.ReadOne(); diff --git a/logic/Client/Util/UtilInfo.cs b/logic/Client/Util/UtilInfo.cs index 6adadfe9..d9d65bf2 100644 --- a/logic/Client/Util/UtilInfo.cs +++ b/logic/Client/Util/UtilInfo.cs @@ -1,22 +1,18 @@ using Protobuf; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Client.Util { public static class UtilInfo { - public static Dictionary ShipTypeNameDict = new Dictionary{ + public static readonly Dictionary ShipTypeNameDict = new() + { { ShipType.NullShipType, "Null" }, { ShipType.CivilianShip, "Civilian" }, { ShipType.MilitaryShip, "Military" }, { ShipType.FlagShip, "FlagShip" } }; - public static Dictionary ShipStateNameDict = new Dictionary + public static readonly Dictionary ShipStateNameDict = new() { { ShipState.Idle, "Idle" }, { ShipState.Producing, "Producing" }, @@ -30,7 +26,7 @@ public static class UtilInfo }; - public static Dictionary ShipArmorTypeNameDict = new Dictionary + public static readonly Dictionary ShipArmorTypeNameDict = new() { //{ ArmorType.NullArmorType, "Null" }, //{ ArmorType.Armor1, "Armor1" }, @@ -42,7 +38,7 @@ public static class UtilInfo { ArmorType.Armor3, "🪖🌟" } }; - public static Dictionary ShipShieldTypeNameDict = new Dictionary + public static readonly Dictionary ShipShieldTypeNameDict = new() { { ShieldType.NullShieldType, "Null" }, { ShieldType.Shield1, "🛡️🔸" }, @@ -50,7 +46,7 @@ public static class UtilInfo { ShieldType.Shield3, "🛡️🌟" } }; - public static Dictionary ShipConstructorNameDict = new Dictionary + public static readonly Dictionary ShipConstructorNameDict = new() { { ConstructorType.NullConstructorType, "Null" }, { ConstructorType.Constructor1, "🔨🔸" }, @@ -58,7 +54,7 @@ public static class UtilInfo { ConstructorType.Constructor3, "🔨🌟" } }; - public static Dictionary ShipProducerTypeNameDict = new Dictionary + public static readonly Dictionary ShipProducerTypeNameDict = new() { { ProducerType.NullProducerType, "Null" }, { ProducerType.Producer1, "⛏🔸" }, @@ -66,7 +62,7 @@ public static class UtilInfo { ProducerType.Producer3, "⛏🌟" } }; - public static Dictionary ShipWeaponTypeNameDict = new Dictionary + public static readonly Dictionary ShipWeaponTypeNameDict = new() { { WeaponType.NullWeaponType, "Null" }, { WeaponType.Lasergun, "Lasergun" }, @@ -79,8 +75,8 @@ public static class UtilInfo public static bool isRedPlayerShipsEmpty = true; public static bool isBluePlayerShipsEmpty = false; - public static int unitWidth = 10; - public static int unitHeight = 10; + public const int unitWidth = 10; + public const int unitHeight = 10; } diff --git a/logic/Client/View/MainPage.xaml.cs b/logic/Client/View/MainPage.xaml.cs index 21e5f17a..c91eb265 100644 --- a/logic/Client/View/MainPage.xaml.cs +++ b/logic/Client/View/MainPage.xaml.cs @@ -25,7 +25,7 @@ public partial class MainPage : ContentPage { private bool UIinitiated = false; - GeneralViewModel viewModel; + readonly GeneralViewModel viewModel; public MainPage() { viewModel = new GeneralViewModel(); @@ -113,9 +113,9 @@ public MainPage() //InitiateObjects(); UIinitiated = true; } - private Label[,] mapPatches_ = new Label[50, 50]; - private List shipCirc = new List(); - private List bulletCirc = new List(); + private readonly Label[,] mapPatches_ = new Label[50, 50]; + private readonly List shipCirc = []; + private readonly List bulletCirc = []; private readonly IDispatcherTimer timer; private long counter; public float unitWidth = 10; diff --git a/logic/Client/ViewModel/GeneralViewModel.cs b/logic/Client/ViewModel/GeneralViewModel.cs index 88a1ae49..b9cf1b1c 100644 --- a/logic/Client/ViewModel/GeneralViewModel.cs +++ b/logic/Client/ViewModel/GeneralViewModel.cs @@ -57,7 +57,7 @@ public List Links { get { - return links ?? (links = new List()); + return links ??= []; } set { @@ -67,9 +67,9 @@ public List Links } private long playerID; - private string ip; - private string port; - private int shipTypeID; + private readonly string ip; + private readonly string port; + private readonly int shipTypeID; private long teamID; ShipType shipType; AvailableService.AvailableServiceClient? client; @@ -92,12 +92,12 @@ public void ConnectToServer(string[] comInfo) throw new Exception("Error Registration Information!"); } - string connect = new string(comInfo[0]); + string connect = new(comInfo[0]); connect += ':'; connect += comInfo[1]; - Channel channel = new Channel(connect, ChannelCredentials.Insecure); + Channel channel = new(connect, ChannelCredentials.Insecure); client = new AvailableService.AvailableServiceClient(channel); - PlayerMsg playerMsg = new PlayerMsg(); + PlayerMsg playerMsg = new(); playerID = Convert.ToInt64(comInfo[2]); playerMsg.PlayerId = playerID; if (!isSpectatorMode) @@ -508,7 +508,7 @@ private void Refresh(object sender, EventArgs e) // if (data.TeamId == (long)PlayerTeam.Red) if (data.TeamId == 0) { - Ship ship = new Ship + Ship ship = new() { HP = data.Hp, Type = data.ShipType, @@ -533,7 +533,7 @@ private void Refresh(object sender, EventArgs e) // else if (data.TeamId == (long)PlayerTeam.Blue) else if (data.TeamId == 1) { - Ship ship = new Ship + Ship ship = new() { HP = data.Hp, Type = data.ShipType, @@ -741,10 +741,12 @@ public GeneralViewModel() myLogger.LogInfo("Client is null or is SpectatorMode or isPlaybackMode"); return; } - MoveMsg movemsg = new MoveMsg(); - movemsg.PlayerId = playerID; - movemsg.TeamId = teamID; - movemsg.Angle = double.Pi; + MoveMsg movemsg = new() + { + PlayerId = playerID, + TeamId = teamID, + Angle = double.Pi + }; lastMoveAngle = movemsg.Angle; movemsg.TimeInMilliseconds = 50; client.Move(movemsg); @@ -769,10 +771,12 @@ Show the error message myLogger.LogInfo("Client is null or is SpectatorMode or isPlaybackMode"); return; } - MoveMsg movemsg = new MoveMsg(); - movemsg.PlayerId = playerID; - movemsg.TeamId = teamID; - movemsg.Angle = double.NegativeZero; + MoveMsg movemsg = new() + { + PlayerId = playerID, + TeamId = teamID, + Angle = double.NegativeZero + }; lastMoveAngle = movemsg.Angle; movemsg.TimeInMilliseconds = moveTime; client.Move(movemsg); @@ -785,10 +789,12 @@ Show the error message myLogger.LogInfo("Client is null or is SpectatorMode or isPlaybackMode"); return; } - MoveMsg movemsg = new MoveMsg(); - movemsg.PlayerId = playerID; - movemsg.TeamId = teamID; - movemsg.Angle = double.Pi * 3 / 2; + MoveMsg movemsg = new() + { + PlayerId = playerID, + TeamId = teamID, + Angle = double.Pi * 3 / 2 + }; lastMoveAngle = movemsg.Angle; movemsg.TimeInMilliseconds = moveTime; client.Move(movemsg); @@ -801,10 +807,12 @@ Show the error message myLogger.LogInfo("Client is null or is SpectatorMode or isPlaybackMode"); return; } - MoveMsg movemsg = new MoveMsg(); - movemsg.PlayerId = playerID; - movemsg.TeamId = teamID; - movemsg.Angle = double.Pi / 2; + MoveMsg movemsg = new() + { + PlayerId = playerID, + TeamId = teamID, + Angle = double.Pi / 2 + }; lastMoveAngle = movemsg.Angle; movemsg.TimeInMilliseconds = moveTime; client.Move(movemsg); @@ -817,10 +825,12 @@ Show the error message myLogger.LogInfo("Client is null or is SpectatorMode or isPlaybackMode"); return; } - MoveMsg movemsg = new MoveMsg(); - movemsg.PlayerId = playerID; - movemsg.TeamId = teamID; - movemsg.Angle = double.Pi * 5 / 4; + MoveMsg movemsg = new() + { + PlayerId = playerID, + TeamId = teamID, + Angle = double.Pi * 5 / 4 + }; lastMoveAngle = movemsg.Angle; movemsg.TimeInMilliseconds = moveTime; client.Move(movemsg); @@ -833,10 +843,12 @@ Show the error message myLogger.LogInfo("Client is null or is SpectatorMode or isPlaybackMode"); return; } - MoveMsg movemsg = new MoveMsg(); - movemsg.PlayerId = playerID; - movemsg.TeamId = teamID; - movemsg.Angle = double.Pi * 3 / 4; + MoveMsg movemsg = new() + { + PlayerId = playerID, + TeamId = teamID, + Angle = double.Pi * 3 / 4 + }; lastMoveAngle = movemsg.Angle; movemsg.TimeInMilliseconds = moveTime; client.Move(movemsg); @@ -849,10 +861,12 @@ Show the error message myLogger.LogInfo("Client is null or is SpectatorMode or isPlaybackMode"); return; } - MoveMsg movemsg = new MoveMsg(); - movemsg.PlayerId = playerID; - movemsg.TeamId = teamID; - movemsg.Angle = double.Pi * 7 / 4; + MoveMsg movemsg = new() + { + PlayerId = playerID, + TeamId = teamID, + Angle = double.Pi * 7 / 4 + }; lastMoveAngle = movemsg.Angle; movemsg.TimeInMilliseconds = moveTime; client.Move(movemsg); @@ -865,10 +879,12 @@ Show the error message myLogger.LogInfo("Client is null or is SpectatorMode or isPlaybackMode"); return; } - MoveMsg movemsg = new MoveMsg(); - movemsg.PlayerId = playerID; - movemsg.TeamId = teamID; - movemsg.Angle = double.Pi / 4; + MoveMsg movemsg = new() + { + PlayerId = playerID, + TeamId = teamID, + Angle = double.Pi / 4 + }; lastMoveAngle = movemsg.Angle; movemsg.TimeInMilliseconds = moveTime; client.Move(movemsg); @@ -881,10 +897,12 @@ Show the error message myLogger.LogInfo("Client is null or is SpectatorMode or isPlaybackMode"); return; } - AttackMsg attackMsg = new AttackMsg(); - attackMsg.PlayerId = playerID; - attackMsg.TeamId = teamID; - attackMsg.Angle = lastMoveAngle; + AttackMsg attackMsg = new() + { + PlayerId = playerID, + TeamId = teamID, + Angle = lastMoveAngle + }; client.Attack(attackMsg); }); @@ -895,9 +913,11 @@ Show the error message myLogger.LogInfo("Client is null or is SpectatorMode or isPlaybackMode"); return; } - RecoverMsg recoverMsg = new RecoverMsg(); - recoverMsg.PlayerId = playerID; - recoverMsg.TeamId = teamID; + RecoverMsg recoverMsg = new() + { + PlayerId = playerID, + TeamId = teamID + }; client.Recover(recoverMsg); }); @@ -908,9 +928,11 @@ Show the error message myLogger.LogInfo("Client is null or is SpectatorMode or isPlaybackMode"); return; } - IDMsg iDMsg = new IDMsg(); - iDMsg.PlayerId = playerID; - iDMsg.TeamId = teamID; + IDMsg iDMsg = new() + { + PlayerId = playerID, + TeamId = teamID + }; client.Produce(iDMsg); }); @@ -921,10 +943,12 @@ Show the error message myLogger.LogInfo("Client is null or is SpectatorMode or isPlaybackMode"); return; } - ConstructMsg constructMsg = new ConstructMsg(); - constructMsg.PlayerId = playerID; - constructMsg.TeamId = teamID; - constructMsg.ConstructionType = ConstructionType.Factory; + ConstructMsg constructMsg = new() + { + PlayerId = playerID, + TeamId = teamID, + ConstructionType = ConstructionType.Factory + }; client.Construct(constructMsg); }); @@ -953,7 +977,7 @@ Show the error message } } - shipCircList = new ObservableCollection(); + shipCircList = []; for (int i = 0; i < numOfShips; i++) { shipCircList.Add(new DrawCircLabel @@ -965,7 +989,7 @@ Show the error message }); } - bulletCircList = new ObservableCollection(); + bulletCircList = []; for (int i = 0; i < numOfBullets; i++) { bulletCircList.Add(new DrawCircLabel @@ -987,17 +1011,19 @@ Show the error message { try { - string[] comInfo = new string[5]; - comInfo[0] = ip; - comInfo[1] = port; - comInfo[2] = Convert.ToString(playerID); - comInfo[3] = Convert.ToString(teamID); - comInfo[4] = Convert.ToString(shipTypeID); - myLogger.LogInfo(String.Format("cominfo[{0}]", comInfo[0])); - myLogger.LogInfo(String.Format("cominfo[{0}]", comInfo[1])); - myLogger.LogInfo(String.Format("cominfo[{0}]", comInfo[2])); - myLogger.LogInfo(String.Format("cominfo[{0}]", comInfo[3])); - myLogger.LogInfo(String.Format("cominfo[{0}]", comInfo[4])); + string[] comInfo = + [ + ip, + port, + Convert.ToString(playerID), + Convert.ToString(teamID), + Convert.ToString(shipTypeID), + ]; + myLogger.LogInfo(string.Format("cominfo[{0}]", comInfo[0])); + myLogger.LogInfo(string.Format("cominfo[{0}]", comInfo[1])); + myLogger.LogInfo(string.Format("cominfo[{0}]", comInfo[2])); + myLogger.LogInfo(string.Format("cominfo[{0}]", comInfo[3])); + myLogger.LogInfo(string.Format("cominfo[{0}]", comInfo[4])); ConnectToServer(comInfo); OnReceive(); } diff --git a/logic/Client/ViewModel/MapViewModel.cs b/logic/Client/ViewModel/MapViewModel.cs index e1735cce..605bd23a 100644 --- a/logic/Client/ViewModel/MapViewModel.cs +++ b/logic/Client/ViewModel/MapViewModel.cs @@ -23,17 +23,17 @@ public partial class GeneralViewModel : BindableObject /* initiate the Lists of Objects and CountList */ private void InitiateObjects() { - listOfAll = new List(); - listOfShip = new List(); ; - listOfBullet = new List(); - listOfBombedBullet = new List(); - listOfFactory = new List(); - listOfCommunity = new List(); - listOfFort = new List(); - listOfResource = new List(); - listOfHome = new List(); - listOfWormhole = new List(); - countMap = new Dictionary(); + listOfAll = []; + listOfShip = []; ; + listOfBullet = []; + listOfBombedBullet = []; + listOfFactory = []; + listOfCommunity = []; + listOfFort = []; + listOfResource = []; + listOfHome = []; + listOfWormhole = []; + countMap = []; } private (int x, int y)[] resourcePositionIndex; private (int x, int y)[] FactoryPositionIndex; @@ -203,7 +203,7 @@ private void GetMap(MessageOfMap obj) // } //} - private Dictionary PatchColorDict = new Dictionary + private readonly Dictionary PatchColorDict = new() { {MapPatchType.RedHome, Color.FromRgb(237, 49, 47)}, {MapPatchType.BlueHome, Colors.Blue}, @@ -703,7 +703,7 @@ public ObservableCollection MapPatchesList { get { - return mapPatchesList ??= new ObservableCollection(); + return mapPatchesList ??= []; } set { @@ -717,7 +717,7 @@ public ObservableCollection ShipCircList { get { - return shipCircList ??= new ObservableCollection(); + return shipCircList ??= []; } set { @@ -731,7 +731,7 @@ public ObservableCollection BulletCircList { get { - return bulletCircList ??= new ObservableCollection(); + return bulletCircList ??= []; } set { diff --git a/logic/GameClass/GameObj/Map/MapGameTimer.cs b/logic/GameClass/GameObj/Map/MapGameTimer.cs index 126e6914..ab14fcbf 100755 --- a/logic/GameClass/GameObj/Map/MapGameTimer.cs +++ b/logic/GameClass/GameObj/Map/MapGameTimer.cs @@ -14,7 +14,7 @@ public partial class Map public class GameTimer : ITimer { private long startTime; - public int nowTime() => (int)(Environment.TickCount64 - startTime); + public int NowTime() => (int)(Environment.TickCount64 - startTime); private readonly AtomicBool isGaming = new(false); public AtomicBool IsGaming => isGaming; diff --git a/logic/Preparation/Interface/ITimer.cs b/logic/Preparation/Interface/ITimer.cs index a9e54dfd..5f4d725d 100755 --- a/logic/Preparation/Interface/ITimer.cs +++ b/logic/Preparation/Interface/ITimer.cs @@ -5,7 +5,7 @@ namespace Preparation.Interface public interface ITimer { AtomicBool IsGaming { get; } - public int nowTime(); + public int NowTime(); public bool StartGame(int timeInMilliseconds); } } diff --git a/logic/Server/GameServer.cs b/logic/Server/GameServer.cs index 6be67b90..3395f2d6 100755 --- a/logic/Server/GameServer.cs +++ b/logic/Server/GameServer.cs @@ -156,7 +156,7 @@ public void ReportGame(GameState gameState, bool requiredGaming = true) currentNews.Clear(); } currentGameInfo.GameState = gameState; - currentGameInfo.AllMessage = GetMessageOfAll(game.GameMap.Timer.nowTime()); + currentGameInfo.AllMessage = GetMessageOfAll(game.GameMap.Timer.NowTime()); mwr?.WriteOne(currentGameInfo); break; default: From 0c6a1418884f3ea58eb3998f6edfeabbeeb08b11 Mon Sep 17 00:00:00 2001 From: 964293341 Date: Fri, 26 Apr 2024 16:13:54 +0800 Subject: [PATCH 07/11] feat(Server): :sparkles: use Logger in Server --- logic/Preparation/Utility/Logger.cs | 82 ++++++--- logic/Server/GameServer.cs | 11 +- logic/Server/HttpSender.cs | 8 +- logic/Server/PlaybackServer.cs | 63 ++++--- logic/Server/Program.cs | 41 +++-- logic/Server/RpcServices.cs | 249 +++++++++++----------------- 6 files changed, 224 insertions(+), 230 deletions(-) diff --git a/logic/Preparation/Utility/Logger.cs b/logic/Preparation/Utility/Logger.cs index 45fd36a5..460011ca 100755 --- a/logic/Preparation/Utility/Logger.cs +++ b/logic/Preparation/Utility/Logger.cs @@ -26,32 +26,37 @@ await Task.Run(() => private LogQueue() { + void WriteInFile() + { + lock (queueLock) + { + while (logInfoQueue.Count != 0) + { + var info = logInfoQueue.Dequeue(); + File.AppendAllText(LoggingData.ServerLogPath, info + Environment.NewLine); + logNum++; + if (logNum >= LoggingData.MaxLogNum) + { + File.Copy(LoggingData.ServerLogPath, + $"{LoggingData.ServerLogPath}-copy{logCopyNum}.txt"); + logCopyNum++; + File.Delete(LoggingData.ServerLogPath); + logNum = 0; + } + } + } + } new Thread(() => { new FrameRateTaskExecutor( loopCondition: () => Global != null, - loopToDo: () => + loopToDo: WriteInFile, + timeInterval: 100, + finallyReturn: () => { - lock (queueLock) - { - while (logInfoQueue.Count != 0) - { - var info = logInfoQueue.Dequeue(); - File.AppendAllText(LoggingData.ServerLogPath, info + Environment.NewLine); - logNum++; - if (logNum >= LoggingData.MaxLogNum) - { - File.Copy(LoggingData.ServerLogPath, - $"{LoggingData.ServerLogPath}-copy{logCopyNum}.txt"); - logCopyNum++; - File.Delete(LoggingData.ServerLogPath); - logNum = 0; - } - } - } - }, - timeInterval: 200, - finallyReturn: () => 0 + WriteInFile(); + return 0; + } ).Start(); }) { IsBackground = true }.Start(); @@ -61,23 +66,48 @@ private LogQueue() public class Logger(string module) { public readonly string Module = module; + public bool Enable { get; set; } = true; + public bool Background { get; set; } = false; public void ConsoleLog(string msg, bool Duplicate = true) { var info = $"[{Module}]{msg}"; - Console.WriteLine(info); - if (Duplicate) - _ = LogQueue.Global.Commit(info); + if (Enable) + { + if (!Background) + Console.WriteLine(info); + if (Duplicate) + _ = LogQueue.Global.Commit(info); + } } public void ConsoleLogDebug(string msg, bool Duplicate = true) { #if DEBUG var info = $"[{Module}]{msg}"; - Console.WriteLine(info); + if (Enable) + { + if (!Background) + Console.WriteLine(info); + if (Duplicate) + _ = LogQueue.Global.Commit(info); + } +#endif + } + public static void RawConsoleLog(string msg, bool Duplicate = true) + { + Console.WriteLine(msg); + if (Duplicate) + _ = LogQueue.Global.Commit(msg); + } + public static void RawConsoleLogDebug(string msg, bool Duplicate = true) + { +#if DEBUG + Console.WriteLine(msg); if (Duplicate) - _ = LogQueue.Global.Commit(info); + _ = LogQueue.Global.Commit(msg); #endif } + public static string TypeName(object obj) => obj.GetType().Name; public static string TypeName(Type tp) diff --git a/logic/Server/GameServer.cs b/logic/Server/GameServer.cs index 3395f2d6..9a53e3ac 100755 --- a/logic/Server/GameServer.cs +++ b/logic/Server/GameServer.cs @@ -5,12 +5,17 @@ using Newtonsoft.Json; using Playback; using Preparation.Utility; +using Preparation.Utility.Logging; using Protobuf; using System.Collections.Concurrent; using Timothy.FrameRateTask; namespace Server { + public static class GameServerLogging + { + public static readonly Logger logger = new("GameServer"); + } partial class GameServer : ServerBase { private readonly ConcurrentDictionary semaDict0 = new(); //for spectator and team0 player @@ -44,7 +49,7 @@ public void StartGame() if (id == GameObj.invalidID) return;//如果有未初始化的玩家,不开始游戏 } } - Console.WriteLine("Game starts!"); + GameServerLogging.logger.ConsoleLog("Game starts!"); CreateStartFile(); game.StartGame((int)options.GameTimeInSecond * 1000); Thread.Sleep(1); @@ -80,7 +85,7 @@ public void CreateStartFile() if (options.StartLockFile != DefaultArgumentOptions.FileName) { using var _ = File.Create(options.StartLockFile); - Console.WriteLine("Successfully Created StartLockFile!"); + GameServerLogging.logger.ConsoleLog("Successfully Created StartLockFile!"); } } @@ -350,7 +355,7 @@ public GameServer(ArgumentOptions options) } catch { - Console.WriteLine($"Error: Cannot create the playback file: {options.FileName}!"); + GameServerLogging.logger.ConsoleLog($"Error: Cannot create the playback file: {options.FileName}!"); } } diff --git a/logic/Server/HttpSender.cs b/logic/Server/HttpSender.cs index 41a99aa7..a745e197 100755 --- a/logic/Server/HttpSender.cs +++ b/logic/Server/HttpSender.cs @@ -26,13 +26,13 @@ public async Task SendHttpRequest(int[] scores, int mode) }, mode })); - Console.WriteLine("Send to web successfully!"); - Console.WriteLine($"Web response: {await response.Content.ReadAsStringAsync()}"); + GameServerLogging.logger.ConsoleLog("Send to web successfully!"); + GameServerLogging.logger.ConsoleLog($"Web response: {await response.Content.ReadAsStringAsync()}"); } catch (Exception e) { - Console.WriteLine("Fail to send msg to web!"); - Console.WriteLine(e); + GameServerLogging.logger.ConsoleLog("Fail to send msg to web!"); + GameServerLogging.logger.ConsoleLog(e.ToString()); } } } diff --git a/logic/Server/PlaybackServer.cs b/logic/Server/PlaybackServer.cs index 85766ab3..45a43090 100755 --- a/logic/Server/PlaybackServer.cs +++ b/logic/Server/PlaybackServer.cs @@ -1,11 +1,16 @@ using Grpc.Core; using Playback; +using Preparation.Utility.Logging; using Protobuf; using System.Collections.Concurrent; using Timothy.FrameRateTask; namespace Server { + public static class PlaybackServerLogging + { + public static readonly Logger logger = new("PlaybackServer"); + } class PlaybackServer(ArgumentOptions options) : ServerBase { protected readonly ArgumentOptions options = options; @@ -50,7 +55,7 @@ public override async Task AddPlayer(PlayerMsg request, IServerStreamWriter responseStream, ServerCallContext context) { - Console.WriteLine($"AddPlayer: {request.PlayerId}"); + PlaybackServerLogging.logger.ConsoleLog($"AddPlayer: {request.PlayerId}"); if (request.PlayerId >= spectatorMinPlayerID && options.NotAllowSpectator == false) { // 观战模式 @@ -58,12 +63,12 @@ public override async Task AddPlayer(PlayerMsg request, { if (semaDict.TryAdd(request.PlayerId, (new SemaphoreSlim(0, 1), new SemaphoreSlim(0, 1)))) { - Console.WriteLine("A new spectator comes to watch this game."); + PlaybackServerLogging.logger.ConsoleLog("A new spectator comes to watch this game"); IsSpectatorJoin = true; } else { - Console.WriteLine($"Duplicated Spectator ID {request.PlayerId}"); + PlaybackServerLogging.logger.ConsoleLog($"Duplicated Spectator ID {request.PlayerId}"); return; } } @@ -75,7 +80,7 @@ public override async Task AddPlayer(PlayerMsg request, if (currentGameInfo != null) { await responseStream.WriteAsync(currentGameInfo); - Console.WriteLine("Send!"); + PlaybackServerLogging.logger.ConsoleLog("Send!", false); } } catch (InvalidOperationException) @@ -88,13 +93,13 @@ public override async Task AddPlayer(PlayerMsg request, semas.Item2.Release(); } catch { } - Console.WriteLine($"The spectator {request.PlayerId} exited"); + PlaybackServerLogging.logger.ConsoleLog($"The spectator {request.PlayerId} exited"); return; } } - catch (Exception) + catch (Exception e) { - // Console.WriteLine(ex); + PlaybackServerLogging.logger.ConsoleLog(e.ToString()); } finally { @@ -142,7 +147,7 @@ public override void WaitForEnd() { using (MessageReader mr = new(options.FileName)) { - Console.WriteLine("Parsing playback file..."); + PlaybackServerLogging.logger.ConsoleLog("Parsing playback file..."); teamScore = new long[mr.teamCount]; finalScore = new int[mr.teamCount]; int infoNo = 0; @@ -159,7 +164,8 @@ public override void WaitForEnd() msg = mr.ReadOne(); if (msg == null) { - Console.WriteLine("The game doesn't come to an end because of timing up!"); + PlaybackServerLogging.logger.ConsoleLog( + "The game doesn't come to an end because of timing up!"); IsGaming = false; goto endParse; } @@ -169,7 +175,8 @@ public override void WaitForEnd() var curTop = Console.CursorTop; var curLeft = Console.CursorLeft; Console.SetCursorPosition(initialLeft, initialTop); - Console.WriteLine($"Parsing messages... Current message number: {infoNo}"); + PlaybackServerLogging.logger.ConsoleLog( + $"Parsing messages... Current message number: {infoNo}"); Console.SetCursorPosition(curLeft, curTop); } @@ -184,21 +191,19 @@ public override void WaitForEnd() if (msg == null) { - Console.WriteLine("No game information in this file!"); + PlaybackServerLogging.logger.ConsoleLog("No game information in this file!"); goto endParse; } if (msg.GameState == GameState.GameEnd) { - Console.WriteLine("Game over normally!"); + PlaybackServerLogging.logger.ConsoleLog("Game over normally!"); finalScore[0] = msg.AllMessage.RedTeamScore; finalScore[1] = msg.AllMessage.BlueTeamScore; goto endParse; } } - endParse: - - Console.WriteLine($"Successfully parsed {infoNo} informations!"); + PlaybackServerLogging.logger.ConsoleLog($"Successfully parsed {infoNo} informations!"); } } else @@ -226,7 +231,8 @@ public override void WaitForEnd() msg = mr.ReadOne(); if (msg == null) { - Console.WriteLine("The game doesn't come to an end because of timing up!"); + PlaybackServerLogging.logger.ConsoleLog( + "The game doesn't come to an end because of timing up!"); IsGaming = false; ReportGame(msg); return false; @@ -237,7 +243,8 @@ public override void WaitForEnd() var curTop = Console.CursorTop; var curLeft = Console.CursorLeft; Console.SetCursorPosition(msgCurLeft, msgCurTop); - Console.WriteLine($"Sending messages... Current message number: {infoNo}."); + PlaybackServerLogging.logger.ConsoleLog( + $"Sending messages... Current message number: {infoNo}"); Console.SetCursorPosition(curLeft, curTop); } if (msg != null) @@ -253,14 +260,14 @@ public override void WaitForEnd() ++infoNo; if (msg == null) { - Console.WriteLine("No game information in this file!"); + PlaybackServerLogging.logger.ConsoleLog("No game information in this file!"); IsGaming = false; ReportGame(msg); return false; } if (msg.GameState == GameState.GameEnd) { - Console.WriteLine("Game over normally!"); + PlaybackServerLogging.logger.ConsoleLog("Game over normally!"); IsGaming = false; finalScore[0] = msg.AllMessage.BlueTeamScore; finalScore[1] = msg.AllMessage.RedTeamScore; @@ -273,9 +280,13 @@ public override void WaitForEnd() finallyReturn: () => 0 ) { AllowTimeExceed = true, MaxTolerantTimeExceedCount = 5 }; - - Console.WriteLine("The server is well prepared! Please MAKE SURE that you have opened all the clients to watch the game!"); - Console.WriteLine("If ALL clients have opened, press any key to start."); + PlaybackServerLogging.logger.ConsoleLog("The server is well prepared!"); + PlaybackServerLogging.logger.ConsoleLog( + "Please MAKE SURE that you have opened all the clients to watch the game!", + false); + PlaybackServerLogging.logger.ConsoleLog( + "If ALL clients have opened, press any key to start", + false); Console.ReadKey(); new Thread @@ -288,7 +299,8 @@ public override void WaitForEnd() { rateCurTop = Console.CursorTop; rateCurLeft = Console.CursorLeft; - Console.WriteLine($"Send message to clients frame rate: {frt.FrameRate}"); + PlaybackServerLogging.logger.ConsoleLog( + $"Send message to clients frame rate: {frt.FrameRate}"); } while (!frt.Finished) { @@ -297,7 +309,8 @@ public override void WaitForEnd() var curTop = Console.CursorTop; var curLeft = Console.CursorLeft; Console.SetCursorPosition(rateCurLeft, rateCurTop); - Console.WriteLine($"Send message to clients frame rate: {frt.FrameRate}"); + PlaybackServerLogging.logger.ConsoleLog( + $"Send message to clients frame rate: {frt.FrameRate}"); Console.SetCursorPosition(curLeft, curTop); } Thread.Sleep(1000); @@ -310,7 +323,7 @@ public override void WaitForEnd() { msgCurLeft = Console.CursorLeft; msgCurTop = Console.CursorTop; - Console.WriteLine("Sending messages..."); + PlaybackServerLogging.logger.ConsoleLog("Sending messages...", false); } frt.Start(); } diff --git a/logic/Server/Program.cs b/logic/Server/Program.cs index ad4cf179..d144e4a1 100755 --- a/logic/Server/Program.cs +++ b/logic/Server/Program.cs @@ -1,5 +1,6 @@ using CommandLine; using Grpc.Core; +using Preparation.Utility.Logging; using Protobuf; namespace Server @@ -24,37 +25,34 @@ _________ __ __ __ \/ \/ \/ \/ """; - static ServerBase CreateServer(ArgumentOptions options) - { - return options.Playback ? new PlaybackServer(options) : new GameServer(options); - //return new PlaybackServer(options); - } + static (ServerBase, Logger) CreateServer(ArgumentOptions options) + => options.Playback ? (new PlaybackServer(options), PlaybackServerLogging.logger) + : (new GameServer(options), GameServerLogging.logger); static int Main(string[] args) { + string args_str = ""; foreach (var arg in args) - { - Console.Write($"{arg} "); - } - Console.WriteLine(); + args_str += arg + " "; + Logger.RawConsoleLog(args_str); ArgumentOptions? options = null; _ = Parser.Default.ParseArguments(args).WithParsed(o => { options = o; }); if (options == null) { - Console.WriteLine("Argument parsing failed!"); + Logger.RawConsoleLog("Argument parsing failed!"); return 1; } if (options.StartLockFile == "114514") { - Console.WriteLine(welcome); + Logger.RawConsoleLog(welcome, false); } - Console.WriteLine($"Server begins to run: {options.ServerPort}"); + Logger.RawConsoleLog($"Server begins to run: {options.ServerPort}"); try { - var server = CreateServer(options); + var (server, logger) = CreateServer(options); Grpc.Core.Server rpcServer = new([new ChannelOption(ChannelOptions.SoReuseport, 0)]) { Services = { AvailableService.BindService(server) }, @@ -62,21 +60,22 @@ static int Main(string[] args) }; rpcServer.Start(); - Console.WriteLine("Server begins to listen!"); + logger.ConsoleLog("Server begins to listen!"); server.WaitForEnd(); - Console.WriteLine("Server end!"); + logger.ConsoleLog("Server end!"); rpcServer.ShutdownAsync().Wait(); Thread.Sleep(50); - Console.WriteLine(""); - Console.WriteLine("=================== Final Score ===================="); - Console.WriteLine($"Team0: {server.GetScore()[0]}"); //红队 - Console.WriteLine($"Team1: {server.GetScore()[1]}"); //蓝队 + Logger.RawConsoleLog("", false); + logger.ConsoleLog("=================== Final Score ====================", false); + logger.ConsoleLog($"Team0: {server.GetScore()[0]}"); //红队 + logger.ConsoleLog($"Team1: {server.GetScore()[1]}"); //蓝队 } catch (Exception ex) { - Console.WriteLine(ex.ToString()); - Console.WriteLine(ex.StackTrace); + Logger.RawConsoleLog(ex.ToString()); + if (ex.StackTrace is not null) + Logger.RawConsoleLog(ex.StackTrace); } return 0; } diff --git a/logic/Server/RpcServices.cs b/logic/Server/RpcServices.cs index 5a5bbe6e..0a3080db 100755 --- a/logic/Server/RpcServices.cs +++ b/logic/Server/RpcServices.cs @@ -27,23 +27,20 @@ protected bool IsSpectatorJoin } public override Task TryConnection(IDMsg request, ServerCallContext context) { -#if DEBUG - Console.WriteLine($"TRY TryConnection: Player {request.PlayerId} from Team {request.TeamId}"); -#endif + GameServerLogging.logger.ConsoleLogDebug( + $"TRY TryConnection: Player {request.PlayerId} from Team {request.TeamId}"); var onConnection = new BoolRes(); lock (gameLock) { if (0 <= request.PlayerId && request.PlayerId < playerNum) { onConnection.ActSuccess = true; - Console.WriteLine(onConnection.ActSuccess); + GameServerLogging.logger.ConsoleLog($"TryConnection: {onConnection.ActSuccess}"); return Task.FromResult(onConnection); } } onConnection.ActSuccess = false; -#if DEBUG - Console.WriteLine("END TryConnection"); -#endif + GameServerLogging.logger.ConsoleLogDebug("END TryConnection"); return Task.FromResult(onConnection); } @@ -53,24 +50,22 @@ public override Task TryConnection(IDMsg request, ServerCallContext con public override async Task AddPlayer(PlayerMsg request, IServerStreamWriter responseStream, ServerCallContext context) { #if !DEBUG - Console.WriteLine($"AddPlayer: Player {request.PlayerId} from Team {request.TeamId}"); + GameServerLogging.logger.ConsoleLog($"AddPlayer: Player {request.PlayerId} from Team {request.TeamId}"); #endif if (request.PlayerId >= spectatorMinPlayerID && options.NotAllowSpectator == false) { -#if DEBUG - Console.WriteLine($"TRY Add Spectator: Player {request.PlayerId}"); -#endif + GameServerLogging.logger.ConsoleLogDebug($"TRY Add Spectator: Player {request.PlayerId}"); // 观战模式 lock (spectatorJoinLock) // 具体原因见另一个上锁的地方 { if (semaDict0.TryAdd(request.PlayerId, (new SemaphoreSlim(0, 1), new SemaphoreSlim(0, 1)))) { - Console.WriteLine("A new spectator comes to watch this game."); + GameServerLogging.logger.ConsoleLog("A new spectator comes to watch this game"); IsSpectatorJoin = true; } else { - Console.WriteLine($"Duplicated Spectator ID {request.PlayerId}"); + GameServerLogging.logger.ConsoleLog($"Duplicated Spectator ID {request.PlayerId}"); return; } } @@ -82,7 +77,7 @@ public override async Task AddPlayer(PlayerMsg request, IServerStreamWriter 0 && (ship == null || ship.IsRemoved == true)) { - // Console.WriteLine($"Cannot find ship {request.PlayerId} from Team {request.TeamId}!"); + // GameServerLogging.logger.ConsoleLog($"Cannot find ship {request.PlayerId} from Team {request.TeamId}!"); } else { @@ -208,14 +194,15 @@ public override async Task AddPlayer(PlayerMsg request, IServerStreamWriter GetMap(NullRequest request, ServerCallContext context) { -#if DEBUG - Console.WriteLine($"GetMap: IP {context.Peer}"); -#endif + GameServerLogging.logger.ConsoleLogDebug($"GetMap: IP {context.Peer}"); return Task.FromResult(MapMsg()); } @@ -240,9 +225,7 @@ public override Task GetMap(NullRequest request, ServerCallContext /*public override Task Activate(ActivateMsg request, ServerCallContext context) { -#if DEBUG - Console.WriteLine($"TRY Activate: Player {request.PlayerId} from Team {request.TeamId}"); -#endif + GameServerLogging.logger.ConsoleLogDebug($"TRY Activate: Player {request.PlayerId} from Team {request.TeamId}"); BoolRes boolRes = new(); if (request.PlayerId >= spectatorMinPlayerID) { @@ -252,17 +235,15 @@ public override Task GetMap(NullRequest request, ServerCallContext // var gameID = communicationToGameID[request.TeamId][request.PlayerId]; boolRes.ActSuccess = game.ActivateShip(request.TeamId, Transformation.ShipTypeFromProto(request.ShipType)); if (!game.GameMap.Timer.IsGaming) boolRes.ActSuccess = false; -#if DEBUG - Console.WriteLine($"END Activate: {boolRes.ActSuccess}"); -#endif + GameServerLogging.logger.ConsoleLogDebug($"END Activate: {boolRes.ActSuccess}"); return Task.FromResult(boolRes); }*/ public override Task Move(MoveMsg request, ServerCallContext context) { -#if DEBUG - Console.WriteLine($"TRY Move: Player {request.PlayerId} from Team {request.TeamId}, TimeInMilliseconds: {request.TimeInMilliseconds}"); -#endif + GameServerLogging.logger.ConsoleLogDebug( + $"TRY Move: Player {request.PlayerId} from Team {request.TeamId}, " + + $"TimeInMilliseconds: {request.TimeInMilliseconds}"); MoveRes moveRes = new(); if (request.PlayerId >= spectatorMinPlayerID) { @@ -275,20 +256,19 @@ public override Task Move(MoveMsg request, ServerCallContext context) return Task.FromResult(moveRes); } // var gameID = communicationToGameID[request.TeamId][request.PlayerId]; - moveRes.ActSuccess = game.MoveShip(request.TeamId, request.PlayerId, (int)request.TimeInMilliseconds, request.Angle); + moveRes.ActSuccess = game.MoveShip( + request.TeamId, request.PlayerId, + (int)request.TimeInMilliseconds, request.Angle); if (!game.GameMap.Timer.IsGaming) moveRes.ActSuccess = false; -#if DEBUG - Console.WriteLine($"END Move: {moveRes.ActSuccess}"); -#endif + GameServerLogging.logger.ConsoleLogDebug($"END Move: {moveRes.ActSuccess}"); return Task.FromResult(moveRes); } public override Task Recover(RecoverMsg request, ServerCallContext context) { -#if DEBUG - Console.WriteLine($"TRY Recover: Player {request.PlayerId} from Team {request.TeamId}"); -#endif + GameServerLogging.logger.ConsoleLogDebug( + $"TRY Recover: Player {request.PlayerId} from Team {request.TeamId}"); BoolRes boolRes = new(); if (request.PlayerId >= spectatorMinPlayerID) { @@ -297,17 +277,14 @@ public override Task Recover(RecoverMsg request, ServerCallContext cont } // var gameID = communicationToGameID[request.TeamId][request.PlayerId]; boolRes.ActSuccess = game.Recover(request.TeamId, request.PlayerId, request.Recover); -#if DEBUG - Console.WriteLine("END Recover"); -#endif + GameServerLogging.logger.ConsoleLogDebug("END Recover"); return Task.FromResult(boolRes); } public override Task Produce(IDMsg request, ServerCallContext context) { -#if DEBUG - Console.WriteLine($"TRY Produce: Player {request.PlayerId} from Team {request.TeamId}"); -#endif + GameServerLogging.logger.ConsoleLogDebug( + $"TRY Produce: Player {request.PlayerId} from Team {request.TeamId}"); BoolRes boolRes = new(); if (request.PlayerId >= spectatorMinPlayerID) { @@ -316,17 +293,14 @@ public override Task Produce(IDMsg request, ServerCallContext context) } // var gameID = communicationToGameID[request.TeamId][request.PlayerId]; boolRes.ActSuccess = game.Produce(request.TeamId, request.PlayerId); -#if DEBUG - Console.WriteLine("END Produce"); -#endif + GameServerLogging.logger.ConsoleLogDebug("END Produce"); return Task.FromResult(boolRes); } public override Task Rebuild(ConstructMsg request, ServerCallContext context) { -#if DEBUG - Console.WriteLine($"TRY Rebuild: Player {request.PlayerId} from Team {request.TeamId}"); -#endif + GameServerLogging.logger.ConsoleLogDebug( + $"TRY Rebuild: Player {request.PlayerId} from Team {request.TeamId}"); BoolRes boolRes = new(); if (request.PlayerId >= spectatorMinPlayerID) { @@ -334,18 +308,17 @@ public override Task Rebuild(ConstructMsg request, ServerCallContext co return Task.FromResult(boolRes); } // var gameID = communicationToGameID[request.TeamId][request.PlayerId]; - boolRes.ActSuccess = game.Construct(request.TeamId, request.PlayerId, Transformation.ConstructionFromProto(request.ConstructionType)); -#if DEBUG - Console.WriteLine("END Rebuild"); -#endif + boolRes.ActSuccess = game.Construct( + request.TeamId, request.PlayerId, + Transformation.ConstructionFromProto(request.ConstructionType)); + GameServerLogging.logger.ConsoleLogDebug("END Rebuild"); return Task.FromResult(boolRes); } public override Task Construct(ConstructMsg request, ServerCallContext context) { -#if DEBUG - Console.WriteLine($"TRY Construct: Player {request.PlayerId} from Team {request.TeamId}"); -#endif + GameServerLogging.logger.ConsoleLogDebug( + $"TRY Construct: Player {request.PlayerId} from Team {request.TeamId}"); BoolRes boolRes = new(); if (request.PlayerId >= spectatorMinPlayerID) { @@ -353,18 +326,17 @@ public override Task Construct(ConstructMsg request, ServerCallContext return Task.FromResult(boolRes); } // var gameID = communicationToGameID[request.TeamId][request.PlayerId]; - boolRes.ActSuccess = game.Construct(request.TeamId, request.PlayerId, Transformation.ConstructionFromProto(request.ConstructionType)); -#if DEBUG - Console.WriteLine("END Construct"); -#endif + boolRes.ActSuccess = game.Construct( + request.TeamId, request.PlayerId, + Transformation.ConstructionFromProto(request.ConstructionType)); + GameServerLogging.logger.ConsoleLogDebug("END Construct"); return Task.FromResult(boolRes); } public override Task Attack(AttackMsg request, ServerCallContext context) { -#if DEBUG - Console.WriteLine($"TRY Attack: Player {request.PlayerId} from Team {request.TeamId}"); -#endif + GameServerLogging.logger.ConsoleLogDebug( + $"TRY Attack: Player {request.PlayerId} from Team {request.TeamId}"); BoolRes boolRes = new(); if (request.PlayerId >= spectatorMinPlayerID) { @@ -378,40 +350,35 @@ public override Task Attack(AttackMsg request, ServerCallContext contex } // var gameID = communicationToGameID[request.TeamId][request.PlayerId]; boolRes.ActSuccess = game.Attack(request.TeamId, request.PlayerId, request.Angle); -#if DEBUG - Console.WriteLine("END Attack"); -#endif + GameServerLogging.logger.ConsoleLogDebug("END Attack"); return Task.FromResult(boolRes); } public override Task Send(SendMsg request, ServerCallContext context) { -#if DEBUG - Console.WriteLine($"TRY Send: From Player {request.PlayerId} To Player {request.ToPlayerId} from Team {request.TeamId}"); -#endif + GameServerLogging.logger.ConsoleLogDebug( + $"TRY Send: From Player {request.PlayerId} To Player {request.ToPlayerId} from Team {request.TeamId}"); var boolRes = new BoolRes(); if (request.PlayerId >= spectatorMinPlayerID || PlayerDeceased((int)request.PlayerId)) { boolRes.ActSuccess = false; return Task.FromResult(boolRes); } - if (!ValidPlayerID(request.PlayerId) || !ValidPlayerID(request.ToPlayerId) || request.PlayerId == request.ToPlayerId) + if (!ValidPlayerID(request.PlayerId) + || !ValidPlayerID(request.ToPlayerId) + || request.PlayerId == request.ToPlayerId) { boolRes.ActSuccess = false; return Task.FromResult(boolRes); } -#if DEBUG - Console.WriteLine($"As {request.MessageCase}"); -#endif + GameServerLogging.logger.ConsoleLogDebug($"Send: As {request.MessageCase}"); switch (request.MessageCase) { case SendMsg.MessageOneofCase.TextMessage: { if (request.TextMessage.Length > 256) { -#if DEBUG - Console.WriteLine("Text message string is too long!"); -#endif + GameServerLogging.logger.ConsoleLogDebug("Send: Text message string is too long!"); boolRes.ActSuccess = false; return Task.FromResult(boolRes); } @@ -425,22 +392,16 @@ public override Task Send(SendMsg request, ServerCallContext context) { currentNews.Add(news); } -#if DEBUG - Console.WriteLine(news.TextMessage); -#endif + GameServerLogging.logger.ConsoleLogDebug("Send: Text: " + news.TextMessage); boolRes.ActSuccess = true; -#if DEBUG - Console.WriteLine($"END Send"); -#endif + GameServerLogging.logger.ConsoleLogDebug($"END Send"); return Task.FromResult(boolRes); } case SendMsg.MessageOneofCase.BinaryMessage: { if (request.BinaryMessage.Length > 256) { -#if DEBUG - Console.WriteLine("Binary message string is too long!"); -#endif + GameServerLogging.logger.ConsoleLogDebug("Send: Binary message string is too long!"); boolRes.ActSuccess = false; return Task.FromResult(boolRes); } @@ -454,14 +415,9 @@ public override Task Send(SendMsg request, ServerCallContext context) { currentNews.Add(news); } -#if DEBUG - Console.Write("BinaryMessageLength: "); - Console.WriteLine(news.BinaryMessage.Length); -#endif + GameServerLogging.logger.ConsoleLogDebug($"BinaryMessageLength: {news.BinaryMessage.Length}"); boolRes.ActSuccess = true; -#if DEBUG - Console.WriteLine($"END Send"); -#endif + GameServerLogging.logger.ConsoleLogDebug($"END Send"); return Task.FromResult(boolRes); } default: @@ -478,9 +434,8 @@ public override Task Send(SendMsg request, ServerCallContext context) public override Task InstallModule(InstallMsg request, ServerCallContext context) { -#if DEBUG - Console.WriteLine($"TRY InstallModule: Player {request.PlayerId} from Team {request.TeamId}"); -#endif + GameServerLogging.logger.ConsoleLogDebug( + $"TRY InstallModule: Player {request.PlayerId} from Team {request.TeamId}"); BoolRes boolRes = new(); if (request.PlayerId >= spectatorMinPlayerID) { @@ -488,18 +443,17 @@ public override Task InstallModule(InstallMsg request, ServerCallContex return Task.FromResult(boolRes); } // var gameID = communicationToGameID[request.TeamId][request.PlayerId]; - boolRes.ActSuccess = game.InstallModule(request.TeamId, request.PlayerId, Transformation.ModuleFromProto(request.ModuleType)); -#if DEBUG - Console.WriteLine("END InstallModule"); -#endif + boolRes.ActSuccess = game.InstallModule( + request.TeamId, request.PlayerId, + Transformation.ModuleFromProto(request.ModuleType)); + GameServerLogging.logger.ConsoleLogDebug("END InstallModule"); return Task.FromResult(boolRes); } public override Task Recycle(IDMsg request, ServerCallContext context) { -#if DEBUG - Console.WriteLine($"TRY Recycle: Player {request.PlayerId} from Team {request.TeamId}"); -#endif + GameServerLogging.logger.ConsoleLogDebug( + $"TRY Recycle: Player {request.PlayerId} from Team {request.TeamId}"); BoolRes boolRes = new(); if (request.PlayerId >= spectatorMinPlayerID) { @@ -508,17 +462,14 @@ public override Task Recycle(IDMsg request, ServerCallContext context) } // var gameID = communicationToGameID[request.TeamId][request.PlayerId]; boolRes.ActSuccess = game.Recycle(request.TeamId, request.PlayerId); -#if DEBUG - Console.WriteLine("END Recycle"); -#endif + GameServerLogging.logger.ConsoleLogDebug("END Recycle"); return Task.FromResult(boolRes); } public override Task BuildShip(BuildShipMsg request, ServerCallContext context) { -#if DEBUG - Console.WriteLine($"TRY BuildShip: ShipType {request.ShipType} from Team {request.TeamId}"); -#endif + GameServerLogging.logger.ConsoleLogDebug( + $"TRY BuildShip: ShipType {request.ShipType} from Team {request.TeamId}"); var activateCost = Transformation.ShipTypeFromProto(request.ShipType) switch { Utility.ShipType.CivilShip => GameData.CivilShipCost, @@ -534,21 +485,21 @@ public override Task BuildShip(BuildShipMsg request, ServerCallContext BoolRes boolRes = new() { ActSuccess = - game.ActivateShip(request.TeamId, Transformation.ShipTypeFromProto(request.ShipType), request.BirthpointIndex) != GameObj.invalidID + game.ActivateShip( + request.TeamId, + Transformation.ShipTypeFromProto(request.ShipType), + request.BirthpointIndex) + != GameObj.invalidID }; if (boolRes.ActSuccess) teamMoneyPool.SubMoney(activateCost); -#if DEBUG - Console.WriteLine("END BuildShip"); -#endif + GameServerLogging.logger.ConsoleLogDebug("END BuildShip"); return Task.FromResult(boolRes); } public override Task BuildShipRID(BuildShipMsg request, ServerCallContext context) { -#if DEBUG - Console.WriteLine($"TRY BuildShipRID: ShipType {request.ShipType} from Team {request.TeamId}"); -#endif - + GameServerLogging.logger.ConsoleLogDebug( + $"TRY BuildShipRID: ShipType {request.ShipType} from Team {request.TeamId}"); var activateCost = Transformation.ShipTypeFromProto(request.ShipType) switch { Utility.ShipType.CivilShip => GameData.CivilShipCost, @@ -561,9 +512,10 @@ public override Task BuildShipRID(BuildShipMsg request, ServerCall { return Task.FromResult(new BuildShipRes { ActSuccess = false }); } - var playerId = game.ActivateShip(request.TeamId, - Transformation.ShipTypeFromProto(request.ShipType), - request.BirthpointIndex); + var playerId = game.ActivateShip( + request.TeamId, + Transformation.ShipTypeFromProto(request.ShipType), + request.BirthpointIndex); BuildShipRes buildShipRes = new() { @@ -571,17 +523,14 @@ public override Task BuildShipRID(BuildShipMsg request, ServerCall PlayerId = playerId }; if (buildShipRes.ActSuccess) teamMoneyPool.SubMoney(activateCost); -#if DEBUG - Console.WriteLine("END BuildShipRID"); -#endif + GameServerLogging.logger.ConsoleLogDebug("END BuildShipRID"); return Task.FromResult(buildShipRes); } public override Task EndAllAction(IDMsg request, ServerCallContext context) { -#if DEBUG - Console.WriteLine($"TRY EndAllAction: Player {request.PlayerId} from Team {request.TeamId}"); -#endif + GameServerLogging.logger.ConsoleLogDebug( + $"TRY EndAllAction: Player {request.PlayerId} from Team {request.TeamId}"); BoolRes boolRes = new(); if (request.PlayerId >= spectatorMinPlayerID) { @@ -590,9 +539,7 @@ public override Task EndAllAction(IDMsg request, ServerCallContext cont } // var gameID = communicationToGameID[request.TeamId][request.PlayerId]; boolRes.ActSuccess = game.Stop(request.TeamId, request.PlayerId); -#if DEBUG - Console.WriteLine("END EndAllAction"); -#endif + GameServerLogging.logger.ConsoleLogDebug("END EndAllAction"); return Task.FromResult(boolRes); } From 5980e6597a5bcac2318e4f48f3149e5e8d1b5925 Mon Sep 17 00:00:00 2001 From: 964293341 Date: Fri, 26 Apr 2024 16:21:46 +0800 Subject: [PATCH 08/11] fix: add log in MoveEngine when merge --- logic/GameEngine/MoveEngine.cs | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/logic/GameEngine/MoveEngine.cs b/logic/GameEngine/MoveEngine.cs index 7c861de0..6152a7f3 100755 --- a/logic/GameEngine/MoveEngine.cs +++ b/logic/GameEngine/MoveEngine.cs @@ -216,14 +216,11 @@ public void MoveObj(IMovable obj, int moveTime, double direction, long stateNum) MaxTolerantTimeExceedCount = ulong.MaxValue, TimeExceedAction = b => { - if (b) - Console.WriteLine("Fatal Error: The computer runs so slow that the object cannot finish moving during this time!!!!!!"); -#if DEBUG - else - { - Console.WriteLine("Debug info: Object moving time exceed for once."); - } -#endif + if (b) GameEngineLogging.logger.ConsoleLog( + "Fatal Error: The computer runs so slow that " + + "the object cannot finish moving during this time!!!!!!"); + else GameEngineLogging.logger.ConsoleLogDebug( + "Debug info: Object moving time exceed for once"); } }.Start(); if (!isEnded && obj.StateNum == stateNum && obj.CanMove && !obj.IsRemoved) From b4cd8337e33f7f7fe871f6b12926eec74c385270 Mon Sep 17 00:00:00 2001 From: 964293341 Date: Fri, 26 Apr 2024 17:34:25 +0800 Subject: [PATCH 09/11] feat: :sparkles: add time log --- logic/GameClass/GameObj/Ship.cs | 3 -- logic/Gaming/ShipManager.cs | 34 ++++++++++------------- logic/Preparation/Utility/Logger.cs | 43 +++++++++++++++++++++-------- logic/Server/RpcServices.cs | 3 +- 4 files changed, 48 insertions(+), 35 deletions(-) diff --git a/logic/GameClass/GameObj/Ship.cs b/logic/GameClass/GameObj/Ship.cs index 569eaac8..2fdb73ca 100755 --- a/logic/GameClass/GameObj/Ship.cs +++ b/logic/GameClass/GameObj/Ship.cs @@ -476,8 +476,5 @@ public Ship(int initRadius, ShipType shipType, MoneyPool moneyPool) : ArmorModule.SetROri(ModuleFactory.FindIArmor(ShipType, ArmorType.Null)); ShieldModule.SetROri(ModuleFactory.FindIShield(ShipType, ShieldType.Null)); WeaponModule.SetROri(ModuleFactory.FindIWeapon(ShipType, weaponType)); - ShipLogging.logger.ConsoleLogDebug( - ShipLogging.ShipLogInfo(this) - + "Ship created"); } } diff --git a/logic/Gaming/ShipManager.cs b/logic/Gaming/ShipManager.cs index fc702efd..2faf0dcd 100755 --- a/logic/Gaming/ShipManager.cs +++ b/logic/Gaming/ShipManager.cs @@ -25,13 +25,15 @@ private class ShipManager(Game game, Map gameMap) newShip.TeamID.SetROri(teamID); newShip.PlayerID.SetROri(playerID); ShipManagerLogging.logger.ConsoleLogDebug( - "Added ship: " + newShip.ShipType + " with " - + newShip.ProducerModuleType + ", " - + newShip.ConstructorModuleType + ", " - + newShip.ArmorModuleType + ", " - + newShip.ShieldModuleType + ", " - + newShip.WeaponModuleType - ); + ShipLogging.ShipLogInfo(newShip) + + " created"); + ShipManagerLogging.logger.ConsoleLogDebug( + $"Added ship: {newShip.ShipType} with " + + $"{newShip.ProducerModuleType}, " + + $"{newShip.ConstructorModuleType}, " + + $"{newShip.ArmorModuleType}, " + + $"{newShip.ShieldModuleType}, " + + $"{newShip.WeaponModuleType}"); return newShip; } public static bool ActivateShip(Ship ship, XY pos) @@ -44,20 +46,17 @@ public static bool ActivateShip(Ship ship, XY pos) ship.SetShipState(RunningStateType.Null, ShipStateType.Null); ShipManagerLogging.logger.ConsoleLogDebug( ShipLogging.ShipLogInfo(ship) - + " is activated!" - ); + + " is activated!"); return true; } public void BeAttacked(Ship ship, Bullet bullet) { ShipManagerLogging.logger.ConsoleLogDebug( ShipLogging.ShipLogInfo(ship) - + " is attacked!" - ); + + " is attacked!"); ShipManagerLogging.logger.ConsoleLogDebug( Logger.TypeName(bullet) - + $" 's AP is {bullet.AP}" - ); + + $" 's AP is {bullet.AP}"); if (bullet!.Parent!.TeamID == ship.TeamID) { return; @@ -68,24 +67,21 @@ public void BeAttacked(Ship ship, Bullet bullet) ship.Shield.SubPositiveV((long)(subHP * bullet.ShieldModifier)); ShipManagerLogging.logger.ConsoleLogDebug( ShipLogging.ShipLogInfo(ship) - + $" 's shield is {ship.Shield}" - ); + + $" 's shield is {ship.Shield}"); } else if (ship.Armor > 0) { ship.Armor.SubPositiveV((long)(subHP * bullet.ArmorModifier)); ShipManagerLogging.logger.ConsoleLogDebug( ShipLogging.ShipLogInfo(ship) - + $" 's armor is {ship.Armor}" - ); + + $" 's armor is {ship.Armor}"); } else { ship.HP.SubPositiveV(subHP); ShipManagerLogging.logger.ConsoleLogDebug( ShipLogging.ShipLogInfo(ship) - + $" 's HP is {ship.HP}" - ); + + $" 's HP is {ship.HP}"); } if (ship.HP == 0) { diff --git a/logic/Preparation/Utility/Logger.cs b/logic/Preparation/Utility/Logger.cs index 460011ca..8810b71e 100755 --- a/logic/Preparation/Utility/Logger.cs +++ b/logic/Preparation/Utility/Logger.cs @@ -26,7 +26,20 @@ await Task.Run(() => private LogQueue() { - void WriteInFile() + if (File.Exists(LoggingData.ServerLogPath)) + File.Delete(LoggingData.ServerLogPath); + File.AppendAllText(LoggingData.ServerLogPath, $"[{Logger.NowDate()}]" + Environment.NewLine); + void LogCopy() + { + string copyPath = $"{LoggingData.ServerLogPath}-copy{logCopyNum}.txt"; + if (File.Exists(copyPath)) + File.Delete(copyPath); + File.Copy(LoggingData.ServerLogPath, copyPath); + logCopyNum++; + File.Delete(LoggingData.ServerLogPath); + logNum = 0; + } + void LogWrite() { lock (queueLock) { @@ -36,13 +49,7 @@ void WriteInFile() File.AppendAllText(LoggingData.ServerLogPath, info + Environment.NewLine); logNum++; if (logNum >= LoggingData.MaxLogNum) - { - File.Copy(LoggingData.ServerLogPath, - $"{LoggingData.ServerLogPath}-copy{logCopyNum}.txt"); - logCopyNum++; - File.Delete(LoggingData.ServerLogPath); - logNum = 0; - } + LogCopy(); } } } @@ -50,11 +57,12 @@ void WriteInFile() { new FrameRateTaskExecutor( loopCondition: () => Global != null, - loopToDo: WriteInFile, + loopToDo: LogWrite, timeInterval: 100, finallyReturn: () => { - WriteInFile(); + LogWrite(); + LogCopy(); return 0; } ).Start(); @@ -71,7 +79,7 @@ public class Logger(string module) public void ConsoleLog(string msg, bool Duplicate = true) { - var info = $"[{Module}]{msg}"; + var info = $"[{NowTime()}][{Module}] {msg}"; if (Enable) { if (!Background) @@ -83,7 +91,7 @@ public void ConsoleLog(string msg, bool Duplicate = true) public void ConsoleLogDebug(string msg, bool Duplicate = true) { #if DEBUG - var info = $"[{Module}]{msg}"; + var info = $"[{NowTime()}][{Module}] {msg}"; if (Enable) { if (!Background) @@ -118,6 +126,17 @@ public static string ObjInfo(object obj, string msg = "") public static string ObjInfo(Type tp, string msg = "") => msg == "" ? $"<{TypeName(tp)}>" : $"<{TypeName(tp)} {msg}>"; + + public static string NowTime() + { + DateTime now = DateTime.Now; + return $"{now.Hour}:{now.Minute}:{now.Second}.{now.Millisecond:D3}"; + } + public static string NowDate() + { + DateTime now = DateTime.Today; + return $"{now.Year}/{now.Month}/{now.Day} {now.DayOfWeek}"; + } } public static class LoggingData diff --git a/logic/Server/RpcServices.cs b/logic/Server/RpcServices.cs index 0a3080db..578b125c 100755 --- a/logic/Server/RpcServices.cs +++ b/logic/Server/RpcServices.cs @@ -195,7 +195,8 @@ public override async Task AddPlayer(PlayerMsg request, IServerStreamWriter Date: Sat, 27 Apr 2024 20:18:37 +0800 Subject: [PATCH 10/11] fix: :bug: logger didn't writein the last log, so wait 1s --- logic/Preparation/Utility/GameData.cs | 2 +- logic/Preparation/Utility/Logger.cs | 68 ++++++++++++++++----------- logic/Server/ArgumentOptions.cs | 3 +- logic/Server/Program.cs | 6 ++- 4 files changed, 48 insertions(+), 31 deletions(-) diff --git a/logic/Preparation/Utility/GameData.cs b/logic/Preparation/Utility/GameData.cs index 3931b5b3..8d60ed01 100755 --- a/logic/Preparation/Utility/GameData.cs +++ b/logic/Preparation/Utility/GameData.cs @@ -9,7 +9,7 @@ public static class GameData public const int NumOfStepPerSecond = 100; // 每秒行走的步数 public const int FrameDuration = 50; // 每帧时长 public const int CheckInterval = 10; // 检查间隔 - public const long GameDuration = 600000; // 游戏时长 + public const uint GameDurationInSecond = 60*10; // 游戏时长 public const int LimitOfStopAndMove = 15; // 停止和移动的最大间隔 public const int TolerancesLength = 3; diff --git a/logic/Preparation/Utility/Logger.cs b/logic/Preparation/Utility/Logger.cs index 8810b71e..073ac337 100755 --- a/logic/Preparation/Utility/Logger.cs +++ b/logic/Preparation/Utility/Logger.cs @@ -24,35 +24,47 @@ await Task.Run(() => }); } - private LogQueue() + public static bool IsClosed { get; private set; } = false; + public static void Close() { - if (File.Exists(LoggingData.ServerLogPath)) - File.Delete(LoggingData.ServerLogPath); - File.AppendAllText(LoggingData.ServerLogPath, $"[{Logger.NowDate()}]" + Environment.NewLine); - void LogCopy() - { - string copyPath = $"{LoggingData.ServerLogPath}-copy{logCopyNum}.txt"; - if (File.Exists(copyPath)) - File.Delete(copyPath); - File.Copy(LoggingData.ServerLogPath, copyPath); - logCopyNum++; - File.Delete(LoggingData.ServerLogPath); - logNum = 0; - } - void LogWrite() + if (IsClosed) return; + LogWrite(); + LogCopy(); + IsClosed = true; + } + + static void LogCopy() + { + if (IsClosed) return; + string copyPath = $"{LoggingData.ServerLogPath}-copy{logCopyNum}.txt"; + if (File.Exists(copyPath)) + File.Delete(copyPath); + File.Copy(LoggingData.ServerLogPath, copyPath); + logCopyNum++; + File.Delete(LoggingData.ServerLogPath); + logNum = 0; + } + static void LogWrite() + { + if (IsClosed) return; + lock (queueLock) { - lock (queueLock) + while (Global.logInfoQueue.Count != 0) { - while (logInfoQueue.Count != 0) - { - var info = logInfoQueue.Dequeue(); - File.AppendAllText(LoggingData.ServerLogPath, info + Environment.NewLine); - logNum++; - if (logNum >= LoggingData.MaxLogNum) - LogCopy(); - } + var info = Global.logInfoQueue.Dequeue(); + File.AppendAllText(LoggingData.ServerLogPath, info + Environment.NewLine); + logNum++; + if (logNum >= LoggingData.MaxLogNum) + LogCopy(); } } + } + + private LogQueue() + { + if (File.Exists(LoggingData.ServerLogPath)) + File.Delete(LoggingData.ServerLogPath); + File.AppendAllText(LoggingData.ServerLogPath, $"[{Logger.NowDate()}]" + Environment.NewLine); new Thread(() => { new FrameRateTaskExecutor( @@ -61,13 +73,13 @@ void LogWrite() timeInterval: 100, finallyReturn: () => { - LogWrite(); - LogCopy(); + Close(); return 0; } ).Start(); }) { IsBackground = true }.Start(); + var t = new Thread(() => { }); } } @@ -130,12 +142,12 @@ public static string ObjInfo(Type tp, string msg = "") public static string NowTime() { DateTime now = DateTime.Now; - return $"{now.Hour}:{now.Minute}:{now.Second}.{now.Millisecond:D3}"; + return $"{now.Hour:D2}:{now.Minute:D2}:{now.Second:D2}.{now.Millisecond:D3}"; } public static string NowDate() { DateTime now = DateTime.Today; - return $"{now.Year}/{now.Month}/{now.Day} {now.DayOfWeek}"; + return $"{now.Year:D4}/{now.Month:D2}/{now.Day:D2} {now.DayOfWeek}"; } } diff --git a/logic/Server/ArgumentOptions.cs b/logic/Server/ArgumentOptions.cs index 4d97803f..ce8b5d75 100755 --- a/logic/Server/ArgumentOptions.cs +++ b/logic/Server/ArgumentOptions.cs @@ -1,4 +1,5 @@ using CommandLine; +using Preparation.Utility; namespace Server { @@ -27,7 +28,7 @@ public class ArgumentOptions public ushort HomeCount { get; set; } = 1; [Option('g', "gameTimeInSecond", Required = false, HelpText = "The time of the game in second, 10 minutes by default")] - public uint GameTimeInSecond { get; set; } = 10 * 60; + public uint GameTimeInSecond { get; set; } = GameData.GameDurationInSecond; [Option('f', "fileName", Required = false, HelpText = "The file to store playback file or to read file.")] public string FileName { get; set; } = "114514"; [Option("notAllowSpectator", Required = false, HelpText = "Whether to allow a spectator to watch the game.")] diff --git a/logic/Server/Program.cs b/logic/Server/Program.cs index d144e4a1..c3d62b0e 100755 --- a/logic/Server/Program.cs +++ b/logic/Server/Program.cs @@ -65,7 +65,6 @@ static int Main(string[] args) logger.ConsoleLog("Server end!"); rpcServer.ShutdownAsync().Wait(); - Thread.Sleep(50); Logger.RawConsoleLog("", false); logger.ConsoleLog("=================== Final Score ====================", false); logger.ConsoleLog($"Team0: {server.GetScore()[0]}"); //红队 @@ -77,6 +76,11 @@ static int Main(string[] args) if (ex.StackTrace is not null) Logger.RawConsoleLog(ex.StackTrace); } + finally + { + Thread.Sleep(1000); // 确保log被Duplicate + LogQueue.Close(); + } return 0; } } From 66d626f80187ab5d7688f9323489a2ca0d1eb417 Mon Sep 17 00:00:00 2001 From: 964293341 Date: Sat, 27 Apr 2024 20:26:12 +0800 Subject: [PATCH 11/11] format --- logic/Preparation/Utility/GameData.cs | 2 +- logic/Preparation/Utility/Logger.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/logic/Preparation/Utility/GameData.cs b/logic/Preparation/Utility/GameData.cs index 8d60ed01..7749f527 100755 --- a/logic/Preparation/Utility/GameData.cs +++ b/logic/Preparation/Utility/GameData.cs @@ -9,7 +9,7 @@ public static class GameData public const int NumOfStepPerSecond = 100; // 每秒行走的步数 public const int FrameDuration = 50; // 每帧时长 public const int CheckInterval = 10; // 检查间隔 - public const uint GameDurationInSecond = 60*10; // 游戏时长 + public const uint GameDurationInSecond = 60 * 10; // 游戏时长 public const int LimitOfStopAndMove = 15; // 停止和移动的最大间隔 public const int TolerancesLength = 3; diff --git a/logic/Preparation/Utility/Logger.cs b/logic/Preparation/Utility/Logger.cs index 073ac337..b41006c4 100755 --- a/logic/Preparation/Utility/Logger.cs +++ b/logic/Preparation/Utility/Logger.cs @@ -24,7 +24,7 @@ await Task.Run(() => }); } - public static bool IsClosed { get; private set; } = false; + public static bool IsClosed { get; private set; } = false; public static void Close() { if (IsClosed) return;