创建九个button控件,点击button控件,判断该button是否与空白button相邻,若相邻则交换,直到完成拼图
const int N = 3;//按钮的行列数
Button[,] buttons = new Button[N, N];//定义按钮的数组,名字叫buttons
private void Form1_Load(object sender, EventArgs e)
{
this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;//把图片按比例缩放
//自动产生所有的按钮
GenerateAllButtons();
//打乱
Shuffle();
}
void GenerateAllButtons()
{
int x0 = 100, y0 = 10, w = 200, d = 200;//w是每个方块的边长,d是相邻方块定点间距离
for (int i = 0; i < N; i++)//i行变量
{
for (int j = 0; j < N; j++)//j列变量
{
int num = i * N + j +1;//每个小块的代号
Button btn = new Button();
//btn.Text = num.ToString();
btn.Top = y0 + i * d;
btn.Left = x0 + j * d;
btn.Width = w;
btn.Height = w;//设计每个button的属性
btn.Visible = true;
btn.Tag = i * N + j;
//导入图片
btn.BackgroundImage = Bitmap.FromFile(@"C:\userdata\Matlabdata\dividepicture\"+num.ToString()+".png");//直接通过Bitmap.FromFile读取图片
//btn.BackgroundImage = block_game.Properties.Resources.(Tag + 1).Tostring();
btn.BackgroundImageLayout = ImageLayout.Zoom;//把图片按比例zoom
//注册事件,又新注册btn_Click
btn.Click += new EventHandler(btn_Click);
buttons[i, j] = btn;//把生成的控件放到数组中
this.Controls.Add(btn);//加载到form界面中
}
}
buttons[N - 1, N - 1].Visible = false;//最后一个不可见,有个空来挪位置
}
//打乱顺序
void Shuffle()
{
Random rnd = new Random();
for(int i=0;i<100;i++)//打乱
{
int a = rnd.Next(N);
int b = rnd.Next(N);
int c = rnd.Next(N);
int d = rnd.Next(N);
swap(buttons[a, b], buttons[c, d]);
}
}
void swap(Button a, Button b)//函数参数要对应,这个是要返回值的
{
string str = a.Text;
a.Text = b.Text;
b.Text = str;
bool v = a.Visible;
a.Visible = b.Visible;
b.Visible = v;//不光要交换块的文本,还要交换块的可见性
Image p = a.BackgroundImage;
a.BackgroundImage = b.BackgroundImage;
b.BackgroundImage = p;
}
//还原时,点一下和空白的交换的事件
void btn_Click(object sender, EventArgs e)
{
//throw new NotImplementedException();这句是自动生成的
//把当前你点击的块赋给btn,程序检查这两个是否相邻,判断是否完成,能否交换
Button btn = sender as Button;
//找到空白的块赋给blank
Button blank = FindHiddenButton();//又引入一个找空白块的函数
//判断相邻
if(IsNeighbor(btn,blank ))
{
swap(btn, blank);
blank.Focus();
}
//判断是否完成
if(ResultOk())
{
MessageBox.Show("拼图成功!");
}
}
//查找blank方法
Button FindHiddenButton()
{
for(int i=0;i< N;i++)
{
for(int j=0;j< N;j++)
{
if (!buttons[i, j].Visible)
return (buttons[i, j]);
}
}
return null;
}
bool IsNeighbor(Button btna,Button btnb)
{
int a = (int)btna.Tag;
int b = (int)btnb.Tag;
int r1 = a / N, c1 = a % N;
int r2 = b / N, c2 = b % N;
if ((r1 == r2 && (c1 == c2 - 1 || c1 == c2 + 1)) || (c1 == c2 && (r1 == r2 + 1 || r1 == r2 - 1)))
return true;
else
return false;
}
bool ResultOk()
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
if (buttons[i, j].Text != (i * N + j + 1).ToString())
return false;
}
}
return true;
}