我目前创建了一个棋盘,其中填充了棋子的图像并为棋盘着色等,我有 2 个关于点击事件方法的问题,我希望你能帮助我解决这个问题?单击正方形时,我当前的方法会更改正方形颜色并显示一个消息框,显示 xy 坐标和棋子类型,或者如果它未被棋子占用则仅显示坐标:
问题1:如果我再次点击同一个方格或不同的方格,如何让颜色变回原来的颜色?
问题 2:如何在文本框或标签中显示 Form1.cs 上的信息而不是显示消息框?
以下是我的 GridSqaure.cs 类中的代码:
namespace Chess
{
public class GridSquare : PictureBox
{
private int x;
private int y;
private ChessPiece piece;
public int X { get { return x; } }
public int Y { get { return y; } }
public ChessPiece Piece
{
get { return piece; }
set
{
piece = value;
if (value == null)
this.BackgroundImage = null;
else
this.BackgroundImage = piece.GetImage();
}
}
public GridSquare(int x, int y)
{
int ButtonWidth = 64;
int ButtonHeight = 64;
int Distance = 20;
int start_x = 10;
int start_y = 10;
this.x = x;
this.y = y;
this.Top = start_x + (x * ButtonHeight + Distance + x);
this.Left = start_y + (y * ButtonWidth + Distance + y);
this.Width = ButtonWidth;
this.Height = ButtonHeight;
this.Text = "X: " + x.ToString() + " Y: " + y.ToString();
this.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.Click += new System.EventHandler(gridSquare_Click);
}
private void gridSquare_Click(object sender, EventArgs e)
{
GridSquare gs = (GridSquare)sender;
if (gs.Piece != null)
{
//Change: need to show xy of sqaure clicked on a label or textbox on the main window.
MessageBox.Show("You clicked a " + gs.Piece.GetName() + " at (" + gs.X + ", " + gs.Y + ")");
//Change: need to click for change in colour, then second click to revert back
this.BackColor = Color.LightBlue;
}
else
{
//Change: need to show xy of clicked square but including meesage stating the sqaure needs to be occupied by a piece.
MessageBox.Show("You clicked (" + gs.X + ", " + gs.Y + ")");
}
}
}
}
请您参考如下方法:
我会避免让一个类处理它自己的事件之一。这不是一个好的做法。
相反,我会使用回调策略。
首先,像这样重新编码 GridSquare:
public class GridSquare : PictureBox
{
/* As before */
public GridSquare(int x, int y, Action<GridSquare> clicked)
{
/* As before */
this.Click += (s, e) => clicked(this);
}
/* NO private void gridSquare_Click(object sender, EventArgs e) */
}
现在由调用代码来完成艰苦的工作。
我假设您正在使用诸如嵌套 for 循环之类的东西创建板,这些循环将每个创建的 GridSquare 添加到表单的 Controls 集合中。如果是这种情况,您需要像这样编写代码:
for (var x = 0; x < 8; x++)
{
for (var y = 0; y < 8; y++)
{
this.Controls.Add(new GridSquare(x, y, clicked));
}
}
现在您只需要定义 clicked - 当每个 GridSquare 被点击时的回调 - 该代码如下所示:
GridSquare lastClicked = null;
Color lastBackColor = Color.Transparent;
Action<GridSquare> clicked = gs =>
{
lastClicked.BackColor = lastBackColor;
if (!lastClicked.Equals(gs))
{
lastClicked = gs;
lastBackColor = gs.BackColor;
gs.BackColor = Color.LightBlue;
var inner = gs.Piece != null
? String.Format("a {0} at ", gs.Piece.GetName())
: "";
var msg = String.Format("You clicked {0}({1}, {2})", inner, gs.X, gs.Y);
MessageBox.Show(msg);
}
};
显然这段代码在创建网格方 block 之前。
这应该相对容易理解,但如果不是,请询问,我会详细说明。
让我知道这是否适合您。
