close

圖片有註解

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 WindowsFormsApplication9
{
public partial class Form1 : Form
{
Button[,] buttons = new Button[36, 36];
int[] array = new int[36]; 
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
// Instantiating all the buttons in the array

 

for (int i = 0; i < 25; i++)
{
array[i] = i;
}


for (int j = 0; j < 5; j++)
{
for (int i = 0; i < 5; i++)

buttons[i, j] = new Button();
buttons[i, j].Location = new Point(i * 50, j * 50);
buttons[i, j].Size = new Size(50, 50);
buttons[i, j].Text = (j * 4 + i).ToString();
this.Controls.Add(buttons[i ,j]);
buttons[i, j].Click += new EventHandler(Button1_Click);
}
}
}

private void Button1_Click(object sender, EventArgs e)
{
string late;
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
if (buttons[i, j].Text == "0")
{//顯示"0"的座標位置(i,j)
MessageBox.Show("i=" + i + ",j=" + j + " " + buttons[i, j].Text);
}

}
}

for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{//顯示當下點擊按鈕座標(i,j)
if (sender == buttons[i, j])
{movebutton(i, j, buttons[i, j].Text);

//檢查按鈕右邊是否為"0",是的話則與原點擊按鈕交換

if (buttons[i + 1, j].Text == "0")  
{
late = buttons[i, j].Text;
buttons[i, j].Text = buttons[i + 1, j].Text;
buttons[i + 1, j].Text = late;
}

//檢查按鈕左邊是否為"0",是的話則與原點擊按鈕交換
else if (buttons[i - 1, j].Text == "0")
{
late = buttons[i, j].Text;
buttons[i, j].Text = buttons[i - 1, j].Text;
buttons[i - 1, j].Text = late;
}

//檢查按鈕上面是否為"0",是的話則與原點擊按鈕交換
else if (buttons[i, j + 1].Text == "0")
{
late = buttons[i, j].Text;
buttons[i, j].Text = buttons[i, j+1].Text;
buttons[i, j+1].Text = late;
}

//檢查按鈕下面是否為"0",是的話則與原點擊按鈕交換
else if (buttons[i, j - 1].Text == "0")
{
late = buttons[i, j].Text;
buttons[i, j].Text = buttons[i, j-1].Text;
buttons[i, j-1].Text = late;
}

}
}
}

}

private void movebutton(int i,int j,string s) {
MessageBox.Show("i=" + i + ",j=" + j + " " + s);
}

private void button1_Click(object sender, EventArgs e)
{
int d1, tmp, k;

Random irand = new Random();
d1 = irand.Next(1, 10);
label1.Text = d1.ToString();

for (int j = 1; j < 26; j++)
{
k =25 - j+1 ;
tmp = array[d1];
array[d1] = array[k];
array[k] = tmp;
}

//buttons[1, 1].Text = array[1].ToString();
for (int j = 0; j < 5; j++)
{
for (int i = 0; i < 5; i++)
{
//buttons[i, j] = new Button();
buttons[i, j].Location = new Point(j * 50, i * 50);
buttons[i, j].Text = array[j*5+i+1].ToString();
this.Controls.Add(buttons[i, j]);

}

}

label2.Text = array[d1].ToString();

}
}
}

1  

顯示"0"的座標位置(i,j)

2  

顯示當下點擊按鈕座標(i,j)

3  

檢查按鈕右邊是否為"0",是的話則與原點擊按鈕交換

 

arrow
arrow
    全站熱搜

    許暐豐 發表在 痞客邦 留言(0) 人氣()