所以我最近一直在尝试学习 C#,所以我想我会尝试我的简单项目,例如井字游戏。我目前正在尝试添加点击功能,以确保它正常工作,我放入 MessageBox.Show 以确保它是我点击的新区域。但是,当我运行它时,没有出现错误,但是当我单击一个框时,什么也没发生。有谁知道我的代码有什么问题?是 MessageBox.Show 代码还是其他问题?这是我的代码:
在 Board.cs 文件中,我有:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
class Board
{
private Rectangle[,] slots = new Rectangle[3, 3];
private Holder[,] holders = new Holder[3, 3];
public const int X = 0;
public const int O = 1;
public const int B = 2;
public void initBoard()
{
for (int x = 0; x < 3; x++)
{
for (int y = 0; y < 3; y++)
{
slots[x, y] = new Rectangle(x * 167, y * 167, 167, 167);
holders[x, y] = new Holder();
holders[x, y].setValue(B);
holders[x, y].setLocation(new Point(x, y));
}
}
}
public void detectHit(Point loc)
{
int x = 0;
int y = 0;
if (loc.X < 167)
{
x = 0;
}
else if (loc.X > 167 && loc.X < 334)
{
x = 1;
}
else if (loc.X > 334)
{
x = 2;
}
if (loc.Y < 167)
{
y = 0;
}
else if (loc.Y > 167 && loc.Y < 334)
{
y = 1;
}
else if (loc.Y > 334 && loc.Y < 500)
{
y = 2;
}
MessageBox.Show(x.ToString() + ", " + y.ToString() + "/n/n" + loc.ToString());
}
}
class Holder
{
private Point location;
private int value = Board.B;
public void setLocation(Point p)
{
location = p;
}
public Point getLocation()
{
return location;
}
public void setValue(int i)
{
value = i;
}
public int getValue()
{
return value;
}
}
}
然后在我的 Form1.cs 文件中,我有:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
GFX engine;
Board theBoard;
public Form1()
{
InitializeComponent();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
Graphics toPass = panel1.CreateGraphics();
engine = new GFX(toPass);
theBoard = new Board();
theBoard.initBoard();
}
private void Form1_Click(object sender, EventArgs e)
{
Point mouse = Cursor.Position;
mouse = panel1.PointToClient(mouse);
theBoard.detectHit(mouse);
}
}
}