ZZY e16f76e11f refactor(重构): 重构了事件驱动的代码体系,使用全新命名和版本,以及测试套件的初试
- 移除了.csproj文件
- 更新了.gitignore,添加了.editorconfig
- 重构了IBoard和IPiece接口,引入了新的事件处理机制
- 优化了CCBoard、CCPiece等类的实现,使用新的事件驱动模型
- 删除了冗余代码,提高了代码的可读性和可维护性
2024-11-24 15:42:30 +08:00

88 lines
2.5 KiB
C#

// Chessboard.cs
using System;
using Godot;
using ChineseChess;
using Godot.Collections;
using static IBoard;
public partial class ChessBoard : Node2D, ICCBoardOn {
public event EventHandler<Vector2>? OnMouseClicked;
public event EventHandler<Vector2>? OnPosClicked;
public event EventHandler<int>? OnStepsChanged;
public Vector2 from = Vector2.Inf, to = Vector2.Inf;
public Array<Vector2> canMovePos = [];
public override void _Ready() {
}
public void Clear() {
from = to = Vector2.Inf;
QueueRedraw();
}
void IBoardOn.OnInsert(object self, IPiece piece) {
ChessPiece? node = piece.On as ChessPiece;
// throw new InvalidOperationException();
node ??= new ChessPiece((CCPiece)piece);
node.ShowBehindParent = true;
AddChild(node);
// 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);
}
void IBoardOn.OnRemove(object self, IPiece piece) {
if (piece.On is not ChessPiece node) {
throw new InvalidOperationException();
}
RemoveChild(node);
}
void IBoardOn.OnMove(object self, IBoardOn.MoveEventArgs vals) {
from = PosTrans.transArrToPix * new Vector2(vals.From.X, vals.From.Y);
to = PosTrans.transArrToPix * new Vector2(vals.To.X, vals.To.Y);
QueueRedraw();
}
void ICCBoardOn.OnSteps(object _self, int oldSteps) {
if (_self is not CCBoard self) return;
OnStepsChanged?.Invoke(self, self.Steps);
}
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
);
}
}