/* csc /target:winexe Form1.cs */ using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 :Form { const int cellSize = 70;//ブロックのサイズ int[,] table = new int[4, 4];//盤面 Point selectCell = new Point(0, 0);//選択されているブロック PictureBox pictureBox1 = new PictureBox();//盤面を描画するピクチャーボックス [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } public Form1() { pictureBox1.Dock = DockStyle.Fill; pictureBox1.Paint +=new PaintEventHandler(pictureBox1_Paint); pictureBox1.MouseMove += new MouseEventHandler(pictureBox1_MouseMove); pictureBox1.MouseDown += new MouseEventHandler(pictureBox1_MouseDown); this.FormBorderStyle = FormBorderStyle.FixedSingle; this.ClientSize = new Size(cellSize * 4 + 1, cellSize * 4 + 1); this.KeyPreview = true; this.Text = "15パズル"; this.Load +=new EventHandler(Form1_Load); this.KeyDown += new KeyEventHandler(Form1_KeyDown); this.Controls.Add(pictureBox1); } private void Form1_Load(object sender, EventArgs e) { //1~15のリストを作りランダムにソート //盤面の左上から順番に値をセット Random rnd = new Random(); do { List<int> list = new List<int>(); for(int i = 1; i <= 15; i++) { list.Add(i); } list.Sort( (a, b) => { if(a == b) return 0; return rnd.Next(0, 2) == 0 ? -1 : 1; } ); for(int y = 0; y < 4; y++) { for(int x = 0; x < 4; x++) { table[x, y] = list[list.Count - 1]; list.RemoveAt(list.Count - 1); if(list.Count == 0) break; } } } while(!verification()); //解ける盤面になっているかをチェックして、ダメなら作り直し } //ユーザーのキー入力を処理 private void Form1_KeyDown(object sender, KeyEventArgs e) { switch(e.KeyCode) { case Keys.Up: if(selectCell.Y > 0) selectCell.Y--; break; case Keys.Down: if(selectCell.Y < 3) selectCell.Y++; break; case Keys.Right: if(selectCell.X < 3) selectCell.X++; break; case Keys.Left: if(selectCell.X > 0) selectCell.X--; break; case Keys.Enter: case Keys.Space: slide(); break; } pictureBox1.Refresh(); judge();//解けているかどうか判定 }