1.用C#编辑出来一个小游戏,和小时玩的拼图游戏有些类似,还是蛮有趣得到,来和大家分享一下。
2.该十五字游戏下面有三个按钮,作用分别为:乱序:打乱上面十五个数字的顺序;提交:当你把游戏恢复到原位后,点提交按钮,会判断你的顺序对不对,若是正确的,出现“你真棒”字样,若不正确,不会出现;排序:自动把十五个数字顺序排好。
3.程序代码如下:
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 十五字游戏
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
const int N = 4;
Button [,] buttons = new Button[N,N];
private void Form1_Load(object sender, EventArgs e)
{
//产生所有按钮
GenerateAllButtons();
}
void GenerateAllButtons()
{
int x0 = 100, y0 = 50, w = 45, d = 50;
for (int i=0;i<N;i++)
{
for (int j = 0; j < N; j++)
{
int number = i * N + j;
Button btn = new Button();
btn.Text = (number+1).ToString();
btn.Top = y0 + i*d;
btn.Left = x0 + j*d;
btn.Width = w;
btn.Height = w;
btn.Tag = i * N + j;
btn.Visible = true;
buttons[i, j] = btn;
//注册事件
btn.Click += new EventHandler(btn_Click);
this.Controls.Add(btn);
}
}
buttons[N - 1, N - 1].Visible = false;
}
void btn_Click(Object sender, EventArgs e)
{
Button btn = sender as Button;
Button blank = FindHiddenButton();
//判断是否相邻
if (IsNeighbor(btn, blank))
{
Swap(btn, blank);
blank.Focus();
}
}
//交换两个按钮
void Swap(Button btna,Button btnb)
{
string s = btna.Text;
btna.Text = btnb.Text;
btnb.Text = s;
bool b = btna.Visible;
btna.Visible = btnb.Visible;
btnb.Visible = b;
}
//判断是否相邻的函数
bool IsNeighbor(Button btn,Button blank)
{
int a = (int)btn.Tag;
int b = (int)blank.Tag;
int c1 = a / N; int d1 = a % N;
int c2 = b / N;int d2 = b % N;
if ((c1 == c2 && ((d1 == d2 - 1) || (d1 == d2 + 1)))||(d1==d2&&((c1==c2-1)||(c1==c2+1))))
{
return true;
}
return false;
}
Button FindHiddenButton()
{
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
if (buttons[i, j].Visible == false)
{
return buttons[i, j];
}
}
}
return null;
}
private void button3_Click(object sender, EventArgs e)
{
//点击后自动排序
Sort();
GenerateAllButtons();
}
void Sort()
{
Button btn = new Button();
btn.Visible = false;
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
buttons[i, j].Visible = btn.Visible ;
}
}
}
private void button1_Click(object sender, EventArgs e)
{
//点击后随机乱序
Shuffle();
}
void Shuffle()
{
//多次交换两个按钮
Random r = new Random();
for(int i=0;i<100;i++)
{
int a = r.Next(N);
int b = r.Next(N);
int c = r.Next(N);
int d = r.Next(N);
Swap(buttons[a, b], buttons[c, d]);
}
}
private void button2_Click(object sender, EventArgs e)
{
//判断是否找回正确顺序
if(ResultIsOk())
{
MessageBox.Show("你真棒");
}
}
bool ResultIsOk()
{
for(int i=0;i<N;i++)
{
for (int j = 0; j < N; j++)
{
if (int.Parse(buttons[i, j].Text) != (i*N+j+1))
{
return false;
}
}
}
return true ;
}
}
}