Skip to content

Instantly share code, notes, and snippets.

@mrgarita
Created November 6, 2017 08:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrgarita/0bf7750ba5e80890a59b26a731fa86b8 to your computer and use it in GitHub Desktop.
Save mrgarita/0bf7750ba5e80890a59b26a731fa86b8 to your computer and use it in GitHub Desktop.
C#:8パズルをコントロール配列を使って作ってみる
using System;
using System.Windows.Forms;
namespace _9puzzle
{
public partial class Form1 : Form
{
// 9つのボタンを配列化するためのコントロール変数
Control[] cell = new Control[9];
public Form1()
{
InitializeComponent();
}
// 起動時の処理
private void Form1_Load(object sender, EventArgs e)
{
this.Text = Application.ProductName;
// ボタンを配列化する
cell[0] = this.button1;
cell[1] = this.button2;
cell[2] = this.button3;
cell[3] = this.button4;
cell[4] = this.button5;
cell[5] = this.button6;
cell[6] = this.button7;
cell[7] = this.button8;
cell[8] = this.button9;
// ボタンの文字とイベント処理を設定
for(int i=0; i<cell.Length; i++)
{
// ボタンに数値を表示1~8まで(9は空欄にしておく)
cell[i].Text = (i + 1).ToString();
if (cell[i].Text == "9") cell[i].Text = "";
// ボタンのタグに番号をつける(0~8)
cell[i].Tag = i.ToString();
// ボタンクリック時のイベント処理を設定
cell[i].Click += new System.EventHandler(btnClick);
}
// ボタンのテキストをシャッフル
Random r = new Random();
for (int i=0; i<1000; i++)
{
// 入れ替え位置を乱数で設定
int no = r.Next(cell.Length);
// 入れ替え可能かチェック
checkSwap(no);
}
}
// ボタンクリック時の処理
private void btnClick(object sender, System.EventArgs e)
{
// 押されたボタンのTagを取得(0~8)
Button btn = (Button)sender;
int no = int.Parse(btn.Tag.ToString());
// 入れ替え可能かチェック
checkSwap(no);
// 揃ったかチェック
checkText();
}
// 入れ替え可能かチェックする
private void checkSwap(int no)
{
if (no >= 3 && cell[no - 3].Text == "") // 上側と入れ替え
{
swapText(no, no - 3);
}
else if (no <= 5 && cell[no + 3].Text == "") // 下側と入れ替え
{
swapText(no, no + 3);
}
else if (no % 3 != 2 && cell[no + 1].Text == "") // 右側と入れ替え
{
swapText(no, no + 1);
}
else if (no % 3 != 0 && cell[no - 1].Text == "") // 左側と入れ替え
{
swapText(no, no - 1);
}
}
// テキスト入れ替え
private void swapText(int n, int m)
{
string work = cell[n].Text;
cell[n].Text = cell[m].Text;
cell[m].Text = work;
}
// 番号が揃ったかチェックする
private void checkText()
{
int i;
// 配列添え字0~7まで(最後の8は空欄になるため)
for(i=0; i<cell.Length-1; i++)
{
if(cell[i].Text != (i+1).ToString())
{
break;
}
}
// カウンタiが8なら全部揃っている
if(i == cell.Length-1)
{
MessageBox.Show("クリア!");
}
}
}
}
@mrgarita
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment