update: 更新到godot4.4.1,并大量重构代码

This commit is contained in:
ZZY
2025-06-09 18:17:06 +08:00
parent b27abb55a2
commit 3fa39fc71e
39 changed files with 801 additions and 790 deletions

View File

@ -5,7 +5,7 @@ using ChineseChess;
public partial class ChessGame : Node2D {
ChessBoard board;
Global global;
GlobalManager global = GlobalManager.Instance;
ConfirmationDialog dialog;
private bool isSession = false;
ChessCore Game;
@ -15,15 +15,17 @@ public partial class ChessGame : Node2D {
// Called when the node enters the scene tree for the first time.
public override void _Ready() {
// Init.Call();
global = GetNode<Global>("/root/Global");
board = GetNode<ChessBoard>("Chessboard");
isSession = global.RPClient.IsOnline();
// ChessGameAPI api = new();
// api.BindToLua(global.ModManager.lua);
// isSession = global.RPClient.IsOnline();
GetNode<LineEdit>("Control/VBoxContainer/MarginContainer3/HFlowContainer/LineEdit")
.Text = global.GlobalData["player_color"].AsString();
LineEdit turnSideEdit = GetNode<LineEdit>("Control/VBoxContainer/MarginContainer3/HFlowContainer/LineEdit2");
turnSideEdit.Text = "red";
GD.Print("ChessGame uid:", global.RPClient.GetUserId(), " color:",global.GlobalData["player_color"]);
// GD.Print("ChessGame uid:", global.RPClient.GetUserId(), " color:",global.GlobalData["player_color"]);
dialog = new ConfirmationDialog {
DialogAutowrap = true,
@ -52,12 +54,12 @@ public partial class ChessGame : Node2D {
Vector.Vector2I vector = new(posX, posY);
if (isSession) {
Game.OnPosClicked(vector, ChessCore.PlayerSideType.Self);
var res = global.RPClient.SendSessionToAll(global.sessionId, new Dictionary {
{"type", "mouseClicked"},
{"X", pos.X},
{"Y", pos.Y},
{"id", global.RPClient.GetUserId()}
});
// var res = global.RPClient.SendSessionToAll(global.sessionId, new Dictionary {
// {"type", "mouseClicked"},
// {"X", pos.X},
// {"Y", pos.Y},
// {"id", global.RPClient.GetUserId()}
// });
} else {
Game.OnPosClicked(vector);
}
@ -66,13 +68,13 @@ public partial class ChessGame : Node2D {
if (isSession) {
GD.Print("ws is connected");
global.RPClient.OnPRCSessionExit += (cmd, code) => {
GoHome();
};
// global.RPClient.OnPRCSessionExit += (cmd, code) => {
// GoHome();
// };
global.RPClient.OnPRCSessionRecv += (msg) => {
SessionMsgHandle(msg["msg"].AsGodotDictionary());
};
// global.RPClient.OnPRCSessionRecv += (msg) => {
// SessionMsgHandle(msg["msg"].AsGodotDictionary());
// };
}
}
@ -80,50 +82,50 @@ public partial class ChessGame : Node2D {
public override void _Process(double delta) {
}
private void SessionMsgHandle(Dictionary msg) {
GD.PrintErr($"session msg: {msg}");
switch (msg["type"].AsString()) {
case "over":
if (global.RPClient.GetUserId() == msg["id"].AsString()) {
break;
}
dialog.Title = "Opponent Finished";
dialog.DialogText = "Turn On You\n";
dialog.Visible = true;
break;
case "mouseClicked":
if (msg["id"].ToString() == global.RPClient.GetUserId()) {
break;
}
Vector2 mouseClicked = new(GD.StrToVar(msg["X"].ToString()).AsInt32(),
GD.StrToVar(msg["Y"].ToString()).AsInt32());
Vector.Vector2I vector = new((int)mouseClicked.X, (int)mouseClicked.Y);
Game.OnPosClicked(vector, ChessCore.PlayerSideType.Opponent);
break;
case "undo":
Game.Undo();
break;
case "reInit":
Game.ReInit();
break;
}
}
// private void SessionMsgHandle(Dictionary msg) {
// GD.PrintErr($"session msg: {msg}");
// switch (msg["type"].AsString()) {
// case "over":
// if (global.RPClient.GetUserId() == msg["id"].AsString()) {
// break;
// }
// dialog.Title = "Opponent Finished";
// dialog.DialogText = "Turn On You\n";
// dialog.Visible = true;
// break;
// case "mouseClicked":
// if (msg["id"].ToString() == global.RPClient.GetUserId()) {
// break;
// }
// Vector2 mouseClicked = new(GD.StrToVar(msg["X"].ToString()).AsInt32(),
// GD.StrToVar(msg["Y"].ToString()).AsInt32());
// Vector.Vector2I vector = new((int)mouseClicked.X, (int)mouseClicked.Y);
// Game.OnPosClicked(vector, ChessCore.PlayerSideType.Opponent);
// break;
// case "undo":
// Game.Undo();
// break;
// case "reInit":
// Game.ReInit();
// break;
// }
// }
private void BtnOver() {
GD.Print($"BtnOver {isSession}");
if (isSession == false) {
return;
}
global.RPClient.SendSessionToAll(global.sessionId, new Dictionary{
{"type", "over"},
{"id", global.RPClient.GetUserId()},
});
// global.RPClient.SendSessionToAll(global.sessionId, new Dictionary{
// {"type", "over"},
// {"id", global.RPClient.GetUserId()},
// });
}
public void GoHome() {
if (global.RPClient.IsOnline()) {
global.RPClient.ExitServer();
}
// if (global.RPClient.IsOnline()) {
// global.RPClient.ExitServer();
// }
global.GotoScene("res://Main.tscn");
}
@ -131,10 +133,10 @@ public partial class ChessGame : Node2D {
GD.Print($"Undo {isSession}");
if (isSession) {
global.RPClient.SendSessionToAll(global.sessionId, new Dictionary{
{"type", "undo"},
{"id", global.RPClient.GetUserId()},
});
// global.RPClient.SendSessionToAll(global.sessionId, new Dictionary{
// {"type", "undo"},
// {"id", global.RPClient.GetUserId()},
// });
} else {
if (Game.board.Steps == 0) board.Clear();
Game.Undo();
@ -143,11 +145,11 @@ public partial class ChessGame : Node2D {
public void ReInit() {
GD.PrintErr($"ReInit {isSession}");
if (isSession) {
global.RPClient.SendSessionToAll(global.sessionId, new Dictionary{
{"type", "reInit"},
});
// global.RPClient.SendSessionToAll(global.sessionId, new Dictionary{
// {"type", "reInit"},
// });
} else {
Game.ReInit();
board.Clear();

View File

@ -3,7 +3,7 @@ using Godot;
using Godot.Collections;
public partial class GameLobby : Control {
Global global = null;
GlobalManager global = GlobalManager.Instance;
Timer timer = null;
ItemList lists = null;
@ -15,93 +15,92 @@ public partial class GameLobby : Control {
// Called when the node enters the scene tree for the first time.
public override void _Ready() {
global = GetNode<Global>("/root/Global");
lists = GetNode<ItemList>("MarginContainer/VBoxContainer/MarginContainer3/ItemList");
dialog = GetNode<ConfirmationDialog>("Dialogs/ConfirmationDialog");
URL = global.GlobalConfigDict["server_url"].AsString();
userName = global.GlobalConfigDict["user_name"].AsString();
URL = global.ConfigManager.GetValue<string>("server_url");
userName = global.ConfigManager.GetValue<string>("user_name");
dialog.MinSize = new Vector2I(400, 200);
dialog.DialogAutowrap = true;
dialog.Canceled += () => {
if (dialog.Title == "Session Created")
global.RPClient.SessionAckCreate(dialog.GetMeta("sessionId").ToString(), false);
// if (dialog.Title == "Session Created")
// global.RPClient.SessionAckCreate(dialog.GetMeta("sessionId").ToString(), false);
};
dialog.Confirmed += () => {
if (dialog.Title == "Session Created") {
// FIXME
isAcceptedPart = true;
global.RPClient.SessionAckCreate(dialog.GetMeta("sessionId").ToString(), true);
// global.RPClient.SessionAckCreate(dialog.GetMeta("sessionId").ToString(), true);
}
};
global.RPClient.OnOpen += (string eventName, object[] args) => {
global.RPClient.UserInit(userName, "godot chessboard", () => {
global.RPClient.UserRename(userName);
return global.RPClient.RegionAdd("server");
});
};
// global.RPClient.OnOpen += (eventName, args) => {
// global.RPClient.UserInit(userName, "godot chessboard", () => {
// global.RPClient.UserRename(userName);
// return global.RPClient.RegionAdd("server");
// });
// };
// global.RPClient.OnOpen += (eventName, args) => {
// global.RPClient.UserInit(userName, "none", () => {
// GD.PrintErr($"User Init Success");
// return true;
// });
// // global.RPClient.UserRename(userName);
// };
global.RPClient.RegSessionAckCreateCallback((sessionId, res, reqUserId, reqUserName) => {
if (reqUserId != null) {
dialog.Title = "Session Created";
dialog.SetMeta("reqUserName", reqUserName);
dialog.SetMeta("reqUserId", reqUserId);
dialog.SetMeta("sessionId", sessionId);
// dialog.GetLabel==>Text = $"{sessdata["reqUserName"]}";
dialog.DialogText = $"username: {reqUserName}\n" +
$"reqUserId: {reqUserId}\n";
dialog.Visible = true;
} else {
if (res) {
// TODO FIXME
global.sessionId = sessionId;
if (!isAcceptedPart) {
global.GlobalData["player_color"] = "red";
} else {
global.GlobalData["player_color"] = "black";
}
// GD.PrintErr("sessionId: ", reqUserId, "color: ", global.GlobalData["player_color"].AsString());
global.GotoScene("res://Scenes/ChessGame.tscn");
} else {
dialog.Title = "Failed";
dialog.DialogText = $"session create failed";
dialog.Visible = true;
}
}
return true;
});
// global.RPClient.RegSessionAckCreateCallback((sessionId, res, reqUserId, reqUserName) => {
// if (reqUserId != null) {
// dialog.Title = "Session Created";
// dialog.SetMeta("reqUserName", reqUserName);
// dialog.SetMeta("reqUserId", reqUserId);
// dialog.SetMeta("sessionId", sessionId);
// // dialog.GetLabel==>Text = $"{sessdata["reqUserName"]}";
// dialog.DialogText = $"username: {reqUserName}\n" +
// $"reqUserId: {reqUserId}\n";
// dialog.Visible = true;
// } else {
// if (res) {
// // TODO FIXME
// global.sessionId = sessionId;
// if (!isAcceptedPart) {
// global.GlobalData["player_color"] = "red";
// } else {
// global.GlobalData["player_color"] = "black";
// }
// // GD.PrintErr("sessionId: ", reqUserId, "color: ", global.GlobalData["player_color"].AsString());
// global.GotoScene("res://Scenes/ChessGame.tscn");
// } else {
// dialog.Title = "Failed";
// dialog.DialogText = $"session create failed";
// dialog.Visible = true;
// }
// }
// return true;
// });
timer = new Timer();
AddChild(timer);
// timer = new Timer();
// AddChild(timer);
ColorRect colorRect = GetNode<ColorRect>("MarginContainer/VBoxContainer/MarginContainer2/MarginContainer2/ColorRect");
timer.Connect("timeout", Callable.From(() => {
if (global.RPClient.GetIsConnected()) {
colorRect.Color = Colors.Green;
} else {
colorRect.Color = Colors.Red;
}
FlushData();
}));
timer.Start(1);
// timer.Connect("timeout", Callable.From(() => {
// if (global.RPClient.GetIsConnected()) {
// colorRect.Color = Colors.Green;
// } else {
// colorRect.Color = Colors.Red;
// }
// FlushData();
// }));
// timer.Start(1);
Connect();
}
public void Connect() {
GD.Print("Connect");
if (global.RPClient.GetIsConnected()) {
return;
}
// if (global.RPClient.GetIsConnected()) {
// return;
// }
// global.RPClient.ExitServer();
global.RPClient.ConnectToUrlEx(URL);
// global.RPClient.ConnectToUrlEx(URL);
global.SetProcess(true);
}
@ -109,33 +108,33 @@ public partial class GameLobby : Control {
Dictionary item = lists.GetItemMetadata(index).AsGodotDictionary();
GD.Print($"Item {index} selected, {item}");
string[] strings = { item["id"].ToString() };
global.RPClient.SessionCreate(strings);
// global.RPClient.SessionCreate(strings);
}
private void FlushData() {
global.RPClient.RegionInspect("server", (data) => {
// GD.Print(data);
lists?.Clear();
foreach (Dictionary<string, string> user in data) {
string userId = user["id"].ToString();
string userName = user["name"].ToString();
if (userId == global.RPClient.GetUserId()) {
lists.SetItemDisabled(
lists.AddItem($"Name: {userName}"),
true);
continue;
}
var idx = lists.AddItem($"Name: {userName}");
lists.SetItemMetadata(idx, user);
lists.SetItemTooltip(idx, $"User ID: {userId}");
}
return true;
});
// global.RPClient.RegionInspect("server", (data) => {
// // GD.Print(data);
// lists?.Clear();
// foreach (Dictionary<string, string> user in data) {
// string userId = user["id"].ToString();
// string userName = user["name"].ToString();
// if (userId == global.RPClient.GetUserId()) {
// lists.SetItemDisabled(
// lists.AddItem($"Name: {userName}"),
// true);
// continue;
// }
// var idx = lists.AddItem($"Name: {userName}");
// lists.SetItemMetadata(idx, user);
// lists.SetItemTooltip(idx, $"User ID: {userId}");
// }
// return true;
// });
}
private void OnBack() {
global.RPClient.ExitServer();
// global.RPClient.ExitServer();
global.GotoScene("res://Main.tscn");
}
}

View File

@ -0,0 +1,30 @@
using Godot;
using System;
public partial class Mods : Control {
GlobalManager global = GlobalManager.Instance;
public override void _Ready() {
// RunDemo();
// ModManager modManager = new();
// modManager.RegistryFunc("OnInit", () => { GD.Print("OnInit"); }, true);
// modManager.RegistryFunc("foo", () => { GD.Print("Hello"); });
// LuaMod mod = new(ProjectSettings.GlobalizePath("res://Protos/test.lua"));
// mod.BindFunc(modManager);
// try {
// modManager.InvokeFunc<Action>("OnInit");
// }
// catch (System.Exception e) {
// GD.PrintErr("OnInit error: ", e.Message, e.StackTrace);
// }
}
public void OnOpenModFileDir() {
OS.ShellOpen(global.ConfigManager.GetValue<string>("mods_fpath") ?? "user://Mods/");
}
public void OnBack() {
ArgumentNullException.ThrowIfNull(global);
global.GotoScene("res://Main.tscn");
}
}

View File

@ -0,0 +1 @@
uid://c8t8d8e7inajy

View File

@ -1,65 +1,59 @@
using Godot;
using System;
using System.IO;
public partial class Setting : Control
{
Global global;
public partial class Setting : Control {
private GlobalManager global = GlobalManager.Instance;
private IConfigManager config = GlobalManager.Instance.ConfigManager;
int font_size;
LineEdit fontOut;
private LineEdit fontOut = null!;
// Called when the node enters the scene tree for the first time.
public override void _Ready()
{
global = GetNode<Global>("/root/Global");
public override void _Ready() {
fontOut = GetNode<LineEdit>("BoxContainer/MarginContainer5/HBoxContainer/FontSize");
font_size = (int)global.GlobalConfigDict["font_size"];
font_size = config.GetValue<int>("font_size");
GetNode<HSlider>("BoxContainer/MarginContainer6/FontSizeBar")
.Value = font_size;
fontOut.Text = font_size.ToString();
FillingData();
}
private void FillingData()
{
private void FillingData() {
GetNode<LineEdit>("BoxContainer/MarginContainer2/Server/LineEdit")
.Text = global.GlobalConfigDict["server_url"].ToString();
.Text = config.GetValue<string>("server_url");
GetNode<LineEdit>("BoxContainer/MarginContainer3/Name/LineEdit")
.Text = global.GlobalConfigDict["user_name"].ToString();
.Text = config.GetValue<string>("user_name");
}
// Called every frame. 'delta' is the elapsed time since the previous frame.
public override void _Process(double delta)
{
public override void _Process(double delta) {
}
private void OnBack() {
global.GotoScene("res://Main.tscn", null);
}
private void OnSave() {
global.SaveConfig();
// OS.Alert("Saved", "Setting");
}
void OnNameChanged(string Value)
{
global.GlobalConfigDict["user_name"] = Value;
// global.ConfigFlush();
}
void OnNameChanged(string Value) {
config.SetValue("user_name", Value);
// config.GetValue<>Flush();
}
private void OnServerUrlChanged(string Value)
{
global.GlobalConfigDict["server_url"] = Value;
// global.ConfigFlush();
}
private void OnServerUrlChanged(string Value) {
config.SetValue("server_url", Value);
// config.GetValue<>Flush();
}
private void OnFontSizeChanged(float Value)
{
private void OnFontSizeChanged(float Value) {
font_size = (int)Value;
global.GlobalConfigDict["font_size"] = font_size;
global.ConfigFlush();
config.SetValue("font_size", font_size);
global.GlobalThemeConfigFlush();
fontOut.Text = font_size.ToString();
}
}
private static void OnClearData() {
// ProjectSettings.GlobalizePath("user://");
@ -77,6 +71,11 @@ public partial class Setting : Control
}
}
private static void OnGetSettingsFile() {
string path = ProjectSettings.GlobalizePath(GlobalManager.ConfigPath);
OS.ShellOpen(Path.GetDirectoryName(path));
}
private static void OnGetCacheDir() {
OS.Alert(OS.GetCacheDir(), "Cache Dir");
}
@ -92,4 +91,7 @@ public partial class Setting : Control
private static void OnGetUserDataDir() {
OS.Alert(OS.GetUserDataDir(), "User Data Dir");
}
private static void ChangeLangZHCN(bool _) => TranslationServer.SetLocale("zh_CN");
private static void ChangeLangEN(bool _) => TranslationServer.SetLocale("en");
}