C#实现十五子游戏

时间:2021-09-09 07:21:58

最近由于工作需要,做一个C#的简单程序。学习了一些基础东西先记下来。

主要有:

1.生成初始框架

2.打乱顺序

3.游戏部分,点击按钮后与空白部分交换的只是Text和Visible部分

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
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 GenerateAllButtons()
{
  int x0 = 100, y0 = 10, w = 45, d = 50;
   for( int row = 0; row < N; row++ )
    for ( int col = 0; col < N; col++ )
    {
      int num = row * N + col;  //数字编号
      Button btn = new Button();
      btn.Text = (num + 1).ToString();
      btn.Top = y0 + row * d;
      btn.Left = x0 + col * d;
      btn.Width = w;
      btn.Height = w;
      btn.Visible = true;
      btn.Tag = row * N + col;  //button位置
 
      //注册button点击事件
      btn.Click += new EventHandler(btn_Click);
 
      buttons[row, col] = btn;
      this.Controls.Add(btn);
    }
  buttons[N - 1, N - 1].Visible = false;
}
 
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]);
  }
}
// 进行游戏
private 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 row = 0; row < N; row++)
    for (int col = 0; col < N; col++)
    {
      if (!buttons[row,col].Visible)
      {
        return buttons[row, col];
      }
    }
  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 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;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。