C realizes fifteen sub games

  • 2021-12-12 09:26:39
  • OfStack

Recently, due to the need of work, do a simple program of C #. After learning some basic things, write them down first.

There are mainly:

1. Generate the initial framework

STEP 2 Disturb the order

3. In the game part, only Text and Visible parts are exchanged with the blank part after clicking the button


const int N = 4; // Number of rows and columns 
Button[,] buttons = new Button[N, N];

private void Form1_Load(object sender, EventArgs e)
{
  // Generate all buttons 
  GenerateAllButtons();
}

private void button1_Click(object sender, EventArgs e)
{
  // Disturb the order 
  Shuffle();
}

// Generate button 
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;  // Digital number 
      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 Position 

      // Registration button Click event 
      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]);
  }
}
//  Play a game 
private void btn_Click(object sender, EventArgs e)
{
  Button btn = sender as Button;
  Button blank = FindHiddenButton();

  //  Judge whether it is adjacent or not 
  if ( IsNeighbor(btn, blank) )
  {
    Swap(btn, blank);
    blank.Focus();
  }

  //  Judge whether it is completed 
  if ( ResultIsOk() )
  {
    MessageBox.Show("OK!");
  }
}

//  Find Blank Button 
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;
}

//  Judge whether it is adjacent or not 
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;
}

// Check whether it is complete 
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;
}
// Swap two buttons 
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;
}


Related articles: