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 _15Puzzle
{
public partial class Form1 : Form
{
TableLayoutPanel panel;
Puzzle puzzle;
public Form1()
{
InitializeComponent();
Init();
}
private void Init()
{
this.Width = 290;
this.Height = 314;
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.Text = "15 Puzzle";
panel = new TableLayoutPanel();
panel.Parent = this;
panel.Dock = DockStyle.Fill;
panel.RowCount = 4;
panel.ColumnCount = 4;
foreach (ColumnStyle style in panel.ColumnStyles)
{
style.SizeType = SizeType.AutoSize;
}
foreach (RowStyle style in panel.RowStyles)
{
style.SizeType = SizeType.AutoSize;
}
for (int i = 0; i <= 3; i++)
{
for (int j = 0; j <= 3; j++)
{
if (i == 3 && j == 3)
{
break;
}
Button btn = new Button();
btn.Size = new Size(65, 65);
btn.Parent = panel;
panel.SetCellPosition(btn, new TableLayoutPanelCellPosition(j, i));
Font fnt = btn.Font;
btn.Font = new Font(fnt.FontFamily, 16, fnt.Style);
btn.Text = (4 * i + j + 1).ToString();
btn.Click += new EventHandler(btn_Click);
}
}
puzzle = new Puzzle();
}
private void btn_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
TableLayoutPanelCellPosition position = panel.GetCellPosition(btn);
int row = position.Row;
int column = position.Column;
if (puzzle.Move(ref row, ref column))
{
panel.SetCellPosition(btn, new TableLayoutPanelCellPosition(column, row));
}
}
}
public class Puzzle
{
int[,] tiles;
public Puzzle()
{
Init();
}
private void Init()
{
tiles = new int[4, 4];
for (int i = 0; i <= 3; i++)
{
for (int j = 0; j <= 3; j++)
{
tiles[i, j] = 4 * i + j + 1;
}
}
tiles[3, 3] = 0;
}
public bool Move(ref int row, ref int column)
{
//test jestli je v okoli dlazdice prazdne misto
for (int i = row - 1; i <= row + 1; i++)
{
for (int j = column - 1; j <= column + 1; j++)
{
if (i >= 0 && i <= 3 && j >= 0 && j <= 3)
{
//je prazdne misto
if ((i == row || j == column) && tiles[i, j] == 0)
{
//posuneme dlazdici na prazdne misto
tiles[i, j] = tiles[row, column];
tiles[row, column] = 0;
row = i;
column = j;
return true;
}
}
}
}
return false;
}
}
}