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 WindowsFormsApplication15{ 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(); } private void button1_Click(object sender, EventArgs e) { //点击“开始”按钮,打乱顺序 Shuffle(); } //打乱顺序函数 void Shuffle() { //多次随机交换两个按钮 Random rnd = new Random(); for(int i = 0; i < 100; i++) { int a = rnd.Next(N); int b = rnd.Next(N); int c = rnd.Next(N); int d = rnd.Next(N); Swap(buttons[a, b], buttons[c, d]);//交换两个按钮位置 } } //生成所有按钮函数 void GenerateAllButtons() { int x0 = 100, y0 = 10, w = 45, d = 50; for (int r = 0; r < N; r++) { for (int c = 0; c < N; c++) { int num = r * N + c; Button btn = new Button(); btn.Text = (num + 1).ToString();//设置按钮显示的数字 btn.Top = y0 + r * d;//设置按钮的左边缘与容器的上边缘之间的距离 btn.Left = x0 + c * d;//设置按钮的左边缘与容器的左边缘之间的距离 btn.Width = w;//按钮宽度 btn.Height = w;//按钮高度 btn.Visible = true;//是否显示按钮 btn.Tag = r * N + c;//Tag属性是给程序员自己用的,做点标记,类似于按钮的ID,此处这个数据用来表示它所在的行列位置 //注册事件 btn.Click += new EventHandler(btn_click); buttons[r, c] = btn;//放到数组中 this.Controls.Add(btn);//加到界面上 } } buttons[N - 1, N - 1].Visible = false;//定义最后一个按钮不可见 } //交换两个按钮函数 void Swap(Button btna,Button btnb) { //两个按钮的值交换 string t = btna.Text; btna.Text = btnb.Text; btnb.Text = t; //两个按钮的可见属性交换 bool v = btna.Visible; btna.Visible = btnb.Visible; btnb.Visible = v; } //按钮点击事件处理 void btn_click(object sender,EventArgs e) { Button btn = sender as Button;//当前点中的按钮 Button blank = FindHiddenButton();//空白按钮 //判断是否与空白按钮相邻,如果是,则交换 if (IsNeighbor(btn,blank)) { Swap(btn, blank); blank.Focus(); } //判断是否完成了游戏 if (ResultIsOk()) { MessageBox.Show("OK"); } } //查找要隐藏的按钮函数 Button FindHiddenButton() { for (int r = 0; r < N; r++) { for (int c = 0; c < N; c++) { if (!buttons[r,c].Visible) { return buttons[r, c]; } } } return null; } //判断是否相邻函数 bool IsNeighbor(Button btnA,Button btnB) { int a = (int)btnA.Tag;//获取Tag中保存的位置信息(0-15的值) 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; } private void Btn_Click(object sender, EventArgs e) { throw new NotImplementedException(); } }}
详细解决方案
C#10五子游戏
热度:150 发布时间:2016-04-28 08:27:53.0
相关解决方案