这次首先对以前的结构进行了调整:
第一步:把MyButton按钮的属性独立成一个类,放在一个单独的MyButton.cs中,把图片的初始化也放到里面。
调整代码如下:
public class MyButton : Button
{
//图片的名称,用于判断两个按钮是否为同一个
public int Flag { get; set; }//Button所在行
public int RowNum { get; set; }//所在列
public int ColNum { get; set; }public MyButton(int flag, int romNum, int colNum)
{
this.Flag = flag;
this.RowNum = romNum;
this.ColNum = colNum;if (flag != 0)
{
Image img = new Image();
img.Source = new BitmapImage(new Uri(@"images\" + flag + ".png", UriKind.Relative));
this.Content = img;
}
}
}
第二步:将设置随机数独立成MyRandom.cs,这里将图片个数等一些属性都设置成了可变的,调整内容如下
public class MyRandom { private int Count; //产生多少个数字 private int Amount; //产生几份 private int Max; //最大数(不包含) private int Min; //最小数 /// <summary> /// /// </summary> /// <param name="count">产生多少个数字</param> /// <param name="amount">产生几份(须为count的约数)</param> /// <param name="min">最小数</param> /// <param name="max">最大数(不包含)</param> public MyRandom(int count, int amount, int min, int max) { if (count % amount != 0) throw new Exception("count须为amount的整数倍"); if (min > max) throw new Exception("min必须小于等于max"); Count = count; Amount = amount; Max = max; Min = min; } public List<int> Get() { Random rand = new Random(); List<int> ran = new List<int>(); for (int n = 0; n < Count / Amount; n++) ran.Add(rand.Next(Min, Max)); for (int i = 1; i < Amount; i++) { List<int> temp = new List<int>(); temp.AddRange(ran); for (int n = 0; n < Count / Amount; n++) { int r = rand.Next(0, temp.Count); ran.Insert(rand.Next(0, ran.Count), temp[r]); temp.RemoveAt(r); } } return ran; } }
第三步:对Add方法进行了调整,为了方便理解将变量i,j,调整为r,c(对应行列),同时根据上述变化做了其他一些调整,内容如下:
MyButton[,] maps = new MyButton[10, 10]; int Count; public void Add() { for (int i = 0; i < 10; i++) { RowDefinition rowDef = new RowDefinition(); GridGame.RowDefinitions.Add(rowDef); ColumnDefinition colDef = new ColumnDefinition(); GridGame.ColumnDefinitions.Add(colDef); } Count = 8; Amount = 32; List<int> ran = (new MyRandom(64, 2, 1, Count)).Get(); for (int r = 0; r < 10; r++) { for (int c = 0; c < 10; c++) { MyButton btn; if (r == 0 || r == 9 || c == 0 || c == 9) { btn = new MyButton(0, r, c); btn.Visibility = System.Windows.Visibility.Hidden; } else btn = new MyButton((int)ran[(r - 1) * 8 + c - 1], r, c); btn.Click += btn_Click; maps[r, c] = btn; Grid.SetColumn(btn, c); Grid.SetRow(btn, r ); GridGame.Children.Add(btn); } } }
好了,到目前为止,我们得到了一个可以玩的连连看了。这一篇虽然比起上一篇没有多大的进度,只是对结构进行了调整,代码进行了优化。这样结构也稍微清晰了许多,也便于理解。
倒计时我大概已经有了思路,也基本已经成型了,但连线还没想好怎么弄,有志同道合的朋友可以讨论下。
最后,如果感觉对您有所帮助,请帮忙推荐下……感谢!