From 584e6fc494f650728d5a0e341b1c38e3fa570a6a Mon Sep 17 00:00:00 2001 From: ONLOX <3316820553@qq.com> Date: Tue, 23 Apr 2024 19:38:20 +0800 Subject: [PATCH 001/179] feat: :alien: --- .github/workflows/docker.yml | 29 +++++++++ .../{Dockerfile_run => Docker_run_client} | 4 +- dependency/Dockerfile/Docker_run_server | 20 ++++++ dependency/shell/Unix2dos.sh | 18 ++++++ dependency/shell/compile.sh | 31 +++++++++ dependency/shell/cpp_output.sh | 8 +++ dependency/shell/docker.sh | 23 +++++++ dependency/shell/generate_proto.sh | 10 +++ dependency/shell/run_client.sh | 64 +++++++++++++++++++ dependency/shell/run_server.sh | 55 ++++++++++++++++ 10 files changed, 260 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/docker.yml rename dependency/Dockerfile/{Dockerfile_run => Docker_run_client} (89%) mode change 100755 => 100644 create mode 100644 dependency/Dockerfile/Docker_run_server create mode 100644 dependency/shell/Unix2dos.sh create mode 100644 dependency/shell/compile.sh create mode 100644 dependency/shell/cpp_output.sh create mode 100644 dependency/shell/docker.sh create mode 100644 dependency/shell/generate_proto.sh create mode 100644 dependency/shell/run_client.sh create mode 100644 dependency/shell/run_server.sh diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml new file mode 100644 index 00000000..4d0acd25 --- /dev/null +++ b/.github/workflows/docker.yml @@ -0,0 +1,29 @@ +name: "docker" +on: + push: + branches: [main] + +jobs: + upload_docker_images: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Log in to DockerHub + run: docker login -u ${{ secrets.DOCKER_USERNAME }} -p ${{ secrets.DOCKER_PASSWORD }} + + #- name: Build base docker image + # run: docker build -t ${{ secrets.DOCKER_USERNAME }}/thuai6_base:base -f ./dependency/Dockerfile/Dockerfile_base . + #- name: Push base image to DockerHub + # run: docker push ${{ secrets.DOCKER_USERNAME }}/thuai6_base:base + + + - name: Build cpp_compile docker image + run: docker build -t ${{ secrets.DOCKER_USERNAME }}/thuai6_cpp:latest -f ./dependency/Dockerfile/Dockerfile_cpp . + - name: Push cpp_compile image to DockerHub + run: docker push ${{ secrets.DOCKER_USERNAME }}/thuai6_cpp:latest + + - name: Build run docker image + run: docker build -t ${{ secrets.DOCKER_USERNAME }}/thuai6_run:latest -f ./dependency/Dockerfile/Dockerfile_run . + - name: Push run image to DockerHub + run: docker push ${{ secrets.DOCKER_USERNAME }}/thuai6_run:latest + diff --git a/dependency/Dockerfile/Dockerfile_run b/dependency/Dockerfile/Docker_run_client old mode 100755 new mode 100644 similarity index 89% rename from dependency/Dockerfile/Dockerfile_run rename to dependency/Dockerfile/Docker_run_client index 474e1658..9df6ff40 --- a/dependency/Dockerfile/Dockerfile_run +++ b/dependency/Dockerfile/Docker_run_client @@ -9,7 +9,7 @@ MAINTAINER eesast WORKDIR /usr/local COPY --from=build /usr/local/Server . RUN mkdir /usr/local/team1 && mkdir /usr/local/team2 && mkdir /usr/local/playback -COPY ./dependency/shell/run.sh . +COPY ./dependency/shell/run_client.sh . COPY ./CAPI/python /usr/local/PlayerCode/CAPI/python COPY ./dependency/proto /usr/local/PlayerCode/dependency/proto COPY ./dependency/shell /usr/local/PlayerCode/dependency/shell @@ -17,4 +17,4 @@ WORKDIR /usr/local/PlayerCode/CAPI/python RUN bash ../../dependency/shell/generate_proto.sh WORKDIR /usr/local -ENTRYPOINT [ "bash","./run.sh" ] +ENTRYPOINT [ "bash","./run_client.sh" ] diff --git a/dependency/Dockerfile/Docker_run_server b/dependency/Dockerfile/Docker_run_server new file mode 100644 index 00000000..aa5984dd --- /dev/null +++ b/dependency/Dockerfile/Docker_run_server @@ -0,0 +1,20 @@ +FROM mcr.microsoft.com/dotnet/sdk:8.0.204-jammy-amd64 AS build +MAINTAINER eesast +WORKDIR /usr/local +COPY . . +RUN dotnet publish logic/Server/Server.csproj -c Release -o /usr/local/Server --self-contained true -r linux-x64 + +FROM eesast/thuai7_base:base +MAINTAINER eesast +WORKDIR /usr/local +COPY --from=build /usr/local/Server . +RUN mkdir /usr/local/team1 && mkdir /usr/local/team2 && mkdir /usr/local/playback +COPY ./dependency/shell/run_server.sh . +COPY ./CAPI/python /usr/local/PlayerCode/CAPI/python +COPY ./dependency/proto /usr/local/PlayerCode/dependency/proto +COPY ./dependency/shell /usr/local/PlayerCode/dependency/shell +WORKDIR /usr/local/PlayerCode/CAPI/python +RUN bash ../../dependency/shell/generate_proto.sh + +WORKDIR /usr/local +ENTRYPOINT [ "bash","./run_server.sh" ] diff --git a/dependency/shell/Unix2dos.sh b/dependency/shell/Unix2dos.sh new file mode 100644 index 00000000..feebe3c0 --- /dev/null +++ b/dependency/shell/Unix2dos.sh @@ -0,0 +1,18 @@ +#!/bin/bash +function lsdir() +{ +for i in `ls`; +do + if [ -d $i ] + then + pushd ./$i + lsdir + popd + else + unix2dos $i + fi +done +} +yum -y install unix2dos +cd $1 +lsdir diff --git a/dependency/shell/compile.sh b/dependency/shell/compile.sh new file mode 100644 index 00000000..c616ba85 --- /dev/null +++ b/dependency/shell/compile.sh @@ -0,0 +1,31 @@ +#! /bin/bash +# WORKDIR /usr/local/PlayerCode/CAPI/cpp +workdir=/usr/local/PlayerCode/CAPI/cpp +bind=/usr/local/code +output=/usr/local/output + +flag=1 + +cd $bind +file_count=$(ls -l *.cpp | wc -l); +if [ $file_count -eq 1 ] +then + filename=$(ls *.cpp) + base_name=$(basename "$filename" .cpp) + cd $workdir + cp -f $bind/$filename $workdir/API/src/AI.cpp + cmake ./CMakeLists.txt && make -j$(nproc) >$base_name.log 2>&1 + mv ./capi $output/$base_name + if [ $? -ne 0 ]; then + flag=0 + fi + mv ./$base_name.log $output/$base_name.log +else + flag=0 +fi + +if [ $flag -eq 1 ]; then + curl $URL -X POST -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" -d '{"compile_status":"Success"}' > $output/$base_name.curl.log +else + curl $URL -X POST -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" -d '{"compile_status":"Failed"}' > $output/$base_name.curl.log +fi diff --git a/dependency/shell/cpp_output.sh b/dependency/shell/cpp_output.sh new file mode 100644 index 00000000..a8b07973 --- /dev/null +++ b/dependency/shell/cpp_output.sh @@ -0,0 +1,8 @@ +protoc Message2Clients.proto --cpp_out=. +protoc MessageType.proto --cpp_out=. +protoc Message2Server.proto --cpp_out=. +protoc Services.proto --grpc_out=. --plugin=protoc-gen-grpc=`which grpc_cpp_plugin` +protoc Services.proto --cpp_out=. +chmod -R 755 ./ +mv -f ./*.h ../../CAPI/cpp/proto +mv -f ./*.cc ../../CAPI/cpp/proto diff --git a/dependency/shell/docker.sh b/dependency/shell/docker.sh new file mode 100644 index 00000000..ef4beb39 --- /dev/null +++ b/dependency/shell/docker.sh @@ -0,0 +1,23 @@ + +while getopts ':cr' 'OPT'; do + case ${OPT} in + 'c') #传入cpp文件并编译 + #echo v"$VERSION" + cd /usr/local/PlayerCode/CAPI/cpp + ./compile.sh + exit + ;; + 'r') #运行 + #NO_PROMPT='true' + cd /usr/local + ./run_server.sh + ./run_client.sh + ;; + 'l') + + ;; + 'i') + INSTALL_VERSION="${OPTARG}" + ;; + esac +done \ No newline at end of file diff --git a/dependency/shell/generate_proto.sh b/dependency/shell/generate_proto.sh new file mode 100644 index 00000000..a0ebe224 --- /dev/null +++ b/dependency/shell/generate_proto.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash + +python -m pip install -r requirements.txt + +mkdir -p proto + +python -m grpc_tools.protoc -I../../dependency/proto/ --python_out=./proto --pyi_out=./proto MessageType.proto +python -m grpc_tools.protoc -I../../dependency/proto/ --python_out=./proto --pyi_out=./proto Message2Clients.proto +python -m grpc_tools.protoc -I../../dependency/proto/ --python_out=./proto --pyi_out=./proto Message2Server.proto +python -m grpc_tools.protoc -I../../dependency/proto/ --python_out=./proto --pyi_out=./proto --grpc_python_out=./proto Services.proto diff --git a/dependency/shell/run_client.sh b/dependency/shell/run_client.sh new file mode 100644 index 00000000..e55aaa4c --- /dev/null +++ b/dependency/shell/run_client.sh @@ -0,0 +1,64 @@ +#!/usr/local + +python_dir=/usr/local/PlayerCode/CAPI/python/PyAPI +python_main_dir=/usr/local/PlayerCode/CAPI/python +playback_dir=/usr/local/playback + +sleep 5 +for k in {1..2} +do + pushd /usr/local/team$k + if [ $k -eq 1 ]; then + for i in {1..4} + do + j=$((i - 1)) + if [ -f "./player$i.py" ]; then + cp -r $python_main_dir $python_main_dir$i + cp -f ./player$i.py $python_main_dir$i/PyAPI/AI.py + nice -0 python3 $python_main_dir$i/PyAPI/main.py -I 127.0.0.1 -P 8888 -p $j > $playback_dir/team$k-player$j.log 2>&1 & + elif [ -f "./capi$i" ]; then + nice -0 ./capi$i -I 127.0.0.1 -P 8888 -p $j > $playback_dir/team$k-player$j.log 2>&1 & + else + echo "ERROR. $i is not found." + fi + done + else + for i in {5..5} + do + j=$((i - 1)) + if [ -f "./player$i.py" ]; then + cp -r $python_main_dir $python_main_dir$i + cp -f ./player$i.py $python_main_dir$i/PyAPI/AI.py + nice -0 python3 $python_main_dir$i/PyAPI/main.py -I 127.0.0.1 -P 8888 -p $j > $playback_dir/team$k-player$j.log 2>&1 & + elif [ -f "./capi$i" ]; then + nice -0 ./capi$i -I 127.0.0.1 -P 8888 -p $j > $playback_dir/team$k-player$j.log 2>&1 & + else + echo "ERROR. $i is not found." + fi + done + fi + popd +done + +sleep 10 + +if [ -f $playback_dir/start.lock ]; then + ps -p $server_pid + while [ $? -eq 0 ] + do + sleep 1 + ps -p $server_pid > /dev/null 2>&1 + done + # result=$(cat /usr/local/playback/result.json) + # score0=$(echo "$result" | grep -oP '(?<="Student":)\d+') + # score1=$(echo "$result" | grep -oP '(?<="Tricker":)\d+') + # curl $URL -X PUT -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" -d '{"result":[{"team_id":0, "score":'${score0}'}, {"team_id":1, "score":'${score1}'}], "mode":'${MODE}'}'> $playback_dir/send.log 2>&1 + touch $playback_dir/finish.lock + echo "Finish" +else + echo "Failed to start game." + touch $playback_dir/finish.lock + touch temp.lock + mv -f temp.lock $playback_dir/video.thuaipb + kill -9 $server_pid +fi diff --git a/dependency/shell/run_server.sh b/dependency/shell/run_server.sh new file mode 100644 index 00000000..18b02d94 --- /dev/null +++ b/dependency/shell/run_server.sh @@ -0,0 +1,55 @@ +#!/usr/local + +python_dir=/usr/local/PlayerCode/CAPI/python/PyAPI +python_main_dir=/usr/local/PlayerCode/CAPI/python +playback_dir=/usr/local/playback + +if [ $EXPOSED -eq 1 ]; then + nice -10 ./Server --port 8888 --TeamCount 2 --ShipNum 4 --resultFileName $playback_dir/result --gameTimeInSecond $TIME --mode $MODE --mapResource $MAP --url $URL --token $TOKEN --fileName $playback_dir/video --startLockFile $playback_dir/start.lock > $playback_dir/server.log 2>&1 & + server_pid=$! +else + nice -10 ./Server --port 8888 --TeamCount 2 --ShipNum 1 --resultFileName $playback_dir/result --gameTimeInSecond $TIME --mode $MODE --mapResource $MAP --notAllowSpectator --url $URL --token $TOKEN --fileName $playback_dir/video --startLockFile $playback_dir/start.lock > $playback_dir/server.log 2>&1 & + server_pid=$! +fi +sleep 5 +for k in {1..2} +do + pushd /usr/local/team$k + for i in {1..5} + do + j=$((i - 1)) + if [ -f "./player$i.py" ]; then + cp -r $python_main_dir $python_main_dir$i + cp -f ./player$i.py $python_main_dir$i/PyAPI/AI.py + nice -0 python3 $python_main_dir$i/PyAPI/main.py -I 127.0.0.1 -P 8888 -p $j > $playback_dir/team$k-player$j.log 2>&1 & + elif [ -f "./capi$i" ]; then + nice -0 ./capi$i -I 127.0.0.1 -P 8888 -p $j > $playback_dir/team$k-player$j.log 2>&1 & + else + echo "ERROR. $i is not found." + fi + done + popd +done + +sleep 10 + +if [ -f $playback_dir/start.lock ]; then + ps -p $server_pid + while [ $? -eq 0 ] + do + sleep 1 + ps -p $server_pid > /dev/null 2>&1 + done + # result=$(cat /usr/local/playback/result.json) + # score0=$(echo "$result" | grep -oP '(?<="Student":)\d+') + # score1=$(echo "$result" | grep -oP '(?<="Tricker":)\d+') + # curl $URL -X PUT -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" -d '{"result":[{"team_id":0, "score":'${score0}'}, {"team_id":1, "score":'${score1}'}], "mode":'${MODE}'}'> $playback_dir/send.log 2>&1 + touch $playback_dir/finish.lock + echo "Finish" +else + echo "Failed to start game." + touch $playback_dir/finish.lock + touch temp.lock + mv -f temp.lock $playback_dir/video.thuaipb + kill -9 $server_pid +fi From 24176ef9b4eedf59551f9e7345a971c61bf253ce Mon Sep 17 00:00:00 2001 From: shangfengh <3495281661@qq.com> Date: Thu, 25 Apr 2024 11:44:27 +0800 Subject: [PATCH 002/179] perf(SafeValue): :sparkles: make the Timer SafeValue --- logic/GameClass/GameObj/Map/Map.cs | 4 +++ logic/GameClass/GameObj/Map/MapGameTimer.cs | 33 ------------------- logic/GameEngine/MoveEngine.cs | 3 +- logic/Gaming/Game.cs | 11 +------ logic/Preparation/Interface/IMap.cs | 2 +- logic/Preparation/Interface/ITimer.cs | 11 ------- .../Utility/Value/SafeValue/MyTimer.cs | 30 +++++++++++++++++ .../Utility/Value/ValueInterface/IMyTimer.cs | 11 +++++++ logic/Server/GameServer.cs | 2 +- 9 files changed, 49 insertions(+), 58 deletions(-) delete mode 100755 logic/GameClass/GameObj/Map/MapGameTimer.cs delete mode 100755 logic/Preparation/Interface/ITimer.cs create mode 100644 logic/Preparation/Utility/Value/SafeValue/MyTimer.cs create mode 100644 logic/Preparation/Utility/Value/ValueInterface/IMyTimer.cs diff --git a/logic/GameClass/GameObj/Map/Map.cs b/logic/GameClass/GameObj/Map/Map.cs index 201b0b21..e8ed31aa 100755 --- a/logic/GameClass/GameObj/Map/Map.cs +++ b/logic/GameClass/GameObj/Map/Map.cs @@ -19,6 +19,10 @@ public partial class Map : IMap public readonly PlaceType[,] protoGameMap; public PlaceType[,] ProtoGameMap => protoGameMap; + // xfgg说:爱因斯坦说,每个坐标系都有与之绑定的时钟,(x, y, z, ict) 构成四维时空坐标,在洛伦兹变换下满足矢量性(狗头) + private readonly MyTimer timer = new(); + public IMyTimer Timer => timer; + #region 大本营相关 public List Homes { get; } private readonly long currentHomeNum = 0; diff --git a/logic/GameClass/GameObj/Map/MapGameTimer.cs b/logic/GameClass/GameObj/Map/MapGameTimer.cs deleted file mode 100755 index f9a92db6..00000000 --- a/logic/GameClass/GameObj/Map/MapGameTimer.cs +++ /dev/null @@ -1,33 +0,0 @@ -using Preparation.Utility; -using System; -using System.Threading; -using ITimer = Preparation.Interface.ITimer; - -namespace GameClass.GameObj -{ - public partial class Map - { - // xfgg说:爱因斯坦说,每个坐标系都有与之绑定的时钟,(x, y, z, ict) 构成四维时空坐标,在洛伦兹变换下满足矢量性(狗头) - private readonly GameTimer timer = new(); - public ITimer Timer => timer; - - public class GameTimer : ITimer - { - private long startTime; - public int nowTime() => (int)(Environment.TickCount64 - startTime); - - private readonly AtomicBool isGaming = new(false); - public AtomicBool IsGaming => isGaming; - - public bool StartGame(int timeInMilliseconds) - { - if (!IsGaming.TrySet(true)) - return false; - startTime = Environment.TickCount64; - Thread.Sleep(timeInMilliseconds); - IsGaming.SetROri(false); - return true; - } - } - } -} diff --git a/logic/GameEngine/MoveEngine.cs b/logic/GameEngine/MoveEngine.cs index 8d43c19b..a5b7e25a 100755 --- a/logic/GameEngine/MoveEngine.cs +++ b/logic/GameEngine/MoveEngine.cs @@ -3,7 +3,6 @@ using System; using System.Threading; using Timothy.FrameRateTask; -using ITimer = Preparation.Interface.ITimer; namespace GameEngine { @@ -35,7 +34,7 @@ public enum AfterCollision Destroyed = 2 // 物体已经毁坏 } - private readonly ITimer gameTimer = gameMap.Timer; + private readonly IMyTimer gameTimer = gameMap.Timer; private readonly Action EndMove = EndMove; public IGameObj? CheckCollision(IMovable obj, XY Pos) diff --git a/logic/Gaming/Game.cs b/logic/Gaming/Game.cs index be2506dc..aedda949 100755 --- a/logic/Gaming/Game.cs +++ b/logic/Gaming/Game.cs @@ -115,16 +115,7 @@ public bool StartGame(int milliSeconds) actionManager.AddMoneyNaturally(team); ActivateShip(team.TeamID, ShipType.CivilShip); } - new Thread - ( - () => - { - if (!gameMap.Timer.StartGame(milliSeconds)) - return; - EndGame(); // 游戏结束时要做的事 - } - ) - { IsBackground = true }.Start(); + gameMap.Timer.Start(() => { }, () => EndGame(), milliSeconds); return true; } public void EndGame() diff --git a/logic/Preparation/Interface/IMap.cs b/logic/Preparation/Interface/IMap.cs index 6a4cf884..84d8f166 100755 --- a/logic/Preparation/Interface/IMap.cs +++ b/logic/Preparation/Interface/IMap.cs @@ -5,7 +5,7 @@ namespace Preparation.Interface { public interface IMap { - ITimer Timer { get; } + IMyTimer Timer { get; } // the two dicts must have same keys Dictionary> GameObjDict { get; } diff --git a/logic/Preparation/Interface/ITimer.cs b/logic/Preparation/Interface/ITimer.cs deleted file mode 100755 index bbcaee20..00000000 --- a/logic/Preparation/Interface/ITimer.cs +++ /dev/null @@ -1,11 +0,0 @@ -using Preparation.Utility; - -namespace Preparation.Interface -{ - public interface ITimer - { - AtomicBool IsGaming { get; } - public int nowTime(); - public bool StartGame(int timeInMilliseconds); - } -} diff --git a/logic/Preparation/Utility/Value/SafeValue/MyTimer.cs b/logic/Preparation/Utility/Value/SafeValue/MyTimer.cs new file mode 100644 index 00000000..1a7be738 --- /dev/null +++ b/logic/Preparation/Utility/Value/SafeValue/MyTimer.cs @@ -0,0 +1,30 @@ +using System; +using System.Threading; + +namespace Preparation.Utility +{ + public class MyTimer : IMyTimer + { + private readonly AtomicLong startTime = new(long.MaxValue); + public int NowTime() => (int)(Environment.TickCount64 - startTime); + public bool IsGaming => startTime != long.MaxValue; + + public bool Start(Action start, Action end, int timeInMilliseconds) + { + start(); + if (startTime.CompareExROri(Environment.TickCount64, long.MaxValue) != long.MaxValue) + return false; + new Thread + ( + () => + { + Thread.Sleep(timeInMilliseconds); + startTime.SetROri(long.MaxValue); + end(); + } + ) + { IsBackground = true }.Start(); + return true; + } + } +} diff --git a/logic/Preparation/Utility/Value/ValueInterface/IMyTimer.cs b/logic/Preparation/Utility/Value/ValueInterface/IMyTimer.cs new file mode 100644 index 00000000..7294083c --- /dev/null +++ b/logic/Preparation/Utility/Value/ValueInterface/IMyTimer.cs @@ -0,0 +1,11 @@ +using System; + +namespace Preparation.Utility +{ + public interface IMyTimer + { + bool IsGaming { get; } + public int NowTime(); + public bool Start(Action start, Action end, int timeInMilliseconds); + } +} diff --git a/logic/Server/GameServer.cs b/logic/Server/GameServer.cs index 4ee277b8..6bfd1717 100755 --- a/logic/Server/GameServer.cs +++ b/logic/Server/GameServer.cs @@ -155,7 +155,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 d2544487014644027138985454fcc59d5097426a Mon Sep 17 00:00:00 2001 From: 964293341 Date: Thu, 25 Apr 2024 12:39:31 +0800 Subject: [PATCH 003/179] 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 004/179] 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 005/179] 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 006/179] 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 3be1a04ce4a84a6b6577d9eaa2219fb73e5ef85f Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Thu, 25 Apr 2024 21:20:26 +0800 Subject: [PATCH 007/179] feat: :zap: Compress the logs before too big to analyse. --- installer/Model/Downloader.cs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/installer/Model/Downloader.cs b/installer/Model/Downloader.cs index 0b8391fa..27da7f69 100755 --- a/installer/Model/Downloader.cs +++ b/installer/Model/Downloader.cs @@ -76,12 +76,19 @@ public Downloader() { Data = new Local_Data(); Log = LoggerProvider.FromFile(Path.Combine(Data.LogPath, "Main.log")); - if (Log.LastRecordTime != DateTime.MinValue && DateTime.Now.Month != Log.LastRecordTime.Month) + long size = 0; + foreach (var log in new DirectoryInfo(Data.LogPath).EnumerateFiles()) + { + size += log.Length; + } + // 检测到最近日志为上个月或日志总量达到10MB以上时压缩logs + if ((Log.LastRecordTime != DateTime.MinValue && DateTime.Now.Month != Log.LastRecordTime.Month) + || size >= (10 << 20)) { string tardir = Path.Combine(Data.Config.InstallPath, "LogArchieved"); if (!Directory.Exists(tardir)) Directory.CreateDirectory(tardir); - string tarPath = Path.Combine(tardir, $"Backup-{Log.LastRecordTime.Year}-{Log.LastRecordTime.Month}.tar"); + string tarPath = Path.Combine(tardir, $"LogBackup_{DateTime.Now:yyyy_MM_dd_HH_mm}.tar"); if (File.Exists(tarPath)) File.Delete(tarPath); if (File.Exists(tarPath + ".gz")) @@ -98,6 +105,8 @@ public Downloader() { File.Delete(log); } + if (Data.Log is FileLogger) ((FileLogger)Data.Log).Path = ((FileLogger)Data.Log).Path; + if (Log is FileLogger) ((FileLogger)Log).Path = ((FileLogger)Log).Path; } Route = Data.Config.InstallPath; Cloud = new Tencent_Cos("1319625962", "ap-beijing", "thuai7", From fb9d85fa96371c64940fc0cfb1d6c6ba18b8549e Mon Sep 17 00:00:00 2001 From: 964293341 Date: Thu, 25 Apr 2024 21:53:57 +0800 Subject: [PATCH 008/179] 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 009/179] 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 010/179] 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 011/179] 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 012/179] 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: Fri, 26 Apr 2024 21:07:11 +0000 Subject: [PATCH 013/179] chore(deps): update dependency microsoft.maui.controls to v8.0.21 --- installer/installer.csproj | 2 +- logic/Client/Client.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/installer/installer.csproj b/installer/installer.csproj index d3cad6d2..5f1a1213 100755 --- a/installer/installer.csproj +++ b/installer/installer.csproj @@ -91,7 +91,7 @@ - + diff --git a/logic/Client/Client.csproj b/logic/Client/Client.csproj index 78cddb44..ab2ad8ba 100755 --- a/logic/Client/Client.csproj +++ b/logic/Client/Client.csproj @@ -79,7 +79,7 @@ - + From 3648d207afb61d56689e906c62b94aff3e45c88d Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sat, 27 Apr 2024 04:47:46 +0000 Subject: [PATCH 014/179] chore(deps): update dependency grpcio-tools to v1.62.2 --- CAPI/python/requirements.txt | 2 +- CAPI/python_exp/requirements.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CAPI/python/requirements.txt b/CAPI/python/requirements.txt index 9991b533..a5dab242 100644 --- a/CAPI/python/requirements.txt +++ b/CAPI/python/requirements.txt @@ -1,3 +1,3 @@ grpcio==1.62.2 -grpcio-tools==1.54.2 +grpcio-tools==1.62.2 numpy diff --git a/CAPI/python_exp/requirements.txt b/CAPI/python_exp/requirements.txt index 9991b533..a5dab242 100644 --- a/CAPI/python_exp/requirements.txt +++ b/CAPI/python_exp/requirements.txt @@ -1,3 +1,3 @@ grpcio==1.62.2 -grpcio-tools==1.54.2 +grpcio-tools==1.62.2 numpy From cbade2830acea21f6ffb356d129da93af28a6c20 Mon Sep 17 00:00:00 2001 From: DragonAura <32223554+DragonAura@users.noreply.github.com> Date: Sat, 27 Apr 2024 13:40:27 +0800 Subject: [PATCH 015/179] fix: update logic.py --- CAPI/python/PyAPI/logic.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CAPI/python/PyAPI/logic.py b/CAPI/python/PyAPI/logic.py index 1b8a5ff1..54be0ba3 100644 --- a/CAPI/python/PyAPI/logic.py +++ b/CAPI/python/PyAPI/logic.py @@ -107,7 +107,7 @@ def GetGameInfo(self) -> THUAI7.GameInfo: def Move(self, time: int, angle: float) -> bool: self.__logger.debug("Called Move") - return self.__comm.Move(time, angle, self.__playerID) + return self.__comm.Move(time, angle, self.__playerID, self.__teamID) def SendMessage(self, toID: int, message: Union[str, bytes]) -> bool: self.__logger.debug("Called SendMessage") From 78a05f79a07f9e495eddb48b5dc9b9d7800a1a86 Mon Sep 17 00:00:00 2001 From: DragonAura <32223554+DragonAura@users.noreply.github.com> Date: Sat, 27 Apr 2024 13:40:54 +0800 Subject: [PATCH 016/179] Update Communication.py --- CAPI/python/PyAPI/Communication.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CAPI/python/PyAPI/Communication.py b/CAPI/python/PyAPI/Communication.py index d24fccea..d5c785fe 100644 --- a/CAPI/python/PyAPI/Communication.py +++ b/CAPI/python/PyAPI/Communication.py @@ -30,7 +30,7 @@ def __init__(self, sIP: str, sPort: str): self.__limit = 50 self.__moveLimit = 10 - def Move(self, time: int, angle: float, playerID: int) -> bool: + def Move(self, time: int, angle: float, playerID: int, teamID: int) -> bool: try: with self.__mtxLimit: if ( @@ -41,7 +41,7 @@ def Move(self, time: int, angle: float, playerID: int) -> bool: self.__counter += 1 self.__counterMove += 1 moveResult: Message2Clients.MoveRes = self.__THUAI7Stub.Move( - THUAI72Proto.THUAI72ProtobufMoveMsg(time, angle, playerID) + THUAI72Proto.THUAI72ProtobufMoveMsg(playerID, teamID, time, angle) ) except grpc.RpcError: return False From c2c496f24f8088dffc70e063e003c2325fff72e5 Mon Sep 17 00:00:00 2001 From: sigureling <1678348940@qq.com> Date: Sat, 27 Apr 2024 14:53:41 +0800 Subject: [PATCH 017/179] feat: :bug: Update logic.py --- CAPI/python/PyAPI/logic.py | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/CAPI/python/PyAPI/logic.py b/CAPI/python/PyAPI/logic.py index 54be0ba3..6c608088 100644 --- a/CAPI/python/PyAPI/logic.py +++ b/CAPI/python/PyAPI/logic.py @@ -248,7 +248,7 @@ def InstallModule(self, moduleType: THUAI7.ModuleType) -> bool: def Recycle(self) -> bool: self.__logger.debug("Called Recycle") - return self.__comm.Recycle(self.__playerID, self.__playerID, self.__teamID) + return self.__comm.Recycle(self.__playerID, self.__teamID) def BuildShip(self, shipType: THUAI7.ShipType, birthIndex: int) -> bool: self.__logger.debug("Called BuildShip") @@ -356,7 +356,10 @@ def __LoadBufferSelf(self, message: Message2Clients.MessageToClient) -> None: if self.__playerType == THUAI7.PlayerType.Ship: for item in message.obj_message: if item.WhichOneof("message_of_obj") == "ship_message": - if item.ship_message.player_id == self.__playerID and item.ship_message.team_id == self.__teamID: + if ( + item.ship_message.player_id == self.__playerID + and item.ship_message.team_id == self.__teamID + ): self.__bufferState.self = Proto2THUAI7.Protobuf2THUAI7Ship( item.ship_message ) @@ -364,7 +367,10 @@ def __LoadBufferSelf(self, message: Message2Clients.MessageToClient) -> None: self.__logger.debug("Load self ship") else: for item in message.obj_message: - if item.WhichOneof("message_of_obj") == "team_message" and item.team_message.team_id==self.__teamID: + if ( + item.WhichOneof("message_of_obj") == "team_message" + and item.team_message.team_id == self.__teamID + ): self.__bufferState.self = Proto2THUAI7.Protobuf2THUAI7Team( item.team_message ) @@ -399,13 +405,16 @@ def __LoadBufferCase(self, item: Message2Clients.MessageOfObj) -> None: self.__logger.debug("Load ship") elif item.WhichOneof("message_of_obj") == "bullet_message": - if item.bullet_message.team_id!=self.__teamID and AssistFunction.HaveView( - self.__bufferState.self.viewRange, - self.__bufferState.self.x, - self.__bufferState.self.y, - item.bullet_message.x, - item.bullet_message.y, - self.__bufferState.gameMap, + if ( + item.bullet_message.team_id != self.__teamID + and AssistFunction.HaveView( + self.__bufferState.self.viewRange, + self.__bufferState.self.x, + self.__bufferState.self.y, + item.bullet_message.x, + item.bullet_message.y, + self.__bufferState.gameMap, + ) ): self.__bufferState.bullets.append( Proto2THUAI7.Protobuf2THUAI7Bullet(item.bullet_message) From a87c1299926eb86e357da33ea2b36fec0bebe490 Mon Sep 17 00:00:00 2001 From: DragonAura <32223554+DragonAura@users.noreply.github.com> Date: Sat, 27 Apr 2024 18:00:04 +0800 Subject: [PATCH 018/179] fix: update logic.py --- CAPI/python/PyAPI/logic.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/CAPI/python/PyAPI/logic.py b/CAPI/python/PyAPI/logic.py index 6c608088..5b1569bc 100644 --- a/CAPI/python/PyAPI/logic.py +++ b/CAPI/python/PyAPI/logic.py @@ -242,13 +242,13 @@ def Construct(self, constructionType: THUAI7.ConstructionType) -> bool: self.__logger.debug("Called Construct") return self.__comm.Construct(constructionType, self.__playerID, self.__teamID) - def InstallModule(self, moduleType: THUAI7.ModuleType) -> bool: + def InstallModule(self, playerID: int, moduleType: THUAI7.ModuleType) -> bool: self.__logger.debug("Called InstallModule") - return self.__comm.InstallModule(moduleType, self.__playerID, self.__teamID) + return self.__comm.InstallModule(moduleType, playerID, self.__teamID) - def Recycle(self) -> bool: + def Recycle(self, playerID: int) -> bool: self.__logger.debug("Called Recycle") - return self.__comm.Recycle(self.__playerID, self.__teamID) + return self.__comm.Recycle(playerID, self.__teamID) def BuildShip(self, shipType: THUAI7.ShipType, birthIndex: int) -> bool: self.__logger.debug("Called BuildShip") From f9649281527d573184e84f27e4f8a94e2eb30368 Mon Sep 17 00:00:00 2001 From: Xuc Pan Date: Sat, 27 Apr 2024 18:04:28 +0800 Subject: [PATCH 019/179] fix: :bug: installModule return wrong money --- logic/GameClass/GameObj/Ship.cs | 36 ++++++++++++++++++++------------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/logic/GameClass/GameObj/Ship.cs b/logic/GameClass/GameObj/Ship.cs index a0bf7fd8..496ba8da 100755 --- a/logic/GameClass/GameObj/Ship.cs +++ b/logic/GameClass/GameObj/Ship.cs @@ -94,45 +94,48 @@ public bool InstallModule(ModuleType moduleType) case ModuleType.Producer1: if (ProducerModuleType != ProducerType.Producer1) { - SubMoney( - ProducerModule.SetROri( - ModuleFactory.FindIProducer(ShipType, ProducerType.Producer1) - ).Cost); + ProducerModule.SetROri(ModuleFactory.FindIProducer(ShipType, ProducerType.Producer1)); + SubMoney(ProducerModule.Get().Cost); return true; } break; case ModuleType.Producer2: if (ProducerModuleType != ProducerType.Producer2) { - SubMoney(ProducerModule.SetROri(ModuleFactory.FindIProducer(ShipType, ProducerType.Producer2)).Cost); + ProducerModule.SetROri(ModuleFactory.FindIProducer(ShipType, ProducerType.Producer2)); + SubMoney(ProducerModule.Get().Cost); return true; } break; case ModuleType.Producer3: if (ProducerModuleType != ProducerType.Producer3) { - SubMoney(ProducerModule.SetROri(ModuleFactory.FindIProducer(ShipType, ProducerType.Producer3)).Cost); + ProducerModule.SetROri(ModuleFactory.FindIProducer(ShipType, ProducerType.Producer3)); + SubMoney(ProducerModule.Get().Cost); return true; } break; case ModuleType.Constructor1: if (ConstructorModuleType != ConstructorType.Constructor1) { - SubMoney(ConstructorModule.SetROri(ModuleFactory.FindIConstructor(ShipType, ConstructorType.Constructor1)).Cost); + ConstructorModule.SetROri(ModuleFactory.FindIConstructor(ShipType, ConstructorType.Constructor1)); + SubMoney(ConstructorModule.Get().Cost); return true; } break; case ModuleType.Constructor2: if (ConstructorModuleType != ConstructorType.Constructor2) { - SubMoney(ConstructorModule.SetROri(ModuleFactory.FindIConstructor(ShipType, ConstructorType.Constructor2)).Cost); + ConstructorModule.SetROri(ModuleFactory.FindIConstructor(ShipType, ConstructorType.Constructor2)); + SubMoney(ConstructorModule.Get().Cost); return true; } break; case ModuleType.Constructor3: if (ConstructorModuleType != ConstructorType.Constructor3) { - SubMoney(ConstructorModule.SetROri(ModuleFactory.FindIConstructor(ShipType, ConstructorType.Constructor3)).Cost); + ConstructorModule.SetROri(ModuleFactory.FindIConstructor(ShipType, ConstructorType.Constructor3)); + SubMoney(ConstructorModule.Get().Cost); return true; } break; @@ -198,14 +201,16 @@ public bool InstallModule(ModuleType moduleType) case ModuleType.LaserGun: if (WeaponModuleType != WeaponType.LaserGun) { - SubMoney(WeaponModule.SetROri(ModuleFactory.FindIWeapon(ShipType, WeaponType.LaserGun)).Cost); + WeaponModule.SetROri(ModuleFactory.FindIWeapon(ShipType, WeaponType.LaserGun)); + SubMoney(WeaponModule.Get().Cost); return true; } break; case ModuleType.PlasmaGun: if (WeaponModuleType != WeaponType.PlasmaGun) { - SubMoney(WeaponModule.SetROri(ModuleFactory.FindIWeapon(ShipType, WeaponType.PlasmaGun)).Cost); + WeaponModule.SetROri(ModuleFactory.FindIWeapon(ShipType, WeaponType.PlasmaGun)); + SubMoney(WeaponModule.Get().Cost); return true; } break; @@ -213,7 +218,8 @@ public bool InstallModule(ModuleType moduleType) case ModuleType.ShellGun: if (WeaponModuleType != WeaponType.ShellGun) { - SubMoney(WeaponModule.SetROri(ModuleFactory.FindIWeapon(ShipType, WeaponType.ShellGun)).Cost); + WeaponModule.SetROri(ModuleFactory.FindIWeapon(ShipType, WeaponType.ShellGun)); + SubMoney(WeaponModule.Get().Cost); return true; } break; @@ -221,7 +227,8 @@ public bool InstallModule(ModuleType moduleType) case ModuleType.MissileGun: if (WeaponModuleType != WeaponType.MissileGun) { - SubMoney(WeaponModule.SetROri(ModuleFactory.FindIWeapon(ShipType, WeaponType.MissileGun)).Cost); + WeaponModule.SetROri(ModuleFactory.FindIWeapon(ShipType, WeaponType.MissileGun)); + SubMoney(WeaponModule.Get().Cost); return true; } break; @@ -229,7 +236,8 @@ public bool InstallModule(ModuleType moduleType) case ModuleType.ArcGun: if (WeaponModuleType != WeaponType.ArcGun) { - SubMoney(WeaponModule.SetROri(ModuleFactory.FindIWeapon(ShipType, WeaponType.ArcGun)).Cost); + WeaponModule.SetROri(ModuleFactory.FindIWeapon(ShipType, WeaponType.ArcGun)); + SubMoney(WeaponModule.Get().Cost); return true; } break; From 3df7e583cda236118e0c7aef523bb59ca12d873f Mon Sep 17 00:00:00 2001 From: 964293341 Date: Sat, 27 Apr 2024 20:18:37 +0800 Subject: [PATCH 020/179] 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 103d7c81067ed4aabf97dbe7d0a49754b1690969 Mon Sep 17 00:00:00 2001 From: Xuc Pan Date: Sat, 27 Apr 2024 20:20:01 +0800 Subject: [PATCH 021/179] fix: :bug: fort attack everyone --- logic/GameClass/GameObj/Map/Map.cs | 4 ++-- logic/Gaming/ActionManager.cs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/logic/GameClass/GameObj/Map/Map.cs b/logic/GameClass/GameObj/Map/Map.cs index 201b0b21..88cf3e8f 100755 --- a/logic/GameClass/GameObj/Map/Map.cs +++ b/logic/GameClass/GameObj/Map/Map.cs @@ -110,10 +110,10 @@ public static bool WormholeInteract(Wormhole gameObj, XY Pos) return (GameObj?)GameObjDict[gameObjType].Find(gameObj => GameData.IsInTheRange(gameObj.Position, Pos, range)); } - public List? ShipInTheRange(XY Pos, int range) + public List? ShipInTheRangeNotTeamID(XY Pos, int range, long teamID) { return GameObjDict[GameObjType.Ship].Cast()?.FindAll(ship => - GameData.IsInTheRange(ship.Position, Pos, range)); + (GameData.IsInTheRange(ship.Position, Pos, range) && ship.TeamID != teamID)); } public List? ShipInTheList(List PosList) { diff --git a/logic/Gaming/ActionManager.cs b/logic/Gaming/ActionManager.cs index 7fa2daec..d88b96d1 100755 --- a/logic/Gaming/ActionManager.cs +++ b/logic/Gaming/ActionManager.cs @@ -203,8 +203,8 @@ public bool Construct(Ship ship, ConstructionType constructionType) gameMap.Timer.IsGaming && !construction.HP.IsBelowMaxTimes(0.5), loopToDo: () => { - var ships = gameMap.ShipInTheRange( - construction.Position, GameData.FortRange); + var ships = gameMap.ShipInTheRangeNotTeamID( + construction.Position, GameData.FortRange, construction.TeamID); if (ships == null || ships.Count == 0) { return true; From 87fc9559cc3e092d12dbe773df158108591c6606 Mon Sep 17 00:00:00 2001 From: GuoWQ222 Date: Sat, 27 Apr 2024 20:24:45 +0800 Subject: [PATCH 022/179] BUG --- CAPI/cpp/API/src/Communication.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CAPI/cpp/API/src/Communication.cpp b/CAPI/cpp/API/src/Communication.cpp index bf088e5f..d1cb86b5 100755 --- a/CAPI/cpp/API/src/Communication.cpp +++ b/CAPI/cpp/API/src/Communication.cpp @@ -202,7 +202,7 @@ bool Communication::BuildShip(int32_t teamID, THUAI7::ShipType ShipType, int32_t auto request = THUAI72Proto::THUAI72ProtobufBuildShipMsg(teamID, ShipType, birthIndex); auto status = THUAI7Stub->BuildShip(&context, request, &reply); if (status.ok()) - return true; + return reply.act_success(); else return false; } From 66d626f80187ab5d7688f9323489a2ca0d1eb417 Mon Sep 17 00:00:00 2001 From: 964293341 Date: Sat, 27 Apr 2024 20:26:12 +0800 Subject: [PATCH 023/179] 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; From 5f34135c6f851c0212927b052ddd1ee913af7ecc Mon Sep 17 00:00:00 2001 From: shangfengh <3495281661@qq.com> Date: Sat, 27 Apr 2024 20:59:40 +0800 Subject: [PATCH 024/179] feat(SafeValue): :sparkles: MyTimer add a method --- .../Utility/Value/SafeValue/MyTimer.cs | 59 +++++++++++++++---- .../Utility/Value/ValueInterface/IAddable.cs | 2 +- .../Utility/Value/ValueInterface/IDouble.cs | 2 +- 3 files changed, 49 insertions(+), 14 deletions(-) diff --git a/logic/Preparation/Utility/Value/SafeValue/MyTimer.cs b/logic/Preparation/Utility/Value/SafeValue/MyTimer.cs index 1a7be738..921554b0 100644 --- a/logic/Preparation/Utility/Value/SafeValue/MyTimer.cs +++ b/logic/Preparation/Utility/Value/SafeValue/MyTimer.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 { public class MyTimer : IMyTimer { @@ -9,21 +10,55 @@ public class MyTimer : IMyTimer public int NowTime() => (int)(Environment.TickCount64 - startTime); public bool IsGaming => startTime != long.MaxValue; + public bool Start(Action start, Action endBefore, Action endAfter, int timeInMilliseconds) + { + start(); + if (startTime.CompareExROri(Environment.TickCount64, long.MaxValue) != long.MaxValue) + return false; + try + { + new Thread + ( + () => + { + Thread.Sleep(timeInMilliseconds); + endBefore(); + startTime.SetROri(long.MaxValue); + endAfter(); + } + ) + { IsBackground = true }.Start(); + } + catch (Exception ex) + { + startTime.SetROri(long.MaxValue); + Console.WriteLine(ex.Message); + } + return true; + } public bool Start(Action start, Action end, int timeInMilliseconds) { start(); if (startTime.CompareExROri(Environment.TickCount64, long.MaxValue) != long.MaxValue) return false; - new Thread - ( - () => - { - Thread.Sleep(timeInMilliseconds); - startTime.SetROri(long.MaxValue); - end(); - } - ) - { IsBackground = true }.Start(); + try + { + new Thread + ( + () => + { + Thread.Sleep(timeInMilliseconds); + startTime.SetROri(long.MaxValue); + end(); + } + ) + { IsBackground = true }.Start(); + } + catch (Exception ex) + { + startTime.SetROri(long.MaxValue); + Console.WriteLine(ex.Message); + } return true; } } diff --git a/logic/Preparation/Utility/Value/ValueInterface/IAddable.cs b/logic/Preparation/Utility/Value/ValueInterface/IAddable.cs index 81c125cc..175eb6d8 100644 --- a/logic/Preparation/Utility/Value/ValueInterface/IAddable.cs +++ b/logic/Preparation/Utility/Value/ValueInterface/IAddable.cs @@ -1,4 +1,4 @@ -namespace Preparation.Interface +namespace Preparation.Utility { public interface IAddable { diff --git a/logic/Preparation/Utility/Value/ValueInterface/IDouble.cs b/logic/Preparation/Utility/Value/ValueInterface/IDouble.cs index f6ca8639..a2c2f206 100644 --- a/logic/Preparation/Utility/Value/ValueInterface/IDouble.cs +++ b/logic/Preparation/Utility/Value/ValueInterface/IDouble.cs @@ -1,4 +1,4 @@ -namespace Preparation.Interface +namespace Preparation.Utility { public interface IDouble { From cb44e8b9afafe6bfaffa301bd025e23f2b1702fe Mon Sep 17 00:00:00 2001 From: ONLOX <3316820553@qq.com> Date: Sat, 27 Apr 2024 21:31:41 +0800 Subject: [PATCH 025/179] feat: :alien: add spectator checkbox --- installer/Page/DebugPage.xaml | 16 +++++++++- installer/ViewModel/DebugViewModel.cs | 44 +++++++++++++++++++++------ 2 files changed, 50 insertions(+), 10 deletions(-) diff --git a/installer/Page/DebugPage.xaml b/installer/Page/DebugPage.xaml index 5e1a4536..2ae7f171 100644 --- a/installer/Page/DebugPage.xaml +++ b/installer/Page/DebugPage.xaml @@ -146,6 +146,20 @@ + + + - public class InVariableRangeOnlyAddScore(T value, T maxValue, double speed = 1.0) : InVariableRange(value, maxValue), IIntAddable, IAddable + public class InVariableRangeOnlyAddScore(T value, T maxValue, double speed = 1.0) : InVariableRange(value, maxValue) where T : IConvertible, IComparable, INumber { private IIntAddable score = new AtomicInt(0); diff --git a/logic/Preparation/Utility/Value/SafeValue/LockedValue/LockedDouble.cs b/logic/Preparation/Utility/Value/SafeValue/LockedValue/LockedDouble.cs index 9b3163cd..e790f732 100644 --- a/logic/Preparation/Utility/Value/SafeValue/LockedValue/LockedDouble.cs +++ b/logic/Preparation/Utility/Value/SafeValue/LockedValue/LockedDouble.cs @@ -1,11 +1,99 @@ using Preparation.Interface; +using System; namespace Preparation.Utility.Value.SafeValue.LockedValue { - public class LockedDouble(double x) : LockedValue, IDouble + public class LockedDouble(double x) : LockedValue, IDouble, IConvertible { private double v = x; + #region 实现IConvertible接口 + public TypeCode GetTypeCode() + { + return ReadNeed(() => v.GetTypeCode()); + } + + public bool ToBoolean(IFormatProvider? provider) + { + return ReadNeed(() => Convert.ToBoolean(v, provider)); + } + + public char ToChar(IFormatProvider? provider) + { + return ReadNeed(() => Convert.ToChar(v, provider)); + } + + public sbyte ToSByte(IFormatProvider? provider) + { + return ReadNeed(() => Convert.ToSByte(v, provider)); + } + + public byte ToByte(IFormatProvider? provider) + { + return ReadNeed(() => Convert.ToByte(v, provider)); + } + + public short ToInt16(IFormatProvider? provider) + { + return ReadNeed(() => Convert.ToInt16(v, provider)); + } + + public ushort ToUInt16(IFormatProvider? provider) + { + return ReadNeed(() => Convert.ToUInt16(v, provider)); + } + + public int ToInt32(IFormatProvider? provider) + { + return ReadNeed(() => Convert.ToInt32(v, provider)); + } + + public uint ToUInt32(IFormatProvider? provider) + { + return ReadNeed(() => Convert.ToUInt32(v, provider)); + } + + public long ToInt64(IFormatProvider? provider) + { + return ReadNeed(() => Convert.ToInt64(v, provider)); + } + + public ulong ToUInt64(IFormatProvider? provider) + { + return ReadNeed(() => Convert.ToUInt64(v, provider)); + } + + public float ToSingle(IFormatProvider? provider) + { + return ReadNeed(() => Convert.ToSingle(v, provider)); + } + + public double ToDouble(IFormatProvider? provider) + { + return ReadNeed(() => v); + } + + public decimal ToDecimal(IFormatProvider? provider) + { + return ReadNeed(() => Convert.ToDecimal(v, provider)); + } + + public DateTime ToDateTime(IFormatProvider? provider) + { + return ReadNeed(() => Convert.ToDateTime(v, provider)); + } + + public string ToString(IFormatProvider? provider) + { + return ReadNeed(() => v.ToString(provider)); + } + + public object ToType(Type conversionType, IFormatProvider? provider) + { + return ReadNeed(() => Convert.ChangeType(v, conversionType, provider)); + } + #endregion + public override string ToString() { return ReadNeed(() => v.ToString()); @@ -16,6 +104,14 @@ public double Get() } public double ToDouble() => Get(); public static implicit operator double(LockedDouble adouble) => adouble.Get(); + public override bool Equals(object? obj) + { + return obj != null && (obj is IConvertible k) && ToDouble(null) == k.ToDouble(null); + } + public override int GetHashCode() + { + return ReadNeed(() => v.GetHashCode()); + } public void Set(double value) { diff --git a/logic/Preparation/Utility/Value/SafeValue/LockedValue/PositiveV.cs b/logic/Preparation/Utility/Value/SafeValue/LockedValue/PositiveV.cs index 001cc5da..97b4e182 100644 --- a/logic/Preparation/Utility/Value/SafeValue/LockedValue/PositiveV.cs +++ b/logic/Preparation/Utility/Value/SafeValue/LockedValue/PositiveV.cs @@ -10,10 +10,97 @@ namespace Preparation.Utility.Value.SafeValue.LockedValue /// 建议使用类似[0,int.MaxValue]的InVariableRange /// 其对应属性不应当有set访问器,避免不安全的=赋值 /// - public class PositiveValue : LockedValue, IIntAddable, IAddable + public class PositiveValue : LockedValue, IIntAddable, IAddable, IConvertible where T : IConvertible, IComparable, INumber { protected T v; + + #region 实现IConvertible接口 + public TypeCode GetTypeCode() + { + return ReadNeed(() => v.GetTypeCode()); + } + + public bool ToBoolean(IFormatProvider? provider) + { + return ReadNeed(() => v.ToBoolean(provider)); + } + public byte ToByte(IFormatProvider? provider) + { + return ReadNeed(() => v.ToByte(provider)); + } + + public char ToChar(IFormatProvider? provider) + { + return ReadNeed(() => v.ToChar(provider)); + } + + public DateTime ToDateTime(IFormatProvider? provider) + { + return ReadNeed(() => v.ToDateTime(provider)); + } + + public decimal ToDecimal(IFormatProvider? provider) + { + return ReadNeed(() => v.ToDecimal(provider)); + } + + public double ToDouble(IFormatProvider? provider) + { + return ReadNeed(() => v.ToDouble(provider)); + } + + public short ToInt16(IFormatProvider? provider) + { + return ReadNeed(() => v.ToInt16(provider)); + } + + public int ToInt32(IFormatProvider? provider) + { + return ReadNeed(() => v.ToInt32(provider)); + } + + public long ToInt64(IFormatProvider? provider) + { + return ReadNeed(() => v.ToInt64(provider)); + } + + public sbyte ToSByte(IFormatProvider? provider) + { + return ReadNeed(() => v.ToSByte(provider)); + } + + public float ToSingle(IFormatProvider? provider) + { + return ReadNeed(() => v.ToSingle(provider)); + } + + public string ToString(IFormatProvider? provider) + { + return ReadNeed(() => v.ToString(provider)); + } + + public object ToType(Type conversionType, IFormatProvider? provider) + { + return ReadNeed(() => v.ToType(conversionType, provider)); + } + + public ushort ToUInt16(IFormatProvider? provider) + { + return ReadNeed(() => v.ToUInt16(provider)); + } + + public uint ToUInt32(IFormatProvider? provider) + { + return ReadNeed(() => v.ToUInt32(provider)); + } + + public ulong ToUInt64(IFormatProvider? provider) + { + return ReadNeed(() => v.ToUInt64(provider)); + } + #endregion + #region 构造与读取 public PositiveValue(T value) : base() { @@ -35,6 +122,14 @@ public override string ToString() } public T Get() { return ReadNeed(() => v); } public static implicit operator T(PositiveValue aint) => aint.Get(); + public override bool Equals(object? obj) + { + return obj != null && (obj is IConvertible k) && ToDouble(null) == k.ToDouble(null); + } + public override int GetHashCode() + { + return ReadNeed(() => v.GetHashCode()); + } public bool IsZero() { return ReadNeed(() => v == T.Zero); } #endregion diff --git a/logic/Preparation/Utility/Value/SafeValue/TimeBased.cs b/logic/Preparation/Utility/Value/SafeValue/TimeBased.cs index 9b4d955e..d75bc234 100644 --- a/logic/Preparation/Utility/Value/SafeValue/TimeBased.cs +++ b/logic/Preparation/Utility/Value/SafeValue/TimeBased.cs @@ -16,7 +16,7 @@ public static class TimeBasedLogging /// 记录上次Start的时间,尚未Start则为long.MaxValue /// 当前不为long.MaxValue则不能Start /// - public class StartTime + public class StartTime : IConvertible { private long _time; public StartTime(long time) @@ -24,8 +24,106 @@ public StartTime(long time) _time = time; } public StartTime() { _time = long.MaxValue; } + + #region 实现IConvertible接口 + + public TypeCode GetTypeCode() + { + return TypeCode.Int64; + } + + public bool ToBoolean(IFormatProvider? provider) + { + return Convert.ToBoolean(Get(), provider); + } + + public char ToChar(IFormatProvider? provider) + { + return Convert.ToChar(Get(), provider); + } + + public sbyte ToSByte(IFormatProvider? provider) + { + return Convert.ToSByte(Get(), provider); + } + + public byte ToByte(IFormatProvider? provider) + { + return Convert.ToByte(Get(), provider); + } + + public short ToInt16(IFormatProvider? provider) + { + return Convert.ToInt16(Get(), provider); + } + + public ushort ToUInt16(IFormatProvider? provider) + { + return Convert.ToUInt16(Get(), provider); + } + + public int ToInt32(IFormatProvider? provider) + { + return Convert.ToInt32(Get(), provider); + } + + public uint ToUInt32(IFormatProvider? provider) + { + return Convert.ToUInt32(Get(), provider); + } + + public long ToInt64(IFormatProvider? provider) + { + return Convert.ToInt64(Get(), provider); + } + + public ulong ToUInt64(IFormatProvider? provider) + { + return Convert.ToUInt64(Get(), provider); + } + + public float ToSingle(IFormatProvider? provider) + { + return Convert.ToSingle(Get(), provider); + } + + public double ToDouble(IFormatProvider? provider) + { + return Get(); + } + + public decimal ToDecimal(IFormatProvider? provider) + { + return Convert.ToDecimal(Get(), provider); + } + + public DateTime ToDateTime(IFormatProvider? provider) + { + return Convert.ToDateTime(Get(), provider); + } + + public string ToString(IFormatProvider? provider) + { + return Get().ToString(provider); + } + + public object ToType(Type conversionType, IFormatProvider? provider) + { + return Convert.ChangeType(Get(), conversionType, provider); + } + #endregion + public long Get() => Interlocked.CompareExchange(ref _time, -2, -2); public override string ToString() => Get().ToString(); + public override bool Equals(object? obj) + { + return obj != null && (obj is IConvertible k) && ToDouble(null) == k.ToDouble(null); + } + public override int GetHashCode() + { + return Get().GetHashCode(); + } + /// 返回操作前的值 public long Start() => Interlocked.CompareExchange(ref _time, Environment.TickCount64, long.MaxValue); /// 返回操作前的值 diff --git a/logic/Preparation/Utility/Value/ValueInterface/IReturnClass.cs b/logic/Preparation/Utility/Value/ValueInterface/IReturnClass.cs new file mode 100644 index 00000000..8cd1ee40 --- /dev/null +++ b/logic/Preparation/Utility/Value/ValueInterface/IReturnClass.cs @@ -0,0 +1,7 @@ +namespace Preparation.Utility +{ + public interface IReturnClass + { + public T? Get(); + } +} From 5ba1f4b7f597f2d344b4b850774c522b5ad5046d Mon Sep 17 00:00:00 2001 From: xiangmy21 <90919434+xiangmy21@users.noreply.github.com> Date: Wed, 1 May 2024 20:17:07 +0800 Subject: [PATCH 055/179] Update compile.sh --- dependency/shell/compile.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dependency/shell/compile.sh b/dependency/shell/compile.sh index c616ba85..d87eddb9 100644 --- a/dependency/shell/compile.sh +++ b/dependency/shell/compile.sh @@ -25,7 +25,7 @@ else fi if [ $flag -eq 1 ]; then - curl $URL -X POST -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" -d '{"compile_status":"Success"}' > $output/$base_name.curl.log + curl $URL -X POST -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" -d '{"compile_status":"Completed"}' > $output/$base_name.curl.log else curl $URL -X POST -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" -d '{"compile_status":"Failed"}' > $output/$base_name.curl.log fi From 4fe2090b5e2dfec390af778b1f17d288780553dd Mon Sep 17 00:00:00 2001 From: DragonAura Date: Thu, 2 May 2024 20:27:32 +0800 Subject: [PATCH 056/179] fix: :bug: fix wrong obj & update allGuids --- CAPI/cpp/API/include/state.h | 2 +- CAPI/cpp/API/src/logic.cpp | 6 +++--- CAPI/python/PyAPI/State.py | 4 ++-- CAPI/python/PyAPI/logic.py | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/CAPI/cpp/API/include/state.h b/CAPI/cpp/API/include/state.h index 6c45942f..3c90c746 100755 --- a/CAPI/cpp/API/include/state.h +++ b/CAPI/cpp/API/include/state.h @@ -25,7 +25,7 @@ struct State std::shared_ptr mapInfo; std::shared_ptr gameInfo; std::vector guids; - std::vector guids_all; + std::vector allGuids; }; #endif diff --git a/CAPI/cpp/API/src/logic.cpp b/CAPI/cpp/API/src/logic.cpp index b12a0f43..470e7f20 100755 --- a/CAPI/cpp/API/src/logic.cpp +++ b/CAPI/cpp/API/src/logic.cpp @@ -821,14 +821,14 @@ void Logic::LoadBuffer(const protobuf::MessageToClient& message) bufferState->enemyShips.clear(); bufferState->bullets.clear(); bufferState->guids.clear(); - bufferState->guids_all.clear(); + bufferState->allGuids.clear(); logger->info("Buffer cleared!"); // 读取新的信息 for (const auto& obj : message.obj_message()) if (Proto2THUAI7::messageOfObjDict[obj.message_of_obj_case()] == THUAI7::MessageOfObj::ShipMessage) { - bufferState->guids_all.push_back(obj.ship_message().guid()); - if (obj.obj.ship_message().team_id() == teamID) + bufferState->allGuids.push_back(obj.ship_message().guid()); + if (obj.ship_message().team_id() == teamID) bufferState->guids.push_back(obj.ship_message().guid()); } bufferState->gameInfo = Proto2THUAI7::Protobuf2THUAI7GameInfo(message.all_message()); diff --git a/CAPI/python/PyAPI/State.py b/CAPI/python/PyAPI/State.py index c47bc884..fed99139 100644 --- a/CAPI/python/PyAPI/State.py +++ b/CAPI/python/PyAPI/State.py @@ -14,7 +14,7 @@ def __init__(self) -> None: self.mapInfo = THUAI7.GameMap() self.gameInfo = THUAI7.GameInfo() self.guids = [] - self.guids_all = [] + self.allGuids = [] teamScore: int self: Union[THUAI7.Ship, THUAI7.Team] @@ -32,4 +32,4 @@ def __init__(self) -> None: gameInfo: THUAI7.GameInfo guids: List[int] - guids_all: List[int] + allGuids: List[int] diff --git a/CAPI/python/PyAPI/logic.py b/CAPI/python/PyAPI/logic.py index 2ccc5d36..0e7dbf61 100644 --- a/CAPI/python/PyAPI/logic.py +++ b/CAPI/python/PyAPI/logic.py @@ -314,12 +314,12 @@ def __LoadBuffer(self, message: Message2Clients.MessageToClient) -> None: self.__bufferState.bullets.clear() self.__bufferState.bombedBullets.clear() self.__bufferState.guids.clear() - self.__bufferState.guids_all.clear() + self.__bufferState.allGuids.clear() self.__logger.debug("Buffer cleared") for obj in message.obj_message: if obj.WhichOneof("message_of_obj") == "ship_message": - self.__bufferState.guids_all.append(obj.ship_message.guid) + self.__bufferState.allGuids.append(obj.ship_message.guid) if obj.ship_message.team_id == self.__teamID: self.__bufferState.guids.append(obj.ship_message.guid) From 69e89b30cc70ef38c518119e8867c2290ce0de9c Mon Sep 17 00:00:00 2001 From: 964293341 Date: Fri, 3 May 2024 13:07:34 +0800 Subject: [PATCH 057/179] fix(PyAPI): :bug: add energy & homehp copy from proto to `gameInfo` --- CAPI/python/PyAPI/utils.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CAPI/python/PyAPI/utils.py b/CAPI/python/PyAPI/utils.py index 913fe8ac..4ed820af 100644 --- a/CAPI/python/PyAPI/utils.py +++ b/CAPI/python/PyAPI/utils.py @@ -280,6 +280,10 @@ def Protobuf2THUAI7GameInfo( gameInfo.gameTime = allMsg.game_time gameInfo.redScore = allMsg.red_team_score gameInfo.blueScore = allMsg.blue_team_score + gameInfo.redEnergy = allMsg.red_team_energy + gameInfo.blueEnergy = allMsg.blue_team_energy + gameInfo.redHomeHp = allMsg.red_home_hp + gameInfo.blueHomeHp = allMsg.blue_home_hp return gameInfo From 146e15ded60b465f1a4d495aafb3124598377308 Mon Sep 17 00:00:00 2001 From: DragonAura <32223554+DragonAura@users.noreply.github.com> Date: Fri, 3 May 2024 13:38:45 +0800 Subject: [PATCH 058/179] fix: fix wrong wait impl --- CAPI/cpp/API/src/logic.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CAPI/cpp/API/src/logic.cpp b/CAPI/cpp/API/src/logic.cpp index 470e7f20..6a22afde 100755 --- a/CAPI/cpp/API/src/logic.cpp +++ b/CAPI/cpp/API/src/logic.cpp @@ -281,7 +281,8 @@ bool Logic::EndAllAction() bool Logic::WaitThread() { - Update(); + if (asynchronous) + Wait(); return true; } From 31d109d7066f9449ea893edb241242f317f69522 Mon Sep 17 00:00:00 2001 From: DragonAura <32223554+DragonAura@users.noreply.github.com> Date: Fri, 3 May 2024 13:44:51 +0800 Subject: [PATCH 059/179] fix: fix wrong wait impl for python --- CAPI/python/PyAPI/logic.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CAPI/python/PyAPI/logic.py b/CAPI/python/PyAPI/logic.py index 0e7dbf61..cdb42e65 100644 --- a/CAPI/python/PyAPI/logic.py +++ b/CAPI/python/PyAPI/logic.py @@ -126,7 +126,8 @@ def GetMessage(self) -> Tuple[int, Union[str, bytes]]: return self.__messageQueue.get() def WaitThread(self) -> bool: - self.__Update() + if Setting.Asynchronous(): + self.__Wait() return True def GetCounter(self) -> int: From b7cb46c4643bce02db5d4d937fc05d9e4c7e61a8 Mon Sep 17 00:00:00 2001 From: DragonAura <32223554+DragonAura@users.noreply.github.com> Date: Fri, 3 May 2024 14:07:19 +0800 Subject: [PATCH 060/179] fix: fix wrong teamID --- CAPI/python/PyAPI/logic.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CAPI/python/PyAPI/logic.py b/CAPI/python/PyAPI/logic.py index cdb42e65..3ada4741 100644 --- a/CAPI/python/PyAPI/logic.py +++ b/CAPI/python/PyAPI/logic.py @@ -184,7 +184,7 @@ def GetHomeHp(self) -> int: self.__logger.debug("Called GetHomeHp") return copy.deepcopy( self.__currentState.gameInfo.redHomeHp - if self.__teamID == 1 + if self.__teamID == 0 else self.__currentState.gameInfo.blueHomeHp ) @@ -193,7 +193,7 @@ def GetEnergy(self) -> int: self.__logger.debug("Called GetEnergy") return copy.deepcopy( self.__currentState.gameInfo.redEnergy - if self.__teamID == 1 + if self.__teamID == 0 else self.__currentState.gameInfo.blueEnergy ) @@ -202,7 +202,7 @@ def GetScore(self) -> int: self.__logger.debug("Called GetScore") return copy.deepcopy( self.__currentState.gameInfo.redScore - if self.__teamID == 1 + if self.__teamID == 0 else self.__currentState.gameInfo.blueScore ) From ec032630601f06e7336dfece1d46449afcccf68b Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 3 May 2024 21:56:07 +0000 Subject: [PATCH 061/179] chore(deps): update dependency grpc.tools to v2.63.0 --- dependency/proto/Protos.csproj | 2 +- logic/Client/Client.csproj | 2 +- logic/Client/Protos.csproj | 2 +- logic/Server/Server.csproj | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/dependency/proto/Protos.csproj b/dependency/proto/Protos.csproj index 6986b817..31e3021c 100755 --- a/dependency/proto/Protos.csproj +++ b/dependency/proto/Protos.csproj @@ -18,7 +18,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/logic/Client/Client.csproj b/logic/Client/Client.csproj index ab2ad8ba..0d7c909a 100755 --- a/logic/Client/Client.csproj +++ b/logic/Client/Client.csproj @@ -73,7 +73,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/logic/Client/Protos.csproj b/logic/Client/Protos.csproj index 042c759c..a8487848 100755 --- a/logic/Client/Protos.csproj +++ b/logic/Client/Protos.csproj @@ -19,7 +19,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/logic/Server/Server.csproj b/logic/Server/Server.csproj index e62c9f75..4e173894 100755 --- a/logic/Server/Server.csproj +++ b/logic/Server/Server.csproj @@ -13,7 +13,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive From 4758abaf4bb07482b06c79ae097c6bb49f353279 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sat, 4 May 2024 07:21:22 +0000 Subject: [PATCH 062/179] chore(deps): update dependency grpcio to v1.63.0 --- CAPI/python/requirements.txt | 2 +- CAPI/python_exp/requirements.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CAPI/python/requirements.txt b/CAPI/python/requirements.txt index a5dab242..c187d411 100644 --- a/CAPI/python/requirements.txt +++ b/CAPI/python/requirements.txt @@ -1,3 +1,3 @@ -grpcio==1.62.2 +grpcio==1.63.0 grpcio-tools==1.62.2 numpy diff --git a/CAPI/python_exp/requirements.txt b/CAPI/python_exp/requirements.txt index a5dab242..c187d411 100644 --- a/CAPI/python_exp/requirements.txt +++ b/CAPI/python_exp/requirements.txt @@ -1,3 +1,3 @@ -grpcio==1.62.2 +grpcio==1.63.0 grpcio-tools==1.62.2 numpy From b228c5fbb98b12d6ab8d6799a17ec0565d30aaaa Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Sun, 5 May 2024 11:25:32 +0800 Subject: [PATCH 063/179] feat: :zap: Create interface for developer and fix a problem --- CAPI/cpp/API/src/logic.cpp | 2 +- installer/Data/ConfigFileData.cs | 13 ++++++++ installer/Model/Downloader.cs | 11 ++++--- installer/Model/EEsast.cs | 34 ++++++++++++++------- installer/Model/Local_Data.cs | 2 +- installer/ViewModel/DebugViewModel.cs | 35 +++++++++++++++------- installer/ViewModel/InstallViewModel.cs | 4 +-- installer/ViewModel/LaunchViewModel.cs | 2 ++ installer/ViewModel/LoginViewModel.cs | 11 ++++--- logic/Client/ViewModel/GeneralViewModel.cs | 2 +- 10 files changed, 79 insertions(+), 37 deletions(-) diff --git a/CAPI/cpp/API/src/logic.cpp b/CAPI/cpp/API/src/logic.cpp index b12a0f43..87b637f6 100755 --- a/CAPI/cpp/API/src/logic.cpp +++ b/CAPI/cpp/API/src/logic.cpp @@ -828,7 +828,7 @@ void Logic::LoadBuffer(const protobuf::MessageToClient& message) if (Proto2THUAI7::messageOfObjDict[obj.message_of_obj_case()] == THUAI7::MessageOfObj::ShipMessage) { bufferState->guids_all.push_back(obj.ship_message().guid()); - if (obj.obj.ship_message().team_id() == teamID) + if (obj.ship_message().team_id() == teamID) bufferState->guids.push_back(obj.ship_message().guid()); } bufferState->gameInfo = Proto2THUAI7::Protobuf2THUAI7GameInfo(message.all_message()); diff --git a/installer/Data/ConfigFileData.cs b/installer/Data/ConfigFileData.cs index 1e28730d..e3d58d24 100644 --- a/installer/Data/ConfigFileData.cs +++ b/installer/Data/ConfigFileData.cs @@ -129,6 +129,11 @@ public record ConfigDataFile public string UserName { get; set; } = string.Empty; public string Password { get; set; } = string.Empty; public bool Remembered { get; set; } = false; + // 开发人员接口 + public string? DevCppPath { get; set; } = null; + public string? DevPyPath { get; set; } = null; + public string? DevServerPath { get; set; } = null; + public string? DevClientPath { get; set; } = null; public CommandFile Commands { get; set; } = new(); public List Players { get; set; } = []; } @@ -447,6 +452,14 @@ public bool Remembered } } + public string? DevCppPath { get => file.DevCppPath; } + + public string? DevPyPath { get => file.DevPyPath; } + + public string? DevServerPath { get => file.DevServerPath; } + + public string? DevClientPath { get => file.DevClientPath; } + public Command Commands { get => com; diff --git a/installer/Model/Downloader.cs b/installer/Model/Downloader.cs index 27da7f69..6b1981a6 100755 --- a/installer/Model/Downloader.cs +++ b/installer/Model/Downloader.cs @@ -75,7 +75,7 @@ public class Updater public Downloader() { Data = new Local_Data(); - Log = LoggerProvider.FromFile(Path.Combine(Data.LogPath, "Main.log")); + Log = LoggerProvider.FromFile(Path.Combine(Data.LogPath, "Installer.log")); long size = 0; foreach (var log in new DirectoryInfo(Data.LogPath).EnumerateFiles()) { @@ -109,9 +109,8 @@ public Downloader() if (Log is FileLogger) ((FileLogger)Log).Path = ((FileLogger)Log).Path; } Route = Data.Config.InstallPath; - Cloud = new Tencent_Cos("1319625962", "ap-beijing", "thuai7", - LoggerProvider.FromFile(Path.Combine(Data.LogPath, "TencentCos.log"))); - Web = new EEsast(LoggerProvider.FromFile(Path.Combine(Data.LogPath, "EESAST.log"))); + Cloud = new Tencent_Cos("1319625962", "ap-beijing", "thuai7"); + Web = new EEsast(); Web.Token_Changed += SaveToken; Data.Log.Partner.Add(Log); @@ -188,7 +187,7 @@ public void Install(string? path = null) if (Cloud.Log is FileLogger) ((FileLogger)Cloud.Log).Path = Path.Combine(Data.Config.InstallPath, "Logs", "TencentCos.log"); if (Web.Log is FileLogger) ((FileLogger)Web.Log).Path = Path.Combine(Data.Config.InstallPath, "Logs", "EESAST.log"); if (Data.Log is FileLogger) ((FileLogger)Data.Log).Path = Path.Combine(Data.Config.InstallPath, "Logs", "Local_Data.log"); - if (Log is FileLogger) ((FileLogger)Log).Path = Path.Combine(Data.Config.InstallPath, "Logs", "Main.log"); + if (Log is FileLogger) ((FileLogger)Log).Path = Path.Combine(Data.Config.InstallPath, "Logs", "Installer.log"); Data.ResetInstallPath(Data.Config.InstallPath); @@ -276,7 +275,7 @@ public void ResetInstallPath(string newPath) if (Cloud.Log is FileLogger) ((FileLogger)Cloud.Log).Path = Path.Combine(newPath, "Logs", "TencentCos.log"); if (Web.Log is FileLogger) ((FileLogger)Web.Log).Path = Path.Combine(newPath, "Logs", "EESAST.log"); if (Data.Log is FileLogger) ((FileLogger)Data.Log).Path = Path.Combine(newPath, "Logs", "Local_Data.log"); - if (Log is FileLogger) ((FileLogger)Log).Path = Path.Combine(newPath, "Logs", "Main.log"); + if (Log is FileLogger) ((FileLogger)Log).Path = Path.Combine(newPath, "Logs", "Installer.log"); Data.ResetInstallPath(newPath); } Update(); diff --git a/installer/Model/EEsast.cs b/installer/Model/EEsast.cs index 2d6470d7..e2400355 100755 --- a/installer/Model/EEsast.cs +++ b/installer/Model/EEsast.cs @@ -43,6 +43,8 @@ public EEsast(Logger? _log = null) } public async Task LoginToEEsast(HttpClient client, string useremail = "", string userpassword = "") { + Status = LoginStatus.offline; + Token = string.Empty; try { using (var response = await client.PostAsync("https://api.eesast.com/user/login", JsonContent.Create(new @@ -55,9 +57,16 @@ public async Task LoginToEEsast(HttpClient client, string useremail = "", string { case System.Net.HttpStatusCode.OK: var info = JsonSerializer.Deserialize>(await response.Content.ReadAsStringAsync()); - Token = info.Keys.Contains("token") ? info["token"] : string.Empty; - Log.LogInfo($"{Username} logined successfully."); - Status = LoginStatus.logined; + if (info is not null) + { + string? token; + if (info.TryGetValue("token", out token) && token is not null) + { + Token = token; + Log.LogInfo($"{Username} logined successfully."); + Status = LoginStatus.logined; + } + } break; default: int code = ((int)response.StatusCode); @@ -113,15 +122,18 @@ public async Task UploadFilesAsync(HttpClient client, string userfile, stri { case System.Net.HttpStatusCode.OK: var res = JsonSerializer.Deserialize>(await response.Content.ReadAsStringAsync()); - string tmpSecretId = res["TmpSecretId"]; //"临时密钥 SecretId"; - string tmpSecretKey = res["TmpSecretKey"]; //"临时密钥 SecretKey"; - string tmpToken = res["SecurityToken"]; //"临时密钥 token"; - long tmpExpiredTime = Convert.ToInt64(res["ExpiredTime"]); //临时密钥有效截止时间,精确到秒 - EEsast_Cos.UpdateSecret(tmpSecretId, tmpSecretKey, tmpExpiredTime, tmpToken); + if (res is not null) + { + string tmpSecretId = res["TmpSecretId"]; //"临时密钥 SecretId"; + string tmpSecretKey = res["TmpSecretKey"]; //"临时密钥 SecretKey"; + string tmpToken = res["SecurityToken"]; //"临时密钥 token"; + long tmpExpiredTime = Convert.ToInt64(res["ExpiredTime"]); //临时密钥有效截止时间,精确到秒 + EEsast_Cos.UpdateSecret(tmpSecretId, tmpSecretKey, tmpExpiredTime, tmpToken); - string cosPath = $"/THUAI7/{GetTeamId()}/{type}/{plr}"; //对象在存储桶中的位置标识符,即称对象键 - EEsast_Cos.UploadFileAsync(userfile, cosPath).Wait(); - Log.LogInfo($"{userfile}上传成功。"); + string cosPath = $"/THUAI7/{GetTeamId()}/{type}/{plr}"; //对象在存储桶中的位置标识符,即称对象键 + EEsast_Cos.UploadFileAsync(userfile, cosPath).Wait(); + Log.LogInfo($"{userfile}上传成功。"); + } break; case System.Net.HttpStatusCode.Unauthorized: Log.LogError("未登录或登录过期,无法向EEsast上传文件。"); diff --git a/installer/Model/Local_Data.cs b/installer/Model/Local_Data.cs index 059391ca..27cbed03 100755 --- a/installer/Model/Local_Data.cs +++ b/installer/Model/Local_Data.cs @@ -85,7 +85,7 @@ public Local_Data() File.Delete(log); } } - Log = LoggerProvider.FromFile(Path.Combine(LogPath, "LocalData.log")); + Log = LoggerProvider.FromConsole(); Log.PartnerInfo = "[LocalData]"; LangEnabled = new Dictionary(); foreach (var a in typeof(LanguageOption).GetEnumValues()) diff --git a/installer/ViewModel/DebugViewModel.cs b/installer/ViewModel/DebugViewModel.cs index bee0adbb..395623e0 100644 --- a/installer/ViewModel/DebugViewModel.cs +++ b/installer/ViewModel/DebugViewModel.cs @@ -206,6 +206,7 @@ private void ClientStart() bool haveManual = false; + // 启动Manual很慢,先启动API for (int i = 0; i < Players.Count(); i++) { if (Players[i].PlayerMode == "API") @@ -215,12 +216,15 @@ private void ClientStart() else if (PySelect) LaunchPyAPI(Players[i].TeamID, Players[i].PlayerID); } + } + for (int i = 0; i < Players.Count(); i++) + { if (Players[i].PlayerMode == "Manual") { Downloader.Data.Config.Commands.TeamID = Players[i].TeamID; Downloader.Data.Config.Commands.PlayerID = Players[i].PlayerID; Downloader.Data.Config.Commands.ShipType = Players[i].ShipType; - LaunchClient(); + LaunchClient(Players[i].TeamID, Players[i].PlayerID, Players[i].ShipType); haveManual = true; } } @@ -235,13 +239,13 @@ private void ClientStart() throw new Exception(); } Downloader.Data.Config.Commands.PlayerID = id; + LaunchClient(0, id, 0); } catch (Exception) { DebugAlert = "观战ID输入错误"; return; } - LaunchClient(); } } @@ -273,7 +277,7 @@ public bool LaunchServer() { server = Process.Start(new ProcessStartInfo() { - FileName = Path.Combine(Downloader.Data.Config.InstallPath, "logic", "Server", "Server.exe"), + FileName = Downloader.Data.Config.DevServerPath ?? Path.Combine(Downloader.Data.Config.InstallPath, "logic", "Server", "Server.exe"), Arguments = $"--ip 0.0.0.0 --port {Port} --teamCount {TeamCount} --shipNum {ShipCount}", }); if (server is null) @@ -293,19 +297,28 @@ public bool LaunchServer() } - protected Process? client; - public bool LaunchClient() + public bool LaunchClient(int team, int player, int ship) { - client = Process.Start(new ProcessStartInfo() + Downloader.Data.Config.Commands.TeamID = team; + Downloader.Data.Config.Commands.PlayerID = player; + Downloader.Data.Config.Commands.ShipType = ship; + + var client = Process.Start(new ProcessStartInfo() { - FileName = Path.Combine(Downloader.Data.Config.InstallPath, "logic", "Client", "Client.exe"), + FileName = Downloader.Data.Config.DevClientPath ?? Path.Combine(Downloader.Data.Config.InstallPath, "logic", "Client", "Client.exe"), }); if (client is null) { Log.LogError("未能启动Client!"); return false; } - Log.LogInfo("Client成功启动。"); + while (!File.Exists(Path.Combine(Downloader.Data.LogPath, $"lock.{team}.{player}.log"))) + { + Thread.Sleep(500); + } + Thread.Sleep(500); + File.Delete(Path.Combine(Downloader.Data.LogPath, $"lock.{team}.{player}.log")); + Log.LogInfo($"Client({team}: {player})成功启动。"); children.Add(client); return true; } @@ -314,12 +327,12 @@ public bool LaunchClient() protected bool ExplorerLaunched_PyAPI = false; public bool LaunchCppAPI(int team, int player) { - var exe = Path.Combine(Downloader.Data.Config.InstallPath, "CAPI", "cpp", "x64", "Debug", "API.exe"); + var exe = Downloader.Data.Config.DevCppPath ?? Path.Combine(Downloader.Data.Config.InstallPath, "CAPI", "cpp", "x64", "Debug", "API.exe"); if (File.Exists(exe)) { var cpp = Process.Start(new ProcessStartInfo() { - FileName = exe, + FileName = Downloader.Data.Config.DevCppPath ??exe, Arguments = $"-I {IP} -P {Port} -t {team} -p {player} -o" }); if (cpp is null) @@ -357,7 +370,7 @@ public bool LaunchPyAPI(int team, int player) { FileName = "cmd.exe", Arguments = "/c python " - + Path.Combine(Downloader.Data.Config.InstallPath, "CAPI", "python", "PyAPI", "main.py") + + Downloader.Data.Config.DevPyPath ?? Path.Combine(Downloader.Data.Config.InstallPath, "CAPI", "python", "PyAPI", "main.py") + $" -I {IP} -P {Port} -t {team} -p {player} -o" }); if (py is null) diff --git a/installer/ViewModel/InstallViewModel.cs b/installer/ViewModel/InstallViewModel.cs index bb5564f7..b0477540 100644 --- a/installer/ViewModel/InstallViewModel.cs +++ b/installer/ViewModel/InstallViewModel.cs @@ -60,7 +60,7 @@ public string? DebugAlert } } - private string downloadPath; + private string downloadPath = string.Empty; public string DownloadPath { get => downloadPath; @@ -163,7 +163,7 @@ private void ProgressReport(object? sender, EventArgs e) #region 按钮 - private string downloadBtnText; + private string downloadBtnText = string.Empty; public string DownloadBtnText { get => downloadBtnText; diff --git a/installer/ViewModel/LaunchViewModel.cs b/installer/ViewModel/LaunchViewModel.cs index 66885725..8f405cff 100644 --- a/installer/ViewModel/LaunchViewModel.cs +++ b/installer/ViewModel/LaunchViewModel.cs @@ -56,6 +56,8 @@ public LaunchViewModel(Downloader downloader) SaveEnabled = true; StartEnabled = true; + Log.PartnerInfo = "[Launcher]"; + Log.Partner.Add(Downloader.Log); SaveBtnClickedCommand = new AsyncRelayCommand(SaveBtnClicked); } diff --git a/installer/ViewModel/LoginViewModel.cs b/installer/ViewModel/LoginViewModel.cs index 7b612317..9fa54745 100755 --- a/installer/ViewModel/LoginViewModel.cs +++ b/installer/ViewModel/LoginViewModel.cs @@ -87,10 +87,13 @@ await Downloader.LoginAsync() .ContinueWith(t => { ID = Downloader.Username; - if (Remember) - Downloader.RememberUser(); - else - Downloader.ForgetUser(); + if (Downloader.Web.Status == Model.LoginStatus.logined) + { + if (Remember) + Downloader.RememberUser(); + else + Downloader.ForgetUser(); + } LoginStatus = Downloader.Web.Status.ToString(); RemStatus = Remember.ToString(); }); diff --git a/logic/Client/ViewModel/GeneralViewModel.cs b/logic/Client/ViewModel/GeneralViewModel.cs index efe19159..22e830b9 100644 --- a/logic/Client/ViewModel/GeneralViewModel.cs +++ b/logic/Client/ViewModel/GeneralViewModel.cs @@ -802,7 +802,7 @@ public GeneralViewModel() shipTypeID = Convert.ToInt32(d.Commands.ShipType); playbackFile = d.Commands.PlaybackFile; playbackSpeed = d.Commands.PlaybackSpeed; - myLogger = LoggerProvider.FromFile(Path.Combine(d.InstallPath, "Logs", "Client.log")); + myLogger = LoggerProvider.FromFile(Path.Combine(d.InstallPath, "Logs", $"Client.{teamID}.{playerID}.log")); lockGenerator = LoggerProvider.FromFile(Path.Combine(d.InstallPath, "Logs", String.Format("lock.{0}.{1}.log", teamID, playerID))); MoveUpCommand = new Command(() => { From 58d794811b53b5bdff48940c7465faef2ff7ae0b Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Sun, 5 May 2024 11:31:51 +0800 Subject: [PATCH 064/179] docs: :bookmark: Update version weekly. --- installer/Data/MD5FileData.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/installer/Data/MD5FileData.cs b/installer/Data/MD5FileData.cs index 79c74542..3b6c8522 100644 --- a/installer/Data/MD5FileData.cs +++ b/installer/Data/MD5FileData.cs @@ -26,13 +26,13 @@ public class TVersion { // 代码库版本 [JsonInclude] - public Version LibVersion = new Version(1, 0, 1, 0); + public Version LibVersion = new Version(1, 0, 2, 0); // 选手代码模板版本 [JsonInclude] public Version TemplateVersion = new Version(1, 0, 0, 3); // 本体版本 [JsonInclude] - public Version InstallerVersion = new Version(1, 0, 1, 0); + public Version InstallerVersion = new Version(1, 0, 2, 0); public static bool operator <(TVersion l, TVersion r) { return l.LibVersion < r.LibVersion || l.TemplateVersion < r.TemplateVersion || l.InstallerVersion < r.InstallerVersion; From 94beaf00fee98c7768be6beb59be23517ab1333c Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Sun, 5 May 2024 12:25:23 +0800 Subject: [PATCH 065/179] style: :art: Format the installer --- installer/ViewModel/DebugViewModel.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/installer/ViewModel/DebugViewModel.cs b/installer/ViewModel/DebugViewModel.cs index 395623e0..c6f19f96 100644 --- a/installer/ViewModel/DebugViewModel.cs +++ b/installer/ViewModel/DebugViewModel.cs @@ -332,7 +332,7 @@ public bool LaunchCppAPI(int team, int player) { var cpp = Process.Start(new ProcessStartInfo() { - FileName = Downloader.Data.Config.DevCppPath ??exe, + FileName = Downloader.Data.Config.DevCppPath ?? exe, Arguments = $"-I {IP} -P {Port} -t {team} -p {player} -o" }); if (cpp is null) From b21280308a3aa60774edb8e6be1cf4d6e60780d8 Mon Sep 17 00:00:00 2001 From: shangfengh <3495281661@qq.com> Date: Mon, 6 May 2024 16:54:12 +0800 Subject: [PATCH 066/179] fix(Logic): :bug: fix the bug about the HP of the home --- logic/GameClass/GameObj/Areas/Home.cs | 2 +- logic/GameClass/GameObj/Base.cs | 9 +++++++++ logic/GameClass/GameObj/GameObj.cs | 5 +++++ logic/Preparation/Utility/Value/SafeValue/Atomic.cs | 4 ++-- logic/Preparation/Utility/Value/SafeValue/ObjPool.cs | 7 +++---- 5 files changed, 20 insertions(+), 7 deletions(-) diff --git a/logic/GameClass/GameObj/Areas/Home.cs b/logic/GameClass/GameObj/Areas/Home.cs index dbd6da49..3746ca96 100755 --- a/logic/GameClass/GameObj/Areas/Home.cs +++ b/logic/GameClass/GameObj/Areas/Home.cs @@ -9,7 +9,7 @@ public class Home(XY initPos, long id) : Immovable(initPos, GameData.NumOfPosGridPerCell / 2, GameObjType.Home), IHome { public long TeamID { get; } = id; - public InVariableRange HP => new(GameData.HomeHP); + public InVariableRange HP { get; } = new(GameData.HomeHP); public override bool IsRigid => true; public override ShapeType Shape => ShapeType.Square; diff --git a/logic/GameClass/GameObj/Base.cs b/logic/GameClass/GameObj/Base.cs index adc208e9..6f4888f9 100644 --- a/logic/GameClass/GameObj/Base.cs +++ b/logic/GameClass/GameObj/Base.cs @@ -28,6 +28,15 @@ public Base(Home home) ShipPool = new( classfier: (ship) => ship.ShipType, idleChecker: (ship) => ship.IsRemoved, + tryActivator: (ship) => + { + if (ship.IsRemoved.TrySet(false)) + { + ship.CanMove.SetROri(true); + return true; + } + return false; + }, activator: (ship) => { ship.CanMove.SetROri(true); diff --git a/logic/GameClass/GameObj/GameObj.cs b/logic/GameClass/GameObj/GameObj.cs index 95a419ee..d846298e 100755 --- a/logic/GameClass/GameObj/GameObj.cs +++ b/logic/GameClass/GameObj/GameObj.cs @@ -2,10 +2,15 @@ using Preparation.Utility; using Preparation.Utility.Value; using Preparation.Utility.Value.SafeValue.Atomic; +using Preparation.Utility.Logging; using System.Threading; namespace GameClass.GameObj { + public static class GameObjLogger + { + public static readonly Logger logger = new("GameObj"); + } /// /// 一切游戏元素的总基类,与THUAI4不同,继承IMoveable接口(出于一切物体其实都是可运动的指导思想)——LHR /// diff --git a/logic/Preparation/Utility/Value/SafeValue/Atomic.cs b/logic/Preparation/Utility/Value/SafeValue/Atomic.cs index 8390f3e8..82f2ec45 100644 --- a/logic/Preparation/Utility/Value/SafeValue/Atomic.cs +++ b/logic/Preparation/Utility/Value/SafeValue/Atomic.cs @@ -24,7 +24,7 @@ public override bool Equals(object? obj) T? g = Get(); if (g == null) return obj == null; if (g == obj) return true; - return obj != null && (obj is IReturnClass k) && Get() == k.Get(); + return obj != null && (obj is IReturnClass k) && g == k.Get(); } public override int GetHashCode() { @@ -48,7 +48,7 @@ public override bool Equals(object? obj) T? g = Get(); if (g == null) return obj == null; if (g == obj) return true; - return obj != null && (obj is IReturnClass k) && Get() == k.Get(); + return obj != null && (obj is IReturnClass k) && g == k.Get(); } public override int GetHashCode() { diff --git a/logic/Preparation/Utility/Value/SafeValue/ObjPool.cs b/logic/Preparation/Utility/Value/SafeValue/ObjPool.cs index a0109cee..9bf3fd44 100644 --- a/logic/Preparation/Utility/Value/SafeValue/ObjPool.cs +++ b/logic/Preparation/Utility/Value/SafeValue/ObjPool.cs @@ -6,6 +6,7 @@ namespace Preparation.Utility.Value.SafeValue; public class ObjPool(Func classfier, Func idleChecker, + Func tryActivator, Action activator, Action inactivator) : IObjPool @@ -16,6 +17,7 @@ public class ObjPool(Func classfier, private readonly Dictionary> objs = []; private readonly Func classfier = classfier; private readonly Func idleChecker = idleChecker; + private readonly Func tryActivator = tryActivator; private readonly Action activator = activator; private readonly Action inactivator = inactivator; @@ -89,10 +91,7 @@ public void Initiate(TType tp, int num, Func func) lock (dictLock) { if (CheckEmpty(tp) || GetIdleNum(tp) == 0) return null; - var ret = Find(tp, idleChecker); - if (ret is null) return null; - activator(ret); - return ret; + return Find(tp, tryActivator); } } public void ReturnObj(T obj) From b7ac685781300ece416ffb318bb5f1c33075bd3f Mon Sep 17 00:00:00 2001 From: sigureling <1678348940@qq.com> Date: Mon, 6 May 2024 19:36:42 +0800 Subject: [PATCH 067/179] fix: :bug: fix a careless bug in sendmessage --- CAPI/cpp/API/src/logic.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CAPI/cpp/API/src/logic.cpp b/CAPI/cpp/API/src/logic.cpp index 6a22afde..8cf43231 100755 --- a/CAPI/cpp/API/src/logic.cpp +++ b/CAPI/cpp/API/src/logic.cpp @@ -202,7 +202,7 @@ bool Logic::Move(int64_t time, double angle) bool Logic::Send(int32_t toID, std::string message, bool binary) { logger->debug("Called SendMessage"); - return pComm->Send(playerID, teamID, toID, std::move(message), binary); + return pComm->Send(playerID, toID, teamID, std::move(message), binary); } bool Logic::HaveMessage() From 05c73ec90925de0305d69766e150c94474077c59 Mon Sep 17 00:00:00 2001 From: 964293341 Date: Mon, 6 May 2024 20:37:57 +0800 Subject: [PATCH 068/179] refactor: do some chores --- logic/GameClass/GameClassLogging.cs | 5 ++ logic/GameClass/GameObj/Areas/Resource.cs | 2 +- logic/GameClass/GameObj/Areas/Wormhole.cs | 2 +- logic/GameClass/GameObj/Base.cs | 6 +- logic/GameClass/GameObj/GameObj.cs | 4 - logic/GameClass/GameObj/Ship.cs | 2 +- .../Utility/Value/SafeValue/ObjPool.cs | 2 - logic/Server/GameServer.cs | 88 +++++++++---------- 8 files changed, 51 insertions(+), 60 deletions(-) diff --git a/logic/GameClass/GameClassLogging.cs b/logic/GameClass/GameClassLogging.cs index a27aeb53..e679e5b1 100644 --- a/logic/GameClass/GameClassLogging.cs +++ b/logic/GameClass/GameClassLogging.cs @@ -3,6 +3,11 @@ namespace GameClass.GameObj { + public static class GameObjLogger + { + public static readonly Logger logger = new("GameObj"); + } + public static class LoggingFunctional { public static string ShipLogInfo(Ship ship) diff --git a/logic/GameClass/GameObj/Areas/Resource.cs b/logic/GameClass/GameObj/Areas/Resource.cs index 8edc43a8..9f8b151c 100755 --- a/logic/GameClass/GameObj/Areas/Resource.cs +++ b/logic/GameClass/GameObj/Areas/Resource.cs @@ -8,7 +8,7 @@ namespace GameClass.GameObj.Areas; public class Resource(XY initPos) : Immovable(initPos, GameData.NumOfPosGridPerCell / 2, GameObjType.Resource) { - public InVariableRange HP { get; } = new InVariableRange(GameData.ResourceHP); + public InVariableRange HP { get; } = new(GameData.ResourceHP); public override bool IsRigid => true; public override ShapeType Shape => ShapeType.Square; public AtomicInt ProduceNum { get; } = new AtomicInt(0); diff --git a/logic/GameClass/GameObj/Areas/Wormhole.cs b/logic/GameClass/GameObj/Areas/Wormhole.cs index f92035c6..1ad8d881 100755 --- a/logic/GameClass/GameObj/Areas/Wormhole.cs +++ b/logic/GameClass/GameObj/Areas/Wormhole.cs @@ -7,7 +7,7 @@ namespace GameClass.GameObj.Areas; public class Wormhole(List cells, int id) { - public InVariableRange HP = new(GameData.WormholeHP); + public InVariableRange HP { get; } = new(GameData.WormholeHP); private readonly List cells = cells; public List Cells => cells; public AtomicInt RepairNum { get; } = new AtomicInt(0); diff --git a/logic/GameClass/GameObj/Base.cs b/logic/GameClass/GameObj/Base.cs index 6f4888f9..f4d57256 100644 --- a/logic/GameClass/GameObj/Base.cs +++ b/logic/GameClass/GameObj/Base.cs @@ -37,16 +37,12 @@ public Base(Home home) } return false; }, - activator: (ship) => - { - ship.CanMove.SetROri(true); - ship.IsRemoved.SetROri(false); - }, inactivator: (ship) => { ship.CanMove.SetROri(false); ship.IsRemoved.SetROri(true); }); + // 池初始化,但是由于服务器采用逐个添加船只的方式,因此这里不进行任何行为 ShipPool.Initiate(ShipType.CivilShip, 0, () => new(GameData.ShipRadius, ShipType.CivilShip, MoneyPool)); ShipPool.Initiate(ShipType.WarShip, 0, diff --git a/logic/GameClass/GameObj/GameObj.cs b/logic/GameClass/GameObj/GameObj.cs index d846298e..ca9aa34f 100755 --- a/logic/GameClass/GameObj/GameObj.cs +++ b/logic/GameClass/GameObj/GameObj.cs @@ -7,10 +7,6 @@ namespace GameClass.GameObj { - public static class GameObjLogger - { - public static readonly Logger logger = new("GameObj"); - } /// /// 一切游戏元素的总基类,与THUAI4不同,继承IMoveable接口(出于一切物体其实都是可运动的指导思想)——LHR /// diff --git a/logic/GameClass/GameObj/Ship.cs b/logic/GameClass/GameObj/Ship.cs index 425e9aec..731c40f5 100755 --- a/logic/GameClass/GameObj/Ship.cs +++ b/logic/GameClass/GameObj/Ship.cs @@ -46,7 +46,7 @@ public ShipStateType ShipState /// /// 子弹数上限, THUAI7为无穷 /// - public IntNumUpdateEachCD BulletNum => new(int.MaxValue, 1); + public IntNumUpdateEachCD BulletNum { get; } = new(int.MaxValue, 1); /// /// 模块相关 /// diff --git a/logic/Preparation/Utility/Value/SafeValue/ObjPool.cs b/logic/Preparation/Utility/Value/SafeValue/ObjPool.cs index 9bf3fd44..f34e5493 100644 --- a/logic/Preparation/Utility/Value/SafeValue/ObjPool.cs +++ b/logic/Preparation/Utility/Value/SafeValue/ObjPool.cs @@ -7,7 +7,6 @@ namespace Preparation.Utility.Value.SafeValue; public class ObjPool(Func classfier, Func idleChecker, Func tryActivator, - Action activator, Action inactivator) : IObjPool where T : class @@ -18,7 +17,6 @@ public class ObjPool(Func classfier, private readonly Func classfier = classfier; private readonly Func idleChecker = idleChecker; private readonly Func tryActivator = tryActivator; - private readonly Action activator = activator; private readonly Action inactivator = inactivator; #region 属性 diff --git a/logic/Server/GameServer.cs b/logic/Server/GameServer.cs index 2da29523..da7b2000 100755 --- a/logic/Server/GameServer.cs +++ b/logic/Server/GameServer.cs @@ -133,73 +133,69 @@ protected async Task GetLadderScore(double[] scores) // 解析 JSON 字符串 var result = JsonConvert.DeserializeObject>(jsonString); double[] org = (from r in result select (double)(r.score)).ToArray(); - double[] final = Cal(org, scores); + double[] final = LadderCalculate(org, scores); return final; } catch (Exception e) { GameServerLogging.logger.ConsoleLog("No response from ladder URL!"); GameServerLogging.logger.ConsoleLog(e.ToString()); - return new double[0]; + return []; } } else { GameServerLogging.logger.ConsoleLog("Null URL!"); - return new double[0]; + return []; } } - protected double[] Cal(double[] orgScore, double[] competitionScore) + protected static double[] LadderCalculate(double[] oriScores, double[] competitionScores) { - // 调整顺序,让第一个元素成为获胜者,便于计算 - bool reverse = false; // 记录是否需要调整 - if (competitionScore[0] < competitionScore[1]) + // 调整顺序,让第一项成为获胜者,便于计算 + bool scoresReverse = false; // 顺序是否需要交换 + if (competitionScores[0] < competitionScores[1]) // 第一项为落败者 + scoresReverse = true; + else if (competitionScores[0] == competitionScores[1])// 平局 { - reverse = true; - } - else if (competitionScore[0] == competitionScore[1]) - { - if (orgScore[0] == orgScore[1]) - { + if (oriScores[0] == oriScores[1]) // 完全平局,不改变天梯分数 - return orgScore; - } - if (orgScore[0] > orgScore[1]) - { - // 本次游戏平局,但一方天梯分数高,另一方天梯分数低,需要将两者向中间略微靠拢,因此天梯分数低的定为获胜者 - reverse = true; - } + return oriScores; + if (oriScores[0] > oriScores[1]) + // 本次游戏平局,但一方天梯分数高,另一方天梯分数低, + // 需要将两者向中间略微靠拢,因此天梯分数低的定为获胜者 + scoresReverse = true; } - if (reverse) + if (scoresReverse)// 如果需要换,交换两者的顺序 { - // 如果需要换,换两者的顺序 - double t = competitionScore[1]; - competitionScore[1] = competitionScore[0]; - competitionScore[0] = t; - t = orgScore[1]; - orgScore[1] = orgScore[0]; - orgScore[0] = t; + (competitionScores[0], competitionScores[1]) = (competitionScores[1], competitionScores[0]); + (oriScores[0], oriScores[1]) = (oriScores[1], oriScores[0]); } + + const double normalDeltaThereshold = 1000.0; // 分数差标准化参数,同时也是大分数差阈值 + const double correctParam = normalDeltaThereshold * 1.2;// 修正参数 + const double winnerWeight = 9e-6; // 获胜者天梯得分权值 + const double loserWeight = 5e-6; // 落败者天梯得分权值 + const double scoreDeltaThereshold = 2100.0; // 极大分数差阈值 + double[] resScore = [0, 0]; - double deltaWeight = 1000.0; // 差距悬殊判断参数 - double delta = (orgScore[0] - orgScore[1]) / deltaWeight; - // 盈利者天梯得分权值、落败者天梯得分权值 - double firstnerGet = 9e-6; - double secondrGet = 5e-6; - double deltaScore = 2100.0; // 两队竞争分差超过多少时就认为非常大 - double correctRate = (orgScore[0] - orgScore[1]) / (deltaWeight * 1.2); // 订正的幅度,该值越小,则在势均力敌时天梯分数改变越大 - double correct = 0.5 * (Math.Tanh((competitionScore[0] - competitionScore[1] - deltaScore) / deltaScore - correctRate) + 1.0); // 一场比赛中,在双方势均力敌时,减小天梯分数的改变量 - resScore[0] = orgScore[0] + Math.Round(competitionScore[0] * competitionScore[0] * firstnerGet * (1 - Math.Tanh(delta)) * correct); // 胜者所加天梯分 - resScore[1] = orgScore[1] - Math.Round( - (competitionScore[0] - competitionScore[1]) * (competitionScore[0] - competitionScore[1]) * secondrGet * (1 - Math.Tanh(delta)) * correct); // 败者所扣天梯分 - // 如果换过,再换回来 - if (reverse) - { - double t = resScore[1]; - resScore[1] = resScore[0]; - resScore[0] = t; - } + double oriDelta = oriScores[0] - oriScores[1]; // 原分数差 + double competitionDelta = competitionScores[0] - competitionScores[1]; // 本次比赛分数差 + double normalOriDelta = oriDelta / normalDeltaThereshold; // 标准化原分数差 + double correctRate = oriDelta / correctParam; // 修正率,修正方向为缩小分数差 + double correct = 0.5 * (Math.Tanh((competitionDelta - scoreDeltaThereshold) / scoreDeltaThereshold + - correctRate) + + 1.0); // 分数修正 + resScore[0] = oriScores[0] + Math.Round(Math.Pow(competitionScores[0], 2) + * winnerWeight + * (1 - Math.Tanh(normalOriDelta)) + * correct); // 胜者所加天梯分 + resScore[1] = oriScores[1] - Math.Round(Math.Pow(competitionDelta, 2) + * loserWeight + * (1 - Math.Tanh(normalOriDelta)) + * correct); // 败者所扣天梯分 + if (scoresReverse)// 顺序换回 + (resScore[0], resScore[1]) = (resScore[1], resScore[0]); return resScore; } From 65a0c2d7a0df20e44039d7bf0b72533c43e0ce0a Mon Sep 17 00:00:00 2001 From: GuoWQ222 Date: Mon, 6 May 2024 23:56:33 +0800 Subject: [PATCH 069/179] fix bugs --- logic/Server/GameServer.cs | 66 ++++++++++++++++++++++++-------------- logic/Server/HttpSender.cs | 46 ++++++++++++++++++++++++-- 2 files changed, 85 insertions(+), 27 deletions(-) diff --git a/logic/Server/GameServer.cs b/logic/Server/GameServer.cs index da7b2000..fe52c216 100755 --- a/logic/Server/GameServer.cs +++ b/logic/Server/GameServer.cs @@ -111,42 +111,44 @@ private void SaveGameResult(string path) protected void SendGameResult(int[] scores, int mode) // 天梯的 Server 给网站发消息记录比赛结果 { + string? url2 = Environment.GetEnvironmentVariable("FINISH_URL"); + if (url2 == null) + { + GameServerLogging.logger.ConsoleLog("Null FINISH_URL!"); + return; + } + else + { + httpSender.Url = url2; + httpSender.Token = options.Token; + } httpSender?.SendHttpRequest(scores, mode).Wait(); - } - protected async Task GetLadderScore(double[] scores) + protected double[] PullScore(double[] scores) { string? url2 = Environment.GetEnvironmentVariable("SCORE_URL"); if (url2 != null) { - try + httpSender.Url = url2; + httpSender.Token = options.Token; + double[] org = httpSender.GetLadderScore(scores).Result; + if (org.Length == 0) { - var httpClient = new HttpClient(); - httpClient.DefaultRequestHeaders.Authorization = new("Bearer", options.Token); - var response = await httpClient.PostAsync(url2, JsonContent.Create(new { HttpHeaders = options.Token })); - - // 读取响应内容为字符串 - var jsonString = await response.Content.ReadAsStringAsync(); - - // 解析 JSON 字符串 - var result = JsonConvert.DeserializeObject>(jsonString); - double[] org = (from r in result select (double)(r.score)).ToArray(); - double[] final = LadderCalculate(org, scores); - return final; + GameServerLogging.logger.ConsoleLog("Error: No data returned from the web!"); + return new double[0]; } - catch (Exception e) + else { - GameServerLogging.logger.ConsoleLog("No response from ladder URL!"); - GameServerLogging.logger.ConsoleLog(e.ToString()); - return []; + double[] final = Cal(org, scores); + return final; } } else { - GameServerLogging.logger.ConsoleLog("Null URL!"); - return []; + GameServerLogging.logger.ConsoleLog("Null SCORE_URL Environment!"); + return new double[0]; } } @@ -212,9 +214,15 @@ private void OnGameEnd() double[] doubleArray = scores.Select(x => (double)x).ToArray(); if (options.Mode == 2) { - doubleArray = GetLadderScore(doubleArray).Result; + doubleArray = PullScore(doubleArray); scores = doubleArray.Select(x => (int)x).ToArray(); - SendGameResult(scores, options.Mode); + if (scores.Length == 0) + { + Console.WriteLine("Error: No data returned from the web!"); + + } + else + SendGameResult(scores, options.Mode); } endGameSem.Release(); } @@ -453,11 +461,21 @@ public GameServer(ArgumentOptions options) } } - + string? token2 = Environment.GetEnvironmentVariable("TOKEN"); + if (token2 == null) + { + GameServerLogging.logger.ConsoleLog("Null TOKEN Environment!"); + } + else + options.Token = token2; if (options.Url != DefaultArgumentOptions.Url && options.Token != DefaultArgumentOptions.Token) { httpSender = new(options.Url, options.Token); } + else + { + httpSender = new(DefaultArgumentOptions.Url, DefaultArgumentOptions.Token); + } } } } diff --git a/logic/Server/HttpSender.cs b/logic/Server/HttpSender.cs index a745e197..3db5658a 100755 --- a/logic/Server/HttpSender.cs +++ b/logic/Server/HttpSender.cs @@ -1,11 +1,25 @@ -using System.Net.Http.Json; +using Google.Protobuf.WellKnownTypes; +using Newtonsoft.Json; +using System.Net.Http.Json; namespace Server { class HttpSender(string url, string token) { - private readonly string url = url; - private readonly string token = token; + private string url = url; + private string token = token; + + public string Url + { + get { return url; } + set { url = value; } + } + + public string Token + { + get { return token; } + set { token = value; } + } // void Test() // { @@ -35,6 +49,32 @@ public async Task SendHttpRequest(int[] scores, int mode) GameServerLogging.logger.ConsoleLog(e.ToString()); } } + + public async Task GetLadderScore(double[] scores) + { + + try + { + var httpClient = new HttpClient(); + httpClient.DefaultRequestHeaders.Authorization = new("Bearer", token); + var response = await httpClient.PostAsync(url, JsonContent.Create(new { HttpHeaders = token })); + + // 读取响应内容为字符串 + var jsonString = await response.Content.ReadAsStringAsync(); + + // 解析 JSON 字符串 + var result = JsonConvert.DeserializeObject>(jsonString); + double[] org = (from r in result select (double)(r.score)).ToArray(); + return org; + } + catch (Exception e) + { + GameServerLogging.logger.ConsoleLog("Error when pulling ladder score!"); + GameServerLogging.logger.ConsoleLog(e.ToString()); + return new double[0]; + } + + } } internal class TeamScore From 7cc55938a6f60d88547a370618818ed92153969b Mon Sep 17 00:00:00 2001 From: GuoWQ222 Date: Tue, 7 May 2024 00:10:28 +0800 Subject: [PATCH 070/179] fix bugs --- logic/Server/GameServer.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/logic/Server/GameServer.cs b/logic/Server/GameServer.cs index fe52c216..8eafafaf 100755 --- a/logic/Server/GameServer.cs +++ b/logic/Server/GameServer.cs @@ -141,7 +141,7 @@ protected double[] PullScore(double[] scores) } else { - double[] final = Cal(org, scores); + double[] final = LadderCalculate(org, scores); return final; } } From d8d619feb81eb14edb2b65ee757f9cf1dbac5ac0 Mon Sep 17 00:00:00 2001 From: DragonAura <32223554+DragonAura@users.noreply.github.com> Date: Tue, 7 May 2024 15:42:37 +0800 Subject: [PATCH 071/179] fix: disable python version auto update --- renovate.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/renovate.json b/renovate.json index 200ab0a5..0097123c 100755 --- a/renovate.json +++ b/renovate.json @@ -5,5 +5,8 @@ "dependencyDashboard": true, "timezone": "Asia/Shanghai", "schedule": "after 4am and before 8am every saturday", - "labels": ["dependencies", "bot"] + "labels": ["dependencies", "bot"], + "ignorePaths": [ + "dependency/Dockerfile/Dockerfile_base" + ], } From aba79ae9fb79a7e4c6b0788f91207f655894cdb2 Mon Sep 17 00:00:00 2001 From: DragonAura <32223554+DragonAura@users.noreply.github.com> Date: Tue, 7 May 2024 15:43:12 +0800 Subject: [PATCH 072/179] fix: revert python version to 3.9.16 --- dependency/Dockerfile/Dockerfile_base | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dependency/Dockerfile/Dockerfile_base b/dependency/Dockerfile/Dockerfile_base index 2d5255ca..2eeb56ad 100755 --- a/dependency/Dockerfile/Dockerfile_base +++ b/dependency/Dockerfile/Dockerfile_base @@ -1,4 +1,4 @@ -FROM python:3.12.3-bullseye +FROM python:3.9.16-bullseye MAINTAINER eesast WORKDIR /usr/local RUN apt-get update && apt-get install --no-install-recommends -y gcc g++ make wget ca-certificates cmake autoconf automake libtool curl unzip git @@ -12,4 +12,4 @@ RUN cmake -DgRPC_INSTALL=ON \ WORKDIR /usr/local RUN git clone https://gitee.com/mirrors/protobuf_source.git ./protobuf WORKDIR /usr/local/protobuf -RUN git checkout 3.20.x && ./autogen.sh && ./configure && make -j$(nproc) && make install && ldconfig \ No newline at end of file +RUN git checkout 3.20.x && ./autogen.sh && ./configure && make -j$(nproc) && make install && ldconfig From 2d74e62adb83cf98019a601dc7e6acf286435d52 Mon Sep 17 00:00:00 2001 From: ONLOX <3316820553@qq.com> Date: Tue, 7 May 2024 16:36:33 +0800 Subject: [PATCH 073/179] feat: update dockerfile --- dependency/Dockerfile/Docker_run_client | 29 --- dependency/Dockerfile/Docker_run_server | 20 -- dependency/Dockerfile/Dockerfile_run_client | 5 +- dependency/Dockerfile/Dockerfile_run_server | 14 +- dependency/py/rank.py | 205 -------------------- dependency/shell/run.sh | 66 ++++--- dependency/shell/run_client.sh | 86 -------- dependency/shell/run_server.sh | 65 ------- 8 files changed, 45 insertions(+), 445 deletions(-) delete mode 100644 dependency/Dockerfile/Docker_run_client delete mode 100644 dependency/Dockerfile/Docker_run_server delete mode 100644 dependency/py/rank.py delete mode 100644 dependency/shell/run_client.sh delete mode 100644 dependency/shell/run_server.sh diff --git a/dependency/Dockerfile/Docker_run_client b/dependency/Dockerfile/Docker_run_client deleted file mode 100644 index 1d6b633e..00000000 --- a/dependency/Dockerfile/Docker_run_client +++ /dev/null @@ -1,29 +0,0 @@ -FROM mcr.microsoft.com/dotnet/sdk:8.0.204-jammy-amd64 AS build -MAINTAINER eesast -WORKDIR /usr/local -COPY . . -RUN dotnet publish logic/Server/Server.csproj -c Release -o /usr/local/Server --self-contained true -r linux-x64 - -FROM eesast/thuai7_base:base -MAINTAINER eesast -WORKDIR /usr/local -COPY --from=build /usr/local/Server . -RUN mkdir /usr/local/team1 && mkdir /usr/local/team2 && mkdir /usr/local/playback -<<<<<<<< HEAD:dependency/Dockerfile/Docker_run_client -COPY ./dependency/shell/run_client.sh . -======== -COPY ./dependency/shell/run_server.sh . ->>>>>>>> 218cff729c2110699b9e40a0d97a740f58e75462:dependency/Dockerfile/Dockerfile_run_server -COPY ./CAPI/python /usr/local/PlayerCode/CAPI/python -COPY ./dependency/proto /usr/local/PlayerCode/dependency/proto -COPY ./dependency/shell /usr/local/PlayerCode/dependency/shell -WORKDIR /usr/local/PlayerCode/CAPI/python -RUN bash ../../dependency/shell/generate_proto.sh - -WORKDIR /usr/local -<<<<<<<< HEAD:dependency/Dockerfile/Docker_run_client -ENTRYPOINT [ "bash","./run_client.sh" ] -======== -RUN export TERMINAL=SERVER -ENTRYPOINT [ "bash","./run.sh" ] ->>>>>>>> 218cff729c2110699b9e40a0d97a740f58e75462:dependency/Dockerfile/Dockerfile_run_server diff --git a/dependency/Dockerfile/Docker_run_server b/dependency/Dockerfile/Docker_run_server deleted file mode 100644 index aa5984dd..00000000 --- a/dependency/Dockerfile/Docker_run_server +++ /dev/null @@ -1,20 +0,0 @@ -FROM mcr.microsoft.com/dotnet/sdk:8.0.204-jammy-amd64 AS build -MAINTAINER eesast -WORKDIR /usr/local -COPY . . -RUN dotnet publish logic/Server/Server.csproj -c Release -o /usr/local/Server --self-contained true -r linux-x64 - -FROM eesast/thuai7_base:base -MAINTAINER eesast -WORKDIR /usr/local -COPY --from=build /usr/local/Server . -RUN mkdir /usr/local/team1 && mkdir /usr/local/team2 && mkdir /usr/local/playback -COPY ./dependency/shell/run_server.sh . -COPY ./CAPI/python /usr/local/PlayerCode/CAPI/python -COPY ./dependency/proto /usr/local/PlayerCode/dependency/proto -COPY ./dependency/shell /usr/local/PlayerCode/dependency/shell -WORKDIR /usr/local/PlayerCode/CAPI/python -RUN bash ../../dependency/shell/generate_proto.sh - -WORKDIR /usr/local -ENTRYPOINT [ "bash","./run_server.sh" ] diff --git a/dependency/Dockerfile/Dockerfile_run_client b/dependency/Dockerfile/Dockerfile_run_client index 2ed33752..dc469e6d 100644 --- a/dependency/Dockerfile/Dockerfile_run_client +++ b/dependency/Dockerfile/Dockerfile_run_client @@ -6,9 +6,8 @@ COPY . . FROM eesast/thuai7_base:base MAINTAINER eesast WORKDIR /usr/local -COPY --from=build /usr/local/Server . RUN mkdir /usr/local/team1 && mkdir /usr/local/team2 && mkdir /usr/local/playback -COPY ./dependency/shell/run_client.sh . +COPY ./dependency/shell/run.sh . COPY ./CAPI/python /usr/local/PlayerCode/CAPI/python COPY ./dependency/proto /usr/local/PlayerCode/dependency/proto COPY ./dependency/shell /usr/local/PlayerCode/dependency/shell @@ -17,4 +16,4 @@ RUN bash ../../dependency/shell/generate_proto.sh WORKDIR /usr/local RUN export TERMINAL=CLIENT -ENTRYPOINT [ "bash","./run.sh" ] +ENTRYPOINT [ "bash","./run.sh" ] \ No newline at end of file diff --git a/dependency/Dockerfile/Dockerfile_run_server b/dependency/Dockerfile/Dockerfile_run_server index 1d6b633e..b5c1b549 100644 --- a/dependency/Dockerfile/Dockerfile_run_server +++ b/dependency/Dockerfile/Dockerfile_run_server @@ -4,16 +4,10 @@ WORKDIR /usr/local COPY . . RUN dotnet publish logic/Server/Server.csproj -c Release -o /usr/local/Server --self-contained true -r linux-x64 -FROM eesast/thuai7_base:base -MAINTAINER eesast WORKDIR /usr/local COPY --from=build /usr/local/Server . RUN mkdir /usr/local/team1 && mkdir /usr/local/team2 && mkdir /usr/local/playback -<<<<<<<< HEAD:dependency/Dockerfile/Docker_run_client -COPY ./dependency/shell/run_client.sh . -======== -COPY ./dependency/shell/run_server.sh . ->>>>>>>> 218cff729c2110699b9e40a0d97a740f58e75462:dependency/Dockerfile/Dockerfile_run_server +COPY ./dependency/shell/run.sh . COPY ./CAPI/python /usr/local/PlayerCode/CAPI/python COPY ./dependency/proto /usr/local/PlayerCode/dependency/proto COPY ./dependency/shell /usr/local/PlayerCode/dependency/shell @@ -21,9 +15,5 @@ WORKDIR /usr/local/PlayerCode/CAPI/python RUN bash ../../dependency/shell/generate_proto.sh WORKDIR /usr/local -<<<<<<<< HEAD:dependency/Dockerfile/Docker_run_client -ENTRYPOINT [ "bash","./run_client.sh" ] -======== RUN export TERMINAL=SERVER -ENTRYPOINT [ "bash","./run.sh" ] ->>>>>>>> 218cff729c2110699b9e40a0d97a740f58e75462:dependency/Dockerfile/Dockerfile_run_server +ENTRYPOINT [ "bash","./run.sh" ] \ No newline at end of file diff --git a/dependency/py/rank.py b/dependency/py/rank.py deleted file mode 100644 index 3d443df6..00000000 --- a/dependency/py/rank.py +++ /dev/null @@ -1,205 +0,0 @@ -import os -import json -import re - -winGamesMap = {} -totalGamesMap = {} -studentTotalGame = {} -trickerTotalGame = {} -winRateMap = {} -studentWinMap = {} -trickerWinMap = {} -studentWinRateMap = {} -trickerWinRateMap = {} - -winGamesMap1 = {} -totalGamesMap1 = {} -studentTotalGame1 = {} -trickerTotalGame1 = {} -winRateMap1 = {} -studentWinMap1 = {} -trickerWinMap1 = {} -studentWinRateMap1 = {} -trickerWinRateMap1 = {} - -studentWinNum = 0 -trickerWinNum = 0 -totalGameNum = 0 - -studentWinNum1 = 0 -trickerWinNum1 = 0 -totalGameNum1 = 0 - -teamIDtoName = { - "951c89eb-aa9c-45d4-af10-ad9785a047d6": "无名万物之始", "2e504ec6-50b1-4985-b2fd-995927ea9717": "LQ说什么都队", "fb472ad6-65e0-494b-a7be-f6f25ecda018": "是啊我诶", - "3376909b-5ddb-41ab-994c-3c5b5ba60158": "叛逃者联盟", - "9b0f2257-734c-42e2-8061-c267e3d0d231": "ChatGPA", - "2de908c9-1b99-4811-ae00-68140d1c4527": "昊天上帝和他的三个神父", - "94866510-af51-439c-a41a-b4cb42596e25": "少年毕不了业", - "4613ef48-4988-4508-a258-66857a3250b8": "PKT48TeamTS", - "8e14b2a3-fc37-4fb6-b8ac-a722a10707d7": "京ICP备2022019669号-1 2022 EESAST", - "e8db213c-a636-483f-a6ed-84310b3093a4": "拉拉队", - "04abd472-ed7a-4840-8680-87d20db52721": "努力少女戏尔危", - "2bc1b761-ace3-4403-af83-e46ca328bcd0": "测试", - "4c1d6333-e25c-4b0f-bc06-9851db446bd7": "摆烂吧,少女", - "7f819704-99c0-41d8-bc61-26eec0bd73bb": "一会吃萤火虫", - "de915bbf-0751-4a9d-ab30-a470807406b2": "小小做题家", - "28baa2bf-5130-4a1e-ab9c-36e8faf87f84": "数析少女队", - "5c868c42-3b07-4280-a825-a6f80e0d5a2c": "沙壁北京", - "ed03d1ac-810a-4547-b54a-d56cd5213364": "我会出手队", - "5d59e45f-cb0e-4294-90f4-282adb1d476d": "闪电骑士团", - "637e20c1-a904-4f6f-b706-2cea7c4daf5e": "Mukava Poikaa", - "7185eb49-0cb0-43c0-a469-a39e636d66d4": "劝退吧,少女", - "d2a7ba71-4a86-4278-a362-8a8953a368f8": "纵火犯在何方", - "4e266301-7749-4699-b2de-511d458cf537": "土木清华没有水", - "454f37bd-2f54-4463-94d9-2df9aedb4f21": "电电做不队", - "a2573713-28e4-4af7-8c53-ab21f385f789": "王牌飞行队", - "194c3ddf-6846-47ec-a262-ca24f5639531": "快乐Debug", - "97cf5969-e8ff-410e-b85c-0c8359923289": "卷动量守恒", - "4646739a-9ff5-4854-a3b2-27d5b85ea504": "龙井队", - "c431d105-a2b3-4659-b713-6bc97132ec7f": "疯狂Thurs队", - "9ee48de1-a76a-40eb-b267-59c985bbe6cb": "蒸馍", - "5ef8ffbb-0776-4a74-a84f-3d80d5b4c2ae": "你说什么都队", - "65f94306-69c7-42a2-8c68-44cb45749aae": "closeAI", - "ab0406ae-6a0e-4c1e-9d36-eb14115de076": "N/A", - "82cbff06-9ed1-429b-afc3-7e050318bf93": "代码一行都不队", - "6b52346c-4528-424b-ac75-22fa573ebaad": "pqfobj", - "93e7f3f1-d47f-4588-b433-72877089f0bd": "你说得队", - "2f6f9ce3-f2d3-4799-b291-38dc04d048a0": "少女终末旅行", - "07c0ad6c-f612-4375-9b79-52bb89c79d76": "大括号换行委员会", - "bdf5b1c5-4dbc-4589-a6bc-8c5932c04de7": "孤客若风", - "f0d75eee-34a6-4484-8e23-720d26db747d": "/", - "acea715f-d5b0-4113-b6c3-9f6d7822f2e9": "难崩" -} - -dirs = os.listdir(".") -for dir in dirs: - if dir.startswith("Team"): - dirdir = dir.replace("Team_", "") - dirdir = dirdir.split("--vs--") - try: - with open(f"{dir}/result.json", 'r') as f: - result = json.load(f) - for i in (0, 1): - if dirdir[i] not in winGamesMap: - winGamesMap[dirdir[i]] = 0 - if dirdir[i] not in totalGamesMap: - totalGamesMap[dirdir[i]] = 0 - if dirdir[i] not in studentWinMap: - studentWinMap[dirdir[i]] = 0 - if dirdir[i] not in trickerWinMap: - trickerWinMap[dirdir[i]] = 0 - if dirdir[i] not in studentTotalGame: - studentTotalGame[dirdir[i]] = 0 - if dirdir[i] not in trickerTotalGame: - trickerTotalGame[dirdir[i]] = 0 - if dirdir[i] not in winGamesMap1: - winGamesMap1[dirdir[i]] = 0 - if dirdir[i] not in totalGamesMap1: - totalGamesMap1[dirdir[i]] = 0 - if dirdir[i] not in studentWinMap1: - studentWinMap1[dirdir[i]] = 0 - if dirdir[i] not in trickerWinMap1: - trickerWinMap1[dirdir[i]] = 0 - if dirdir[i] not in studentTotalGame1: - studentTotalGame1[dirdir[i]] = 0 - if dirdir[i] not in trickerTotalGame1: - trickerTotalGame1[dirdir[i]] = 0 - - totalGamesMap[dirdir[0]] += 1 - totalGamesMap[dirdir[1]] += 1 - studentTotalGame[dirdir[0]] += 1 - trickerTotalGame[dirdir[1]] += 1 - - totalGameNum += 1 - - if result["Student"] < result["Tricker"]: - winGamesMap[dirdir[1]] += 1 - trickerWinMap[dirdir[1]] += 1 - trickerWinNum += 1 - - elif result["Student"] > result["Tricker"]: - winGamesMap[dirdir[0]] += 1 - studentWinMap[dirdir[0]] += 1 - studentWinNum += 1 - - else: - winGamesMap[dirdir[0]] += 0.5 - winGamesMap[dirdir[1]] += 0.5 - - if result["Student"] != 0 and result["Tricker"] != 0: - - totalGameNum1 += 1 - totalGamesMap1[dirdir[0]] += 1 - totalGamesMap1[dirdir[1]] += 1 - studentTotalGame1[dirdir[0]] += 1 - trickerTotalGame1[dirdir[1]] += 1 - - if result["Student"] < result["Tricker"]: - winGamesMap1[dirdir[1]] += 1 - trickerWinMap1[dirdir[1]] += 1 - trickerWinNum1 += 1 - - elif result["Student"] > result["Tricker"]: - winGamesMap1[dirdir[0]] += 1 - studentWinMap1[dirdir[0]] += 1 - studentWinNum1 += 1 - - else: - winGamesMap1[dirdir[0]] += 0.5 - winGamesMap1[dirdir[1]] += 0.5 - - except: - pass - -for i in totalGamesMap: - winRateMap[i] = winGamesMap[i] / totalGamesMap[i] - if studentTotalGame[i] == 0: - studentWinRateMap[i] = 0 - else: - studentWinRateMap[i] = studentWinMap[i] / studentTotalGame[i] - if trickerTotalGame[i] == 0: - trickerWinRateMap[i] = 0 - else: - trickerWinRateMap[i] = trickerWinMap[i] / trickerTotalGame[i] - - -sortedMap = sorted(winRateMap.items(), key=lambda kv: ( - kv[1], kv[0]), reverse=True) - -print("************************ALL GAMES(with 0 player)************************") - -for i in sortedMap: - width = 33 - len(re.findall('([\u4e00-\u9fa5])', teamIDtoName[i[0]])) - print( - f"Team {teamIDtoName[i[0]]:{width}}({i[0]}) wins {winGamesMap[i[0]]:4}/{totalGamesMap[i[0]]:<2} games({i[1]:.3f}), student wins {studentWinMap[i[0]]:2}/{studentTotalGame[i[0]]:<2}({studentWinRateMap[i[0]]:.3f}), tricker wins {trickerWinMap[i[0]]:2}/{trickerTotalGame[i[0]]:<2}({trickerWinRateMap[i[0]]:.3f})") - -print( - f"Total games: {totalGameNum}, student wins {studentWinNum}, tricker wins {trickerWinNum}") - -for i in totalGamesMap1: - if totalGamesMap1[i] == 0: - winRateMap1[i] = 0 - else: - winRateMap1[i] = winGamesMap1[i] / totalGamesMap1[i] - if studentTotalGame1[i] == 0: - studentWinRateMap1[i] = 0 - else: - studentWinRateMap1[i] = studentWinMap1[i] / studentTotalGame1[i] - if trickerTotalGame1[i] == 0: - trickerWinRateMap1[i] = 0 - else: - trickerWinRateMap1[i] = trickerWinMap1[i] / trickerTotalGame1[i] - - -sortedMap1 = sorted(winRateMap1.items(), key=lambda kv: ( - kv[1], kv[0]), reverse=True) - -print("************************NON-0 GAMES(no 0 player)************************") - -for i in sortedMap1: - width = 33 - len(re.findall('([\u4e00-\u9fa5])', teamIDtoName[i[0]])) - print(f"Team {teamIDtoName[i[0]]:{width}}({i[0]}) wins {winGamesMap1[i[0]]:4}/{totalGamesMap1[i[0]]:<2} games({i[1]:.3f}), student wins {studentWinMap1[i[0]]:2}/{studentTotalGame1[i[0]]:<2}({studentWinRateMap1[i[0]]:.3f}), tricker wins {trickerWinMap1[i[0]]:2}/{trickerTotalGame1[i[0]]:<2}({trickerWinRateMap1[i[0]]:.3f})") - -print( - f"Total games: {totalGameNum1}, student wins {studentWinNum1}, tricker wins {trickerWinNum1}") diff --git a/dependency/shell/run.sh b/dependency/shell/run.sh index db5acd89..c74882db 100644 --- a/dependency/shell/run.sh +++ b/dependency/shell/run.sh @@ -3,6 +3,23 @@ python_dir=/usr/local/PlayerCode/CAPI/python/PyAPI python_main_dir=/usr/local/PlayerCode/CAPI/python playback_dir=/usr/local/playback map_dir=/usr/local/map +mkdir -p $playback_dir + +# initialize +if [[ "${MODE}" == "ARENA" ]]; then + MODE=0 +elif [[ "${MODE}" == "COMPETITION" ]]; then + MODE=1 +fi + +# set default value +: "${TEAM_SEQ_ID:=0}" +: "${TEAM_LABELS:=1:2}" +: "${TEAM_LABEL:=1}" +: "${EXPOSED=1}" +: "${MODE=0}" +: "${TIME=10}" +: "${CONNECT_IP=172.17.0.1}" get_current_team_label() { if [ $TEAM_SEQ_ID -eq $2 ]; then @@ -42,6 +59,8 @@ if [ "$TERMINAL" = "SERVER" ]; then nice -10 ./Server --port 8888 --teamCount 2 --shipNum 4 --resultFileName $playback_dir/result --gameTimeInSecond $TIME --mode $MODE --mapResource $map_path --notAllowSpectator --url $URL --token $TOKEN --fileName $playback_dir/video --startLockFile $playback_dir/start.lock > $playback_dir/server.log 2>&1 & server_pid=$! fi + echo "server pid: $server_pid" + ls $playback_dir sleep 10 @@ -52,10 +71,10 @@ if [ "$TERMINAL" = "SERVER" ]; then sleep 1 ps -p $server_pid > /dev/null 2>&1 done - # result=$(cat /usr/local/playback/result.json) - # score0=$(echo "$result" | grep -oP '(?<="Student":)\d+') - # score1=$(echo "$result" | grep -oP '(?<="Tricker":)\d+') - # curl $URL -X PUT -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" -d '{"result":[{"team_id":0, "score":'${score0}'}, {"team_id":1, "score":'${score1}'}], "mode":'${MODE}'}'> $playback_dir/send.log 2>&1 + result=$(cat /usr/local/playback/result.json) + score0=$(echo "$result" | grep -oP '(?<="Team1":)\d+') + score1=$(echo "$result" | grep -oP '(?<="Team2":)\d+') + curl $URL -X PUT -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" -d '{"result":[{"team_id":0, "score":'${score0}'}, {"team_id":1, "score":'${score1}'}], "mode":'${MODE}'}'> $playback_dir/send.log 2>&1 touch $playback_dir/finish.lock echo "Finish" else @@ -72,35 +91,31 @@ elif [ "$TERMINAL" = "CLIENT" ]; then # parse team label name read_array get_current_team_label $TEAM_LABELS - # k is an enum (1,2), 1 = STUDENT, 2 = TRICKER - if [ "$current_team_label" = "Student" ]; then + if [ "$current_team_label" = "1" ]; then k=1 - elif [ "$current_team_label" = "Tricker" ]; then + elif [ "$current_team_label" = "2" ]; then k=2 else echo "Error: Invalid Team Label" exit fi pushd /usr/local/code - if [ $k -eq 1 ]; then - for i in {1..4} - do - j=$((i - 1)) # student player id from 0 to 3 - code_name=Student$i - if [ -f "./$code_name.py" ]; then - cp -r $python_main_dir $python_main_dir$i - cp -f ./$code_name.py $python_main_dir$i/PyAPI/AI.py - nice -0 python3 $python_main_dir$i/PyAPI/main.py -I 127.0.0.1 -P 8888 -p $j > $playback_dir/team$k-player$j.log 2>&1 & - elif [ -f "./$code_name" ]; then - nice -0 ./$code_name -I 127.0.0.1 -P 8888 -p $j > $playback_dir/team$k-player$j.log 2>&1 & - else - echo "ERROR. $code_name is not found." - fi - done + for i in {0..4} + do + if [ $i -eq 0 ]; then + code_name=Home + if [ -f "./$code_name.py" ]; then + cp -r $python_main_dir $python_main_dir$i + cp -f ./$code_name.py $python_main_dir$i/PyAPI/AI.py + nice -0 python3 $python_main_dir$i/PyAPI/main.py -I + elif [ -f "./$code_name" ]; then + nice -0 ./$code_name -I 127.0.0.1 -P 8888 -p $j > $playback_dir/team$k-player$j.log 2>&1 & + else + echo "ERROR. $code_name is not found." + fi else - i=5 - j=4 # tricker id is 4 - code_name=Tricker + j=$i + code_name=Ship$i if [ -f "./$code_name.py" ]; then cp -r $python_main_dir $python_main_dir$i cp -f ./$code_name.py $python_main_dir$i/PyAPI/AI.py @@ -111,6 +126,7 @@ elif [ "$TERMINAL" = "CLIENT" ]; then echo "ERROR. $code_name is not found." fi fi + done popd else echo "VALUE ERROR: TERMINAL is neither SERVER nor CLIENT." diff --git a/dependency/shell/run_client.sh b/dependency/shell/run_client.sh deleted file mode 100644 index 61a09d5e..00000000 --- a/dependency/shell/run_client.sh +++ /dev/null @@ -1,86 +0,0 @@ -#!/usr/local - -# 该代码暂时弃用,请使用run.sh - -python_dir=/usr/local/PlayerCode/CAPI/python/PyAPI -python_main_dir=/usr/local/PlayerCode/CAPI/python -playback_dir=/usr/local/playback - -sleep 5 -for k in {1..2} -do - pushd /usr/local/team$k - if [ $k -eq 1 ]; then - for i in {1..4} - do - j=$((i - 1)) - if [ -f "./player$i.py" ]; then - cp -r $python_main_dir $python_main_dir$i - cp -f ./player$i.py $python_main_dir$i/PyAPI/AI.py - nice -0 python3 $python_main_dir$i/PyAPI/main.py -I 127.0.0.1 -P 8888 -p $j > $playback_dir/team$k-player$j.log 2>&1 & - elif [ -f "./capi$i" ]; then - nice -0 ./capi$i -I 127.0.0.1 -P 8888 -p $j > $playback_dir/team$k-player$j.log 2>&1 & - else - echo "ERROR. $i is not found." - fi - done - else - for i in {5..5} - do - j=$((i - 1)) - if [ -f "./player$i.py" ]; then - cp -r $python_main_dir $python_main_dir$i - cp -f ./player$i.py $python_main_dir$i/PyAPI/AI.py - nice -0 python3 $python_main_dir$i/PyAPI/main.py -I 127.0.0.1 -P 8888 -p $j > $playback_dir/team$k-player$j.log 2>&1 & - elif [ -f "./capi$i" ]; then - nice -0 ./capi$i -I 127.0.0.1 -P 8888 -p $j > $playback_dir/team$k-player$j.log 2>&1 & - else - echo "ERROR. $i is not found." - fi - done - fi - popd -done - -sleep 10 - -if [ -f $playback_dir/start.lock ]; then - ps -p $server_pid - while [ $? -eq 0 ] - do - sleep 1 - ps -p $server_pid > /dev/null 2>&1 - done - # result=$(cat /usr/local/playback/result.json) - # score0=$(echo "$result" | grep -oP '(?<="Student":)\d+') - # score1=$(echo "$result" | grep -oP '(?<="Tricker":)\d+') - # curl $URL -X PUT -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" -d '{"result":[{"team_id":0, "score":'${score0}'}, {"team_id":1, "score":'${score1}'}], "mode":'${MODE}'}'> $playback_dir/send.log 2>&1 - touch $playback_dir/finish.lock - echo "Finish" -else - echo "Failed to start game." - touch $playback_dir/finish.lock - touch temp.lock - mv -f temp.lock $playback_dir/video.thuaipb - kill -9 $server_pid -fi -for k in {1..2} -do - pushd /usr/local/team$k - - for i in {1..5} - do - j=$((i - 1)) - if [ -f "./player$i.py" ]; then - cp -r $python_main_dir $python_main_dir$i - cp -f ./player$i.py $python_main_dir$i/PyAPI/AI.py - nice -0 python3 $python_main_dir$i/PyAPI/main.py -I 127.0.0.1 -P 8888 -p $j > $playback_dir/team$k-player$j.log 2>&1 & - elif [ -f "./capi$i" ]; then - nice -0 ./capi$i -I 127.0.0.1 -P 8888 -p $j > $playback_dir/team$k-player$j.log 2>&1 & - else - echo "ERROR. $i is not found." - fi - done - - popd -done diff --git a/dependency/shell/run_server.sh b/dependency/shell/run_server.sh deleted file mode 100644 index d833794d..00000000 --- a/dependency/shell/run_server.sh +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/local - -# 该代码暂时弃用,请使用run.sh - -python_dir=/usr/local/PlayerCode/CAPI/python/PyAPI -python_main_dir=/usr/local/PlayerCode/CAPI/python -playback_dir=/usr/local/playback - -if [ $EXPOSED -eq 1 ]; then - nice -10 ./Server --port 8888 --TeamCount 2 --ShipNum 4 --resultFileName $playback_dir/result --gameTimeInSecond $TIME --mode $MODE --mapResource $MAP --url $URL --token $TOKEN --fileName $playback_dir/video --startLockFile $playback_dir/start.lock > $playback_dir/server.log 2>&1 & - server_pid=$! -else - nice -10 ./Server --port 8888 --TeamCount 2 --ShipNum 4 --resultFileName $playback_dir/result --gameTimeInSecond $TIME --mode $MODE --mapResource $MAP --notAllowSpectator --url $URL --token $TOKEN --fileName $playback_dir/video --startLockFile $playback_dir/start.lock > $playback_dir/server.log 2>&1 & - server_pid=$! -fi -sleep 5 -for k in {1..2} -do - pushd /usr/local/team$k - for i in {1..5} - do - j=$((i - 1)) - if [ -f "./player$i.py" ]; then - cp -r $python_main_dir $python_main_dir$i - cp -f ./player$i.py $python_main_dir$i/PyAPI/AI.py - nice -0 python3 $python_main_dir$i/PyAPI/main.py -I 127.0.0.1 -P 8888 -p $j > $playback_dir/team$k-player$j.log 2>&1 & - elif [ -f "./capi$i" ]; then - nice -0 ./capi$i -I 127.0.0.1 -P 8888 -p $j > $playback_dir/team$k-player$j.log 2>&1 & - else - echo "ERROR. $i is not found." - fi - done - popd -done - - - -sleep 10 - nice -10 ./Server --ip 127.0.0.1 --port 8888 --teamCount 2 --shipNum 4 --resultFileName $playback_dir/result --gameTimeInSecond $TIME --mode $MODE --mapResource $MAP --url $URL --token $TOKEN --fileName $playback_dir/video --startLockFile $playback_dir/start.lock > $playback_dir/server.log 2>&1 & - server_pid=$! -else - nice -10 ./Server --ip 127.0.0.1 --port 8888 --teamCount 2 --shipNum 4 --resultFileName $playback_dir/result --gameTimeInSecond $TIME --mode $MODE --mapResource $MAP --notAllowSpectator --url $URL --token $TOKEN --fileName $playback_dir/video --startLockFile $playback_dir/start.lock > $playback_dir/server.log 2>&1 & - server_pid=$! -fi - -if [ -f $playback_dir/start.lock ]; then - ps -p $server_pid - while [ $? -eq 0 ] - do - sleep 1 - ps -p $server_pid > /dev/null 2>&1 - done - # result=$(cat /usr/local/playback/result.json) - # score0=$(echo "$result" | grep -oP '(?<="Student":)\d+') - # score1=$(echo "$result" | grep -oP '(?<="Tricker":)\d+') - # curl $URL -X PUT -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" -d '{"result":[{"team_id":0, "score":'${score0}'}, {"team_id":1, "score":'${score1}'}], "mode":'${MODE}'}'> $playback_dir/send.log 2>&1 - touch $playback_dir/finish.lock - echo "Finish" -else - echo "Failed to start game." - touch $playback_dir/finish.lock - touch temp.lock - mv -f temp.lock $playback_dir/video.thuaipb - kill -9 $server_pid -fi From 39eb0ef50ebe7132616bc3f808fcd675ddea3e26 Mon Sep 17 00:00:00 2001 From: GuoWQ222 Date: Tue, 7 May 2024 17:05:59 +0800 Subject: [PATCH 074/179] fix:Httpsender --- logic/Server/GameServer.cs | 14 ++++++++------ logic/Server/HttpSender.cs | 10 +++------- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/logic/Server/GameServer.cs b/logic/Server/GameServer.cs index 8eafafaf..65efb626 100755 --- a/logic/Server/GameServer.cs +++ b/logic/Server/GameServer.cs @@ -109,7 +109,7 @@ private void SaveGameResult(string path) } - protected void SendGameResult(int[] scores, int mode) // 天梯的 Server 给网站发消息记录比赛结果 + protected void SendGameResult(int[] scores, bool crashed) // 天梯的 Server 给网站发消息记录比赛结果 { string? url2 = Environment.GetEnvironmentVariable("FINISH_URL"); if (url2 == null) @@ -122,7 +122,8 @@ protected void SendGameResult(int[] scores, int mode) // 天梯的 Server 给 httpSender.Url = url2; httpSender.Token = options.Token; } - httpSender?.SendHttpRequest(scores, mode).Wait(); + string state = crashed ? "Crashed" : "Finished"; + httpSender?.SendHttpRequest(scores, state).Wait(); } protected double[] PullScore(double[] scores) @@ -214,15 +215,16 @@ private void OnGameEnd() double[] doubleArray = scores.Select(x => (double)x).ToArray(); if (options.Mode == 2) { + bool crash = false; doubleArray = PullScore(doubleArray); - scores = doubleArray.Select(x => (int)x).ToArray(); - if (scores.Length == 0) + if (doubleArray.Length == 0) { + crash = true; Console.WriteLine("Error: No data returned from the web!"); - } else - SendGameResult(scores, options.Mode); + scores = doubleArray.Select(x => (int)x).ToArray(); + SendGameResult(scores, crash); } endGameSem.Release(); } diff --git a/logic/Server/HttpSender.cs b/logic/Server/HttpSender.cs index 3db5658a..a7ad5980 100755 --- a/logic/Server/HttpSender.cs +++ b/logic/Server/HttpSender.cs @@ -25,7 +25,7 @@ public string Token // { // this.SendHttpRequest(new()).Wait(); // } - public async Task SendHttpRequest(int[] scores, int mode) + public async Task SendHttpRequest(int[] scores, string state) { try { @@ -33,12 +33,8 @@ public async Task SendHttpRequest(int[] scores, int mode) request.DefaultRequestHeaders.Authorization = new("Bearer", token); using var response = await request.PutAsync(url, JsonContent.Create(new { - result = new TeamScore[] - { - new() { TeamID = 0, Score = scores[0], }, - new() { TeamID = 1, Score = scores[1], }, - }, - mode + status = state, + scores = new int[] { scores[0], scores[1] }, })); GameServerLogging.logger.ConsoleLog("Send to web successfully!"); GameServerLogging.logger.ConsoleLog($"Web response: {await response.Content.ReadAsStringAsync()}"); From 8e5a2072907f7f0d35a938f2374fac2182e670b7 Mon Sep 17 00:00:00 2001 From: xiangmy21 <90919434+xiangmy21@users.noreply.github.com> Date: Tue, 7 May 2024 17:15:30 +0800 Subject: [PATCH 075/179] Update run.sh --- dependency/shell/run.sh | 152 ++++++++++++++++++++-------------------- 1 file changed, 77 insertions(+), 75 deletions(-) diff --git a/dependency/shell/run.sh b/dependency/shell/run.sh index db5acd89..6f0cc487 100644 --- a/dependency/shell/run.sh +++ b/dependency/shell/run.sh @@ -1,117 +1,119 @@ #!/usr/local python_dir=/usr/local/PlayerCode/CAPI/python/PyAPI python_main_dir=/usr/local/PlayerCode/CAPI/python -playback_dir=/usr/local/playback +playback_dir=/usr/local/output map_dir=/usr/local/map +mkdir -p $playback_dir -get_current_team_label() { - if [ $TEAM_SEQ_ID -eq $2 ]; then - echo "find current team label: $1" - current_team_label=$1 - fi -} +# initialize +if [[ "${MODE}" == "ARENA" ]]; then + MODE_NUM=2 +elif [[ "${MODE}" == "COMPETITION" ]]; then + MODE_NUM=1 +fi +# set default value +: "${TEAM_SEQ_ID:=0}" +: "${TEAM_LABELS:=Team:Team}" +: "${TEAM_LABEL:=Team}" +: "${EXPOSED=1}" +: "${MODE_NUM=2}" +: "${GAME_TIME=600}" +: "${CONNECT_IP=172.17.0.1}" + +# get_current_team_label() { +# if [ $TEAM_SEQ_ID -eq $2 ]; then +# echo "find current team label: $1" +# current_team_label=$1 +# fi +# } -read_array() { - callback=$1 - echo "read array: set callback command: $callback" +# read_array() { +# callback=$1 +# echo "read array: set callback command: $callback" - IFS=':' read -r -a fields <<< "$2" +# IFS=':' read -r -a fields <<< "$2" - count=0 # loop count +# count=0 # loop count - for field in "${fields[@]}" - do - echo "parse field: $field" - param0=$field +# for field in "${fields[@]}" +# do +# echo "parse field: $field" +# param0=$field - # call command - run_command="$callback $param0 $count" - echo "Call Command: $run_command" - $run_command +# # call command +# run_command="$callback $param0 $count" +# echo "Call Command: $run_command" +# $run_command - count=$((count+1)) - done -} +# count=$((count+1)) +# done +# } if [ "$TERMINAL" = "SERVER" ]; then map_path=$map_dir/$MAP_ID.txt if [ $EXPOSED -eq 1 ]; then - nice -10 ./Server --port 8888 --teamCount 2 --shipNum 4 --resultFileName $playback_dir/result --gameTimeInSecond $TIME --mode $MODE --mapResource $map_path --url $URL --token $TOKEN --fileName $playback_dir/video --startLockFile $playback_dir/start.lock > $playback_dir/server.log 2>&1 & + nice -10 ./Server --port 8888 --teamCount 2 --shipNum 4 --resultFileName $playback_dir/result --gameTimeInSecond $GAME_TIME --mode $MODE_NUM --mapResource $map_path --url $SCORE_URL --token $TOKEN --fileName $playback_dir/video --startLockFile $playback_dir/start.lock > $playback_dir/server.log 2>&1 & server_pid=$! else - nice -10 ./Server --port 8888 --teamCount 2 --shipNum 4 --resultFileName $playback_dir/result --gameTimeInSecond $TIME --mode $MODE --mapResource $map_path --notAllowSpectator --url $URL --token $TOKEN --fileName $playback_dir/video --startLockFile $playback_dir/start.lock > $playback_dir/server.log 2>&1 & + nice -10 ./Server --port 8888 --teamCount 2 --shipNum 4 --resultFileName $playback_dir/result --gameTimeInSecond $GAME_TIME --mode $MODE_NUM --mapResource $map_path --notAllowSpectator --url $SCORE_URL --token $TOKEN --fileName $playback_dir/video --startLockFile $playback_dir/start.lock > $playback_dir/server.log 2>&1 & server_pid=$! fi - sleep 10 + echo "server pid: $server_pid" + ls $playback_dir - if [ -f $playback_dir/start.lock ]; then - ps -p $server_pid - while [ $? -eq 0 ] - do - sleep 1 - ps -p $server_pid > /dev/null 2>&1 - done - # result=$(cat /usr/local/playback/result.json) - # score0=$(echo "$result" | grep -oP '(?<="Student":)\d+') - # score1=$(echo "$result" | grep -oP '(?<="Tricker":)\d+') - # curl $URL -X PUT -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" -d '{"result":[{"team_id":0, "score":'${score0}'}, {"team_id":1, "score":'${score1}'}], "mode":'${MODE}'}'> $playback_dir/send.log 2>&1 - touch $playback_dir/finish.lock - echo "Finish" - else + echo "SCORE URL: $SCORE_URL" + echo "FINISH URL: $FINISH_URL" + + echo "waiting..." + sleep 30 # wait connection time + echo "watching..." + + if [ ! -f $playback_dir/start.lock ]; then echo "Failed to start game." - touch $playback_dir/finish.lock touch temp.lock mv -f temp.lock $playback_dir/video.thuaipb kill -9 $server_pid + finish_payload='{"result": {"status": "Crashed", "scores": [0, 0]}}' + curl $FINISH_URL -X POST -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" -d "${finish_payload}" > $playback_dir/send.log 2>&1 fi elif [ "$TERMINAL" = "CLIENT" ]; then echo "Client Mode! Team Label data - $TEAM_LABELS" - - # parse team label name - read_array get_current_team_label $TEAM_LABELS - # k is an enum (1,2), 1 = STUDENT, 2 = TRICKER - if [ "$current_team_label" = "Student" ]; then - k=1 - elif [ "$current_team_label" = "Tricker" ]; then - k=2 - else - echo "Error: Invalid Team Label" - exit - fi + k = $TEAM_SEQ_ID pushd /usr/local/code - if [ $k -eq 1 ]; then - for i in {1..4} - do - j=$((i - 1)) # student player id from 0 to 3 - code_name=Student$i + for i in {0..4} + do + if [ $i -eq 0 ]; then + code_name=Team if [ -f "./$code_name.py" ]; then + echo "find ./$code_name.py" cp -r $python_main_dir $python_main_dir$i cp -f ./$code_name.py $python_main_dir$i/PyAPI/AI.py - nice -0 python3 $python_main_dir$i/PyAPI/main.py -I 127.0.0.1 -P 8888 -p $j > $playback_dir/team$k-player$j.log 2>&1 & + nice -0 python3 $python_main_dir$i/PyAPI/main.py -I $CONNECT_IP -P $PORT -t $k -p $i > $playback_dir/team$k-$code_name.log 2>&1 & elif [ -f "./$code_name" ]; then - nice -0 ./$code_name -I 127.0.0.1 -P 8888 -p $j > $playback_dir/team$k-player$j.log 2>&1 & + echo "find ./$code_name" + nice -0 ./$code_name -I $CONNECT_IP -P $PORT -t $k -p $i > $playback_dir/team$k-$codename.log 2>&1 & + else + echo "ERROR. $code_name is not found." + fi + else + code_name=Ship$i + if [ -f "./$code_name.py" ]; then + echo "find ./$code_name.py" + cp -r $python_main_dir $python_main_dir$i + cp -f ./$code_name.py $python_main_dir$i/PyAPI/AI.py + nice -0 python3 $python_main_dir$i/PyAPI/main.py -I $CONNECT_IP -P $PORT -t $k -p $i > $playback_dir/team$k-$code_name.log 2>&1 & + elif [ -f "./$code_name" ]; then + echo "find ./$code_name" + nice -0 ./$code_name -I $CONNECT_IP -P $PORT -t $k -p $i > $playback_dir/team$k-$code_name.log 2>&1 & else echo "ERROR. $code_name is not found." fi - done - else - i=5 - j=4 # tricker id is 4 - code_name=Tricker - if [ -f "./$code_name.py" ]; then - cp -r $python_main_dir $python_main_dir$i - cp -f ./$code_name.py $python_main_dir$i/PyAPI/AI.py - nice -0 python3 $python_main_dir$i/PyAPI/main.py -I 127.0.0.1 -P 8888 -p $j > $playback_dir/team$k-player$j.log 2>&1 & - elif [ -f "./$code_name" ]; then - nice -0 ./$code_name -I 127.0.0.1 -P 8888 -p $j > $playback_dir/team$k-player$j.log 2>&1 & - else - echo "ERROR. $code_name is not found." fi - fi + done popd else echo "VALUE ERROR: TERMINAL is neither SERVER nor CLIENT." -fi \ No newline at end of file +fi From 8b603a2b29ec0b772433d28756fe29a2da08e04c Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Tue, 7 May 2024 17:20:08 +0800 Subject: [PATCH 076/179] docs: :bookmark: Update version of lib --- installer/Data/MD5FileData.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/installer/Data/MD5FileData.cs b/installer/Data/MD5FileData.cs index 3b6c8522..f30e30b1 100644 --- a/installer/Data/MD5FileData.cs +++ b/installer/Data/MD5FileData.cs @@ -26,7 +26,7 @@ public class TVersion { // 代码库版本 [JsonInclude] - public Version LibVersion = new Version(1, 0, 2, 0); + public Version LibVersion = new Version(1, 0, 2, 1); // 选手代码模板版本 [JsonInclude] public Version TemplateVersion = new Version(1, 0, 0, 3); From b5e02b027c34a30ba1f282afad9cee00e545aba5 Mon Sep 17 00:00:00 2001 From: ONLOX <3316820553@qq.com> Date: Tue, 7 May 2024 17:30:17 +0800 Subject: [PATCH 077/179] feat: add run server and client docker images --- .github/workflows/docker.yml | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 5a0bb9fc..0e6bdee3 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -22,7 +22,12 @@ jobs: - name: Push cpp_compile image to DockerHub run: docker push ${{ secrets.DOCKER_USERNAME }}/thuai7_cpp:latest - - name: Build run docker image - run: docker build -t ${{ secrets.DOCKER_USERNAME }}/thuai7_run:latest -f ./dependency/Dockerfile/Dockerfile_run . - - name: Push run image to DockerHub - run: docker push ${{ secrets.DOCKER_USERNAME }}/thuai7_run:latest + - name: Build run_server docker image + run: docker build -t ${{ secrets.DOCKER_USERNAME }}/thuai7_run_server:latest -f ./dependency/Dockerfile/Dockerfile_run_server . + - name: Push run_server image to DockerHub + run: docker push ${{ secrets.DOCKER_USERNAME }}/thuai7_run_server:latest + + - name: Build run_client docker image + run: docker build -t ${{ secrets.DOCKER_USERNAME }}/thuai7_run_client:latest -f ./dependency/Dockerfile/Dockerfile_run_client . + - name: Push run_client image to DockerHub + run: docker push ${{ secrets.DOCKER_USERNAME }}/thuai7_run_client:latest \ No newline at end of file From a39673af07630b831abde417738ecac30c84a638 Mon Sep 17 00:00:00 2001 From: xiangmy21 <90919434+xiangmy21@users.noreply.github.com> Date: Tue, 7 May 2024 20:00:06 +0800 Subject: [PATCH 078/179] Update run.sh --- dependency/shell/run.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dependency/shell/run.sh b/dependency/shell/run.sh index 7d0df74f..6b309366 100644 --- a/dependency/shell/run.sh +++ b/dependency/shell/run.sh @@ -81,7 +81,7 @@ if [ "$TERMINAL" = "SERVER" ]; then elif [ "$TERMINAL" = "CLIENT" ]; then echo "Client Mode! Team Label data - $TEAM_LABELS" - k = $TEAM_SEQ_ID + k=$TEAM_SEQ_ID pushd /usr/local/code for i in {0..4} do @@ -116,4 +116,4 @@ elif [ "$TERMINAL" = "CLIENT" ]; then popd else echo "VALUE ERROR: TERMINAL is neither SERVER nor CLIENT." -fi \ No newline at end of file +fi From 37a485cfc7e8ed22d1634ea0ca7e83c5ad75d7ea Mon Sep 17 00:00:00 2001 From: GuoWQ222 Date: Tue, 7 May 2024 20:11:25 +0800 Subject: [PATCH 079/179] fix --- logic/Server/GameServer.cs | 4 ++-- logic/Server/HttpSender.cs | 5 ++--- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/logic/Server/GameServer.cs b/logic/Server/GameServer.cs index 65efb626..acee6f86 100755 --- a/logic/Server/GameServer.cs +++ b/logic/Server/GameServer.cs @@ -23,7 +23,7 @@ partial class GameServer : ServerBase private readonly ConcurrentDictionary semaDict1 = new(); // private object semaDictLock = new(); protected readonly ArgumentOptions options; - private readonly HttpSender? httpSender; + private readonly HttpSender httpSender; private readonly object gameLock = new(); private MessageToClient currentGameInfo = new(); private readonly MessageOfObj currentMapMsg = new(); @@ -220,7 +220,7 @@ private void OnGameEnd() if (doubleArray.Length == 0) { crash = true; - Console.WriteLine("Error: No data returned from the web!"); + GameServerLogging.logger.ConsoleLog("Error: No data returned from the web!"); } else scores = doubleArray.Select(x => (int)x).ToArray(); diff --git a/logic/Server/HttpSender.cs b/logic/Server/HttpSender.cs index a7ad5980..728e627a 100755 --- a/logic/Server/HttpSender.cs +++ b/logic/Server/HttpSender.cs @@ -31,7 +31,7 @@ public async Task SendHttpRequest(int[] scores, string state) { var request = new HttpClient(); request.DefaultRequestHeaders.Authorization = new("Bearer", token); - using var response = await request.PutAsync(url, JsonContent.Create(new + using var response = await request.PostAsync(url, JsonContent.Create(new { status = state, scores = new int[] { scores[0], scores[1] }, @@ -48,12 +48,11 @@ public async Task SendHttpRequest(int[] scores, string state) public async Task GetLadderScore(double[] scores) { - try { var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Authorization = new("Bearer", token); - var response = await httpClient.PostAsync(url, JsonContent.Create(new { HttpHeaders = token })); + var response = await httpClient.PostAsync(url, null); // 读取响应内容为字符串 var jsonString = await response.Content.ReadAsStringAsync(); From 17b6664a427e288d8cff2cf700c1b53b0fd5aafe Mon Sep 17 00:00:00 2001 From: xiangmy21 <90919434+xiangmy21@users.noreply.github.com> Date: Tue, 7 May 2024 21:02:35 +0800 Subject: [PATCH 080/179] Update run.sh --- dependency/shell/run.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/dependency/shell/run.sh b/dependency/shell/run.sh index 6b309366..7ba0d06c 100644 --- a/dependency/shell/run.sh +++ b/dependency/shell/run.sh @@ -113,6 +113,7 @@ elif [ "$TERMINAL" = "CLIENT" ]; then fi fi done + sleep $((GAME_TIME)) popd else echo "VALUE ERROR: TERMINAL is neither SERVER nor CLIENT." From 029b249868b00acc9cf184ec49394e790d48f077 Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Tue, 7 May 2024 22:21:14 +0800 Subject: [PATCH 081/179] style: :hammer: Change obsolete usage MAINTAINER to LABEL maintainer="" --- dependency/Dockerfile/Dockerfile_base | 2 +- dependency/Dockerfile/Dockerfile_cpp | 2 +- dependency/Dockerfile/Dockerfile_run_client | 4 ++-- dependency/Dockerfile/Dockerfile_run_server | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/dependency/Dockerfile/Dockerfile_base b/dependency/Dockerfile/Dockerfile_base index 2eeb56ad..d67ff537 100755 --- a/dependency/Dockerfile/Dockerfile_base +++ b/dependency/Dockerfile/Dockerfile_base @@ -1,5 +1,5 @@ FROM python:3.9.16-bullseye -MAINTAINER eesast +LABEL maintainer="eesast" WORKDIR /usr/local RUN apt-get update && apt-get install --no-install-recommends -y gcc g++ make wget ca-certificates cmake autoconf automake libtool curl unzip git RUN git clone -b v1.46.3 --depth 1 --shallow-submodules https://gitee.com/mirrors/grpc.git && wget -P . https://cloud.tsinghua.edu.cn/f/1f2713efd9e44255abd6/?dl=1 && mv 'index.html?dl=1' third_party.tar.gz diff --git a/dependency/Dockerfile/Dockerfile_cpp b/dependency/Dockerfile/Dockerfile_cpp index d15e577d..9e143950 100755 --- a/dependency/Dockerfile/Dockerfile_cpp +++ b/dependency/Dockerfile/Dockerfile_cpp @@ -1,6 +1,6 @@ #FROM ubuntu:18.04 FROM eesast/thuai7_base:base -MAINTAINER eesast +LABEL maintainer="eesast" WORKDIR /usr/local COPY ./CAPI/cpp /usr/local/PlayerCode/CAPI/cpp diff --git a/dependency/Dockerfile/Dockerfile_run_client b/dependency/Dockerfile/Dockerfile_run_client index dc469e6d..28e9cea2 100644 --- a/dependency/Dockerfile/Dockerfile_run_client +++ b/dependency/Dockerfile/Dockerfile_run_client @@ -1,10 +1,10 @@ FROM mcr.microsoft.com/dotnet/sdk:8.0.204-jammy-amd64 AS build -MAINTAINER eesast +LABEL maintainer="eesast" WORKDIR /usr/local COPY . . FROM eesast/thuai7_base:base -MAINTAINER eesast +LABEL maintainer="eesast" WORKDIR /usr/local RUN mkdir /usr/local/team1 && mkdir /usr/local/team2 && mkdir /usr/local/playback COPY ./dependency/shell/run.sh . diff --git a/dependency/Dockerfile/Dockerfile_run_server b/dependency/Dockerfile/Dockerfile_run_server index b5c1b549..ef635dea 100644 --- a/dependency/Dockerfile/Dockerfile_run_server +++ b/dependency/Dockerfile/Dockerfile_run_server @@ -1,5 +1,5 @@ FROM mcr.microsoft.com/dotnet/sdk:8.0.204-jammy-amd64 AS build -MAINTAINER eesast +LABEL maintainer="eesast" WORKDIR /usr/local COPY . . RUN dotnet publish logic/Server/Server.csproj -c Release -o /usr/local/Server --self-contained true -r linux-x64 From 2ca840ef1741965393342d3503eada338be129a3 Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Wed, 8 May 2024 00:03:20 +0800 Subject: [PATCH 082/179] fix: :ambulance: Set default ip of server from 127.0.0.1 to 0.0.0.0 --- logic/Server/ArgumentOptions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/logic/Server/ArgumentOptions.cs b/logic/Server/ArgumentOptions.cs index d725e9f0..9a64ff05 100755 --- a/logic/Server/ArgumentOptions.cs +++ b/logic/Server/ArgumentOptions.cs @@ -13,7 +13,7 @@ public class DefaultArgumentOptions public class ArgumentOptions { [Option("ip", Required = false, HelpText = "Server listening ip")] - public string ServerIP { get; set; } = "localhost"; + public string ServerIP { get; set; } = "0.0.0.0"; [Option('p', "port", Required = true, HelpText = "Server listening port")] public ushort ServerPort { get; set; } = 8888; From 92330e66c15648638c8596f42366b39752953d14 Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Wed, 8 May 2024 00:37:37 +0800 Subject: [PATCH 083/179] refactor: :art: Docker update. --- .../{docker.yml => docker/docker_client.yml} | 11 ---------- .github/workflows/docker/docker_cpp.yml | 22 +++++++++++++++++++ .github/workflows/docker/docker_server.yml | 22 +++++++++++++++++++ dependency/Dockerfile/Dockerfile_run_server | 10 +++++---- 4 files changed, 50 insertions(+), 15 deletions(-) rename .github/workflows/{docker.yml => docker/docker_client.yml} (59%) create mode 100644 .github/workflows/docker/docker_cpp.yml create mode 100644 .github/workflows/docker/docker_server.yml diff --git a/.github/workflows/docker.yml b/.github/workflows/docker/docker_client.yml similarity index 59% rename from .github/workflows/docker.yml rename to .github/workflows/docker/docker_client.yml index 0e6bdee3..22784b3f 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker/docker_client.yml @@ -16,17 +16,6 @@ jobs: #- name: Push base image to DockerHub # run: docker push ${{ secrets.DOCKER_USERNAME }}/thuai7_base:base - - - name: Build cpp_compile docker image - run: docker build -t ${{ secrets.DOCKER_USERNAME }}/thuai7_cpp:latest -f ./dependency/Dockerfile/Dockerfile_cpp . - - name: Push cpp_compile image to DockerHub - run: docker push ${{ secrets.DOCKER_USERNAME }}/thuai7_cpp:latest - - - name: Build run_server docker image - run: docker build -t ${{ secrets.DOCKER_USERNAME }}/thuai7_run_server:latest -f ./dependency/Dockerfile/Dockerfile_run_server . - - name: Push run_server image to DockerHub - run: docker push ${{ secrets.DOCKER_USERNAME }}/thuai7_run_server:latest - - name: Build run_client docker image run: docker build -t ${{ secrets.DOCKER_USERNAME }}/thuai7_run_client:latest -f ./dependency/Dockerfile/Dockerfile_run_client . - name: Push run_client image to DockerHub diff --git a/.github/workflows/docker/docker_cpp.yml b/.github/workflows/docker/docker_cpp.yml new file mode 100644 index 00000000..11ef43b3 --- /dev/null +++ b/.github/workflows/docker/docker_cpp.yml @@ -0,0 +1,22 @@ +name: "docker" +on: + push: + branches: [main] + +jobs: + upload_docker_images: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Log in to DockerHub + run: docker login -u ${{ secrets.DOCKER_USERNAME }} -p ${{ secrets.DOCKER_PASSWORD }} + + #- name: Build base docker image + # run: docker build -t ${{ secrets.DOCKER_USERNAME }}/thuai7_base:base -f ./dependency/Dockerfile/Dockerfile_base . + #- name: Push base image to DockerHub + # run: docker push ${{ secrets.DOCKER_USERNAME }}/thuai7_base:base + + - name: Build cpp_compile docker image + run: docker build -t ${{ secrets.DOCKER_USERNAME }}/thuai7_cpp:latest -f ./dependency/Dockerfile/Dockerfile_cpp . + - name: Push cpp_compile image to DockerHub + run: docker push ${{ secrets.DOCKER_USERNAME }}/thuai7_cpp:latest \ No newline at end of file diff --git a/.github/workflows/docker/docker_server.yml b/.github/workflows/docker/docker_server.yml new file mode 100644 index 00000000..a869f7c2 --- /dev/null +++ b/.github/workflows/docker/docker_server.yml @@ -0,0 +1,22 @@ +name: "docker" +on: + push: + branches: [main] + +jobs: + upload_docker_images: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Log in to DockerHub + run: docker login -u ${{ secrets.DOCKER_USERNAME }} -p ${{ secrets.DOCKER_PASSWORD }} + + #- name: Build base docker image + # run: docker build -t ${{ secrets.DOCKER_USERNAME }}/thuai7_base:base -f ./dependency/Dockerfile/Dockerfile_base . + #- name: Push base image to DockerHub + # run: docker push ${{ secrets.DOCKER_USERNAME }}/thuai7_base:base + + - name: Build run_server docker image + run: docker build -t ${{ secrets.DOCKER_USERNAME }}/thuai7_run_server:latest -f ./dependency/Dockerfile/Dockerfile_run_server . + - name: Push run_server image to DockerHub + run: docker push ${{ secrets.DOCKER_USERNAME }}/thuai7_run_server:latest \ No newline at end of file diff --git a/dependency/Dockerfile/Dockerfile_run_server b/dependency/Dockerfile/Dockerfile_run_server index ef635dea..62249679 100644 --- a/dependency/Dockerfile/Dockerfile_run_server +++ b/dependency/Dockerfile/Dockerfile_run_server @@ -4,15 +4,17 @@ WORKDIR /usr/local COPY . . RUN dotnet publish logic/Server/Server.csproj -c Release -o /usr/local/Server --self-contained true -r linux-x64 +FROM mcr.microsoft.com/dotnet/sdk:8.0.204-jammy-amd64 +LABEL maintainer="eesast" WORKDIR /usr/local COPY --from=build /usr/local/Server . RUN mkdir /usr/local/team1 && mkdir /usr/local/team2 && mkdir /usr/local/playback COPY ./dependency/shell/run.sh . -COPY ./CAPI/python /usr/local/PlayerCode/CAPI/python +# COPY ./CAPI/python /usr/local/PlayerCode/CAPI/python COPY ./dependency/proto /usr/local/PlayerCode/dependency/proto -COPY ./dependency/shell /usr/local/PlayerCode/dependency/shell -WORKDIR /usr/local/PlayerCode/CAPI/python -RUN bash ../../dependency/shell/generate_proto.sh +# COPY ./dependency/shell /usr/local/PlayerCode/dependency/shell +# WORKDIR /usr/local/PlayerCode/CAPI/python +# RUN bash ../../dependency/shell/generate_proto.sh WORKDIR /usr/local RUN export TERMINAL=SERVER From e974424fde67491b0112fa0711657864c3b26516 Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Wed, 8 May 2024 00:45:10 +0800 Subject: [PATCH 084/179] fix: :art: Fix the error occured in github workflow. --- .../{docker/docker_client.yml => docker.yml} | 11 ++++++++++ .github/workflows/docker/docker_cpp.yml | 22 ------------------- .github/workflows/docker/docker_server.yml | 22 ------------------- 3 files changed, 11 insertions(+), 44 deletions(-) rename .github/workflows/{docker/docker_client.yml => docker.yml} (59%) delete mode 100644 .github/workflows/docker/docker_cpp.yml delete mode 100644 .github/workflows/docker/docker_server.yml diff --git a/.github/workflows/docker/docker_client.yml b/.github/workflows/docker.yml similarity index 59% rename from .github/workflows/docker/docker_client.yml rename to .github/workflows/docker.yml index 22784b3f..0e6bdee3 100644 --- a/.github/workflows/docker/docker_client.yml +++ b/.github/workflows/docker.yml @@ -16,6 +16,17 @@ jobs: #- name: Push base image to DockerHub # run: docker push ${{ secrets.DOCKER_USERNAME }}/thuai7_base:base + + - name: Build cpp_compile docker image + run: docker build -t ${{ secrets.DOCKER_USERNAME }}/thuai7_cpp:latest -f ./dependency/Dockerfile/Dockerfile_cpp . + - name: Push cpp_compile image to DockerHub + run: docker push ${{ secrets.DOCKER_USERNAME }}/thuai7_cpp:latest + + - name: Build run_server docker image + run: docker build -t ${{ secrets.DOCKER_USERNAME }}/thuai7_run_server:latest -f ./dependency/Dockerfile/Dockerfile_run_server . + - name: Push run_server image to DockerHub + run: docker push ${{ secrets.DOCKER_USERNAME }}/thuai7_run_server:latest + - name: Build run_client docker image run: docker build -t ${{ secrets.DOCKER_USERNAME }}/thuai7_run_client:latest -f ./dependency/Dockerfile/Dockerfile_run_client . - name: Push run_client image to DockerHub diff --git a/.github/workflows/docker/docker_cpp.yml b/.github/workflows/docker/docker_cpp.yml deleted file mode 100644 index 11ef43b3..00000000 --- a/.github/workflows/docker/docker_cpp.yml +++ /dev/null @@ -1,22 +0,0 @@ -name: "docker" -on: - push: - branches: [main] - -jobs: - upload_docker_images: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - name: Log in to DockerHub - run: docker login -u ${{ secrets.DOCKER_USERNAME }} -p ${{ secrets.DOCKER_PASSWORD }} - - #- name: Build base docker image - # run: docker build -t ${{ secrets.DOCKER_USERNAME }}/thuai7_base:base -f ./dependency/Dockerfile/Dockerfile_base . - #- name: Push base image to DockerHub - # run: docker push ${{ secrets.DOCKER_USERNAME }}/thuai7_base:base - - - name: Build cpp_compile docker image - run: docker build -t ${{ secrets.DOCKER_USERNAME }}/thuai7_cpp:latest -f ./dependency/Dockerfile/Dockerfile_cpp . - - name: Push cpp_compile image to DockerHub - run: docker push ${{ secrets.DOCKER_USERNAME }}/thuai7_cpp:latest \ No newline at end of file diff --git a/.github/workflows/docker/docker_server.yml b/.github/workflows/docker/docker_server.yml deleted file mode 100644 index a869f7c2..00000000 --- a/.github/workflows/docker/docker_server.yml +++ /dev/null @@ -1,22 +0,0 @@ -name: "docker" -on: - push: - branches: [main] - -jobs: - upload_docker_images: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - name: Log in to DockerHub - run: docker login -u ${{ secrets.DOCKER_USERNAME }} -p ${{ secrets.DOCKER_PASSWORD }} - - #- name: Build base docker image - # run: docker build -t ${{ secrets.DOCKER_USERNAME }}/thuai7_base:base -f ./dependency/Dockerfile/Dockerfile_base . - #- name: Push base image to DockerHub - # run: docker push ${{ secrets.DOCKER_USERNAME }}/thuai7_base:base - - - name: Build run_server docker image - run: docker build -t ${{ secrets.DOCKER_USERNAME }}/thuai7_run_server:latest -f ./dependency/Dockerfile/Dockerfile_run_server . - - name: Push run_server image to DockerHub - run: docker push ${{ secrets.DOCKER_USERNAME }}/thuai7_run_server:latest \ No newline at end of file From 429010dc1c2b76a350bf656ff4c1dd7eea2c6373 Mon Sep 17 00:00:00 2001 From: Guoyun Tian <88619302+BlitherBoom812@users.noreply.github.com> Date: Wed, 8 May 2024 01:05:19 +0800 Subject: [PATCH 085/179] retry command --- dependency/shell/run.sh | 43 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 38 insertions(+), 5 deletions(-) diff --git a/dependency/shell/run.sh b/dependency/shell/run.sh index 7ba0d06c..8db409b4 100644 --- a/dependency/shell/run.sh +++ b/dependency/shell/run.sh @@ -49,6 +49,35 @@ fi # done # } +function retry_command { + local command="$1" + local max_attempts=2 + local attempt_num=1 + local sleep_seconds=10 + + while [ $attempt_num -le $max_attempts ]; do + echo "Attempt $attempt_num / $max_attempts to run command: $command" + + eval $command & + local PID=$! + + sleep $sleep_seconds + + if kill -0 $PID 2>/dev/null; then + echo "Connected to server successfully." + return 0 + else + echo "Failed to connect to server. Retrying..." + ((attempt_num++)) + fi + done + + echo "Failed to connect to server after $max_attempts attempts." + return 1 +} + + + if [ "$TERMINAL" = "SERVER" ]; then map_path=$map_dir/$MAP_ID.txt if [ $EXPOSED -eq 1 ]; then @@ -91,10 +120,12 @@ elif [ "$TERMINAL" = "CLIENT" ]; then echo "find ./$code_name.py" cp -r $python_main_dir $python_main_dir$i cp -f ./$code_name.py $python_main_dir$i/PyAPI/AI.py - nice -0 python3 $python_main_dir$i/PyAPI/main.py -I $CONNECT_IP -P $PORT -t $k -p $i > $playback_dir/team$k-$code_name.log 2>&1 & + command="nice -0 python3 $python_main_dir$i/PyAPI/main.py -I $CONNECT_IP -P $PORT -t $k -p $i > $playback_dir/team$k-$code_name.log 2>&1 &" + retry_command "$command" & elif [ -f "./$code_name" ]; then echo "find ./$code_name" - nice -0 ./$code_name -I $CONNECT_IP -P $PORT -t $k -p $i > $playback_dir/team$k-$codename.log 2>&1 & + command="nice -0 ./$code_name -I $CONNECT_IP -P $PORT -t $k -p $i > $playback_dir/team$k-$codename.log 2>&1 &" + retry_command "$command" & else echo "ERROR. $code_name is not found." fi @@ -104,16 +135,18 @@ elif [ "$TERMINAL" = "CLIENT" ]; then echo "find ./$code_name.py" cp -r $python_main_dir $python_main_dir$i cp -f ./$code_name.py $python_main_dir$i/PyAPI/AI.py - nice -0 python3 $python_main_dir$i/PyAPI/main.py -I $CONNECT_IP -P $PORT -t $k -p $i > $playback_dir/team$k-$code_name.log 2>&1 & + command="nice -0 python3 $python_main_dir$i/PyAPI/main.py -I $CONNECT_IP -P $PORT -t $k -p $i > $playback_dir/team$k-$code_name.log 2>&1 &" + retry_command "$command" & elif [ -f "./$code_name" ]; then echo "find ./$code_name" - nice -0 ./$code_name -I $CONNECT_IP -P $PORT -t $k -p $i > $playback_dir/team$k-$code_name.log 2>&1 & + command="nice -0 ./$code_name -I $CONNECT_IP -P $PORT -t $k -p $i > $playback_dir/team$k-$code_name.log 2>&1 &" + retry_command "$command" & else echo "ERROR. $code_name is not found." fi fi done - sleep $((GAME_TIME)) + sleep $((GAME_TIME+90)) popd else echo "VALUE ERROR: TERMINAL is neither SERVER nor CLIENT." From 2765beb8a3419ee2a46db4e091db8c20efbf3c57 Mon Sep 17 00:00:00 2001 From: xiangmy21 <90919434+xiangmy21@users.noreply.github.com> Date: Wed, 8 May 2024 01:49:22 +0800 Subject: [PATCH 086/179] Update run.sh --- dependency/shell/run.sh | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/dependency/shell/run.sh b/dependency/shell/run.sh index 8db409b4..89f35a3e 100644 --- a/dependency/shell/run.sh +++ b/dependency/shell/run.sh @@ -105,6 +105,14 @@ if [ "$TERMINAL" = "SERVER" ]; then kill -9 $server_pid finish_payload='{"result": {"status": "Crashed", "scores": [0, 0]}}' curl $FINISH_URL -X POST -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" -d "${finish_payload}" > $playback_dir/send.log 2>&1 + else + ps -p $server_pid + while [ $? -eq 0 ] + do + sleep 1 + ps -p $server_pid > /dev/null 2>&1 + done + echo "Server is down." fi elif [ "$TERMINAL" = "CLIENT" ]; then From 12add9001dc3f62e3e5e77ce39fe826a6ab29881 Mon Sep 17 00:00:00 2001 From: xiangmy21 <90919434+xiangmy21@users.noreply.github.com> Date: Wed, 8 May 2024 02:42:50 +0800 Subject: [PATCH 087/179] Update run.sh --- dependency/shell/run.sh | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/dependency/shell/run.sh b/dependency/shell/run.sh index 89f35a3e..bb10d6d1 100644 --- a/dependency/shell/run.sh +++ b/dependency/shell/run.sh @@ -64,11 +64,11 @@ function retry_command { sleep $sleep_seconds if kill -0 $PID 2>/dev/null; then - echo "Connected to server successfully." - return 0 - else echo "Failed to connect to server. Retrying..." ((attempt_num++)) + else + echo "Connected to server successfully." + return 0 fi done @@ -106,6 +106,7 @@ if [ "$TERMINAL" = "SERVER" ]; then finish_payload='{"result": {"status": "Crashed", "scores": [0, 0]}}' curl $FINISH_URL -X POST -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" -d "${finish_payload}" > $playback_dir/send.log 2>&1 else + echo "Game is started." ps -p $server_pid while [ $? -eq 0 ] do From c6566ea79d18395ce523e0b7ea54ff036dae60a4 Mon Sep 17 00:00:00 2001 From: xiangmy21 <90919434+xiangmy21@users.noreply.github.com> Date: Wed, 8 May 2024 03:26:23 +0800 Subject: [PATCH 088/179] Update HttpSender.cs --- logic/Server/HttpSender.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/logic/Server/HttpSender.cs b/logic/Server/HttpSender.cs index 728e627a..c9652b5d 100755 --- a/logic/Server/HttpSender.cs +++ b/logic/Server/HttpSender.cs @@ -58,9 +58,8 @@ public async Task GetLadderScore(double[] scores) var jsonString = await response.Content.ReadAsStringAsync(); // 解析 JSON 字符串 - var result = JsonConvert.DeserializeObject>(jsonString); - double[] org = (from r in result select (double)(r.score)).ToArray(); - return org; + var result = JsonConvert.DeserializeObject(jsonString); + return result.Scores.Select(score => (double)score).ToArray();; } catch (Exception e) { From 242999a28cca3bb464eecae7f5df9d297c11aa2e Mon Sep 17 00:00:00 2001 From: xiangmy21 <90919434+xiangmy21@users.noreply.github.com> Date: Wed, 8 May 2024 03:36:50 +0800 Subject: [PATCH 089/179] fix(http): ContestResult type --- logic/Server/GameServer.cs | 3 ++- logic/Server/HttpSender.cs | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/logic/Server/GameServer.cs b/logic/Server/GameServer.cs index acee6f86..35292541 100755 --- a/logic/Server/GameServer.cs +++ b/logic/Server/GameServer.cs @@ -15,7 +15,8 @@ namespace Server { public class ContestResult { - public int score; + public string status; + public int[] scores; } partial class GameServer : ServerBase { diff --git a/logic/Server/HttpSender.cs b/logic/Server/HttpSender.cs index c9652b5d..8c3e6db1 100755 --- a/logic/Server/HttpSender.cs +++ b/logic/Server/HttpSender.cs @@ -58,8 +58,8 @@ public async Task GetLadderScore(double[] scores) var jsonString = await response.Content.ReadAsStringAsync(); // 解析 JSON 字符串 - var result = JsonConvert.DeserializeObject(jsonString); - return result.Scores.Select(score => (double)score).ToArray();; + var result = JsonConvert.DeserializeObject(jsonString); + return result.Scores.Select(score => (double)score).ToArray(); } catch (Exception e) { From 1fcce7df26b4c0ceff8efbecd420a6722155a046 Mon Sep 17 00:00:00 2001 From: xiangmy21 <90919434+xiangmy21@users.noreply.github.com> Date: Wed, 8 May 2024 03:48:28 +0800 Subject: [PATCH 090/179] fix: ContestResult type --- logic/Server/GameServer.cs | 2 +- logic/Server/HttpSender.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/logic/Server/GameServer.cs b/logic/Server/GameServer.cs index 35292541..82aa7286 100755 --- a/logic/Server/GameServer.cs +++ b/logic/Server/GameServer.cs @@ -16,7 +16,7 @@ namespace Server public class ContestResult { public string status; - public int[] scores; + public double[] scores; } partial class GameServer : ServerBase { diff --git a/logic/Server/HttpSender.cs b/logic/Server/HttpSender.cs index 8c3e6db1..a4d1eb24 100755 --- a/logic/Server/HttpSender.cs +++ b/logic/Server/HttpSender.cs @@ -59,7 +59,7 @@ public async Task GetLadderScore(double[] scores) // 解析 JSON 字符串 var result = JsonConvert.DeserializeObject(jsonString); - return result.Scores.Select(score => (double)score).ToArray(); + return result.scores.Select(score => (double)score).ToArray(); } catch (Exception e) { From 24515fb927a0f5d7d2946435db0d4c81cc0fe045 Mon Sep 17 00:00:00 2001 From: xiangmy21 <90919434+xiangmy21@users.noreply.github.com> Date: Wed, 8 May 2024 03:59:02 +0800 Subject: [PATCH 091/179] fix: ContestResult in run.sh --- dependency/shell/run.sh | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/dependency/shell/run.sh b/dependency/shell/run.sh index bb10d6d1..4ac6370c 100644 --- a/dependency/shell/run.sh +++ b/dependency/shell/run.sh @@ -81,10 +81,10 @@ function retry_command { if [ "$TERMINAL" = "SERVER" ]; then map_path=$map_dir/$MAP_ID.txt if [ $EXPOSED -eq 1 ]; then - nice -10 ./Server --port 8888 --teamCount 2 --shipNum 4 --resultFileName $playback_dir/result --gameTimeInSecond $GAME_TIME --mode $MODE_NUM --mapResource $map_path --url $SCORE_URL --token $TOKEN --fileName $playback_dir/video --startLockFile $playback_dir/start.lock > $playback_dir/server.log 2>&1 & + nice -10 ./Server --port 8888 --teamCount 2 --shipNum 4 --resultFileName $playback_dir/result --gameTimeInSecond $GAME_TIME --mode $MODE_NUM --mapResource $map_path --url $SCORE_URL --token $TOKEN --fileName $playback_dir/playback --startLockFile $playback_dir/start.lock > $playback_dir/server.log 2>&1 & server_pid=$! else - nice -10 ./Server --port 8888 --teamCount 2 --shipNum 4 --resultFileName $playback_dir/result --gameTimeInSecond $GAME_TIME --mode $MODE_NUM --mapResource $map_path --notAllowSpectator --url $SCORE_URL --token $TOKEN --fileName $playback_dir/video --startLockFile $playback_dir/start.lock > $playback_dir/server.log 2>&1 & + nice -10 ./Server --port 8888 --teamCount 2 --shipNum 4 --resultFileName $playback_dir/result --gameTimeInSecond $GAME_TIME --mode $MODE_NUM --mapResource $map_path --notAllowSpectator --url $SCORE_URL --token $TOKEN --fileName $playback_dir/playback --startLockFile $playback_dir/start.lock > $playback_dir/server.log 2>&1 & server_pid=$! fi @@ -101,9 +101,9 @@ if [ "$TERMINAL" = "SERVER" ]; then if [ ! -f $playback_dir/start.lock ]; then echo "Failed to start game." touch temp.lock - mv -f temp.lock $playback_dir/video.thuaipb + mv -f temp.lock $playback_dir/playback.thuaipb kill -9 $server_pid - finish_payload='{"result": {"status": "Crashed", "scores": [0, 0]}}' + finish_payload='{"status": "Crashed", "scores": [0, 0]}' curl $FINISH_URL -X POST -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" -d "${finish_payload}" > $playback_dir/send.log 2>&1 else echo "Game is started." From 7b46b1fdd6fdb008ca288eada0ec7661d5487e69 Mon Sep 17 00:00:00 2001 From: xiangmy21 <90919434+xiangmy21@users.noreply.github.com> Date: Wed, 8 May 2024 04:04:23 +0800 Subject: [PATCH 092/179] refact: thuai7.pb -> thuaipb --- installer/Manual.md | 2 +- logic/Client/ViewModel/GeneralViewModel.cs | 4 ++-- playback/Playback/PlaybackConstant.cs | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/installer/Manual.md b/installer/Manual.md index 6a54fbd9..17b12b1e 100644 --- a/installer/Manual.md +++ b/installer/Manual.md @@ -52,7 +52,7 @@ ### Playback -每次调试后会在 `%InstallPath%\logic\Server` 中生成 `114514.thuai7.pb`,在 `Playback File` 中输入 `114514.thuai7.pb`,点击 `保存` 和 `启动`。也可以对回放文件进行改名,输入对应文件名即可。 +每次调试后会在 `%InstallPath%\logic\Server` 中生成 `114514.thuaipb`,在 `Playback File` 中输入 `114514.thuaipb`,点击 `保存` 和 `启动`。也可以对回放文件进行改名,输入对应文件名即可。 ## Login diff --git a/logic/Client/ViewModel/GeneralViewModel.cs b/logic/Client/ViewModel/GeneralViewModel.cs index 22e830b9..01e7132f 100644 --- a/logic/Client/ViewModel/GeneralViewModel.cs +++ b/logic/Client/ViewModel/GeneralViewModel.cs @@ -1078,7 +1078,7 @@ Show the error message myLogger.LogInfo(String.Format("ip:{0}, port:{1}, playerid:{2}, teamid:{3}, shiptype:{4}, playbackfile:{5}, playbackspeed:{6}", ip, port, playerID, teamID, shipTypeID, playbackFile, playbackSpeed)); - //Playback("E:\\program\\Project\\THUAI7\\logic\\Client\\114514.thuai7.pb", 2.0); + //Playback("E:\\program\\Project\\THUAI7\\logic\\Client\\114514.thuaipb", 2.0); if (playbackFile.Length == 0) { try @@ -1129,7 +1129,7 @@ Show the error message // "1" //}); - //Playback("E:\\program\\Project\\THUAI7\\logic\\Server\\bin\\Debug\\net8.0\\114514.thuai7.pb", 1); + //Playback("E:\\program\\Project\\THUAI7\\logic\\Server\\bin\\Debug\\net8.0\\114514.thuaipb", 1); timerViewModel = Dispatcher.CreateTimer(); timerViewModel.Interval = TimeSpan.FromMilliseconds(50); diff --git a/playback/Playback/PlaybackConstant.cs b/playback/Playback/PlaybackConstant.cs index e514ee0c..8e997465 100755 --- a/playback/Playback/PlaybackConstant.cs +++ b/playback/Playback/PlaybackConstant.cs @@ -8,7 +8,7 @@ public static class Constants /// /// 回放文件扩展名 /// - public static readonly string FileExtension = $".thuai{Version}.pb"; + public static readonly string FileExtension = $".thuaipb"; /// /// 回放文件头 /// From cb1d94d8a65697ebef0c8922de5a575ec9fd7d0b Mon Sep 17 00:00:00 2001 From: xiangmy21 <90919434+xiangmy21@users.noreply.github.com> Date: Wed, 8 May 2024 04:42:55 +0800 Subject: [PATCH 093/179] fix: run.sh retry times --- dependency/shell/run.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/dependency/shell/run.sh b/dependency/shell/run.sh index 4ac6370c..49c80014 100644 --- a/dependency/shell/run.sh +++ b/dependency/shell/run.sh @@ -51,9 +51,9 @@ fi function retry_command { local command="$1" - local max_attempts=2 + local max_attempts=10 local attempt_num=1 - local sleep_seconds=10 + local sleep_seconds=5 while [ $attempt_num -le $max_attempts ]; do echo "Attempt $attempt_num / $max_attempts to run command: $command" @@ -95,7 +95,7 @@ if [ "$TERMINAL" = "SERVER" ]; then echo "FINISH URL: $FINISH_URL" echo "waiting..." - sleep 30 # wait connection time + sleep 60 # wait connection time echo "watching..." if [ ! -f $playback_dir/start.lock ]; then From 0a3e15cbc7975d4111b48f8ca9c4ce42ec95ab68 Mon Sep 17 00:00:00 2001 From: xiangmy21 <90919434+xiangmy21@users.noreply.github.com> Date: Wed, 8 May 2024 05:25:39 +0800 Subject: [PATCH 094/179] try: run.sh > client.log --- dependency/Dockerfile/Dockerfile_run_client | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dependency/Dockerfile/Dockerfile_run_client b/dependency/Dockerfile/Dockerfile_run_client index 28e9cea2..e53d3067 100644 --- a/dependency/Dockerfile/Dockerfile_run_client +++ b/dependency/Dockerfile/Dockerfile_run_client @@ -16,4 +16,4 @@ RUN bash ../../dependency/shell/generate_proto.sh WORKDIR /usr/local RUN export TERMINAL=CLIENT -ENTRYPOINT [ "bash","./run.sh" ] \ No newline at end of file +ENTRYPOINT [ "bash","./run.sh > /usr/local/output/client$TEAM_SEQ_ID.log" ] \ No newline at end of file From 797a835f4ca6a82702e8dd8ad0f656cce234eff3 Mon Sep 17 00:00:00 2001 From: xiangmy21 <90919434+xiangmy21@users.noreply.github.com> Date: Wed, 8 May 2024 05:39:50 +0800 Subject: [PATCH 095/179] try: client log --- dependency/Dockerfile/Dockerfile_run_client | 2 +- dependency/shell/run.sh | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/dependency/Dockerfile/Dockerfile_run_client b/dependency/Dockerfile/Dockerfile_run_client index e53d3067..28e9cea2 100644 --- a/dependency/Dockerfile/Dockerfile_run_client +++ b/dependency/Dockerfile/Dockerfile_run_client @@ -16,4 +16,4 @@ RUN bash ../../dependency/shell/generate_proto.sh WORKDIR /usr/local RUN export TERMINAL=CLIENT -ENTRYPOINT [ "bash","./run.sh > /usr/local/output/client$TEAM_SEQ_ID.log" ] \ No newline at end of file +ENTRYPOINT [ "bash","./run.sh" ] \ No newline at end of file diff --git a/dependency/shell/run.sh b/dependency/shell/run.sh index 49c80014..6288af98 100644 --- a/dependency/shell/run.sh +++ b/dependency/shell/run.sh @@ -130,11 +130,11 @@ elif [ "$TERMINAL" = "CLIENT" ]; then cp -r $python_main_dir $python_main_dir$i cp -f ./$code_name.py $python_main_dir$i/PyAPI/AI.py command="nice -0 python3 $python_main_dir$i/PyAPI/main.py -I $CONNECT_IP -P $PORT -t $k -p $i > $playback_dir/team$k-$code_name.log 2>&1 &" - retry_command "$command" & + retry_command "$command" > $playback_dir/client$k.log & elif [ -f "./$code_name" ]; then echo "find ./$code_name" command="nice -0 ./$code_name -I $CONNECT_IP -P $PORT -t $k -p $i > $playback_dir/team$k-$codename.log 2>&1 &" - retry_command "$command" & + retry_command "$command" > $playback_dir/client$k.log & else echo "ERROR. $code_name is not found." fi @@ -145,11 +145,11 @@ elif [ "$TERMINAL" = "CLIENT" ]; then cp -r $python_main_dir $python_main_dir$i cp -f ./$code_name.py $python_main_dir$i/PyAPI/AI.py command="nice -0 python3 $python_main_dir$i/PyAPI/main.py -I $CONNECT_IP -P $PORT -t $k -p $i > $playback_dir/team$k-$code_name.log 2>&1 &" - retry_command "$command" & + retry_command "$command" > $playback_dir/client$k.log & elif [ -f "./$code_name" ]; then echo "find ./$code_name" command="nice -0 ./$code_name -I $CONNECT_IP -P $PORT -t $k -p $i > $playback_dir/team$k-$code_name.log 2>&1 &" - retry_command "$command" & + retry_command "$command" > $playback_dir/client$k.log & else echo "ERROR. $code_name is not found." fi From ba6823e71d04c517b1f420d11e5ded4c169fb14c Mon Sep 17 00:00:00 2001 From: DragonAura <32223554+DragonAura@users.noreply.github.com> Date: Wed, 8 May 2024 10:22:24 +0800 Subject: [PATCH 096/179] fix: add cpp retry --- CAPI/cpp/API/src/Communication.cpp | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/CAPI/cpp/API/src/Communication.cpp b/CAPI/cpp/API/src/Communication.cpp index d1cb86b5..45100a8e 100755 --- a/CAPI/cpp/API/src/Communication.cpp +++ b/CAPI/cpp/API/src/Communication.cpp @@ -227,14 +227,18 @@ bool Communication::Recycle(int32_t playerID, int32_t teamID) bool Communication::TryConnection(int32_t playerID, int32_t teamID) { - protobuf::BoolRes reply; - ClientContext context; + constexpr int maxRetryNum = 10; auto request = THUAI72Proto::THUAI72ProtobufIDMsg(playerID, teamID); - auto status = THUAI7Stub->TryConnection(&context, request, &reply); - if (status.ok()) - return true; - else - return false; + for (int retryNum = 0; retryNum < maxRetryNum; retryNum++) + { + protobuf::BoolRes reply; + ClientContext context; + std::this_thread::sleep_for(std::chrono::milliseconds(2000)); + auto status = THUAI7Stub->TryConnection(&context, request, &reply); + if (status.ok()) + return true; + } + return false; } void Communication::AddPlayer(int32_t playerID, int32_t teamID, THUAI7::ShipType ShipType) @@ -274,4 +278,4 @@ protobuf::MessageToClient Communication::GetMessage2Client() { return haveNewMessage; }); haveNewMessage = false; return message2Client; -} \ No newline at end of file +} From ec86ecf2fb5b96b47e115eba6bbf8bd390b14944 Mon Sep 17 00:00:00 2001 From: DragonAura <32223554+DragonAura@users.noreply.github.com> Date: Wed, 8 May 2024 10:47:05 +0800 Subject: [PATCH 097/179] fix: add python retry --- CAPI/python/PyAPI/Communication.py | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/CAPI/python/PyAPI/Communication.py b/CAPI/python/PyAPI/Communication.py index d5c785fe..3a997cc9 100644 --- a/CAPI/python/PyAPI/Communication.py +++ b/CAPI/python/PyAPI/Communication.py @@ -235,14 +235,18 @@ def BuildShip( return buildResult.act_success def TryConnection(self, playerID: int, teamID: int) -> bool: - try: - tryResult: Message2Clients.BoolRes = self.__THUAI7Stub.TryConnection( - THUAI72Proto.THUAI72ProtobufIDMsg(playerID, teamID) - ) - except grpc.RpcError: - return False - else: - return tryResult.act_success + maxRetryNum: int = 10 + for _ in range(maxRetryNum): + try: + time.sleep(1) + tryResult: Message2Clients.BoolRes = self.__THUAI7Stub.TryConnection( + THUAI72Proto.THUAI72ProtobufIDMsg(playerID, teamID) + ) + except grpc.RpcError: + continue + else: + return tryResult.act_success + return False def GetMessage2Client(self) -> Message2Clients.MessageToClient: with self.__cvMessage: From f9c71b44b427a77e287faeded794f5ef16af73f6 Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Wed, 8 May 2024 12:17:02 +0800 Subject: [PATCH 098/179] fix: :bug: Fix the bug caused by low priority of ?? operator. --- installer/ViewModel/DebugViewModel.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/installer/ViewModel/DebugViewModel.cs b/installer/ViewModel/DebugViewModel.cs index c6f19f96..62823b4c 100644 --- a/installer/ViewModel/DebugViewModel.cs +++ b/installer/ViewModel/DebugViewModel.cs @@ -370,7 +370,7 @@ public bool LaunchPyAPI(int team, int player) { FileName = "cmd.exe", Arguments = "/c python " - + Downloader.Data.Config.DevPyPath ?? Path.Combine(Downloader.Data.Config.InstallPath, "CAPI", "python", "PyAPI", "main.py") + + (Downloader.Data.Config.DevPyPath ?? Path.Combine(Downloader.Data.Config.InstallPath, "CAPI", "python", "PyAPI", "main.py")) + $" -I {IP} -P {Port} -t {team} -p {player} -o" }); if (py is null) @@ -378,7 +378,7 @@ public bool LaunchPyAPI(int team, int player) Log.LogError($"未能启动main.py, team:{team}, player: {player}!"); return false; } - Log.LogError($"main.py启动成功, team:{team}, player: {player}!"); + Log.LogInfo($"main.py启动成功, team:{team}, player: {player}!"); children.Add(py); return true; } From 6d64ca4a3621eb8563f21ac751251961ad13235f Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Wed, 8 May 2024 12:18:39 +0800 Subject: [PATCH 099/179] chore: :bookmark: Update installer version. --- installer/Data/MD5FileData.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/installer/Data/MD5FileData.cs b/installer/Data/MD5FileData.cs index f30e30b1..ef3ba870 100644 --- a/installer/Data/MD5FileData.cs +++ b/installer/Data/MD5FileData.cs @@ -26,7 +26,7 @@ public class TVersion { // 代码库版本 [JsonInclude] - public Version LibVersion = new Version(1, 0, 2, 1); + public Version LibVersion = new Version(1, 0, 2, 2); // 选手代码模板版本 [JsonInclude] public Version TemplateVersion = new Version(1, 0, 0, 3); From 95a2f6468e230a377899ba19c3976a2f28b72b4c Mon Sep 17 00:00:00 2001 From: GuoWQ222 Date: Wed, 8 May 2024 16:06:40 +0800 Subject: [PATCH 100/179] fix: --- logic/Server/GameServer.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/logic/Server/GameServer.cs b/logic/Server/GameServer.cs index 82aa7286..aec7d444 100755 --- a/logic/Server/GameServer.cs +++ b/logic/Server/GameServer.cs @@ -129,7 +129,6 @@ protected void SendGameResult(int[] scores, bool crashed) // 天梯的 Server protected double[] PullScore(double[] scores) { - string? url2 = Environment.GetEnvironmentVariable("SCORE_URL"); if (url2 != null) { @@ -144,6 +143,8 @@ protected double[] PullScore(double[] scores) else { double[] final = LadderCalculate(org, scores); + final[0] -= org[0]; + final[1] -= org[1]; return final; } } From 65cb19f944c190d8628c0ab0e977bdbf87b6a710 Mon Sep 17 00:00:00 2001 From: Xuc Pan Date: Wed, 8 May 2024 21:39:03 +0800 Subject: [PATCH 101/179] fix: :bug: Home add money after destroyed --- logic/GameClass/GameObj/Base.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/logic/GameClass/GameObj/Base.cs b/logic/GameClass/GameObj/Base.cs index f4d57256..cb4d24a1 100644 --- a/logic/GameClass/GameObj/Base.cs +++ b/logic/GameClass/GameObj/Base.cs @@ -20,7 +20,7 @@ public class Base : IPlayer public Home Home { get; set; } public MoneyPool MoneyPool { get; } = new(); public AtomicInt FactoryNum { get; } = new(0); - public int MoneyAddPerSecond => GameData.ScoreHomePerSecond + FactoryNum * GameData.ScoreFactoryPerSecond; + public int MoneyAddPerSecond => FactoryNum * GameData.ScoreFactoryPerSecond + (Home.HP > 0 ? GameData.ScoreHomePerSecond : 0); public Base(Home home) { TeamID = new(home.TeamID); From f2a356c504b8b8ca30b609adabe6a2a7e57e4238 Mon Sep 17 00:00:00 2001 From: Grange <2634070476@qq.com> Date: Wed, 8 May 2024 22:44:46 +0800 Subject: [PATCH 102/179] =?UTF-8?q?fix:=20=F0=9F=90=9B=20[playback]=20No?= =?UTF-8?q?=20changes=20but=20it=20works,=20don't=20know=20why?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- logic/Client/ViewModel/GeneralViewModel.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/logic/Client/ViewModel/GeneralViewModel.cs b/logic/Client/ViewModel/GeneralViewModel.cs index 01e7132f..05ad23ee 100644 --- a/logic/Client/ViewModel/GeneralViewModel.cs +++ b/logic/Client/ViewModel/GeneralViewModel.cs @@ -1078,7 +1078,7 @@ Show the error message myLogger.LogInfo(String.Format("ip:{0}, port:{1}, playerid:{2}, teamid:{3}, shiptype:{4}, playbackfile:{5}, playbackspeed:{6}", ip, port, playerID, teamID, shipTypeID, playbackFile, playbackSpeed)); - //Playback("E:\\program\\Project\\THUAI7\\logic\\Client\\114514.thuaipb", 2.0); + //Playback("E:\\program\\Project\\playback.thuaipb", 0.5); if (playbackFile.Length == 0) { try @@ -1106,6 +1106,7 @@ Show the error message } else { + //myLogger.LogInfo(String.Format("PlaybackFile:{0}", playbackFile)); Playback(playbackFile, playbackSpeed); } //连接Server,comInfo[] 的格式:0 - ip 1 - port 2 - playerID 3 - teamID 4 - ShipType From c1670f98d6c2b64293f68478b6eb7ae6ef68434e Mon Sep 17 00:00:00 2001 From: sigureling <1678348940@qq.com> Date: Thu, 9 May 2024 00:05:27 +0800 Subject: [PATCH 103/179] fix: :bug: fix import time --- CAPI/python/PyAPI/Communication.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CAPI/python/PyAPI/Communication.py b/CAPI/python/PyAPI/Communication.py index 3a997cc9..9733011f 100644 --- a/CAPI/python/PyAPI/Communication.py +++ b/CAPI/python/PyAPI/Communication.py @@ -6,7 +6,7 @@ import proto.Message2Clients_pb2 as Message2Clients import threading import grpc - +import time from typing import Union From eba892ea9d4b466c095b4c149c365ee31fd8db59 Mon Sep 17 00:00:00 2001 From: DragonAura <32223554+DragonAura@users.noreply.github.com> Date: Thu, 9 May 2024 00:22:45 +0800 Subject: [PATCH 104/179] fix: remove python retry --- CAPI/python/PyAPI/Communication.py | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/CAPI/python/PyAPI/Communication.py b/CAPI/python/PyAPI/Communication.py index 9733011f..8f49aa39 100644 --- a/CAPI/python/PyAPI/Communication.py +++ b/CAPI/python/PyAPI/Communication.py @@ -235,18 +235,14 @@ def BuildShip( return buildResult.act_success def TryConnection(self, playerID: int, teamID: int) -> bool: - maxRetryNum: int = 10 - for _ in range(maxRetryNum): - try: - time.sleep(1) - tryResult: Message2Clients.BoolRes = self.__THUAI7Stub.TryConnection( - THUAI72Proto.THUAI72ProtobufIDMsg(playerID, teamID) - ) - except grpc.RpcError: - continue - else: - return tryResult.act_success - return False + try: + tryResult: Message2Clients.BoolRes = self.__THUAI7Stub.TryConnection( + THUAI72Proto.THUAI72ProtobufIDMsg(playerID, teamID) + ) + except grpc.RpcError: + return False + else: + return tryResult.act_success def GetMessage2Client(self) -> Message2Clients.MessageToClient: with self.__cvMessage: From 30b3530963ad2e11f2190a4d72e07232be3c6c56 Mon Sep 17 00:00:00 2001 From: DragonAura <32223554+DragonAura@users.noreply.github.com> Date: Thu, 9 May 2024 00:23:33 +0800 Subject: [PATCH 105/179] fix: remove cpp retry --- CAPI/cpp/API/src/Communication.cpp | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/CAPI/cpp/API/src/Communication.cpp b/CAPI/cpp/API/src/Communication.cpp index 45100a8e..6c86b7eb 100755 --- a/CAPI/cpp/API/src/Communication.cpp +++ b/CAPI/cpp/API/src/Communication.cpp @@ -227,18 +227,14 @@ bool Communication::Recycle(int32_t playerID, int32_t teamID) bool Communication::TryConnection(int32_t playerID, int32_t teamID) { - constexpr int maxRetryNum = 10; + protobuf::BoolRes reply; + ClientContext context; auto request = THUAI72Proto::THUAI72ProtobufIDMsg(playerID, teamID); - for (int retryNum = 0; retryNum < maxRetryNum; retryNum++) - { - protobuf::BoolRes reply; - ClientContext context; - std::this_thread::sleep_for(std::chrono::milliseconds(2000)); - auto status = THUAI7Stub->TryConnection(&context, request, &reply); - if (status.ok()) - return true; - } - return false; + auto status = THUAI7Stub->TryConnection(&context, request, &reply); + if (status.ok()) + return true; + else + return false; } void Communication::AddPlayer(int32_t playerID, int32_t teamID, THUAI7::ShipType ShipType) From aefc7c9424f775a26b0276679639fcfadf6ad061 Mon Sep 17 00:00:00 2001 From: GuoWQ222 Date: Thu, 9 May 2024 00:35:31 +0800 Subject: [PATCH 106/179] fix --- logic/Server/GameServer.cs | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/logic/Server/GameServer.cs b/logic/Server/GameServer.cs index aec7d444..6e34d182 100755 --- a/logic/Server/GameServer.cs +++ b/logic/Server/GameServer.cs @@ -143,8 +143,6 @@ protected double[] PullScore(double[] scores) else { double[] final = LadderCalculate(org, scores); - final[0] -= org[0]; - final[1] -= org[1]; return final; } } @@ -164,8 +162,11 @@ protected static double[] LadderCalculate(double[] oriScores, double[] competiti else if (competitionScores[0] == competitionScores[1])// 平局 { if (oriScores[0] == oriScores[1]) - // 完全平局,不改变天梯分数 - return oriScores; + // 完全平局,不改变天梯分数 + { + double[] Score = [0, 0]; + return Score; + } if (oriScores[0] > oriScores[1]) // 本次游戏平局,但一方天梯分数高,另一方天梯分数低, // 需要将两者向中间略微靠拢,因此天梯分数低的定为获胜者 @@ -177,11 +178,11 @@ protected static double[] LadderCalculate(double[] oriScores, double[] competiti (oriScores[0], oriScores[1]) = (oriScores[1], oriScores[0]); } - const double normalDeltaThereshold = 1000.0; // 分数差标准化参数,同时也是大分数差阈值 + const double normalDeltaThereshold = 2000.0; // 分数差标准化参数,同时也是大分数差阈值 const double correctParam = normalDeltaThereshold * 1.2;// 修正参数 - const double winnerWeight = 9e-6; // 获胜者天梯得分权值 - const double loserWeight = 5e-6; // 落败者天梯得分权值 - const double scoreDeltaThereshold = 2100.0; // 极大分数差阈值 + const double winnerWeight = 9e-8; // 获胜者天梯得分权值 + const double loserWeight = 5e-8; // 落败者天梯得分权值 + const double scoreDeltaThereshold = 40000.0; // 极大分数差阈值 double[] resScore = [0, 0]; double oriDelta = oriScores[0] - oriScores[1]; // 原分数差 @@ -191,11 +192,11 @@ protected static double[] LadderCalculate(double[] oriScores, double[] competiti double correct = 0.5 * (Math.Tanh((competitionDelta - scoreDeltaThereshold) / scoreDeltaThereshold - correctRate) + 1.0); // 分数修正 - resScore[0] = oriScores[0] + Math.Round(Math.Pow(competitionScores[0], 2) + resScore[0] = Math.Round(Math.Pow(competitionScores[0], 2) * winnerWeight * (1 - Math.Tanh(normalOriDelta)) * correct); // 胜者所加天梯分 - resScore[1] = oriScores[1] - Math.Round(Math.Pow(competitionDelta, 2) + resScore[1] = -Math.Round(Math.Pow(competitionDelta, 2) * loserWeight * (1 - Math.Tanh(normalOriDelta)) * correct); // 败者所扣天梯分 From 62af626d005dbf0ba71bba4a63f91beb0dd44f1b Mon Sep 17 00:00:00 2001 From: sigureling <1678348940@qq.com> Date: Thu, 9 May 2024 01:58:45 +0800 Subject: [PATCH 107/179] feat: :zap: Change GetConstructionHp to GetConstructionState to return building id information --- CAPI/cpp/API/include/API.h | 12 ++-- CAPI/cpp/API/include/logic.h | 2 +- CAPI/cpp/API/src/API.cpp | 8 +-- CAPI/cpp/API/src/DebugAPI.cpp | 8 +-- CAPI/cpp/API/src/logic.cpp | 24 +++++-- CAPI/python/PyAPI/API.py | 8 +-- CAPI/python/PyAPI/DebugAPI.py | 8 +-- CAPI/python/PyAPI/Interface.py | 4 +- CAPI/python/PyAPI/constants.py | 17 +++++ CAPI/python/PyAPI/logic.py | 125 ++++++++++++++++----------------- 10 files changed, 122 insertions(+), 94 deletions(-) diff --git a/CAPI/cpp/API/include/API.h b/CAPI/cpp/API/include/API.h index f5811e6b..5c6c463a 100755 --- a/CAPI/cpp/API/include/API.h +++ b/CAPI/cpp/API/include/API.h @@ -45,7 +45,7 @@ class ILogic [[nodiscard]] virtual std::shared_ptr GetGameInfo() const = 0; [[nodiscard]] virtual std::vector GetPlayerGUIDs() const = 0; [[nodiscard]] virtual THUAI7::PlaceType GetPlaceType(int32_t cellX, int32_t cellY) const = 0; - [[nodiscard]] virtual int32_t GetConstructionHp(int32_t cellX, int32_t cellY) const = 0; + [[nodiscard]] virtual std::pair GetConstructionState(int32_t cellX, int32_t cellY) const = 0; [[nodiscard]] virtual int32_t GetWormholeHp(int32_t cellX, int32_t cellY) const = 0; [[nodiscard]] virtual int32_t GetResourceState(int32_t cellX, int32_t cellY) const = 0; [[nodiscard]] virtual int32_t GetHomeHp() const = 0; @@ -97,7 +97,7 @@ class IAPI [[nodiscard]] virtual std::vector> GetFullMap() const = 0; [[nodiscard]] virtual std::shared_ptr GetGameInfo() const = 0; [[nodiscard]] virtual THUAI7::PlaceType GetPlaceType(int32_t cellX, int32_t cellY) const = 0; - [[nodiscard]] virtual int32_t GetConstructionHp(int32_t cellX, int32_t cellY) const = 0; + [[nodiscard]] virtual std::pair GetConstructionState(int32_t cellX, int32_t cellY) const = 0; [[nodiscard]] virtual int32_t GetWormholeHp(int32_t cellX, int32_t cellY) const = 0; [[nodiscard]] virtual int32_t GetResourceState(int32_t cellX, int32_t cellY) const = 0; [[nodiscard]] virtual int32_t GetHomeHp() const = 0; @@ -203,7 +203,7 @@ class ShipAPI : public IShipAPI, public IGameTimer [[nodiscard]] std::vector> GetBullets() const override; [[nodiscard]] std::vector> GetFullMap() const override; [[nodiscard]] THUAI7::PlaceType GetPlaceType(int32_t cellX, int32_t cellY) const override; - [[nodiscard]] int32_t GetConstructionHp(int32_t cellX, int32_t cellY) const override; + [[nodiscard]] std::pair GetConstructionState(int32_t cellX, int32_t cellY) const override; [[nodiscard]] int32_t GetWormholeHp(int32_t x, int32_t y) const override; [[nodiscard]] int32_t GetResourceState(int32_t cellX, int32_t cellY) const override; [[nodiscard]] std::shared_ptr GetGameInfo() const override; @@ -259,7 +259,7 @@ class TeamAPI : public ITeamAPI, public IGameTimer [[nodiscard]] std::vector> GetBullets() const override; [[nodiscard]] std::vector> GetFullMap() const override; [[nodiscard]] THUAI7::PlaceType GetPlaceType(int32_t cellX, int32_t cellY) const override; - [[nodiscard]] int32_t GetConstructionHp(int32_t cellX, int32_t cellY) const override; + [[nodiscard]] std::pair GetConstructionState(int32_t cellX, int32_t cellY) const override; [[nodiscard]] int32_t GetWormholeHp(int32_t x, int32_t y) const override; [[nodiscard]] int32_t GetResourceState(int32_t cellX, int32_t cellY) const override; [[nodiscard]] int32_t GetHomeHp() const override; @@ -320,7 +320,7 @@ class ShipDebugAPI : public IShipAPI, public IGameTimer [[nodiscard]] std::vector> GetBullets() const override; [[nodiscard]] std::vector> GetFullMap() const override; [[nodiscard]] THUAI7::PlaceType GetPlaceType(int32_t cellX, int32_t cellY) const override; - [[nodiscard]] int32_t GetConstructionHp(int32_t cellX, int32_t cellY) const override; + [[nodiscard]] std::pair GetConstructionState(int32_t cellX, int32_t cellY) const override; [[nodiscard]] int32_t GetWormholeHp(int32_t x, int32_t y) const override; [[nodiscard]] int32_t GetResourceState(int32_t cellX, int32_t cellY) const override; [[nodiscard]] int32_t GetHomeHp() const override; @@ -366,7 +366,7 @@ class TeamDebugAPI : public ITeamAPI, public IGameTimer [[nodiscard]] std::vector> GetBullets() const override; [[nodiscard]] std::vector> GetFullMap() const override; [[nodiscard]] THUAI7::PlaceType GetPlaceType(int32_t cellX, int32_t cellY) const override; - [[nodiscard]] int32_t GetConstructionHp(int32_t cellX, int32_t cellY) const override; + [[nodiscard]] std::pair GetConstructionState(int32_t cellX, int32_t cellY) const override; [[nodiscard]] int32_t GetWormholeHp(int32_t x, int32_t y) const override; [[nodiscard]] int32_t GetResourceState(int32_t cellX, int32_t cellY) const override; [[nodiscard]] int32_t GetHomeHp() const override; diff --git a/CAPI/cpp/API/include/logic.h b/CAPI/cpp/API/include/logic.h index 0f69406d..cd1df973 100755 --- a/CAPI/cpp/API/include/logic.h +++ b/CAPI/cpp/API/include/logic.h @@ -98,7 +98,7 @@ class Logic : public ILogic [[nodiscard]] std::shared_ptr GetGameInfo() const; [[nodiscard]] THUAI7::PlaceType GetPlaceType(int32_t cellX, int32_t cellY) const; [[nodiscard]] std::vector GetPlayerGUIDs() const; - [[nodiscard]] int32_t GetConstructionHp(int32_t cellX, int32_t cellY) const; + [[nodiscard]] std::pair GetConstructionState(int32_t cellX, int32_t cellY) const; [[nodiscard]] int32_t GetWormholeHp(int32_t cellX, int32_t cellY) const; [[nodiscard]] int32_t GetResourceState(int32_t cellX, int32_t cellY) const; [[nodiscard]] int32_t GetHomeHp() const; diff --git a/CAPI/cpp/API/src/API.cpp b/CAPI/cpp/API/src/API.cpp index 3357ec65..69bf5e3b 100755 --- a/CAPI/cpp/API/src/API.cpp +++ b/CAPI/cpp/API/src/API.cpp @@ -140,14 +140,14 @@ THUAI7::PlaceType TeamAPI::GetPlaceType(int32_t cellX, int32_t cellY) const return logic.GetPlaceType(cellX, cellY); } -int32_t ShipAPI::GetConstructionHp(int32_t cellX, int32_t cellY) const +std::pair ShipAPI::GetConstructionState(int32_t cellX, int32_t cellY) const { - return logic.GetConstructionHp(cellX, cellY); + return logic.GetConstructionState(cellX, cellY); } -int32_t TeamAPI::GetConstructionHp(int32_t cellX, int32_t cellY) const +std::pair TeamAPI::GetConstructionState(int32_t cellX, int32_t cellY) const { - return logic.GetConstructionHp(cellX, cellY); + return logic.GetConstructionState(cellX, cellY); } int32_t ShipAPI::GetWormholeHp(int32_t cellX, int32_t cellY) const diff --git a/CAPI/cpp/API/src/DebugAPI.cpp b/CAPI/cpp/API/src/DebugAPI.cpp index b5220ffc..189d7b02 100755 --- a/CAPI/cpp/API/src/DebugAPI.cpp +++ b/CAPI/cpp/API/src/DebugAPI.cpp @@ -201,9 +201,9 @@ THUAI7::PlaceType ShipDebugAPI::GetPlaceType(int32_t cellX, int32_t cellY) const return logic.GetPlaceType(cellX, cellY); } -int32_t ShipDebugAPI::GetConstructionHp(int32_t cellX, int32_t cellY) const +std::pair ShipDebugAPI::GetConstructionState(int32_t cellX, int32_t cellY) const { - return logic.GetConstructionHp(cellX, cellY); + return logic.GetConstructionState(cellX, cellY); } int32_t ShipDebugAPI::GetWormholeHp(int32_t cellX, int32_t cellY) const @@ -395,9 +395,9 @@ THUAI7::PlaceType TeamDebugAPI::GetPlaceType(int32_t cellX, int32_t cellY) const return logic.GetPlaceType(cellX, cellY); } -int32_t TeamDebugAPI::GetConstructionHp(int32_t cellX, int32_t cellY) const +std::pair TeamDebugAPI::GetConstructionState(int32_t cellX, int32_t cellY) const { - return logic.GetConstructionHp(cellX, cellY); + return logic.GetConstructionState(cellX, cellY); } int32_t TeamDebugAPI::GetWormholeHp(int32_t cellX, int32_t cellY) const diff --git a/CAPI/cpp/API/src/logic.cpp b/CAPI/cpp/API/src/logic.cpp index 8cf43231..050b0325 100755 --- a/CAPI/cpp/API/src/logic.cpp +++ b/CAPI/cpp/API/src/logic.cpp @@ -91,26 +91,26 @@ THUAI7::PlaceType Logic::GetPlaceType(int32_t cellX, int32_t cellY) const return currentState->gameMap[cellX][cellY]; } -int32_t Logic::GetConstructionHp(int32_t cellX, int32_t cellY) const +std::pair Logic::GetConstructionState(int32_t cellX, int32_t cellY) const { std::unique_lock lock(mtxState); - logger->debug("Called GetConstructionHp"); + logger->debug("Called GetConstructionState"); auto pos = std::make_pair(cellX, cellY); auto it = currentState->mapInfo->factoryState.find(pos); auto it2 = currentState->mapInfo->communityState.find(pos); auto it3 = currentState->mapInfo->fortState.find(pos); if (it != currentState->mapInfo->factoryState.end()) { - return currentState->mapInfo->factoryState[pos].first; + return currentState->mapInfo->factoryState[pos]; } else if (it2 != currentState->mapInfo->communityState.end()) - return currentState->mapInfo->communityState[pos].first; + return currentState->mapInfo->communityState[pos]; else if (it3 != currentState->mapInfo->fortState.end()) - return currentState->mapInfo->fortState[pos].first; + return currentState->mapInfo->fortState[pos]; else { logger->warn("Construction not found"); - return -1; + return std::make_pair(-1, -1); } } @@ -477,6 +477,7 @@ void Logic::LoadBufferCase(const protobuf::MessageOfObj& item) } else { + bufferState->mapInfo->factoryState[pos].first = item.factory_message().team_id(); bufferState->mapInfo->factoryState[pos].second = item.factory_message().hp(); logger->debug("Update Factory!"); } @@ -491,6 +492,7 @@ void Logic::LoadBufferCase(const protobuf::MessageOfObj& item) } else { + bufferState->mapInfo->factoryState[pos].first = item.factory_message().team_id(); bufferState->mapInfo->factoryState[pos].second = item.factory_message().hp(); logger->debug("Update Factory!"); } @@ -507,6 +509,7 @@ void Logic::LoadBufferCase(const protobuf::MessageOfObj& item) } else { + bufferState->mapInfo->communityState[pos].first = item.community_message().team_id(); bufferState->mapInfo->communityState[pos].second = item.community_message().hp(); logger->debug("Update Community!"); } @@ -521,6 +524,7 @@ void Logic::LoadBufferCase(const protobuf::MessageOfObj& item) } else { + bufferState->mapInfo->communityState[pos].first = item.community_message().team_id(); bufferState->mapInfo->communityState[pos].second = item.community_message().hp(); logger->debug("Update Community!"); } @@ -537,6 +541,7 @@ void Logic::LoadBufferCase(const protobuf::MessageOfObj& item) } else { + bufferState->mapInfo->fortState[pos].first = item.fort_message().team_id(); bufferState->mapInfo->fortState[pos].second = item.fort_message().hp(); logger->debug("Update Fort!"); } @@ -551,6 +556,7 @@ void Logic::LoadBufferCase(const protobuf::MessageOfObj& item) } else { + bufferState->mapInfo->fortState[pos].first = item.fort_message().team_id(); bufferState->mapInfo->fortState[pos].second = item.fort_message().hp(); logger->debug("Update Fort!"); } @@ -675,6 +681,7 @@ void Logic::LoadBufferCase(const protobuf::MessageOfObj& item) } else { + bufferState->mapInfo->factoryState[pos].first = item.factory_message().team_id(); bufferState->mapInfo->factoryState[pos].second = item.factory_message().hp(); logger->debug("Update Factory!"); } @@ -689,6 +696,7 @@ void Logic::LoadBufferCase(const protobuf::MessageOfObj& item) } else { + bufferState->mapInfo->factoryState[pos].first = item.factory_message().team_id(); bufferState->mapInfo->factoryState[pos].second = item.factory_message().hp(); logger->debug("Update Factory!"); } @@ -705,6 +713,7 @@ void Logic::LoadBufferCase(const protobuf::MessageOfObj& item) } else { + bufferState->mapInfo->communityState[pos].first = item.community_message().team_id(); bufferState->mapInfo->communityState[pos].second = item.community_message().hp(); logger->debug("Update Community!"); } @@ -719,6 +728,7 @@ void Logic::LoadBufferCase(const protobuf::MessageOfObj& item) } else { + bufferState->mapInfo->communityState[pos].first = item.community_message().team_id(); bufferState->mapInfo->communityState[pos].second = item.community_message().hp(); logger->debug("Update Community!"); } @@ -735,6 +745,7 @@ void Logic::LoadBufferCase(const protobuf::MessageOfObj& item) } else { + bufferState->mapInfo->fortState[pos].first = item.fort_message().team_id(); bufferState->mapInfo->fortState[pos].second = item.fort_message().hp(); logger->debug("Update Fort!"); } @@ -749,6 +760,7 @@ void Logic::LoadBufferCase(const protobuf::MessageOfObj& item) } else { + bufferState->mapInfo->fortState[pos].first = item.fort_message().team_id(); bufferState->mapInfo->fortState[pos].second = item.fort_message().hp(); logger->debug("Update Fort!"); } diff --git a/CAPI/python/PyAPI/API.py b/CAPI/python/PyAPI/API.py index 6f597a4a..3b336b58 100644 --- a/CAPI/python/PyAPI/API.py +++ b/CAPI/python/PyAPI/API.py @@ -76,8 +76,8 @@ def GetFullMap(self) -> List[List[THUAI7.PlaceType]]: def GetPlaceType(self, cellX: int, cellY: int) -> THUAI7.PlaceType: return self.__logic.GetPlaceType(cellX, cellY) - def GetConstructionHp(self, cellX: int, cellY: int) -> int: - return self.__logic.GetConstructionHp(cellX, cellY) + def GetConstructionState(self, cellX: int, cellY: int) -> tuple: + return self.__logic.GetConstructionState(cellX, cellY) def GetWormholeHp(self, cellX: int, cellY: int) -> int: return self.__logic.GetWormholeHp(cellX, cellY) @@ -184,8 +184,8 @@ def GetFullMap(self) -> List[List[THUAI7.PlaceType]]: def GetPlaceType(self, cellX: int, cellY: int) -> THUAI7.PlaceType: return self.__logic.GetPlaceType(cellX, cellY) - def GetConstructionHp(self, cellX: int, cellY: int) -> int: - return self.__logic.GetConstructionHp(cellX, cellY) + def GetConstructionState(self, cellX: int, cellY: int) -> tuple: + return self.__logic.GetConstructionState(cellX, cellY) def GetWormholeHp(self, cellX: int, cellY: int) -> int: return self.__logic.GetWormholeHp(cellX, cellY) diff --git a/CAPI/python/PyAPI/DebugAPI.py b/CAPI/python/PyAPI/DebugAPI.py index 2967a76c..0cade2ff 100644 --- a/CAPI/python/PyAPI/DebugAPI.py +++ b/CAPI/python/PyAPI/DebugAPI.py @@ -199,8 +199,8 @@ def GetFullMap(self) -> List[List[THUAI7.PlaceType]]: def GetPlaceType(self, cellX: int, cellY: int) -> THUAI7.PlaceType: return self.__logic.GetPlaceType(cellX, cellY) - def GetConstructionHp(self, cellX: int, cellY: int) -> int: - return self.__logic.GetConstructionHp(cellX, cellY) + def GetConstructionState(self, cellX: int, cellY: int) -> tuple: + return self.__logic.GetConstructionState(cellX, cellY) def GetWormholeHp(self, cellX: int, cellY: int) -> int: return self.__logic.GetWormholeHp(cellX, cellY) @@ -440,8 +440,8 @@ def GetFullMap(self) -> List[List[THUAI7.PlaceType]]: def GetPlaceType(self, cellX: int, cellY: int) -> THUAI7.PlaceType: return self.__logic.GetPlaceType(cellX, cellY) - def GetConstructionHp(self, cellX: int, cellY: int) -> int: - return self.__logic.GetConstructionHp(cellX, cellY) + def GetConstructionState(self, cellX: int, cellY: int) -> tuple: + return self.__logic.GetConstructionState(cellX, cellY) def GetWormholeHp(self, cellX: int, cellY: int) -> int: return self.__logic.GetWormholeHp(cellX, cellY) diff --git a/CAPI/python/PyAPI/Interface.py b/CAPI/python/PyAPI/Interface.py index 0c3763f1..884fef3e 100644 --- a/CAPI/python/PyAPI/Interface.py +++ b/CAPI/python/PyAPI/Interface.py @@ -43,7 +43,7 @@ def GetPlaceType(self, cellX: int, cellY: int) -> THUAI7.PlaceType: pass @abstractmethod - def GetConstructionHp(self, cellX: int, cellY: int) -> int: + def GetConstructionState(self, cellX: int, cellY: int) -> tuple: pass @abstractmethod @@ -194,7 +194,7 @@ def GetPlaceType(self, cellX: int, cellY: int) -> THUAI7.PlaceType: pass @abstractmethod - def GetConstructionHp(self, cellX: int, cellY: int) -> int: + def GetConstructionState(self, cellX: int, cellY: int) -> tuple: pass @abstractmethod diff --git a/CAPI/python/PyAPI/constants.py b/CAPI/python/PyAPI/constants.py index d6e5103e..ed893f48 100644 --- a/CAPI/python/PyAPI/constants.py +++ b/CAPI/python/PyAPI/constants.py @@ -11,22 +11,27 @@ class Constants: recycleMultiplier = 0.5 sizeOfShip = 800 + class Home: maxHp = 24000 energySpeed = 100 + class Factory: maxHp = 8000 energySpeed = 300 + class Community: maxHp = 6000 + class Fort: maxHp = 12000 attackRange = 8000 damage = 1200 + class CivilianShip: Speed = 3000 basicArmor = 0 @@ -34,6 +39,7 @@ class CivilianShip: maxHp = 3000 Cost = 4000 + class MilitaryShip: Speed = 2800 basicArmor = 400 @@ -41,6 +47,7 @@ class MilitaryShip: maxHp = 4000 Cost = 12000 + class FlagShip: Speed = 2700 basicArmor = 800 @@ -48,6 +55,7 @@ class FlagShip: maxHp = 12000 Cost = 50000 + class Producer: energySpeed1 = 100 energySpeed2 = 200 @@ -56,6 +64,7 @@ class Producer: Cost2 = 4000 Cost3 = 8000 + class Constructor: constructSpeed1 = 300 constructSpeed2 = 400 @@ -64,6 +73,7 @@ class Constructor: Cost2 = 4000 Cost3 = 8000 + class Armor: armor1 = 2000 armor2 = 3000 @@ -72,6 +82,7 @@ class Armor: Cost2 = 12000 Cost3 = 18000 + class Shield: shield1 = 2000 shield2 = 3000 @@ -80,6 +91,7 @@ class Shield: Cost2 = 12000 Cost3 = 18000 + class Weapon: LaserCost = 0 PlasmaCost = 12000 @@ -87,6 +99,7 @@ class Weapon: MissleCost = 18000 ArcCost = 24000 + class Laser: Damage = 1200 AttackRange = 4000 @@ -96,6 +109,7 @@ class Laser: CastTime = 300 BackSwing = 300 + class Plasma: Damage = 1300 AttackRange = 4000 @@ -105,6 +119,7 @@ class Plasma: CastTime = 400 BackSwing = 400 + class Shell: Damage = 1800 AttackRange = 4000 @@ -114,6 +129,7 @@ class Shell: CastTime = 200 BackSwing = 200 + class Missle: Damage = 1600 AttackRange = 8000 @@ -124,6 +140,7 @@ class Missle: CastTime = 600 BackSwing = 600 + class Arc: Damage = 3200 AttackRange = 8000 diff --git a/CAPI/python/PyAPI/logic.py b/CAPI/python/PyAPI/logic.py index 3ada4741..707bbfd1 100644 --- a/CAPI/python/PyAPI/logic.py +++ b/CAPI/python/PyAPI/logic.py @@ -138,9 +138,9 @@ def GetPlayerGUIDs(self) -> List[int]: with self.__mtxState: return copy.deepcopy(self.__currentState.guids) - def GetConstructionHp(self, cellX: int, cellY: int) -> int: + def GetConstructionState(self, cellX: int, cellY: int) -> tuple: with self.__mtxState: - self.__logger.debug("Called GetConstructionHp") + self.__logger.debug("Called GetConstructionState") if (cellX, cellY) in self.__currentState.mapInfo.factoryState: return copy.deepcopy( self.__currentState.mapInfo.factoryState[(cellX, cellY)] @@ -154,8 +154,8 @@ def GetConstructionHp(self, cellX: int, cellY: int) -> int: self.__currentState.mapInfo.fortState[(cellX, cellY)] ) else: - self.__logger.warning("GetConstructionHp: Out of range") - return -1 + self.__logger.warning("GetConstructionState: Out of range") + return (-1,-1) def GetWormholeHp(self, cellX: int, cellY: int) -> int: with self.__mtxState: @@ -427,15 +427,14 @@ def __LoadBufferCase(self, item: Message2Clients.MessageOfObj) -> None: AssistFunction.GridToCell(item.factory_message.y), ) if pos not in self.__bufferState.mapInfo.factoryState: - self.__bufferState.mapInfo.factoryState[pos] = ( - item.factory_message.hp - ) self.__logger.debug("New Factory") else: - self.__bufferState.mapInfo.factoryState[pos] = ( - item.factory_message.hp - ) self.__logger.debug("Update Factory") + self.__bufferState.mapInfo.factoryState[pos] = ( + item.factory_message.team_id, + item.factory_message.hp, + ) + elif AssistFunction.HaveView( self.__bufferState.self.viewRange, self.__bufferState.self.x, @@ -449,15 +448,13 @@ def __LoadBufferCase(self, item: Message2Clients.MessageOfObj) -> None: AssistFunction.GridToCell(item.factory_message.y), ) if pos not in self.__bufferState.mapInfo.factoryState: - self.__bufferState.mapInfo.factoryState[pos] = ( - item.factory_message.hp - ) self.__logger.debug("New Factory") else: - self.__bufferState.mapInfo.factoryState[pos] = ( - item.factory_message.hp - ) self.__logger.debug("Update Factory") + self.__bufferState.mapInfo.factoryState[pos] = ( + item.factory_message.team_id, + item.factory_message.hp, + ) elif item.WhichOneof("message_of_obj") == "community_message": if item.community_message.team_id == self.__teamID: @@ -466,15 +463,14 @@ def __LoadBufferCase(self, item: Message2Clients.MessageOfObj) -> None: AssistFunction.GridToCell(item.community_message.y), ) if pos not in self.__bufferState.mapInfo.communityState: - self.__bufferState.mapInfo.communityState[pos] = ( - item.community_message.hp - ) self.__logger.debug("New Community") else: - self.__bufferState.mapInfo.communityState[pos] = ( - item.community_message.hp - ) self.__logger.debug("Update Community") + self.__bufferState.mapInfo.communityState[pos] = ( + item.community_message.team_id, + item.community_message.hp, + ) + elif AssistFunction.HaveView( self.__bufferState.self.viewRange, self.__bufferState.self.x, @@ -488,15 +484,13 @@ def __LoadBufferCase(self, item: Message2Clients.MessageOfObj) -> None: AssistFunction.GridToCell(item.community_message.y), ) if pos not in self.__bufferState.mapInfo.communityState: - self.__bufferState.mapInfo.communityState[pos] = ( - item.community_message.hp - ) self.__logger.debug("New Community") else: - self.__bufferState.mapInfo.communityState[pos] = ( - item.community_message.hp - ) self.__logger.debug("Update Community") + self.__bufferState.mapInfo.communityState[pos] = ( + item.community_message.team_id, + item.community_message.hp, + ) elif item.WhichOneof("message_of_obj") == "fort_message": if item.fort_message.team_id == self.__teamID: @@ -505,11 +499,13 @@ def __LoadBufferCase(self, item: Message2Clients.MessageOfObj) -> None: AssistFunction.GridToCell(item.fort_message.y), ) if pos not in self.__bufferState.mapInfo.fortState: - self.__bufferState.mapInfo.fortState[pos] = item.fort_message.hp self.__logger.debug("New Fort") else: - self.__bufferState.mapInfo.fortState[pos] = item.fort_message.hp self.__logger.debug("Update Fort") + self.__bufferState.mapInfo.fortState[pos] = ( + item.fort_message.team_id, + item.fort_message.hp, + ) elif AssistFunction.HaveView( self.__bufferState.self.viewRange, self.__bufferState.self.x, @@ -523,11 +519,13 @@ def __LoadBufferCase(self, item: Message2Clients.MessageOfObj) -> None: AssistFunction.GridToCell(item.fort_message.y), ) if pos not in self.__bufferState.mapInfo.fortState: - self.__bufferState.mapInfo.fortState[pos] = item.fort_message.hp self.__logger.debug("New Fort") else: - self.__bufferState.mapInfo.fortState[pos] = item.fort_message.hp self.__logger.debug("Update Fort") + self.__bufferState.mapInfo.fortState[pos] = ( + item.fort_message.team_id, + item.fort_message.hp, + ) elif item.WhichOneof("message_of_obj") == "wormhole_message": if AssistFunction.HaveView( @@ -553,7 +551,10 @@ def __LoadBufferCase(self, item: Message2Clients.MessageOfObj) -> None: AssistFunction.GridToCell(item.home_message.x), AssistFunction.GridToCell(item.home_message.y), ) - self.__bufferState.mapInfo.homeState[pos] = item.home_message.hp + self.__bufferState.mapInfo.homeState[pos] = ( + item.home_message.team_id, + item.home_message.hp, + ) self.__logger.debug("Update Home") elif AssistFunction.HaveView( self.__bufferState.self.viewRange, @@ -567,7 +568,10 @@ def __LoadBufferCase(self, item: Message2Clients.MessageOfObj) -> None: AssistFunction.GridToCell(item.home_message.x), AssistFunction.GridToCell(item.home_message.y), ) - self.__bufferState.mapInfo.homeState[pos] = item.home_message.hp + self.__bufferState.mapInfo.homeState[pos] = ( + item.home_message.team_id, + item.home_message.hp, + ) self.__logger.debug("Update Home") elif item.WhichOneof("message_of_obj") == "resource_message": @@ -653,30 +657,26 @@ def HaveOverView(targetX: int, targetY: int): AssistFunction.GridToCell(item.factory_message.y), ) if pos not in self.__bufferState.mapInfo.factoryState: - self.__bufferState.mapInfo.factoryState[pos] = ( - item.factory_message.hp - ) self.__logger.debug("New Factory") else: - self.__bufferState.mapInfo.factoryState[pos] = ( - item.factory_message.hp - ) self.__logger.debug("Update Factory") + self.__bufferState.mapInfo.factoryState[pos] = ( + item.factory_message.team_id, + item.factory_message.hp, + ) elif HaveOverView(item.factory_message.x, item.factory_message.y): pos = ( AssistFunction.GridToCell(item.factory_message.x), AssistFunction.GridToCell(item.factory_message.y), ) if pos not in self.__bufferState.mapInfo.factoryState: - self.__bufferState.mapInfo.factoryState[pos] = ( - item.factory_message.hp - ) self.__logger.debug("New Factory") else: - self.__bufferState.mapInfo.factoryState[pos] = ( - item.factory_message.hp - ) self.__logger.debug("Update Factory") + self.__bufferState.mapInfo.factoryState[pos] = ( + item.factory_message.team_id, + item.factory_message.hp, + ) elif item.WhichOneof("message_of_obj") == "community_message": if item.community_message.team_id == self.__teamID: @@ -685,31 +685,26 @@ def HaveOverView(targetX: int, targetY: int): AssistFunction.GridToCell(item.community_message.y), ) if pos not in self.__bufferState.mapInfo.communityState: - self.__bufferState.mapInfo.communityState[pos] = ( - item.community_message.hp - ) self.__logger.debug("New Community") else: - self.__bufferState.mapInfo.communityState[pos] = ( - item.community_message.hp - ) self.__logger.debug("Update Community") + self.__bufferState.mapInfo.communityState[pos] = ( + item.community_message.team_id, + item.community_message.hp, + ) elif HaveOverView(item.community_message.x, item.community_message.y): pos = ( AssistFunction.GridToCell(item.community_message.x), AssistFunction.GridToCell(item.community_message.y), ) if pos not in self.__bufferState.mapInfo.communityState: - self.__bufferState.mapInfo.communityState[pos] = ( - item.community_message.hp - ) self.__logger.debug("New Community") else: - self.__bufferState.mapInfo.communityState[pos] = ( - item.community_message.hp - ) self.__logger.debug("Update Community") - + self.__bufferState.mapInfo.communityState[pos] = ( + item.community_message.team_id, + item.community_message.hp, + ) elif item.WhichOneof("message_of_obj") == "fort_message": if item.fort_message.team_id == self.__teamID: pos = ( @@ -717,22 +712,26 @@ def HaveOverView(targetX: int, targetY: int): AssistFunction.GridToCell(item.fort_message.y), ) if pos not in self.__bufferState.mapInfo.fortState: - self.__bufferState.mapInfo.fortState[pos] = item.fort_message.hp self.__logger.debug("New Fort") else: - self.__bufferState.mapInfo.fortState[pos] = item.fort_message.hp self.__logger.debug("Update Fort") + self.__bufferState.mapInfo.fortState[pos] = ( + item.fort_message.team_id, + item.fort_message.hp, + ) elif HaveOverView(item.fort_message.x, item.fort_message.y): pos = ( AssistFunction.GridToCell(item.fort_message.x), AssistFunction.GridToCell(item.fort_message.y), ) if pos not in self.__bufferState.mapInfo.fortState: - self.__bufferState.mapInfo.fortState[pos] = item.fort_message.hp self.__logger.debug("New Fort") else: - self.__bufferState.mapInfo.fortState[pos] = item.fort_message.hp self.__logger.debug("Update Fort") + self.__bufferState.mapInfo.fortState[pos] = ( + item.fort_message.team_id, + item.fort_message.hp, + ) elif item.WhichOneof("message_of_obj") == "wormhole_message": if HaveOverView(item.wormhole_message.x, item.wormhole_message.y): From 64050accc5aedfe794cf23d9d2abd88bcb6b9ebd Mon Sep 17 00:00:00 2001 From: sigureling <1678348940@qq.com> Date: Thu, 9 May 2024 14:27:19 +0800 Subject: [PATCH 108/179] fix: :bug: fix ViewRange --- CAPI/cpp/API/include/utils.hpp | 2 + CAPI/python/PyAPI/utils.py | 73 +++++++++++++++++----------------- 2 files changed, 38 insertions(+), 37 deletions(-) diff --git a/CAPI/cpp/API/include/utils.hpp b/CAPI/cpp/API/include/utils.hpp index 57ae4955..b2046927 100755 --- a/CAPI/cpp/API/include/utils.hpp +++ b/CAPI/cpp/API/include/utils.hpp @@ -41,6 +41,8 @@ namespace AssistFunction THUAI7::PlaceType newPlace = map[GridToCell(newX)][GridToCell(newY)]; if (newPlace == THUAI7::PlaceType::Shadow && myPlace != THUAI7::PlaceType::Shadow) return false; + if (distance > viewRange * viewRange) + return false; int32_t divide = std::max(std::abs(deltaX), std::abs(deltaY)) / 100; if (divide == 0) return true; diff --git a/CAPI/python/PyAPI/utils.py b/CAPI/python/PyAPI/utils.py index 4ed820af..148fddab 100644 --- a/CAPI/python/PyAPI/utils.py +++ b/CAPI/python/PyAPI/utils.py @@ -32,45 +32,44 @@ def HaveView( newPlace = map[AssistFunction.GridToCell(newX)][AssistFunction.GridToCell(newY)] if myPlace != THUAI7.PlaceType.Shadow and newPlace == THUAI7.PlaceType.Shadow: return False - if distance <= viewRange * viewRange: - divide = max(abs(deltaX), abs(deltaY)) // 100 - if divide == 0: - return True - dx = deltaX / divide - dy = deltaY / divide - selfX = float(x) - selfY = float(y) - if ( - newPlace == THUAI7.PlaceType.Shadow - and myPlace == THUAI7.PlaceType.Shadow - ): - for _ in range(divide): - selfX += dx - selfY += dy - if ( - map[AssistFunction.GridToCell(int(selfX))][ - AssistFunction.GridToCell(int(selfY)) - ] - != THUAI7.PlaceType.Shadow - ): - return False - else: - return True + if distance > viewRange * viewRange: + return False + divide = max(abs(deltaX), abs(deltaY)) // 100 + if divide == 0: + return True + dx = deltaX / divide + dy = deltaY / divide + selfX = float(x) + selfY = float(y) + if ( + newPlace == THUAI7.PlaceType.Shadow + and myPlace == THUAI7.PlaceType.Shadow + ): + for _ in range(divide): + selfX += dx + selfY += dy + if ( + map[AssistFunction.GridToCell(int(selfX))][ + AssistFunction.GridToCell(int(selfY)) + ] + != THUAI7.PlaceType.Shadow + ): + return False else: - for _ in range(divide): - selfX += dx - selfY += dy - if ( - map[AssistFunction.GridToCell(int(selfX))][ - AssistFunction.GridToCell(int(selfY)) - ] - == THUAI7.PlaceType.Ruin - ): - return False - else: - return True + return True else: - return False + for _ in range(divide): + selfX += dx + selfY += dy + if ( + map[AssistFunction.GridToCell(int(selfX))][ + AssistFunction.GridToCell(int(selfY)) + ] + == THUAI7.PlaceType.Ruin + ): + return False + else: + return True class Proto2THUAI7: From 61160f813b6a0dad3361d5e4c9838c49aed8642a Mon Sep 17 00:00:00 2001 From: Timothy Liu Date: Thu, 9 May 2024 17:10:35 +0800 Subject: [PATCH 109/179] build(capi): :building_construction: enable all warnings on linux --- CAPI/cpp/CMakeLists.txt | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/CAPI/cpp/CMakeLists.txt b/CAPI/cpp/CMakeLists.txt index cf0ab28d..6b286890 100755 --- a/CAPI/cpp/CMakeLists.txt +++ b/CAPI/cpp/CMakeLists.txt @@ -7,6 +7,10 @@ set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O2 -pthread") +if(NOT MSVC) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wpedantic") +endif() + aux_source_directory(./API/src CPP_LIST) aux_source_directory(./proto PROTO_CPP_LIST) @@ -21,8 +25,8 @@ add_executable(capi ${CPP_LIST} ${PROTO_CPP_LIST}) target_include_directories(capi PUBLIC ${PROJECT_SOURCE_DIR}/proto ${PROJECT_SOURCE_DIR}/API/include ${PROJECT_SOURCE_DIR}/tclap/include ${PROJECT_SOURCE_DIR}/spdlog/include) target_link_libraries(capi -protobuf::libprotobuf -gRPC::grpc -gRPC::grpc++_reflection -gRPC::grpc++ + protobuf::libprotobuf + gRPC::grpc + gRPC::grpc++_reflection + gRPC::grpc++ ) From 0f48ce91821d4fe41eb72ef72314998bf66433cd Mon Sep 17 00:00:00 2001 From: Xuc Pan Date: Thu, 9 May 2024 14:09:29 +0800 Subject: [PATCH 110/179] fix: :bug: construction miss shield --- logic/Gaming/ShipManager.cs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/logic/Gaming/ShipManager.cs b/logic/Gaming/ShipManager.cs index 99144235..d2314942 100755 --- a/logic/Gaming/ShipManager.cs +++ b/logic/Gaming/ShipManager.cs @@ -109,7 +109,14 @@ public void BeAttacked(Ship ship, long AP, long teamID) { return; } - if (ship.Armor > 0) + if (ship.Shield > 0) + { + ship.Shield.SubPositiveV(AP); + ShipManagerLogging.logger.ConsoleLogDebug( + LoggingFunctional.ShipLogInfo(ship) + + $" 's shield is {ship.Shield}"); + } + else if (ship.Armor > 0) { ship.Armor.SubPositiveV(AP); ShipManagerLogging.logger.ConsoleLogDebug( From 03f9a06fa871d24dcbb27c9abb4807d85ed950db Mon Sep 17 00:00:00 2001 From: Timothy Liu Date: Fri, 10 May 2024 13:28:52 +0800 Subject: [PATCH 111/179] chore(logic): :bug: correct comment of params in score algorithm --- logic/Server/GameServer.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/logic/Server/GameServer.cs b/logic/Server/GameServer.cs index 6e34d182..75fdbe65 100755 --- a/logic/Server/GameServer.cs +++ b/logic/Server/GameServer.cs @@ -178,16 +178,16 @@ protected static double[] LadderCalculate(double[] oriScores, double[] competiti (oriScores[0], oriScores[1]) = (oriScores[1], oriScores[0]); } - const double normalDeltaThereshold = 2000.0; // 分数差标准化参数,同时也是大分数差阈值 - const double correctParam = normalDeltaThereshold * 1.2;// 修正参数 - const double winnerWeight = 9e-8; // 获胜者天梯得分权值 - const double loserWeight = 5e-8; // 落败者天梯得分权值 - const double scoreDeltaThereshold = 40000.0; // 极大分数差阈值 + const double normalDeltaThereshold = 2000.0; // 天梯分数差参数,天梯分差超过此阈值太多则增长缓慢 + const double correctParam = normalDeltaThereshold * 1.2; // 修正参数 + const double winnerWeight = 9e-8; // 获胜者天梯得分权值 + const double loserWeight = 5e-8; // 落败者天梯得分权值 + const double scoreDeltaThereshold = 40000.0; // 比赛得分参数,比赛得分超过此阈值太多则增长缓慢 double[] resScore = [0, 0]; - double oriDelta = oriScores[0] - oriScores[1]; // 原分数差 + double oriDelta = oriScores[0] - oriScores[1]; // 天梯原分数差 double competitionDelta = competitionScores[0] - competitionScores[1]; // 本次比赛分数差 - double normalOriDelta = oriDelta / normalDeltaThereshold; // 标准化原分数差 + double normalOriDelta = oriDelta / normalDeltaThereshold; // 标准化天梯原分数差 double correctRate = oriDelta / correctParam; // 修正率,修正方向为缩小分数差 double correct = 0.5 * (Math.Tanh((competitionDelta - scoreDeltaThereshold) / scoreDeltaThereshold - correctRate) From b4e8f3ffe3cc16025307ea64a2736240fc10df3f Mon Sep 17 00:00:00 2001 From: DragonAura <32223554+DragonAura@users.noreply.github.com> Date: Fri, 10 May 2024 15:31:58 +0800 Subject: [PATCH 112/179] fix: fix send team id --- logic/Server/RpcServices.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/logic/Server/RpcServices.cs b/logic/Server/RpcServices.cs index 578b125c..18ea43b5 100755 --- a/logic/Server/RpcServices.cs +++ b/logic/Server/RpcServices.cs @@ -387,7 +387,8 @@ public override Task Send(SendMsg request, ServerCallContext context) { TextMessage = request.TextMessage, FromId = request.PlayerId, - ToId = request.ToPlayerId + ToId = request.ToPlayerId, + TeamId = request.TeamId }; lock (newsLock) { @@ -410,7 +411,8 @@ public override Task Send(SendMsg request, ServerCallContext context) { BinaryMessage = request.BinaryMessage, FromId = request.PlayerId, - ToId = request.ToPlayerId + ToId = request.ToPlayerId, + TeamId = request.TeamId }; lock (newsLock) { From d6b51523703ea99114579e19192f239cdb186b11 Mon Sep 17 00:00:00 2001 From: Xuc Pan Date: Fri, 10 May 2024 19:14:45 +0800 Subject: [PATCH 113/179] fix: :bug: money value not same as doc --- logic/Gaming/ShipManager.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/logic/Gaming/ShipManager.cs b/logic/Gaming/ShipManager.cs index d2314942..7c15eac2 100755 --- a/logic/Gaming/ShipManager.cs +++ b/logic/Gaming/ShipManager.cs @@ -90,7 +90,7 @@ public void BeAttacked(Ship ship, Bullet bullet) ShipManagerLogging.logger.ConsoleLogDebug( LoggingFunctional.ShipLogInfo(ship) + " is destroyed!"); - var money = ship.GetCost(); + var money = (long)(ship.GetCost() * 0.2); bullet.Parent.AddMoney(money); ShipManagerLogging.logger.ConsoleLogDebug( LoggingFunctional.ShipLogInfo((Ship)bullet.Parent) From 148b32b6611bc783272cdcdefbaeeed41550790b Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 10 May 2024 20:32:23 +0000 Subject: [PATCH 114/179] chore(deps): update dependency grpcio-tools to v1.63.0 --- CAPI/python/requirements.txt | 2 +- CAPI/python_exp/requirements.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CAPI/python/requirements.txt b/CAPI/python/requirements.txt index c187d411..b9abd196 100644 --- a/CAPI/python/requirements.txt +++ b/CAPI/python/requirements.txt @@ -1,3 +1,3 @@ grpcio==1.63.0 -grpcio-tools==1.62.2 +grpcio-tools==1.63.0 numpy diff --git a/CAPI/python_exp/requirements.txt b/CAPI/python_exp/requirements.txt index c187d411..b9abd196 100644 --- a/CAPI/python_exp/requirements.txt +++ b/CAPI/python_exp/requirements.txt @@ -1,3 +1,3 @@ grpcio==1.63.0 -grpcio-tools==1.62.2 +grpcio-tools==1.63.0 numpy From c96dbc3473dd5d29be3ae4e54313ef57b597a551 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sat, 11 May 2024 05:44:09 +0000 Subject: [PATCH 115/179] chore(deps): update actions/checkout action to v4 --- .github/workflows/gh-pages.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml index 19bf71cc..60aeb26c 100644 --- a/.github/workflows/gh-pages.yml +++ b/.github/workflows/gh-pages.yml @@ -29,7 +29,7 @@ jobs: name: github-pages url: ${{ steps.deployment.outputs.page_url }} steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Setup Pages uses: actions/configure-pages@v5 From aa1d1d0cbeaf20dcdb7249a2ccaad32983d3a2c3 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sat, 11 May 2024 05:59:41 +0000 Subject: [PATCH 116/179] chore(deps): update dependency communitytoolkit.maui.core to v9 --- installer/installer.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/installer/installer.csproj b/installer/installer.csproj index 5f1a1213..0dcc3218 100755 --- a/installer/installer.csproj +++ b/installer/installer.csproj @@ -87,7 +87,7 @@ - + From 13390676eec8e23289212ca9aab64c39581b1416 Mon Sep 17 00:00:00 2001 From: xiangmy21 <90919434+xiangmy21@users.noreply.github.com> Date: Sat, 11 May 2024 14:53:50 +0800 Subject: [PATCH 117/179] Update run.sh --- dependency/shell/run.sh | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/dependency/shell/run.sh b/dependency/shell/run.sh index 6288af98..61ab85bc 100644 --- a/dependency/shell/run.sh +++ b/dependency/shell/run.sh @@ -51,9 +51,9 @@ fi function retry_command { local command="$1" - local max_attempts=10 + local max_attempts=5 local attempt_num=1 - local sleep_seconds=5 + local sleep_seconds=10 while [ $attempt_num -le $max_attempts ]; do echo "Attempt $attempt_num / $max_attempts to run command: $command" @@ -130,11 +130,11 @@ elif [ "$TERMINAL" = "CLIENT" ]; then cp -r $python_main_dir $python_main_dir$i cp -f ./$code_name.py $python_main_dir$i/PyAPI/AI.py command="nice -0 python3 $python_main_dir$i/PyAPI/main.py -I $CONNECT_IP -P $PORT -t $k -p $i > $playback_dir/team$k-$code_name.log 2>&1 &" - retry_command "$command" > $playback_dir/client$k.log & + retry_command "$command" > $playback_dir/client$k-$i.log & elif [ -f "./$code_name" ]; then echo "find ./$code_name" - command="nice -0 ./$code_name -I $CONNECT_IP -P $PORT -t $k -p $i > $playback_dir/team$k-$codename.log 2>&1 &" - retry_command "$command" > $playback_dir/client$k.log & + command="nice -0 ./$code_name -I $CONNECT_IP -P $PORT -t $k -p $i > $playback_dir/team$k-$code_name.log 2>&1 &" + retry_command "$command" > $playback_dir/client$k-$i.log & else echo "ERROR. $code_name is not found." fi @@ -145,11 +145,11 @@ elif [ "$TERMINAL" = "CLIENT" ]; then cp -r $python_main_dir $python_main_dir$i cp -f ./$code_name.py $python_main_dir$i/PyAPI/AI.py command="nice -0 python3 $python_main_dir$i/PyAPI/main.py -I $CONNECT_IP -P $PORT -t $k -p $i > $playback_dir/team$k-$code_name.log 2>&1 &" - retry_command "$command" > $playback_dir/client$k.log & + retry_command "$command" > $playback_dir/client$k-$i.log & elif [ -f "./$code_name" ]; then echo "find ./$code_name" command="nice -0 ./$code_name -I $CONNECT_IP -P $PORT -t $k -p $i > $playback_dir/team$k-$code_name.log 2>&1 &" - retry_command "$command" > $playback_dir/client$k.log & + retry_command "$command" > $playback_dir/client$k-$i.log & else echo "ERROR. $code_name is not found." fi From 41b0232b5fc31f357dfb5dd3c5238e3842d5d47f Mon Sep 17 00:00:00 2001 From: GuoWQ222 Date: Sat, 11 May 2024 00:19:14 +0800 Subject: [PATCH 118/179] fix --- logic/Server/GameServer.cs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/logic/Server/GameServer.cs b/logic/Server/GameServer.cs index 75fdbe65..6c396c78 100755 --- a/logic/Server/GameServer.cs +++ b/logic/Server/GameServer.cs @@ -178,11 +178,11 @@ protected static double[] LadderCalculate(double[] oriScores, double[] competiti (oriScores[0], oriScores[1]) = (oriScores[1], oriScores[0]); } - const double normalDeltaThereshold = 2000.0; // 天梯分数差参数,天梯分差超过此阈值太多则增长缓慢 + const double normalDeltaThereshold = 100.0; // 天梯分数差参数,天梯分差超过此阈值太多则增长缓慢 const double correctParam = normalDeltaThereshold * 1.2; // 修正参数 - const double winnerWeight = 9e-8; // 获胜者天梯得分权值 - const double loserWeight = 5e-8; // 落败者天梯得分权值 - const double scoreDeltaThereshold = 40000.0; // 比赛得分参数,比赛得分超过此阈值太多则增长缓慢 + const double winnerWeight = 4e-10; // 获胜者天梯得分权值 + const double loserWeight = 1.5e-10; // 落败者天梯得分权值 + const double scoreDeltaThereshold = 50000.0; // 比赛得分参数,比赛得分超过此阈值太多则增长缓慢 double[] resScore = [0, 0]; double oriDelta = oriScores[0] - oriScores[1]; // 天梯原分数差 @@ -192,14 +192,14 @@ protected static double[] LadderCalculate(double[] oriScores, double[] competiti double correct = 0.5 * (Math.Tanh((competitionDelta - scoreDeltaThereshold) / scoreDeltaThereshold - correctRate) + 1.0); // 分数修正 - resScore[0] = Math.Round(Math.Pow(competitionScores[0], 2) + resScore[0] = Math.Min(300, Math.Round(Math.Pow(competitionScores[0], 2) * winnerWeight * (1 - Math.Tanh(normalOriDelta)) - * correct); // 胜者所加天梯分 - resScore[1] = -Math.Round(Math.Pow(competitionDelta, 2) + * correct)); // 胜者所加天梯分) + resScore[1] = Math.Max(-120,-Math.Round(Math.Pow(competitionDelta, 2) * loserWeight * (1 - Math.Tanh(normalOriDelta)) - * correct); // 败者所扣天梯分 + * correct)); // 败者所扣天梯分 if (scoresReverse)// 顺序换回 (resScore[0], resScore[1]) = (resScore[1], resScore[0]); return resScore; From ec712b651caaccbac99b3e8cadc55c8f2b6fc87c Mon Sep 17 00:00:00 2001 From: GuoWQ222 Date: Sat, 11 May 2024 00:23:29 +0800 Subject: [PATCH 119/179] fix --- logic/Server/GameServer.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/logic/Server/GameServer.cs b/logic/Server/GameServer.cs index 6c396c78..a9bd1bf0 100755 --- a/logic/Server/GameServer.cs +++ b/logic/Server/GameServer.cs @@ -196,7 +196,7 @@ protected static double[] LadderCalculate(double[] oriScores, double[] competiti * winnerWeight * (1 - Math.Tanh(normalOriDelta)) * correct)); // 胜者所加天梯分) - resScore[1] = Math.Max(-120,-Math.Round(Math.Pow(competitionDelta, 2) + resScore[1] = Math.Max(-120, -Math.Round(Math.Pow(competitionDelta, 2) * loserWeight * (1 - Math.Tanh(normalOriDelta)) * correct)); // 败者所扣天梯分 From 6a488f41646af34b2c4ac822010c6c745b3d1dfd Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Fri, 10 May 2024 19:35:52 +0800 Subject: [PATCH 120/179] feat: :zap: Move proto cpp library update out of main process. --- installer/Data/MD5FileData.cs | 4 +-- installer/Model/Downloader.cs | 53 +++++++++++++++++++++++++++++----- installer/Model/Local_Data.cs | 4 +-- installer/Model/Tencent_Cos.cs | 53 ++++++++++++++++++++++++++++------ installer/installer.csproj | 9 ++++++ 5 files changed, 103 insertions(+), 20 deletions(-) diff --git a/installer/Data/MD5FileData.cs b/installer/Data/MD5FileData.cs index ef3ba870..65a63cda 100644 --- a/installer/Data/MD5FileData.cs +++ b/installer/Data/MD5FileData.cs @@ -26,13 +26,13 @@ public class TVersion { // 代码库版本 [JsonInclude] - public Version LibVersion = new Version(1, 0, 2, 2); + public Version LibVersion = new Version(1, 0, 2, 3); // 选手代码模板版本 [JsonInclude] public Version TemplateVersion = new Version(1, 0, 0, 3); // 本体版本 [JsonInclude] - public Version InstallerVersion = new Version(1, 0, 2, 0); + public Version InstallerVersion = new Version(1, 1, 0, 0); public static bool operator <(TVersion l, TVersion r) { return l.LibVersion < r.LibVersion || l.TemplateVersion < r.TemplateVersion || l.InstallerVersion < r.InstallerVersion; diff --git a/installer/Model/Downloader.cs b/installer/Model/Downloader.cs index 6b1981a6..e444d33e 100755 --- a/installer/Model/Downloader.cs +++ b/installer/Model/Downloader.cs @@ -190,28 +190,42 @@ public void Install(string? path = null) if (Log is FileLogger) ((FileLogger)Log).Path = Path.Combine(Data.Config.InstallPath, "Logs", "Installer.log"); Data.ResetInstallPath(Data.Config.InstallPath); - string zp = Path.Combine(Data.Config.InstallPath, "THUAI7.tar.gz"); Status = UpdateStatus.downloading; (CloudReport.ComCount, CloudReport.Count) = (0, 1); - Cloud.Log.LogInfo($"正在下载安装包……"); + Cloud.Log.LogInfo($"正在下载installer安装包……"); Cloud.DownloadFileAsync(zp, "THUAI7.tar.gz").Wait(); CloudReport.ComCount = 1; Status = UpdateStatus.unarchieving; - Cloud.Log.LogInfo($"安装包下载完毕,正在解压……"); + Cloud.Log.LogInfo($"installer安装包下载完毕,正在解压……"); Cloud.ArchieveUnzip(zp, Data.Config.InstallPath); - Cloud.Log.LogInfo($"解压完成"); + Cloud.Log.LogInfo($"installer解压完成"); File.Delete(zp); CurrentVersion = Data.FileHashData.TVersion; Cloud.Log.LogInfo("正在下载选手代码……"); Status = UpdateStatus.downloading; - CloudReport.Count = 3; + CloudReport.Count += 2; var tocpp = Cloud.DownloadFileAsync(Path.Combine(Data.Config.InstallPath, "CAPI", "cpp", "API", "src", "AI.cpp"), $"./Templates/t.{CurrentVersion.TemplateVersion}.cpp").ContinueWith(_ => CloudReport.ComCount++); var topy = Cloud.DownloadFileAsync(Path.Combine(Data.Config.InstallPath, "CAPI", "python", "PyAPI", "AI.py"), $"./Templates/t.{CurrentVersion.TemplateVersion}.py").ContinueWith(_ => CloudReport.ComCount++); Task.WaitAll(tocpp, topy); + + Cloud.Report.Count += 1; + zp = Path.Combine(Data.Config.InstallPath, "protoCpp.tar.gz"); + Cloud.Log.LogInfo("正在下载proto cpp库……"); + Cloud.DownloadFileAsync(zp, "Setup/proto/protoCpp.tar.gz").Wait(); + CloudReport.ComCount += 1; + Status = UpdateStatus.unarchieving; + Cloud.Log.LogInfo($"proto cpp库下载完毕,正在解压……"); + var protoCppLibPath = Path.Combine(Data.Config.InstallPath, "CAPI", "cpp", "lib"); + if (!Directory.Exists(protoCppLibPath)) + Directory.CreateDirectory(protoCppLibPath); + Cloud.ArchieveUnzip(zp, protoCppLibPath); + Cloud.Log.LogInfo($"proto cpp库解压完成"); + File.Delete(zp); + if (CloudReport.ComCount == CloudReport.Count) { Cloud.Log.LogInfo("选手代码下载成功!"); @@ -296,7 +310,7 @@ public bool CheckUpdate(bool writeMD5 = true) Status = UpdateStatus.success; if (Data.MD5Update.Count != 0 || CurrentVersion < Data.FileHashData.TVersion) { - Data.Log.LogInfo("需要更新,请点击更新按钮以更新。"); + Data.Log.LogInfo("代码库需要更新,请点击更新按钮以更新。"); if (writeMD5) { Data.SaveMD5Data(); @@ -312,6 +326,15 @@ public bool CheckUpdate(bool writeMD5 = true) } return true; } + else if (!Directory.Exists(Path.Combine(Data.Config.InstallPath, "CAPI", "cpp", "lib"))) + { + Data.Log.LogInfo("未检测到proto cpp库,请点击更新按钮以修复。"); + if (writeMD5) + { + Data.SaveMD5Data(); + } + return true; + } else { Data.Log.LogInfo("您的版本已经是最新版本!"); @@ -370,7 +393,23 @@ public int Update() return -1; } } - + // 如果缺少proto cpp库,应当立刻下载 + if (!Directory.Exists(Path.Combine(Data.Config.InstallPath, "CAPI", "cpp", "lib"))) + { + Cloud.Report.Count += 1; + string zp = Path.Combine(Data.Config.InstallPath, "protoCpp.tar.gz"); + Cloud.Log.LogInfo("正在下载proto cpp库……"); + Cloud.DownloadFileAsync(zp, "Setup/proto/protoCpp.tar.gz").Wait(); + CloudReport.ComCount += 1; + Status = UpdateStatus.unarchieving; + Cloud.Log.LogInfo($"proto cpp库下载完毕,正在解压……"); + var protoCppLibPath = Path.Combine(Data.Config.InstallPath, "CAPI", "cpp", "lib"); + if (!Directory.Exists(protoCppLibPath)) + Directory.CreateDirectory(protoCppLibPath); + Cloud.ArchieveUnzip(zp, protoCppLibPath); + Cloud.Log.LogInfo($"proto cpp库解压完成"); + File.Delete(zp); + } // 启动器本身需要更新,返回结果为16 if (CurrentVersion.InstallerVersion < Data.FileHashData.TVersion.InstallerVersion) { diff --git a/installer/Model/Local_Data.cs b/installer/Model/Local_Data.cs index 27cbed03..b89739f9 100755 --- a/installer/Model/Local_Data.cs +++ b/installer/Model/Local_Data.cs @@ -288,8 +288,8 @@ public void ScanDir(bool VersionRefresh = true) public static bool IsUserFile(string filename) { filename = filename.Replace(Path.DirectorySeparatorChar, '/'); - if (filename.Contains("/git/") || filename.Contains("bin/") || filename.Contains("/obj/") || filename.Contains("/x64/") - || filename.Contains("__pycache__")) + if (filename.Contains("/git/") || filename.Contains("/bin/") || filename.Contains("/obj/") || filename.Contains("/x64/") + || filename.Contains("__pycache__") || filename.Contains("/CAPI/cpp/lib/")) return true; if (filename.Contains("/vs/") || filename.Contains("/.vs/") || filename.Contains("/.vscode/")) return true; diff --git a/installer/Model/Tencent_Cos.cs b/installer/Model/Tencent_Cos.cs index 0bc0998f..f18b98e1 100755 --- a/installer/Model/Tencent_Cos.cs +++ b/installer/Model/Tencent_Cos.cs @@ -10,6 +10,8 @@ using System; using installer.Data; using System.Threading.Tasks; +using COSXML.Model.Bucket; +using COSXML.Model.Tag; // 禁用对没有调用异步API的异步函数的警告 #pragma warning disable CS1998 @@ -153,12 +155,14 @@ public int DownloadQueue(string basePath, IEnumerable queue) int thID = Log.StartNew(); Log.LogDebug(thID, "Batch download task started."); var array = queue.ToArray(); - Report.Count = array.Count(); - Report.ComCount = 0; - if (Report.Count == 0) - return 0; - var partitionar = Partitioner.Create(0, Report.Count, Report.Count / 4 > 0 ? Report.Count / 4 : Report.Count); - var c = 0; + var count = array.Length; + if (count == 0) + return 0; + var comCount = 0; + var comCountOld = Report.ComCount; + Report.Count += count; + + var partitionar = Partitioner.Create(0, count, count / 4 > 0 ? count / 4 : count); Parallel.ForEach(partitionar, (range, loopState) => { for (long i = range.Item1; i < range.Item2; i++) @@ -177,14 +181,14 @@ public int DownloadQueue(string basePath, IEnumerable queue) } finally { - Interlocked.Increment(ref c); - Report.ComCount = c; + Interlocked.Increment(ref comCount); + Report.ComCount = comCount + comCountOld; Log.LogInfo(thID, $"Child process: {subID} finished."); } } }); Log.LogInfo(thID, "Batch download task finished."); - Report.ComCount = Report.Count; + Report.ComCount = comCount + comCountOld; return thID; } @@ -300,6 +304,37 @@ public void DeleteFile(string remotePath) } } + public List EnumerateDir(string remotePath) + { + int thID = Log.StartNew(); + var result = new List(); + string bucket = $"{BucketName}-{Appid}"; + remotePath = remotePath.TrimStart('.').TrimStart('/'); + Log.LogInfo(thID, $"Enumerate files in {remotePath}"); + + bool truncated = false; + string marker = string.Empty; + do + { + GetBucketRequest request = new GetBucketRequest(bucket); + request.SetPrefix(remotePath); + request.SetDelimiter("/"); + if (!string.IsNullOrEmpty(marker)) + request.SetMarker(marker); + //执行请求 + GetBucketResult res = cosXml.GetBucket(request); + ListBucket info = res.listBucket; + result.AddRange(info.contentsList.Select(i => i.key).Where(i => i != remotePath)); + foreach (var dir in info.commonPrefixesList) + { + result.AddRange(EnumerateDir(dir.prefix)); + } + truncated = info.isTruncated; + marker = info.nextMarker; + } while ( truncated ); + + return result; + } #region 异步方法包装 public Task DownloadFileAsync(string savePath, string? remotePath = null) { diff --git a/installer/installer.csproj b/installer/installer.csproj index 0dcc3218..e82f1be8 100755 --- a/installer/installer.csproj +++ b/installer/installer.csproj @@ -85,6 +85,15 @@ + + + + + + + + + From 672ba267fed1b7aee4ca8e228517d613b606fd0c Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Fri, 10 May 2024 19:46:21 +0800 Subject: [PATCH 121/179] test: :art: Merge the test workflow(diabled). --- .github/workflows/debug.yml.disabled | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 .github/workflows/debug.yml.disabled diff --git a/.github/workflows/debug.yml.disabled b/.github/workflows/debug.yml.disabled new file mode 100644 index 00000000..4db1947b --- /dev/null +++ b/.github/workflows/debug.yml.disabled @@ -0,0 +1,13 @@ +name: CI +on: [push] +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Setup .NET Core + uses: actions/setup-dotnet@v4 + with: + dotnet-version: 8.0.x + - name: Setup tmate session + uses: mxschmitt/action-tmate@v3 \ No newline at end of file From 9f8311d9aa29d23ca13bb81fbd3fb17da8ecf5e8 Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Fri, 10 May 2024 21:20:41 +0800 Subject: [PATCH 122/179] feat: :lipstick: Add select file button to playback screen. --- installer/MauiProgram.cs | 2 +- installer/Page/PlaybackPage.xaml | 10 +++- .../Platforms/Android/AndroidManifest.xml | 6 +-- installer/Platforms/Android/MainActivity.cs | 5 ++ installer/Platforms/iOS/Info.plist | 25 +++++++++ installer/ViewModel/DebugViewModel.cs | 8 +++ installer/ViewModel/LaunchViewModel.cs | 2 + installer/ViewModel/PlaybackViewModel.cs | 54 ++++++++++++++++++- 8 files changed, 106 insertions(+), 6 deletions(-) diff --git a/installer/MauiProgram.cs b/installer/MauiProgram.cs index 3040057e..2bf8f9ef 100755 --- a/installer/MauiProgram.cs +++ b/installer/MauiProgram.cs @@ -67,7 +67,7 @@ public static MauiApp CreateMauiApp() var c = builder.Services.AddSingleton().First(); builder.Services.AddSingleton(FolderPicker.Default); - + builder.Services.AddSingleton(FilePicker.Default); AddViewModelService(builder); AddPageService(builder); diff --git a/installer/Page/PlaybackPage.xaml b/installer/Page/PlaybackPage.xaml index 9a7315e5..c143968f 100644 --- a/installer/Page/PlaybackPage.xaml +++ b/installer/Page/PlaybackPage.xaml @@ -25,10 +25,18 @@ VerticalOptions="Center" FontSize="{Binding ConstFontSize}"/> + + ///property name + public virtual void OnPropertyChanged([CallerMemberName] string propertyName = "") + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } + } + /// + ///BaseCommand + /// + public class BaseCommand : ICommand + { + private Func? _canExecute; + private Action _execute; + + public BaseCommand(Func? canExecute, Action execute) + { + _canExecute = canExecute; + _execute = execute; + } + + public BaseCommand(Action execute) : + this(null, execute) + { + } + + + public event EventHandler? CanExecuteChanged + { + add + { + if (_canExecute != null) + { + //CommandManager.RequerySuggested += value; + } + } + remove + { + if (_canExecute != null) + { + //CommandManager.RequerySuggested -= value; + } + } + } + + public bool CanExecute(object? parameter) + { + return _canExecute == null ? true : _canExecute(parameter); + } + + public void Execute(object? parameter) + { + if (_execute != null && CanExecute(parameter)) + { + _execute(parameter); + } + } + } + + public class RadioConverter + { + public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) + { + if (value == null || parameter == null) + { + return false; + } + string checkvalue = value.ToString() ?? ""; + string targetvalue = parameter.ToString() ?? ""; + bool r = checkvalue.Equals(targetvalue); + return r; + } + + public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) + { + if (value is null || parameter is null) + { + return null; + } + + if ((bool)value) + { + return parameter.ToString(); + } + return null; + } + } + + public abstract class BaseViewModel : NotificationObject + { + private const string constBackgroundColor = "White"; + public string ConstBackgroundColor { get => constBackgroundColor; } + + private const string constFontSize = "18"; + public string ConstFontSize { get => constFontSize; } + + private const string constTextColor = "Blue"; + public string ConstTextColor { get => constTextColor; } + } +} diff --git a/dependency/deploy/Data/FakeData.cs b/dependency/deploy/Data/FakeData.cs new file mode 100644 index 00000000..e9070a6f --- /dev/null +++ b/dependency/deploy/Data/FakeData.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace installer.Data +{ + public enum DevicePlatform + { + WinUI + } + public static class DeviceInfo + { + public static DevicePlatform Platform { get; set; } = DevicePlatform.WinUI; + } +} diff --git a/dependency/deploy/MauiProgram.cs b/dependency/deploy/MauiProgram.cs new file mode 100644 index 00000000..ba2399d2 --- /dev/null +++ b/dependency/deploy/MauiProgram.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace installer +{ + public static class MauiProgram + { + public static bool RefreshLogs_WhileDebug = false; + public static bool ErrorTrigger_WhileDebug = true; + public static string SecretID = "***"; + public static string SecretKey = "***"; + } +} diff --git a/dependency/deploy/Program.cs b/dependency/deploy/Program.cs new file mode 100644 index 00000000..1ef0f1a7 --- /dev/null +++ b/dependency/deploy/Program.cs @@ -0,0 +1,74 @@ +using installer.Data; +using installer.Model; +using installer.Services; +using System.Collections.Concurrent; +using System.Diagnostics; + +Logger Log = LoggerProvider.FromConsole(); + +// 全权读写 +Tencent_Cos Cloud = new Tencent_Cos("1319625962", "ap-beijing", "thuai7", Log); +Cloud.UpdateSecret(args[0], args[1]); + +Downloader d = new Downloader(); +d.Data.Config.InstallPath = @"D:\a\mirror\"; +d.Log.Partner.Add(Log); +// 每次更新需要更新默认值 +d.CurrentVersion = new TVersion(); +File.Create(Path.Combine("D:\\a\\publish", d.CurrentVersion.InstallerVersion.ToString())); + +if (d.CheckUpdate()) +{ + foreach (var r in d.Data.MD5Update) + { + Log.LogInfo($"{r.state}, {r.name}"); + } + + d.Data.SaveMD5Data(); + List l = new List(); + foreach (var r in d.Data.MD5Update) + { + var n = r.name.Replace('\\', '/'); + n = n.TrimStart('.').TrimStart('/'); + if (r.state == System.Data.DataRowState.Added || r.state == System.Data.DataRowState.Modified) + { + l.Add(Cloud.UploadFileAsync(Path.Combine(d.Data.Config.InstallPath, r.name), n)); + } + else if (r.state == System.Data.DataRowState.Deleted) + { + l.Add(Cloud.DeleteFileAsync(n)); + } + } + Task.WaitAll(l.ToArray()); +} +else +{ + Log.LogInfo("Nothing to update"); +} + +var found = (from i in d.Data.MD5Data + where i.Key.Contains("interface") + select i).ToList(); + +d.Data.SaveMD5Data(); +Cloud.UploadFile(Path.Combine(d.Data.Config.InstallPath, "hash.json"), "hash.json"); + +Cloud.UploadFile(Path.Combine(d.Data.Config.InstallPath, "CAPI", "cpp", "API", "src", "AI.cpp"), + $"Templates/t.{d.CurrentVersion.TemplateVersion}.cpp"); +Cloud.UploadFile(Path.Combine(d.Data.Config.InstallPath, "CAPI", "python", "PyAPI", "AI.py"), + $"Templates/t.{d.CurrentVersion.TemplateVersion}.py"); +Log.LogInfo("User code uploaded."); + +var list = (from i in d.Data.MD5Data + select i.Key.Replace(Path.DirectorySeparatorChar, '/').TrimStart('.').TrimStart('/')).ToArray(); +Log.LogInfo(list[0]); +using (FileStream s = new FileStream(Path.Combine(d.Data.Config.InstallPath, "compress.csv"), FileMode.Create, FileAccess.Write)) +using (StreamWriter w = new StreamWriter(s)) +{ + foreach (var item in list) + { + w.WriteLine("https://thuai7-1319625962.cos.ap-beijing.myqcloud.com/" + item); + } +} +Cloud.UploadFile(Path.Combine(d.Data.Config.InstallPath, "compress.csv"), "compress.csv"); +Log.LogInfo("Compress csv generated."); \ No newline at end of file diff --git a/dependency/deploy/Services/OtherService.cs b/dependency/deploy/Services/OtherService.cs new file mode 100644 index 00000000..94e080d5 --- /dev/null +++ b/dependency/deploy/Services/OtherService.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace installer.Services +{ + public static class Application + { + public static App? Current; + } + + public class App + { + public void Quit() + { + + } + } +} diff --git a/dependency/deploy/deploy.csproj b/dependency/deploy/deploy.csproj new file mode 100644 index 00000000..6dbb2996 --- /dev/null +++ b/dependency/deploy/deploy.csproj @@ -0,0 +1,31 @@ + + + + Exe + net8.0 + enable + enable + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/dependency/deploy/deploy.sln b/dependency/deploy/deploy.sln new file mode 100644 index 00000000..d40fc769 --- /dev/null +++ b/dependency/deploy/deploy.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.8.34309.116 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Deploy", "Deploy.csproj", "{1E0F079D-EECF-4DC8-A783-A86F25A2397E}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {1E0F079D-EECF-4DC8-A783-A86F25A2397E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1E0F079D-EECF-4DC8-A783-A86F25A2397E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1E0F079D-EECF-4DC8-A783-A86F25A2397E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1E0F079D-EECF-4DC8-A783-A86F25A2397E}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {7B9F1497-D14B-47E1-AEEF-A4254398185F} + EndGlobalSection +EndGlobal From bbbbf9fc6a16053fcff0e0502d9905defea715f3 Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Fri, 10 May 2024 22:42:23 +0800 Subject: [PATCH 125/179] fix: :green_heart: Fix name error of deploy.yml. --- .github/workflows/deploy.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 3427acc1..bee3df6c 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -1,4 +1,4 @@ -name: build +name: deploy on: push: branches: [dev, main, master] From 74f58dff8640876f2962f993b7e010408d0a8218 Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Fri, 10 May 2024 22:48:58 +0800 Subject: [PATCH 126/179] fix: :bug: Change cmd-like /S to powershell-like -S --- .github/workflows/deploy.yml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index bee3df6c..54ddd4a0 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -28,11 +28,11 @@ jobs: run: copy D:\a\THUAI7 D:\a\mirror - name: Remove directories not needed run: | - rmdir /S /Q D:\a\mirror\.git - rmdir /S /Q D:\a\mirror\.github - rmdir /S /Q D:\a\mirror\installer - rmdir /S /Q D:\a\mirror\interface - rmdir /S /Q D:\a\mirror\logic + rmdir -S -Q D:\a\mirror\.git + rmdir -S -Q D:\a\mirror\.github + rmdir -S -Q D:\a\mirror\installer + rmdir -S -Q D:\a\mirror\interface + rmdir -S -Q D:\a\mirror\logic - name: Build Server run: | mkdir D:\a\mirror\logic @@ -45,7 +45,7 @@ jobs: run: | cd D:\a\publish for /f "delims=" %i in ('dir /b /a-d') do set version=%i - del /S /F /Q %version% + del -S -F -Q %version% cd D:\a\THUAI7 dotnet publish "./installer/installer.csproj" -o "D:\a\installer" -f net8.0-windows10.0.19041.0 -c Release -p:RuntimeIdentifierOverride=win10-x64 -p:WindowsPackageType=None -p:WindowsAppSDKSelfContained=true ./dependency/7z/7za.exe a -r D:\a\publish\Installer_v%version%.zip D:\a\installer\* From 57a017b7919ab5b90d17a298ce65e856532419de Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Fri, 10 May 2024 23:02:15 +0800 Subject: [PATCH 127/179] fix: :construction: Change copy to xcopy --- .github/workflows/deploy.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 54ddd4a0..fa995521 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -25,7 +25,7 @@ jobs: mkdir D:\a\installer mkdir D:\a\publish - name: Copy THUAI7 - run: copy D:\a\THUAI7 D:\a\mirror + run: xcopy -S -E -Y D:\a\THUAI7 D:\a\mirror - name: Remove directories not needed run: | rmdir -S -Q D:\a\mirror\.git From a5b051234e3092efc473d7784b47501cef187e64 Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Fri, 10 May 2024 23:06:27 +0800 Subject: [PATCH 128/179] fix: :bug: Fix the usage of xcopy --- .github/workflows/deploy.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index fa995521..d7a30d0a 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -25,7 +25,7 @@ jobs: mkdir D:\a\installer mkdir D:\a\publish - name: Copy THUAI7 - run: xcopy -S -E -Y D:\a\THUAI7 D:\a\mirror + run: xcopy /S /E /Y D:\a\THUAI7 D:\a\mirror - name: Remove directories not needed run: | rmdir -S -Q D:\a\mirror\.git From 0cd0d4bb9122cb1116557e75a37455ebdf24bd36 Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Fri, 10 May 2024 23:11:48 +0800 Subject: [PATCH 129/179] fix: :bug: Remove command dealing with non-existing .git folder --- .github/workflows/deploy.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index d7a30d0a..c48d28d6 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -28,7 +28,6 @@ jobs: run: xcopy /S /E /Y D:\a\THUAI7 D:\a\mirror - name: Remove directories not needed run: | - rmdir -S -Q D:\a\mirror\.git rmdir -S -Q D:\a\mirror\.github rmdir -S -Q D:\a\mirror\installer rmdir -S -Q D:\a\mirror\interface From 87b2dd835b3ffd55f7af70c0b5ca42889f4b5ae5 Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Fri, 10 May 2024 23:16:15 +0800 Subject: [PATCH 130/179] fix: :bug: Change D:\a\THUAI7 to D:\a\THUAI7\THUAI7 --- .github/workflows/deploy.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index c48d28d6..70d597ad 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -25,7 +25,7 @@ jobs: mkdir D:\a\installer mkdir D:\a\publish - name: Copy THUAI7 - run: xcopy /S /E /Y D:\a\THUAI7 D:\a\mirror + run: xcopy /S /E /Y D:\a\THUAI7\THUAI7 D:\a\mirror - name: Remove directories not needed run: | rmdir -S -Q D:\a\mirror\.github @@ -45,11 +45,11 @@ jobs: cd D:\a\publish for /f "delims=" %i in ('dir /b /a-d') do set version=%i del -S -F -Q %version% - cd D:\a\THUAI7 + cd D:\a\THUAI7\THUAI7 dotnet publish "./installer/installer.csproj" -o "D:\a\installer" -f net8.0-windows10.0.19041.0 -c Release -p:RuntimeIdentifierOverride=win10-x64 -p:WindowsPackageType=None -p:WindowsAppSDKSelfContained=true ./dependency/7z/7za.exe a -r D:\a\publish\Installer_v%version%.zip D:\a\installer\* - name: Upload installer package uses: actions/upload-artifact@v4 with: name: Installer_v%version%.zip - path: /home/runner/work/THUAI7/hash.json \ No newline at end of file + path: D:\a\publish\Installer_v%version%.zip \ No newline at end of file From 5754370d0253dba36de08b4ebf6b4860dc2027c3 Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Fri, 10 May 2024 23:23:49 +0800 Subject: [PATCH 131/179] chore: :construction: Add test --- .github/workflows/deploy.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 70d597ad..67ed7bbe 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -26,6 +26,8 @@ jobs: mkdir D:\a\publish - name: Copy THUAI7 run: xcopy /S /E /Y D:\a\THUAI7\THUAI7 D:\a\mirror + - name: Test + run: tree D:\a\mirror - name: Remove directories not needed run: | rmdir -S -Q D:\a\mirror\.github From 40d42b230049f0631c707dc6eb5d109b126718c1 Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Fri, 10 May 2024 23:37:24 +0800 Subject: [PATCH 132/179] style: :construction: Change to powershell command. --- .github/workflows/deploy.yml | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 67ed7bbe..62742475 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -25,15 +25,15 @@ jobs: mkdir D:\a\installer mkdir D:\a\publish - name: Copy THUAI7 - run: xcopy /S /E /Y D:\a\THUAI7\THUAI7 D:\a\mirror + run: Copy-Item -recurse D:\a\THUAI7\THUAI7 D:\a\mirror - name: Test run: tree D:\a\mirror - name: Remove directories not needed run: | - rmdir -S -Q D:\a\mirror\.github - rmdir -S -Q D:\a\mirror\installer - rmdir -S -Q D:\a\mirror\interface - rmdir -S -Q D:\a\mirror\logic + Remove-Item -recurse D:\a\mirror\.github + Remove-Item -recurse D:\a\mirror\installer + Remove-Item -recurse D:\a\mirror\interface + Remove-Item -recurse D:\a\mirror\logic - name: Build Server run: | mkdir D:\a\mirror\logic @@ -44,10 +44,7 @@ jobs: run: dotnet run "./dependency/deploy/deploy.csproj" "***" "***" - name: Get installer package(No Key contained for safety) run: | - cd D:\a\publish - for /f "delims=" %i in ('dir /b /a-d') do set version=%i - del -S -F -Q %version% - cd D:\a\THUAI7\THUAI7 + $version=Get-ChildItem -Path D:\a\publish | ForEach-Object { $_.name } dotnet publish "./installer/installer.csproj" -o "D:\a\installer" -f net8.0-windows10.0.19041.0 -c Release -p:RuntimeIdentifierOverride=win10-x64 -p:WindowsPackageType=None -p:WindowsAppSDKSelfContained=true ./dependency/7z/7za.exe a -r D:\a\publish\Installer_v%version%.zip D:\a\installer\* - name: Upload installer package From 811301f6f62ae1dc3baa90e3af4066e264cf9ce7 Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Fri, 10 May 2024 23:43:02 +0800 Subject: [PATCH 133/179] fix: :bug: Fix a bug or create a bug? --- .github/workflows/deploy.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 62742475..bae70dfe 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -25,7 +25,7 @@ jobs: mkdir D:\a\installer mkdir D:\a\publish - name: Copy THUAI7 - run: Copy-Item -recurse D:\a\THUAI7\THUAI7 D:\a\mirror + run: Copy-Item -recurse D:\a\THUAI7 D:\a\mirror - name: Test run: tree D:\a\mirror - name: Remove directories not needed From 14df00d6134f3c670b03ea1bbfb81700d1ba2d1e Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Fri, 10 May 2024 23:46:32 +0800 Subject: [PATCH 134/179] chore: Just a test --- .github/workflows/deploy.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index bae70dfe..4d4348e9 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -27,7 +27,7 @@ jobs: - name: Copy THUAI7 run: Copy-Item -recurse D:\a\THUAI7 D:\a\mirror - name: Test - run: tree D:\a\mirror + run: tree D:\a\THUAI7 - name: Remove directories not needed run: | Remove-Item -recurse D:\a\mirror\.github From 40d20a866f6609bd52d3767b291dc26a3f093141 Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Fri, 10 May 2024 23:52:41 +0800 Subject: [PATCH 135/179] Just testing... --- .github/workflows/deploy.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 4d4348e9..62742475 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -25,9 +25,9 @@ jobs: mkdir D:\a\installer mkdir D:\a\publish - name: Copy THUAI7 - run: Copy-Item -recurse D:\a\THUAI7 D:\a\mirror + run: Copy-Item -recurse D:\a\THUAI7\THUAI7 D:\a\mirror - name: Test - run: tree D:\a\THUAI7 + run: tree D:\a\mirror - name: Remove directories not needed run: | Remove-Item -recurse D:\a\mirror\.github From 38c46ecdd12a8b9fbb8f9972f766d990b87a75e8 Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Fri, 10 May 2024 23:56:28 +0800 Subject: [PATCH 136/179] Just testing... --- .github/workflows/deploy.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 62742475..824ddd0c 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -25,7 +25,7 @@ jobs: mkdir D:\a\installer mkdir D:\a\publish - name: Copy THUAI7 - run: Copy-Item -recurse D:\a\THUAI7\THUAI7 D:\a\mirror + run: Copy-Item -recurse D:\a\THUAI7\THUAI7\ D:\a\mirror\ - name: Test run: tree D:\a\mirror - name: Remove directories not needed From 398a7c26a10743932f23910c5ce461ffff3d7622 Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Sat, 11 May 2024 00:00:33 +0800 Subject: [PATCH 137/179] Just testing... --- .github/workflows/deploy.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 824ddd0c..404913fb 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -25,7 +25,7 @@ jobs: mkdir D:\a\installer mkdir D:\a\publish - name: Copy THUAI7 - run: Copy-Item -recurse D:\a\THUAI7\THUAI7\ D:\a\mirror\ + run: Copy-Item -recurse D:\a\THUAI7\THUAI7\THUAI7\ D:\a\mirror\ - name: Test run: tree D:\a\mirror - name: Remove directories not needed From 2166d47b8ebed1ae0c5377d56655b95468b259d8 Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Sat, 11 May 2024 00:04:47 +0800 Subject: [PATCH 138/179] fix: :bug: Copy to a non-existing folder to prevent repeated top folder name. --- .github/workflows/deploy.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 404913fb..84d56bab 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -21,11 +21,10 @@ jobs: run: dotnet workload install maui-windows - name: Create Folders need run: | - mkdir D:\a\mirror mkdir D:\a\installer mkdir D:\a\publish - name: Copy THUAI7 - run: Copy-Item -recurse D:\a\THUAI7\THUAI7\THUAI7\ D:\a\mirror\ + run: Copy-Item -recurse D:\a\THUAI7\THUAI7\ D:\a\mirror\ - name: Test run: tree D:\a\mirror - name: Remove directories not needed From 90a4896e134bc3be58787994130f9d372bebb40b Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Sat, 11 May 2024 00:18:23 +0800 Subject: [PATCH 139/179] Just testing... --- .github/workflows/deploy.yml | 2 +- dependency/deploy/Program.cs | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 84d56bab..82447384 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -40,7 +40,7 @@ jobs: - name: Build Client run: dotnet publish "./logic/Client/Client.csproj" -o "D:\a\mirror\logic\Client" -f net8.0-windows10.0.19041.0 -c Release -p:RuntimeIdentifierOverride=win10-x64 -p:WindowsPackageType=None -p:WindowsAppSDKSelfContained=true - name: Deploy to bucket - run: dotnet run "./dependency/deploy/deploy.csproj" "***" "***" + run: dotnet run --project "./dependency/deploy/deploy.csproj" ${{ secrets.INSTALLER_COS_SECRET_ID }} ${{ secrets.INSTALLER_COS_SECRET_KEY }} - name: Get installer package(No Key contained for safety) run: | $version=Get-ChildItem -Path D:\a\publish | ForEach-Object { $_.name } diff --git a/dependency/deploy/Program.cs b/dependency/deploy/Program.cs index 1ef0f1a7..3a722a82 100644 --- a/dependency/deploy/Program.cs +++ b/dependency/deploy/Program.cs @@ -11,6 +11,7 @@ Cloud.UpdateSecret(args[0], args[1]); Downloader d = new Downloader(); +d.Cloud.UpdateSecret(args[0], args[1]); d.Data.Config.InstallPath = @"D:\a\mirror\"; d.Log.Partner.Add(Log); // 每次更新需要更新默认值 @@ -23,6 +24,7 @@ { Log.LogInfo($"{r.state}, {r.name}"); } + return; d.Data.SaveMD5Data(); List l = new List(); From 4649fe91e2efc34452f918139b8a782035139517 Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Sat, 11 May 2024 00:30:59 +0800 Subject: [PATCH 140/179] fix: :bug: Fix the bug when install path ends with path seperator char. --- dependency/deploy/Program.cs | 4 ---- installer/Services/FileService.cs | 1 + 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/dependency/deploy/Program.cs b/dependency/deploy/Program.cs index 3a722a82..3ae81069 100644 --- a/dependency/deploy/Program.cs +++ b/dependency/deploy/Program.cs @@ -48,10 +48,6 @@ Log.LogInfo("Nothing to update"); } -var found = (from i in d.Data.MD5Data - where i.Key.Contains("interface") - select i).ToList(); - d.Data.SaveMD5Data(); Cloud.UploadFile(Path.Combine(d.Data.Config.InstallPath, "hash.json"), "hash.json"); diff --git a/installer/Services/FileService.cs b/installer/Services/FileService.cs index 4d8f16ea..580769c7 100644 --- a/installer/Services/FileService.cs +++ b/installer/Services/FileService.cs @@ -44,6 +44,7 @@ public static string GetFileMd5Hash(string strFileFullPath) public static string ConvertAbsToRel(string basePath, string fullPath) { + basePath = basePath.TrimEnd(Path.DirectorySeparatorChar); if (fullPath.StartsWith(basePath)) { fullPath = fullPath.Replace(basePath, "."); From fe8011a33df176f1f28aebb2832593e8cdcc84e9 Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Sat, 11 May 2024 00:51:14 +0800 Subject: [PATCH 141/179] ci: :sparkles: Auto deploy to cos bucket. --- .github/workflows/deploy.yml | 11 ++++++++--- dependency/deploy/Program.cs | 1 - installer/Model/Tencent_Cos.cs | 4 ++-- installer/Platforms/Android/MainActivity.cs | 4 ++-- 4 files changed, 12 insertions(+), 8 deletions(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 82447384..aa9b78cf 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -4,6 +4,10 @@ on: branches: [dev, main, master] pull_request: branches: [dev, main, master] + +env: + version: 1.0.0.0 + jobs: deploy-to-tencent-cos: runs-on: windows-latest @@ -29,6 +33,7 @@ jobs: run: tree D:\a\mirror - name: Remove directories not needed run: | + Remove-Item -recurse D:\a\mirror\.git Remove-Item -recurse D:\a\mirror\.github Remove-Item -recurse D:\a\mirror\installer Remove-Item -recurse D:\a\mirror\interface @@ -45,9 +50,9 @@ jobs: run: | $version=Get-ChildItem -Path D:\a\publish | ForEach-Object { $_.name } dotnet publish "./installer/installer.csproj" -o "D:\a\installer" -f net8.0-windows10.0.19041.0 -c Release -p:RuntimeIdentifierOverride=win10-x64 -p:WindowsPackageType=None -p:WindowsAppSDKSelfContained=true - ./dependency/7z/7za.exe a -r D:\a\publish\Installer_v%version%.zip D:\a\installer\* + ./dependency/7z/7za.exe a -r D:\a\publish\Installer_v${version}.zip D:\a\installer\* - name: Upload installer package uses: actions/upload-artifact@v4 with: - name: Installer_v%version%.zip - path: D:\a\publish\Installer_v%version%.zip \ No newline at end of file + name: Installer_v${{ env.version }}.zip + path: D:\a\publish\Installer_v${{ env.version }}.zip \ No newline at end of file diff --git a/dependency/deploy/Program.cs b/dependency/deploy/Program.cs index 3ae81069..05fccc45 100644 --- a/dependency/deploy/Program.cs +++ b/dependency/deploy/Program.cs @@ -24,7 +24,6 @@ { Log.LogInfo($"{r.state}, {r.name}"); } - return; d.Data.SaveMD5Data(); List l = new List(); diff --git a/installer/Model/Tencent_Cos.cs b/installer/Model/Tencent_Cos.cs index f18b98e1..b717b704 100755 --- a/installer/Model/Tencent_Cos.cs +++ b/installer/Model/Tencent_Cos.cs @@ -157,7 +157,7 @@ public int DownloadQueue(string basePath, IEnumerable queue) var array = queue.ToArray(); var count = array.Length; if (count == 0) - return 0; + return 0; var comCount = 0; var comCountOld = Report.ComCount; Report.Count += count; @@ -331,7 +331,7 @@ public List EnumerateDir(string remotePath) } truncated = info.isTruncated; marker = info.nextMarker; - } while ( truncated ); + } while (truncated); return result; } diff --git a/installer/Platforms/Android/MainActivity.cs b/installer/Platforms/Android/MainActivity.cs index 23b6221b..5160ce42 100755 --- a/installer/Platforms/Android/MainActivity.cs +++ b/installer/Platforms/Android/MainActivity.cs @@ -6,8 +6,8 @@ namespace installer { [Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)] - [IntentFilter(new[] { Intent.ActionView }, - Categories = new[] { Intent.CategoryDefault }, + [IntentFilter(new[] { Intent.ActionView }, + Categories = new[] { Intent.CategoryDefault }, DataMimeType = @"application/com.thueesast.thuaiplayback", DataPathSuffix = "thuaipb")] public class MainActivity : MauiAppCompatActivity From 905cac6fd5f16f80e09e72f2a83f1cfc211228b1 Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Sat, 11 May 2024 00:58:11 +0800 Subject: [PATCH 142/179] fix: :zap: Forcely delete .git directory. --- .github/workflows/deploy.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index aa9b78cf..49d6d00b 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -33,7 +33,7 @@ jobs: run: tree D:\a\mirror - name: Remove directories not needed run: | - Remove-Item -recurse D:\a\mirror\.git + Remove-Item -recurse -force D:\a\mirror\.git Remove-Item -recurse D:\a\mirror\.github Remove-Item -recurse D:\a\mirror\installer Remove-Item -recurse D:\a\mirror\interface From a11c10010dc112471f3188b16572023b0df08bf3 Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Sat, 11 May 2024 01:06:57 +0800 Subject: [PATCH 143/179] feat: :zap: Try to send out the version id. --- .github/workflows/deploy.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 49d6d00b..5e3cf9f4 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -49,6 +49,7 @@ jobs: - name: Get installer package(No Key contained for safety) run: | $version=Get-ChildItem -Path D:\a\publish | ForEach-Object { $_.name } + $env:version=$version dotnet publish "./installer/installer.csproj" -o "D:\a\installer" -f net8.0-windows10.0.19041.0 -c Release -p:RuntimeIdentifierOverride=win10-x64 -p:WindowsPackageType=None -p:WindowsAppSDKSelfContained=true ./dependency/7z/7za.exe a -r D:\a\publish\Installer_v${version}.zip D:\a\installer\* - name: Upload installer package From 6ea84e55cdc1d8cb2d02db67275a38cf12d7b530 Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Sat, 11 May 2024 01:19:54 +0800 Subject: [PATCH 144/179] feat: :zap: Another try. --- .github/workflows/deploy.yml | 2 +- dependency/deploy/Program.cs | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 5e3cf9f4..67b3f561 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -49,7 +49,7 @@ jobs: - name: Get installer package(No Key contained for safety) run: | $version=Get-ChildItem -Path D:\a\publish | ForEach-Object { $_.name } - $env:version=$version + [Environment]::SetEnvironmentVariable("version", $version, "User") dotnet publish "./installer/installer.csproj" -o "D:\a\installer" -f net8.0-windows10.0.19041.0 -c Release -p:RuntimeIdentifierOverride=win10-x64 -p:WindowsPackageType=None -p:WindowsAppSDKSelfContained=true ./dependency/7z/7za.exe a -r D:\a\publish\Installer_v${version}.zip D:\a\installer\* - name: Upload installer package diff --git a/dependency/deploy/Program.cs b/dependency/deploy/Program.cs index 05fccc45..a447df36 100644 --- a/dependency/deploy/Program.cs +++ b/dependency/deploy/Program.cs @@ -13,6 +13,7 @@ Downloader d = new Downloader(); d.Cloud.UpdateSecret(args[0], args[1]); d.Data.Config.InstallPath = @"D:\a\mirror\"; +d.Data.Config.MD5DataPath = Path.Combine(Config.InstallPath, "hash.json"); d.Log.Partner.Add(Log); // 每次更新需要更新默认值 d.CurrentVersion = new TVersion(); @@ -48,7 +49,7 @@ } d.Data.SaveMD5Data(); -Cloud.UploadFile(Path.Combine(d.Data.Config.InstallPath, "hash.json"), "hash.json"); +Cloud.UploadFile(d.Data.Config.MD5DataPath, "hash.json"); Cloud.UploadFile(Path.Combine(d.Data.Config.InstallPath, "CAPI", "cpp", "API", "src", "AI.cpp"), $"Templates/t.{d.CurrentVersion.TemplateVersion}.cpp"); From 62febf8ed10012f1d37a55d8624fd06daa5fcdbe Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Sat, 11 May 2024 01:26:18 +0800 Subject: [PATCH 145/179] fix: :bug: Spell the filename correctly. --- dependency/deploy/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dependency/deploy/Program.cs b/dependency/deploy/Program.cs index a447df36..02582cff 100644 --- a/dependency/deploy/Program.cs +++ b/dependency/deploy/Program.cs @@ -13,7 +13,7 @@ Downloader d = new Downloader(); d.Cloud.UpdateSecret(args[0], args[1]); d.Data.Config.InstallPath = @"D:\a\mirror\"; -d.Data.Config.MD5DataPath = Path.Combine(Config.InstallPath, "hash.json"); +d.Data.Config.MD5DataPath = @"D:\a\mirror\hash.json"; d.Log.Partner.Add(Log); // 每次更新需要更新默认值 d.CurrentVersion = new TVersion(); From d68e8251301c9a50817c3fff462d1f3f2f04285f Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Sat, 11 May 2024 01:37:32 +0800 Subject: [PATCH 146/179] fix: :bug: Try to fix an unexpected bug. --- .github/workflows/deploy.yml | 2 +- dependency/deploy/Program.cs | 1 + installer/Model/Local_Data.cs | 1 + 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 67b3f561..6fc80948 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -49,7 +49,7 @@ jobs: - name: Get installer package(No Key contained for safety) run: | $version=Get-ChildItem -Path D:\a\publish | ForEach-Object { $_.name } - [Environment]::SetEnvironmentVariable("version", $version, "User") + [Environment]::SetEnvironmentVariable("version", $version, "Machine") dotnet publish "./installer/installer.csproj" -o "D:\a\installer" -f net8.0-windows10.0.19041.0 -c Release -p:RuntimeIdentifierOverride=win10-x64 -p:WindowsPackageType=None -p:WindowsAppSDKSelfContained=true ./dependency/7z/7za.exe a -r D:\a\publish\Installer_v${version}.zip D:\a\installer\* - name: Upload installer package diff --git a/dependency/deploy/Program.cs b/dependency/deploy/Program.cs index 02582cff..481c1c9b 100644 --- a/dependency/deploy/Program.cs +++ b/dependency/deploy/Program.cs @@ -48,6 +48,7 @@ Log.LogInfo("Nothing to update"); } +d.Data.Config.MD5DataPath = @"D:\a\mirror\hash.json"; d.Data.SaveMD5Data(); Cloud.UploadFile(d.Data.Config.MD5DataPath, "hash.json"); diff --git a/installer/Model/Local_Data.cs b/installer/Model/Local_Data.cs index b89739f9..d3d28a4c 100755 --- a/installer/Model/Local_Data.cs +++ b/installer/Model/Local_Data.cs @@ -216,6 +216,7 @@ public void SaveMD5Data(bool VersionRefresh = true) })); sw.Flush(); } + Log.LogInfo("MD5Data saved."); } catch (Exception e) { From 4b385782e97803d9274c098b7dd699b7d1fc658e Mon Sep 17 00:00:00 2001 From: DreamEnderKing Date: Sat, 11 May 2024 01:45:31 +0800 Subject: [PATCH 147/179] fix: :bug: Fix an unexpected bug. --- dependency/deploy/Program.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/dependency/deploy/Program.cs b/dependency/deploy/Program.cs index 481c1c9b..16659d6f 100644 --- a/dependency/deploy/Program.cs +++ b/dependency/deploy/Program.cs @@ -13,7 +13,7 @@ Downloader d = new Downloader(); d.Cloud.UpdateSecret(args[0], args[1]); d.Data.Config.InstallPath = @"D:\a\mirror\"; -d.Data.Config.MD5DataPath = @"D:\a\mirror\hash.json"; +d.Data.MD5DataPath = @"D:\a\mirror\hash.json"; d.Log.Partner.Add(Log); // 每次更新需要更新默认值 d.CurrentVersion = new TVersion(); @@ -48,7 +48,6 @@ Log.LogInfo("Nothing to update"); } -d.Data.Config.MD5DataPath = @"D:\a\mirror\hash.json"; d.Data.SaveMD5Data(); Cloud.UploadFile(d.Data.Config.MD5DataPath, "hash.json"); From 2b4a3089b15c6c3e317576171aa773aeaa0c090d Mon Sep 17 00:00:00 2001 From: DreamEnderKing <58102615+DreamEnderKing@users.noreply.github.com> Date: Sat, 11 May 2024 01:54:17 +0800 Subject: [PATCH 148/179] =?UTF-8?q?fix:=20=F0=9F=90=9B=20Fix=20an=20unexpe?= =?UTF-8?q?cted=20bug.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- installer/Model/Local_Data.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/installer/Model/Local_Data.cs b/installer/Model/Local_Data.cs index d3d28a4c..c2cb39ae 100755 --- a/installer/Model/Local_Data.cs +++ b/installer/Model/Local_Data.cs @@ -216,7 +216,7 @@ public void SaveMD5Data(bool VersionRefresh = true) })); sw.Flush(); } - Log.LogInfo("MD5Data saved."); + // Log.LogInfo("MD5Data saved."); } catch (Exception e) { From 40859fbd739703337b31e1e567662a1a85f2d06b Mon Sep 17 00:00:00 2001 From: DreamEnderKing <58102615+DreamEnderKing@users.noreply.github.com> Date: Sat, 11 May 2024 02:05:43 +0800 Subject: [PATCH 149/179] =?UTF-8?q?fix:=20=F0=9F=90=9B=20Fix=20an=20unexpe?= =?UTF-8?q?cted=20bug.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dependency/deploy/Program.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/dependency/deploy/Program.cs b/dependency/deploy/Program.cs index 16659d6f..7531360e 100644 --- a/dependency/deploy/Program.cs +++ b/dependency/deploy/Program.cs @@ -13,7 +13,7 @@ Downloader d = new Downloader(); d.Cloud.UpdateSecret(args[0], args[1]); d.Data.Config.InstallPath = @"D:\a\mirror\"; -d.Data.MD5DataPath = @"D:\a\mirror\hash.json"; + d.Log.Partner.Add(Log); // 每次更新需要更新默认值 d.CurrentVersion = new TVersion(); @@ -49,7 +49,7 @@ } d.Data.SaveMD5Data(); -Cloud.UploadFile(d.Data.Config.MD5DataPath, "hash.json"); +Cloud.UploadFile(d.Data.MD5DataPath, "hash.json"); Cloud.UploadFile(Path.Combine(d.Data.Config.InstallPath, "CAPI", "cpp", "API", "src", "AI.cpp"), $"Templates/t.{d.CurrentVersion.TemplateVersion}.cpp"); @@ -69,4 +69,4 @@ } } Cloud.UploadFile(Path.Combine(d.Data.Config.InstallPath, "compress.csv"), "compress.csv"); -Log.LogInfo("Compress csv generated."); \ No newline at end of file +Log.LogInfo("Compress csv generated."); From b90b40890e44a029a69c7fad1a71a4186e238f27 Mon Sep 17 00:00:00 2001 From: DreamEnderKing <58102615+DreamEnderKing@users.noreply.github.com> Date: Sat, 11 May 2024 02:13:50 +0800 Subject: [PATCH 150/179] =?UTF-8?q?ci:=20=E2=9C=A8=20Auto=20deploy=20to=20?= =?UTF-8?q?cos=20bucket.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/deploy.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 6fc80948..7c978b31 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -6,7 +6,7 @@ on: branches: [dev, main, master] env: - version: 1.0.0.0 + version: 1.1.0.0 jobs: deploy-to-tencent-cos: @@ -56,4 +56,4 @@ jobs: uses: actions/upload-artifact@v4 with: name: Installer_v${{ env.version }}.zip - path: D:\a\publish\Installer_v${{ env.version }}.zip \ No newline at end of file + path: D:\a\publish\Installer_v${{ env.version }}.zip From b22a44ac223c4a1837e99306cb8ebf86add289e9 Mon Sep 17 00:00:00 2001 From: Grange <2634070476@qq.com> Date: Sat, 11 May 2024 20:32:31 +0800 Subject: [PATCH 151/179] =?UTF-8?q?feat:=20=E2=9C=A8=20differ=20color=20of?= =?UTF-8?q?=20factory,=20community=20and=20fort?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- logic/Client/ViewModel/MapViewModel.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/logic/Client/ViewModel/MapViewModel.cs b/logic/Client/ViewModel/MapViewModel.cs index 605bd23a..d79b6f70 100644 --- a/logic/Client/ViewModel/MapViewModel.cs +++ b/logic/Client/ViewModel/MapViewModel.cs @@ -212,8 +212,8 @@ private void GetMap(MessageOfMap obj) {MapPatchType.Asteroid, Color.FromRgb(164, 217, 235)}, {MapPatchType.Resource, Color.FromRgb(160, 75, 166)}, {MapPatchType.Factory, Color.FromRgb(231, 144, 74)}, - {MapPatchType.Community, Color.FromRgb(231, 144, 74)}, - {MapPatchType.Fort, Color.FromRgb(231, 144, 74)}, + {MapPatchType.Community, Color.FromRgb(131, 144, 74)}, + {MapPatchType.Fort, Color.FromRgb(131, 34, 74)}, {MapPatchType.WormHole, Color.FromRgb(137, 17, 26)}, {MapPatchType.Space, Color.FromRgb(255, 255, 255)}, {MapPatchType.Null, Color.FromRgb(0,0,0)} From dd2011ef6ab280ba595371b6c789f49c3458608c Mon Sep 17 00:00:00 2001 From: Xuc Pan Date: Sat, 11 May 2024 20:35:27 +0800 Subject: [PATCH 152/179] fix: :bug: rebuild ship --- logic/Gaming/Game.cs | 2 +- logic/Gaming/ShipManager.cs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/logic/Gaming/Game.cs b/logic/Gaming/Game.cs index 1b44ebc7..8d1c577c 100755 --- a/logic/Gaming/Game.cs +++ b/logic/Gaming/Game.cs @@ -95,7 +95,7 @@ public long ActivateShip(long teamID, ShipType shipType, int birthPointIndex = 0 birthPointIndex = teamList[(int)teamID].BirthPointList.Count - 1; XY pos = teamList[(int)teamID].BirthPointList[birthPointIndex]; pos += new XY(((random.Next() & 2) - 1) * 1000, ((random.Next() & 2) - 1) * 1000); - if (ShipManager.ActivateShip(ship, pos)) + if (shipManager.ActivateShip(ship, pos)) { GameLogging.logger.ConsoleLogDebug($"Successfully activated {teamID} {shipType} at {pos}"); return ship.PlayerID; diff --git a/logic/Gaming/ShipManager.cs b/logic/Gaming/ShipManager.cs index 7c15eac2..e978aa86 100755 --- a/logic/Gaming/ShipManager.cs +++ b/logic/Gaming/ShipManager.cs @@ -17,7 +17,6 @@ private class ShipManager(Game game, Map gameMap) public Ship? AddShip(long teamID, long playerID, ShipType shipType, MoneyPool moneyPool) { Ship newShip = new(GameData.ShipRadius, shipType, moneyPool); - gameMap.Add(newShip); newShip.TeamID.SetROri(teamID); newShip.PlayerID.SetROri(playerID); ShipManagerLogging.logger.ConsoleLogDebug( @@ -32,12 +31,13 @@ private class ShipManager(Game game, Map gameMap) + $"{newShip.WeaponModuleType}"); return newShip; } - public static bool ActivateShip(Ship ship, XY pos) + public bool ActivateShip(Ship ship, XY pos) { if (ship.ShipState != ShipStateType.Deceased) { return false; } + gameMap.Add(ship); ship.ReSetPos(pos); ship.SetShipState(RunningStateType.Null, ShipStateType.Null); ShipManagerLogging.logger.ConsoleLogDebug( From 219743e17d34a027fcd0df434a8413c53f332b2b Mon Sep 17 00:00:00 2001 From: sigureling <1678348940@qq.com> Date: Sat, 11 May 2024 20:36:58 +0800 Subject: [PATCH 153/179] fix: :bug: fix parameter align bug --- CAPI/cpp/API/src/API.cpp | 2 +- CAPI/cpp/API/src/DebugAPI.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CAPI/cpp/API/src/API.cpp b/CAPI/cpp/API/src/API.cpp index 69bf5e3b..0059658d 100755 --- a/CAPI/cpp/API/src/API.cpp +++ b/CAPI/cpp/API/src/API.cpp @@ -290,7 +290,7 @@ std::future ShipAPI::Construct(THUAI7::ConstructionType constructionType) bool ShipAPI::HaveView(int32_t targetX, int32_t targetY) const { auto selfInfo = GetSelfInfo(); - return logic.HaveView(targetX, targetY, selfInfo->x, selfInfo->y, selfInfo->viewRange); + return logic.HaveView(selfInfo->x, selfInfo->y, targetX, targetY, selfInfo->viewRange); } // Team独有 diff --git a/CAPI/cpp/API/src/DebugAPI.cpp b/CAPI/cpp/API/src/DebugAPI.cpp index 189d7b02..c2641e32 100755 --- a/CAPI/cpp/API/src/DebugAPI.cpp +++ b/CAPI/cpp/API/src/DebugAPI.cpp @@ -239,7 +239,7 @@ std::shared_ptr ShipDebugAPI::GetSelfInfo() const bool ShipDebugAPI::HaveView(int32_t targetX, int32_t targetY) const { auto selfInfo = GetSelfInfo(); - return logic.HaveView(targetX, targetY, selfInfo->x, selfInfo->y, selfInfo->viewRange); + return logic.HaveView(selfInfo->x, selfInfo->y, targetX, targetY, selfInfo->viewRange); } int32_t ShipDebugAPI::GetEnergy() const From 928b9314a3ac6b6651c771b84b17de2fea4aa39b Mon Sep 17 00:00:00 2001 From: Xuc Pan Date: Sat, 11 May 2024 20:38:41 +0800 Subject: [PATCH 154/179] set AddShip static --- logic/Gaming/Game.cs | 2 +- logic/Gaming/ShipManager.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/logic/Gaming/Game.cs b/logic/Gaming/Game.cs index 8d1c577c..7d9f26ca 100755 --- a/logic/Gaming/Game.cs +++ b/logic/Gaming/Game.cs @@ -63,7 +63,7 @@ public long AddPlayer(PlayerInitInfo playerInitInfo) default: return GameObj.invalidID; } - Ship? newShip = shipManager.AddShip(playerInitInfo.teamID, + Ship? newShip = ShipManager.AddShip(playerInitInfo.teamID, playerInitInfo.playerID, playerInitInfo.shipType, teamList[(int)playerInitInfo.teamID].MoneyPool); diff --git a/logic/Gaming/ShipManager.cs b/logic/Gaming/ShipManager.cs index e978aa86..64b492e1 100755 --- a/logic/Gaming/ShipManager.cs +++ b/logic/Gaming/ShipManager.cs @@ -14,7 +14,7 @@ private class ShipManager(Game game, Map gameMap) { private readonly Game game = game; private readonly Map gameMap = gameMap; - public Ship? AddShip(long teamID, long playerID, ShipType shipType, MoneyPool moneyPool) + public static Ship? AddShip(long teamID, long playerID, ShipType shipType, MoneyPool moneyPool) { Ship newShip = new(GameData.ShipRadius, shipType, moneyPool); newShip.TeamID.SetROri(teamID); From 006f9f0638cfc28c132da394a0ec5b7754127c9a Mon Sep 17 00:00:00 2001 From: Xuc Pan Date: Sat, 11 May 2024 20:53:59 +0800 Subject: [PATCH 155/179] fix: :bug: stunned cannot die? --- logic/GameClass/GameObj/Ship.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/logic/GameClass/GameObj/Ship.cs b/logic/GameClass/GameObj/Ship.cs index 731c40f5..8f0aa20b 100755 --- a/logic/GameClass/GameObj/Ship.cs +++ b/logic/GameClass/GameObj/Ship.cs @@ -334,19 +334,19 @@ public long SetShipState(RunningStateType running, ShipStateType value = ShipSta switch (nowShipState) { case ShipStateType.Attacking: - if (value == ShipStateType.Null || value == ShipStateType.Stunned || value == ShipStateType.Swinging) + if (value == ShipStateType.Null || value == ShipStateType.Deceased || value == ShipStateType.Stunned || value == ShipStateType.Swinging) return ChangeShipState(running, value, gameObj); else return -1; case ShipStateType.Stunned: - if (value == ShipStateType.Null) + if (value == ShipStateType.Null || value == ShipStateType.Deceased) return ChangeShipState(running, value, gameObj); else return -1; case ShipStateType.Swinging: - if (value == ShipStateType.Null || value == ShipStateType.Stunned) + if (value == ShipStateType.Null || value == ShipStateType.Deceased || value == ShipStateType.Stunned) return ChangeShipState(running, value, gameObj); else return -1; case ShipStateType.Deceased: - if (value == ShipStateType.Null) + if (value == ShipStateType.Null || value == ShipStateType.Deceased) return ChangeShipState(running, value, gameObj); else return -1; default: From 8debba9ff10adece88dd75c88325bccb68658a54 Mon Sep 17 00:00:00 2001 From: Xuc Pan Date: Sat, 11 May 2024 20:57:12 +0800 Subject: [PATCH 156/179] fix: :bug: cannot die twice --- logic/GameClass/GameObj/Ship.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/logic/GameClass/GameObj/Ship.cs b/logic/GameClass/GameObj/Ship.cs index 8f0aa20b..a9818643 100755 --- a/logic/GameClass/GameObj/Ship.cs +++ b/logic/GameClass/GameObj/Ship.cs @@ -346,7 +346,7 @@ public long SetShipState(RunningStateType running, ShipStateType value = ShipSta return ChangeShipState(running, value, gameObj); else return -1; case ShipStateType.Deceased: - if (value == ShipStateType.Null || value == ShipStateType.Deceased) + if (value == ShipStateType.Null) return ChangeShipState(running, value, gameObj); else return -1; default: From 03bb2ec7bbbfe300afcdf99da3826f377309cf4f Mon Sep 17 00:00:00 2001 From: Xuc Pan Date: Sat, 11 May 2024 21:03:12 +0800 Subject: [PATCH 157/179] fix: :bug: home with HP 0 should do nothing --- logic/Server/RpcServices.cs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/logic/Server/RpcServices.cs b/logic/Server/RpcServices.cs index 18ea43b5..2b8d21d8 100755 --- a/logic/Server/RpcServices.cs +++ b/logic/Server/RpcServices.cs @@ -446,6 +446,10 @@ public override Task InstallModule(InstallMsg request, ServerCallContex return Task.FromResult(boolRes); } // var gameID = communicationToGameID[request.TeamId][request.PlayerId]; + if (game.TeamList[(int)request.TeamId].Home.HP <= 0) + { + return Task.FromResult(new BoolRes { ActSuccess = false }); + } boolRes.ActSuccess = game.InstallModule( request.TeamId, request.PlayerId, Transformation.ModuleFromProto(request.ModuleType)); @@ -464,6 +468,10 @@ public override Task Recycle(IDMsg request, ServerCallContext context) return Task.FromResult(boolRes); } // var gameID = communicationToGameID[request.TeamId][request.PlayerId]; + if (game.TeamList[(int)request.TeamId].Home.HP <= 0) + { + return Task.FromResult(new BoolRes { ActSuccess = false }); + } boolRes.ActSuccess = game.Recycle(request.TeamId, request.PlayerId); GameServerLogging.logger.ConsoleLogDebug("END Recycle"); return Task.FromResult(boolRes); @@ -485,6 +493,10 @@ public override Task BuildShip(BuildShipMsg request, ServerCallContext { return Task.FromResult(new BoolRes { ActSuccess = false }); } + if (game.TeamList[(int)request.TeamId].Home.HP <= 0) + { + return Task.FromResult(new BoolRes { ActSuccess = false }); + } BoolRes boolRes = new() { ActSuccess = @@ -515,6 +527,10 @@ public override Task BuildShipRID(BuildShipMsg request, ServerCall { return Task.FromResult(new BuildShipRes { ActSuccess = false }); } + if (game.TeamList[(int)request.TeamId].Home.HP <= 0) + { + return Task.FromResult(new BuildShipRes { ActSuccess = false }); + } var playerId = game.ActivateShip( request.TeamId, Transformation.ShipTypeFromProto(request.ShipType), From 22e66cef3bc17b9433be9af646a8e272842815a4 Mon Sep 17 00:00:00 2001 From: 964293341 Date: Sat, 11 May 2024 21:05:56 +0800 Subject: [PATCH 158/179] docs(PyAPI): :memo: add docs for PyAPI --- CAPI/python/PyAPI/API.py | 14 +-- CAPI/python/PyAPI/DebugAPI.py | 8 +- CAPI/python/PyAPI/Interface.py | 210 +++++++++++++++++++++++++++++---- CAPI/python/PyAPI/logic.py | 2 +- 4 files changed, 201 insertions(+), 33 deletions(-) diff --git a/CAPI/python/PyAPI/API.py b/CAPI/python/PyAPI/API.py index 3b336b58..2a2a2375 100644 --- a/CAPI/python/PyAPI/API.py +++ b/CAPI/python/PyAPI/API.py @@ -10,8 +10,8 @@ def __init__(self, logic: ILogic) -> None: self.__logic = logic self.__pool = ThreadPoolExecutor(20) - def Move(self, timeInMilliseconds: int, angle: float) -> Future[bool]: - return self.__pool.submit(self.__logic.Move, timeInMilliseconds, angle) + def Move(self, timeInMilliseconds: int, angleInRadian: float) -> Future[bool]: + return self.__pool.submit(self.__logic.Move, timeInMilliseconds, angleInRadian) def MoveRight(self, timeInMilliseconds: int) -> Future[bool]: return self.Move(timeInMilliseconds, pi * 0.5) @@ -25,8 +25,8 @@ def MoveUp(self, timeInMilliseconds: int) -> Future[bool]: def MoveDown(self, timeInMilliseconds: int) -> Future[bool]: return self.Move(timeInMilliseconds, 0) - def Attack(self, angle: float) -> Future[bool]: - return self.__pool.submit(self.__logic.Attack, angle) + def Attack(self, angleInRadian: float) -> Future[bool]: + return self.__pool.submit(self.__logic.Attack, angleInRadian) def Recover(self, recover: int) -> Future[bool]: return self.__pool.submit(self.__logic.Recover, recover) @@ -76,7 +76,7 @@ def GetFullMap(self) -> List[List[THUAI7.PlaceType]]: def GetPlaceType(self, cellX: int, cellY: int) -> THUAI7.PlaceType: return self.__logic.GetPlaceType(cellX, cellY) - def GetConstructionState(self, cellX: int, cellY: int) -> tuple: + def GetConstructionState(self, cellX: int, cellY: int) -> Tuple[int, int]: return self.__logic.GetConstructionState(cellX, cellY) def GetWormholeHp(self, cellX: int, cellY: int) -> int: @@ -112,7 +112,7 @@ def HaveView(self, gridX: int, gridY: int) -> bool: self.GetSelfInfo().viewRange, ) - def Print(self, cont: str) -> None: + def Print(self, string: str) -> None: pass def PrintShip(self) -> None: @@ -184,7 +184,7 @@ def GetFullMap(self) -> List[List[THUAI7.PlaceType]]: def GetPlaceType(self, cellX: int, cellY: int) -> THUAI7.PlaceType: return self.__logic.GetPlaceType(cellX, cellY) - def GetConstructionState(self, cellX: int, cellY: int) -> tuple: + def GetConstructionState(self, cellX: int, cellY: int) -> Tuple[int, int]: return self.__logic.GetConstructionState(cellX, cellY) def GetWormholeHp(self, cellX: int, cellY: int) -> int: diff --git a/CAPI/python/PyAPI/DebugAPI.py b/CAPI/python/PyAPI/DebugAPI.py index 0cade2ff..820f0daf 100644 --- a/CAPI/python/PyAPI/DebugAPI.py +++ b/CAPI/python/PyAPI/DebugAPI.py @@ -199,7 +199,7 @@ def GetFullMap(self) -> List[List[THUAI7.PlaceType]]: def GetPlaceType(self, cellX: int, cellY: int) -> THUAI7.PlaceType: return self.__logic.GetPlaceType(cellX, cellY) - def GetConstructionState(self, cellX: int, cellY: int) -> tuple: + def GetConstructionState(self, cellX: int, cellY: int) -> Tuple[int, int]: return self.__logic.GetConstructionState(cellX, cellY) def GetWormholeHp(self, cellX: int, cellY: int) -> int: @@ -235,8 +235,8 @@ def HaveView(self, gridX: int, gridY: int) -> bool: self.GetSelfInfo().viewRange, ) - def Print(self, cont: str) -> None: - self.__logger.info(cont) + def Print(self, string: str) -> None: + self.__logger.info(string) def PrintShip(self) -> None: for ship in self.__logic.GetShips(): @@ -440,7 +440,7 @@ def GetFullMap(self) -> List[List[THUAI7.PlaceType]]: def GetPlaceType(self, cellX: int, cellY: int) -> THUAI7.PlaceType: return self.__logic.GetPlaceType(cellX, cellY) - def GetConstructionState(self, cellX: int, cellY: int) -> tuple: + def GetConstructionState(self, cellX: int, cellY: int) -> Tuple[int, int]: return self.__logic.GetConstructionState(cellX, cellY) def GetWormholeHp(self, cellX: int, cellY: int) -> int: diff --git a/CAPI/python/PyAPI/Interface.py b/CAPI/python/PyAPI/Interface.py index 884fef3e..dbe92363 100644 --- a/CAPI/python/PyAPI/Interface.py +++ b/CAPI/python/PyAPI/Interface.py @@ -75,7 +75,7 @@ def HaveMessage(self) -> bool: pass @abstractmethod - def GetMessage(self) -> Tuple[int, str]: + def GetMessage(self) -> Tuple[int, Union[str, bytes]]: pass @abstractmethod @@ -134,181 +134,349 @@ def BuildShip(self, shipType: THUAI7.ShipType, birthIndex: int) -> bool: class IAPI(metaclass=ABCMeta): - """ - 选手可执行的操作,应当保证所有函数的返回值都应当为 `asyncio.Future`,例如下面的移动函数:\n - 指挥本角色进行移动: - - `timeInMilliseconds` 为移动时间,单位为毫秒 - - `angleInRadian` 表示移动的方向,单位是弧度,使用极坐标——竖直向下方向为 x 轴,水平向右方向为 y 轴\n - 发送信息、接受信息,注意收消息时无消息则返回 `nullopt` - """ - @abstractmethod def SendMessage(self, toPlayerID: int, message: Union[str, bytes]) -> Future[bool]: + """发送消息 + + :param toPlayerID: 接收方队内编号, 舰船为1~4, 基地为0 + :param message: 待发送消息, 分为 `str` 型和 `bytes` 型 + :return: 发送是否成功, 通过 `.result()` 方法等待获取 `bool` + """ pass @abstractmethod def HaveMessage(self) -> bool: + """检查是否拥有待接收消息 + + :return: 是否拥有待接收消息 + """ pass @abstractmethod - def GetMessage(self) -> Tuple[int, str]: + def GetMessage(self) -> Tuple[int, Union[str, bytes]]: + """接收消息队列的第一个消息 + + :return: 消息发送方的队内编号与消息, 如无消息发送方编号为-1 + """ pass - # 获取游戏目前所进行的帧数 @abstractmethod def GetFrameCount(self) -> int: - "获取游戏目前所进行的帧数" + """获取当前帧率 + + :raise: `NotImplementedError` + """ pass @abstractmethod def Wait(self) -> Future[bool]: - "等待下一帧" + """等待一帧 + - 在 `Setting.Asynchronous() == True` 下 + + :return: 等待是否成功, 通过 `.result()` 方法等待获取 `bool` + """ pass @abstractmethod def EndAllAction(self) -> Future[bool]: + """发出停止一切行动指令 + + :return: 是否进入无行动状态, 通过 `.result()` 方法等待获取 `bool` + """ pass @abstractmethod def GetShips(self) -> List[THUAI7.Ship]: + """获取本队所有舰船 + + :return: 本队所有舰船 + """ pass @abstractmethod def GetEnemyShips(self) -> List[THUAI7.Ship]: + """获取敌方舰船 + - 需要敌方舰船处于视野内, 对于 `TeamAPI` 指所有舰船视野 + + :return: 视野内敌方所有舰船 + """ pass @abstractmethod def GetBullets(self) -> List[THUAI7.Bullet]: + """获取敌方子弹 + - 需要子弹处于视野内 + + :return: 视野内敌方所有子弹 + :raise: `NotImplementedError` 对于 `TeamAPI` + """ pass @abstractmethod def GetFullMap(self) -> List[List[THUAI7.PlaceType]]: + """获取地图 + + :return: `THUAI7.PlaceType` 的二维数组 + """ pass @abstractmethod def GetGameInfo(self) -> THUAI7.GameInfo: + """获取当前游戏信息 + + :return: 当前游戏信息, 详见 `THUAI7.GameInfo` 定义 + """ pass @abstractmethod def GetPlaceType(self, cellX: int, cellY: int) -> THUAI7.PlaceType: + """获取区域类型 + + :param cellX: X坐标, 单位Cell + :param cellY: Y坐标, 单位Cell + :return: 该坐标的区域类型 + """ pass @abstractmethod - def GetConstructionState(self, cellX: int, cellY: int) -> tuple: + def GetConstructionState(self, cellX: int, cellY: int) -> Tuple[int, int]: + """获取当前建筑状态 + + :param cellX: X坐标, 单位Cell + :param cellY: Y坐标, 单位Cell + :return: 该建筑当前的所属队伍编号与血量 + """ pass @abstractmethod def GetWormholeHp(self, cellX: int, cellY: int) -> int: + """获取当前虫洞状态 + + :param cellX: X坐标, 单位Cell + :param cellY: Y坐标, 单位Cell + :return: 当前虫洞血量 + """ pass @abstractmethod def GetResourceState(self, cellX: int, cellY: int) -> int: + """获取当前资源状态 + + :param cellX: X坐标, 单位Cell + :param cellY: Y坐标, 单位Cell + :return: 当前资源剩余可开采量 + """ pass @abstractmethod def GetHomeHp(self) -> int: + """获取当前大本营血量 + + :return: 当前大本营血量 + """ pass @abstractmethod def GetEnergy(self) -> int: + """获取当前经济 + + :return: 当前经济 + """ pass @abstractmethod def GetScore(self) -> int: + """获取当前得分 + + :return: 当前得分 + """ pass @abstractmethod def GetPlayerGUIDs(self) -> List[int]: + """获取本队所有舰船GUID + + :return: 本队所有舰船GUID + """ pass @abstractmethod def Print(self, string: str) -> None: + """(DEBUG)打印字符串 + + :param string: 待打印字符串 + """ pass @abstractmethod def PrintShip(self) -> None: + """(DEBUG)打印所有舰船 + """ pass @abstractmethod def PrintTeam(self) -> None: + """(DEBUG)打印队伍信息 + """ pass @abstractmethod def PrintSelfInfo(self) -> None: - pass - - @abstractmethod - def GetSelfInfo(self) -> Union[THUAI7.Ship, THUAI7.Team]: + """(DEBUG)打印自身信息, `ShipDebugAPI` 打印舰船信息, `TeamDebugAPI` 打印队伍信息 + """ pass class IShipAPI(IAPI, metaclass=ABCMeta): @abstractmethod def Move(self, timeInMilliseconds: int, angleInRadian: float) -> Future[bool]: + """发出移动指令 + + :param timeInMilliseconds: 期望移动的毫秒数 + :param angleInRadian: 期望移动的弧度数, 向下为x轴正方向, 向右为y轴正方向 + :return: 移动是否成功, 通过 `.result()` 方法等待获取 `bool` + """ pass @abstractmethod def MoveRight(self, timeInMilliseconds: int) -> Future[bool]: + """发出向右移动指令 + + :param timeInMilliseconds: 期望移动的毫秒数 + :return: 移动是否成功, 通过 `.result()` 方法等待获取 `bool` + """ pass @abstractmethod def MoveUp(self, timeInMilliseconds: int) -> Future[bool]: + """发出向上移动指令 + + :param timeInMilliseconds: 期望移动的毫秒数 + :return: 移动是否成功, 通过 `.result()` 方法等待获取 `bool` + """ pass @abstractmethod def MoveLeft(self, timeInMilliseconds: int) -> Future[bool]: + """发出向左移动指令 + + :param timeInMilliseconds: 期望移动的毫秒数 + :return: 移动是否成功, 通过 `.result()` 方法等待获取 `bool` + """ pass @abstractmethod def MoveDown(self, timeInMilliseconds: int) -> Future[bool]: + """发出向下移动指令 + + :param timeInMilliseconds: 期望移动的毫秒数 + :return: 移动是否成功, 通过 `.result()` 方法等待获取 `bool` + """ pass @abstractmethod def Attack(self, angleInRadian: float) -> Future[bool]: + """发出攻击指令 + + :param angleInRadian: 期望攻击的弧度值, 向下为x轴正方向, 向右为y轴正方向 + :return: 攻击是否成功, 通过 `.result()` 方法等待获取 `bool` + """ pass @abstractmethod def Recover(self, recover: int) -> Future[bool]: + """发出回复指令 + - 需要接近可用的 `Home` 或 `Community`(`Construction`) + + :param recover: 期望回复生命值 + :return: 回复是否成功, 通过 `.result()` 方法等待获取 `bool` + """ pass @abstractmethod def Produce(self) -> Future[bool]: + """发出生产指令 + - 需要接近未采集完的 `Resource` + + :return: 进入生产状态是否成功, 通过 `.result()` 方法等待获取 `bool` + """ pass @abstractmethod def Rebuild(self, constructionType: THUAI7.ConstructionType) -> Future[bool]: + """发出重建指令 + - 需要接近待重建 `Construction` + + :param constructionType: 建筑类型 + :return: 进入建造状态是否成功, 通过 `.result()` 方法等待获取 `bool` + """ pass @abstractmethod def Construct(self, constructionType: THUAI7.ConstructionType) -> Future[bool]: + """发出建造指令 + - 需要接近待建 `Construction` + + :param constructionType: 建筑类型 + :return: 进入建造状态是否成功, 通过 `.result()` 方法等待获取 `bool` + """ pass @abstractmethod def GetSelfInfo(self) -> THUAI7.Ship: + """获取本舰船信息 + + :return: 舰船信息, 详见 `THUAI7.Ship` 定义 + """ pass @abstractmethod def HaveView(self, gridX: int, gridY: int) -> bool: + """检测是否拥有视野 + + :param gridX: 待检测X坐标, 单位Grid + :param gridY: 待检测Y坐标, 单位Grid + :return: 是否拥有视野 + """ pass class ITeamAPI(IAPI, metaclass=ABCMeta): @abstractmethod def GetSelfInfo(self) -> THUAI7.Team: + """获取本队伍信息 + + :return: 队伍信息, 详见 `THUAI7.Team` 定义 + """ pass @abstractmethod - def InstallModule( - self, playerID: int, moduleType: THUAI7.ModuleType - ) -> Future[bool]: + def InstallModule(self, playerID: int, moduleType: THUAI7.ModuleType) -> Future[bool]: + """安装模块 + + :param playerID: 待安装模块的舰船编号 + :param moduleType: 模块类型 + :return: 安装是否成功, 通过 `.result()` 方法等待获取 `bool` + """ pass @abstractmethod def Recycle(self, playerID: int) -> Future[bool]: + """回收舰船 + + :param playerID: 待回收舰船编号 + :return: 回收是否成功, 通过 `.result()` 方法等待获取 `bool` + """ pass @abstractmethod def BuildShip(self, shipType: THUAI7.ShipType, birthIndex: int) -> Future[bool]: + """建造舰船 + + :param shipType: 舰船类型 + :param birthIndex: 出生点 (可用的 `Home` 与 `Community`(`Construction`)) 编号 + :return: 建造是否成功, 通过 `.result()` 方法等待获取 `bool` + """ pass diff --git a/CAPI/python/PyAPI/logic.py b/CAPI/python/PyAPI/logic.py index 707bbfd1..4fbb56ad 100644 --- a/CAPI/python/PyAPI/logic.py +++ b/CAPI/python/PyAPI/logic.py @@ -155,7 +155,7 @@ def GetConstructionState(self, cellX: int, cellY: int) -> tuple: ) else: self.__logger.warning("GetConstructionState: Out of range") - return (-1,-1) + return (-1, -1) def GetWormholeHp(self, cellX: int, cellY: int) -> int: with self.__mtxState: From 43196ee631f3405b4d82387ea8b70a82d3f5e25e Mon Sep 17 00:00:00 2001 From: ONLOX <3316820553@qq.com> Date: Sat, 11 May 2024 21:19:08 +0800 Subject: [PATCH 159/179] style: format --- installer/Page/DebugPage.xaml | 322 ++++++++++++++----------------- installer/Page/InstallPage.xaml | 157 +++++++-------- installer/Page/LoginPage.xaml | 67 +++---- installer/Page/PlaybackPage.xaml | 126 +++++------- 4 files changed, 312 insertions(+), 360 deletions(-) diff --git a/installer/Page/DebugPage.xaml b/installer/Page/DebugPage.xaml index da6acc56..561cc281 100644 --- a/installer/Page/DebugPage.xaml +++ b/installer/Page/DebugPage.xaml @@ -4,31 +4,32 @@ x:Class="installer.Page.DebugPage" Title="Launcher"> - + + HorizontalOptions="Center" + WidthRequest="600" + RowDefinitions="*,*,*,*,*,*,*,*,*,*" + ColumnDefinitions="*"> + Grid.Row="0" + Grid.RowSpan="9" + HorizontalOptions="Center" + VerticalOptions="Center"> + IsVisible="{Binding IPVisible}">