74 lines
2.2 KiB
C#

// Chesspiece.cs
using Godot;
public partial class ChessPiece : Sprite2D {
// 文字内容
[Export]
public string PieceLabel { get; set; } = null;
// 文字颜色(可导出以编辑器调整)
[Export]
public Color LabelColor { get; set; } = new Color("black");
private Vector2 textureSize;
private Label labelOfChessName;
private readonly VirtualPiece piece;
public VirtualPiece GetVirtualPiece() {
return piece;
}
private void OnMove(Vector2 newPos) {
Position = PosTrans.transArrToPix * new Vector2(newPos.X, newPos.Y);
}
public void OnSelected(bool isSelected) {
if (isSelected) {
GD.Print($"{piece.Pos()} is selected");
Transform *= transToSeleted;
} else {
GD.Print($"{piece.Pos()} is deselected");
Transform *= transToSeleted.AffineInverse();
}
}
Transform2D transToSeleted = new Transform2D(
new Vector2(1.2f, 0),
new Vector2(0, 1.2f),
new Vector2(0, 0)
);
public ChessPiece() : this("", Vector2.Zero){
}
public ChessPiece(string name, Vector2 pos) {
PieceLabel = name;
piece = new VirtualPiece(name, pos);
piece.OnMove += OnMove;
piece.OnSelected += OnSelected;
piece.data = this;
}
// Called when the node enters the scene tree for the first time.
public override void _Ready() {
InitLabel();
}
private void InitLabel() {
// this.Texture.ResourcePath = "res://Asserts/ChesspieceBase.tres";
Texture ??= (Texture2D)ResourceLoader.Load("res://Asserts/ChesspieceBase.tres");
textureSize = Texture.GetSize();
Vector2 labalPosition = new(
-textureSize.X / 2,
-textureSize.Y / 2);
labelOfChessName = new Label {
Text = PieceLabel,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
Modulate = LabelColor,
Position = labalPosition,
Size = textureSize,
};
// labelOfChessName.SetAnchorsPreset(Control.LayoutPreset.FullRect);
AddChild(labelOfChessName);
}
}