// Chessboard.cs using System; using Godot; using ChineseChess; using Godot.Collections; public partial class ChessBoard : Node2D { public event EventHandler OnMouseClicked; public event EventHandler OnPosClicked; public Vector2 from = Vector2.Inf, to = Vector2.Inf; public Array canMovePos = new(); public override void _Ready() { } public void Clear() { from = to = Vector2.Inf; QueueRedraw(); } public void LoadBoard(CCBoard board) { board.OnRemove += (sender, piece) => { if (piece?.Data.TryGetValue("Godot", out object node) ?? false) { RemoveChild(node as Node); } }; board.OnInsert += (sender, piece) => { ChessPiece chessPiece = null; if (piece.Data.TryGetValue("Godot", out object node)) { chessPiece = node as ChessPiece; } else { chessPiece = new((CCPiece)piece); } chessPiece.ShowBehindParent = true; AddChild(chessPiece); }; board.OnMove += (sender, vals) => { from = PosTrans.transArrToPix * new Vector2(vals.From.X, vals.From.Y); to = PosTrans.transArrToPix * new Vector2(vals.To.X, vals.To.Y); QueueRedraw(); }; } public override void _Draw() { Color color = new(0.7f, 0.7f, 0.7f, 0.5f); DrawLine(from, to, color, PosTrans.pixGripSize / 5); DrawCircle(from, PosTrans.pixGripSize / 2.2f, color); foreach (Vector2 pos in canMovePos) { DrawCircle(pos, PosTrans.pixGripSize / 2.2f, color.Inverted()); } } public override void _Input(InputEvent @event) { if (@event is InputEventMouseButton mouseEvent && mouseEvent.Pressed && mouseEvent.ButtonIndex == MouseButton.Left) { OnMouseClicked?.Invoke(this, GetLocalMousePosition()); OnPosClicked?.Invoke(this, (PosTrans.transArrToPix.AffineInverse() * GetLocalMousePosition()).Round()); } } public static class PosTrans { public static readonly int pixGripSize = 32; public static readonly Transform2D transArrToPix = new( new Vector2(pixGripSize, 0), new Vector2(0, pixGripSize), new Vector2(-4, -4.5f) * pixGripSize ); } }