您现在的位置: 破洛洛 >> 服务器 >> WEB服务器 >> 正文

C#实现十五子游戏教程

作者:佚名 来源:网络整理 更新时间:2017-5-24
分享到

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

主要有:

1.生成初始框架

2.打乱顺序

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

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;
}

转载请注明:破洛洛(谢谢合作)
网友评论: