using System;
using System.Drawing;
using System.Windows.Forms;
namespace game99
{
public partial class Form1 : Form
{
Button[,] buttons = new Button[10, 10];
int emptyRow = 9;
int emptyCol = 9;
public Form1()
{
InitializeComponent();
CreateGrid();
}
void CreateGrid()
{
int number = 1;
int size = 50;
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
Button btn = new Button();
btn.Size = new Size(size, size);
btn.Location = new Point(j * size, i * size);
if (number <= 99)
btn.Text = number.ToString();
else
btn.Text = "";
btn.Click += Button_Click;
buttons[i, j] = btn;
this.Controls.Add(btn);
number++;
}
}
}
private void Button_Click(object sender, EventArgs e)
{
Button clicked = (Button)sender;
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
if (buttons[i, j] == clicked)
{
if (CanMove(i, j))
{
Move(i, j);
}
}
}
}
}
bool CanMove(int row, int col)
{
return (Math.Abs(row - emptyRow) == 1 && col == emptyCol) ||
(Math.Abs(col - emptyCol) == 1 && row == emptyRow);
}
void Move(int row, int col)
{
buttons[emptyRow, emptyCol].Text = buttons[row, col].Text;
buttons[row, col].Text = "";
emptyRow = row;
emptyCol = col;
}
}
}