一个小时候经常玩的游戏:
通过只移动空白处周围的小方块 最终将所有方块移动到目标位置即完成游戏
程序的逻辑并不难:
1.初始化所有(4X4)按钮属性(位置 ,大小,标号,是否可见) 和方法(点击按钮 交换),并按顺序排列
2.点击洗牌 开始游戏 (通过随机交换任意两个按钮X次)
3.每次点击某个按钮 判断是否在隐藏按钮周围,在周围则交换这两个按钮,否则无反应
4.每次点击按钮 判断所有按钮是否达到目标位置,达到则弹出消息窗口
Project是 Windows form Application
代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
const int N = 4;
Button[,] buttons = new Button[N, N]; //创建N X N大小的按钮数组
void swap(Button btn1, Button btn2) //交换两个按钮 实际上只需要交换两个属性(显示的标号Text,是否可见Visible)即可
{
string str1 = btn1.Text;
btn1.Text = btn2.Text;
btn2.Text = str1;
bool a = btn1.Visible;
btn1.Visible = btn2.Visible;
btn2.Visible = a;
}
private void button1_Click(object sender, EventArgs e) //点击开始按钮
{
for (int i = 0; i < 1000; i++) //随机交换两个按钮 1000次实现洗牌
{
Random rnd = new Random();
int a, b, c, d;
a = rnd.Next(N); //产生四个不大于N的随机数
b = rnd.Next(N);
c = rnd.Next(N);
d = rnd.Next(N);
swap(buttons[a, b], buttons[c, d]);
}
}
Button FindHiddenButton() //找到那个没显示的按钮
{
int i, j;
for (i = 0; i < N; i++)
for (j = 0; j < N; j++)
if (buttons[i, j].Visible == false)
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;
return false;
}
bool ResultIsOk() //判断是否完成
{
for (int r = 0; r < N; r++)
for (int c = 0; c < N; c++)
{
if (buttons[r, c].Text != (r * N + c + 1).ToString())
{
return false;
}
}
return true;
}
void btn_Click(object sender, EventArgs e) //点击某个按钮
{
Button btn = sender as Button; //当前点中的按钮
Button blank = FindHiddenButton();
if (IsNeighbor(btn, blank))
{
swap(btn, blank);
blank.Focus(); //duang 给"移动"的格子加特效
}
//判断是否完成了
if (ResultIsOk())
{
MessageBox.Show("You Win"); //弹出消息窗
}
}
void GenerateAllButtons() //生成所有按钮
{
int x0 = 100, y0 = 10, wid1 = 50, wid2 = 45;
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
{
Button btn = new Button();
btn.Top = y0 + i * wid1;
btn.Left = x0 + j * wid1;
btn.Width = wid2;
btn.Height = wid2;
btn.Visible = true;
btn.Text = (i * N + j + 1).ToString(); //初始化按钮所有属性
btn.Tag = i * N + j; //保存行号 列号
btn.Click += new EventHandler(btn_Click);
buttons[i, j] = btn; //放到数组上
this.Controls.Add(btn); //加到界面上
}
buttons[N - 1, N - 1].Visible = false;
}
private void Form1_Load(object sender, EventArgs e) //初始化
{
GenerateAllButtons();
}
}
}