当前位置: 移动技术网 > IT编程>开发语言>c# > C#实现十五子游戏

C#实现十五子游戏

2019年07月18日  | 移动技术网IT编程  | 我要评论

最近由于工作需要,做一个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;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网