ゲームの初めにタイルをランダムに配置するメソッドを作る
前回の記事では、15パズルのプログラムの基本的な機能を完成させたところまで進みました。今回はその続きです。まずはゲーム開始時にタイルをランダムに配置するメソッドを作りましょう(プログラムを実行して、初めからタイルの位置が並んでいてはパズルになりませんからね)。メソッド名はgameInitialize()とします。また、このメソッドではランダム値を使いたいので、Randomクラスのインスタンスを作成するコードをForm1クラスに記述します。gameInitialize()メソッドもForm1クラスに次のように記述します。
リスト1:RandomクラスのインスタンスとgameInitalize()メソッド
1 | Random myRandom = new System.Random(); |
2 | private void gameInitialize() |
gameInitialize()メソッドの中身を作りましょう。ボタンの位置を交換するメソッドはカスタムボタンのMove()メソッドでした。()内の引数に、位置を交換したい相手のカスタムボタンオブジェクトを与えるものでした。たとえば12番のボタンを15番のボタンと位置交換するコードは、myCustomButton[12].Move(myCustomButton[15])のようにすればよいのでした。ランダムな数字を得るには、ランダムクラスのNext()メソッドを使います。たとえばmyRandomオブジェクトで0以上15未満のランダムな値を得るには、myRandom.Next(0, 15)とします。
ランダムにタイルの位置を交換するには、カスタムボタン配列の添え字の番号をランダムにすればよいので、gameInitialize()メソッドのコードは次のようになります。ランダムに位置を交換した後、移動可能を判定するsetMovable();メソッドも実行しています。
リスト2:gameInitialize()メソッドの内容
1 | private void gameInitialize() |
3 | for (int i = 0; i < 30; i++) |
5 | myCustomButton[myRandom.Next(0, 15)].Move(myCustomButton[15]); |
gameInitialize()メソッドができたら、このメソッドがフォームの起動時に実行されるように、Form1_Load()メソッドにgameInitialize();を記述します。ここまでできたら、Visual Studioで緑の三角「開始」ボタンをクリックするか、「デバッグ」メニューの「デバッグの開始」でビルドしてプログラムを実行します。実行するとボタンのいくつかがランダムに位置交換されてゲーム開始となります。
ランダムに位置を交換するコードはfor文で繰り返す構造になっています。ここではデバッグをしやすくするために、繰り返す回数を30回と少なめにしています。この回数では、次の実行結果のように、全体のタイルの位置が大きく変わることなく、右下の空欄に近いところのタイル数個の位置が変わるだけになります。デバッグが終わればfor文の繰り返し回数を増やすことにします。実行したらタイルをクリックしてパズルを完成させてみましょう。
プログラム開始時にgameInitialize()メソッドを実行してパズルを始める
ここまでのコードは次のようになります。
リスト3:ここまでのコード全体(expand sourceをクリックで表示)
002 | using System.Collections.Generic; |
003 | using System.ComponentModel; |
008 | using System.Threading.Tasks; |
009 | using System.Windows.Forms; |
011 | namespace _15puzzle_objective_Text |
013 | public partial class Form1 : Form |
015 | CustomButton[] myCustomButton; |
016 | Random myRandom = new System.Random(); |
020 | InitializeComponent(); |
023 | private void Form1_Load(object sender, EventArgs e) |
025 | this.ClientSize = new Size(400, 400); |
026 | myCustomButton = new CustomButton[16]; |
028 | for (int i = 0; i < 16; i++) |
030 | myCustomButton[i] = new CustomButton(); |
031 | myCustomButton[i].Click += myCustomButton_Click; |
032 | this.Controls.Add(myCustomButton[i]); |
033 | myCustomButton[i].Initialize(i); |
036 | myCustomButton[15].Visible = false; |
042 | private void myCustomButton_Click(object sender, EventArgs e) |
044 | ((CustomButton)sender).Move(myCustomButton[15]); |
049 | private void setMovable() |
051 | foreach (CustomButton allCustomButton in myCustomButton) |
053 | if ((allCustomButton.Top == myCustomButton[15].Top & Math.Abs(allCustomButton.Left - myCustomButton[15].Left) == 100 | (allCustomButton.Left == myCustomButton[15].Left & Math.Abs(allCustomButton.Top - myCustomButton[15].Top) == 100))) |
055 | allCustomButton.isMovable = true; |
059 | allCustomButton.isMovable = false; |
062 | allCustomButton.Text = allCustomButton.Name + allCustomButton.isMovable + allCustomButton.Position;//テスト用のコード |
065 | private void gameInitialize() |
067 | for (int i = 0; i < 30; i++) |
069 | myCustomButton[myRandom.Next(0, 15)].Move(myCustomButton[15]); |
074 | class CustomButton : Button |
076 | public string Position; |
077 | public bool isMovable; |
079 | public CustomButton() |
083 | this.Font = new Font("Arial", 20); |
084 | this.isMovable = false; |
086 | public void Initialize(int i) |
088 | this.Name = (i + 1).ToString(); |
089 | this.Position = (i + 1).ToString(); |
090 | this.Text = (i + 1).ToString(); |
092 | this.Top = (i / 4) * 100; |
093 | this.Left = (i % 4) * 100; |
094 | this.Text = this.Name + this.isMovable + this.Position;//テスト用のコード |
097 | public void Move(CustomButton cb) |
099 | if (this.isMovable == true) |
105 | tempLeft = this.Left; |
106 | tempPosition = this.Position; |
109 | this.Position = cb.Position; |
112 | cb.Position = tempPosition; |
パズルの完成をチェックするcheckComplete()メソッドを作る
次にパズルの完成を判定させましょう。パズルの完成は、カスタムボタンクラスに定義したPositionフィールドの値で判定します。パズルの完成は、1番のタイルのPositionが「1」に、2番のタイルのPositionが「2」に、というように、すべてのボタンの番号とPositionフィールドの値が一致したときと判定できます。カスタムボタンは配列なので、foreach文で一括処理をすることができます。これがオブジェクト指向プログラミングの便利なところですね。
次のforeachステートメントは、myCustomButton配列のすべての要素に対して、CustomButtonクラスのallCustomButtonという名前で処理をするコードです。
リスト4:foreachステートメントですべてのボタンに対して処理を行う
1 | foreach (CustomButton allCustomButton in myCustomButton) |
すべてのボタンの番号とPositionフィールドの値が一致すればパズル完成です。メソッドの名前はcheckComplete()とします。次のコードではローカル変数int complete = 0;を定義し、foreach文で値が一致するタイルの位置を数えます。Completeの値が16になれば全部のタイルが正しい位置にあると判定できるので、メッセージボックスで「Complete!」を表示します。
リスト5:checkComplete()メソッド
01 | private void checkComplete() |
05 | foreach (CustomButton allCustomButton in myCustomButton) |
07 | if (Convert.ToInt16(allCustomButton.Name) == Convert.ToInt16(allCustomButton.Position)) |
15 | MessageBox.Show("Complete!"); |
最後に、ボタンをクリックするたびにパズル完成を判定するため、myCustomButton_Click()メソッドにこのcheckComplete();を記述します。これで15パズルゲームは完成です。Visual Studioで緑の三角「開始」ボタンをクリックするか、「デバッグ」メニューの「デバッグの開始」でビルドしてプログラムを実行します。タイルをクリックで移動し、パズルを完成させてください。ここまでのコードは次のようになります。
リスト6:ここまでのコード全体(expand sourceをクリックで表示)
002 | using System.Collections.Generic; |
003 | using System.ComponentModel; |
008 | using System.Threading.Tasks; |
009 | using System.Windows.Forms; |
011 | namespace _15puzzle_objective_Text |
013 | public partial class Form1 : Form |
015 | CustomButton[] myCustomButton; |
016 | Random myRandom = new System.Random(); |
020 | InitializeComponent(); |
023 | private void Form1_Load(object sender, EventArgs e) |
025 | this.ClientSize = new Size(400, 400); |
026 | myCustomButton = new CustomButton[16]; |
028 | for (int i = 0; i < 16; i++) |
030 | myCustomButton[i] = new CustomButton(); |
031 | myCustomButton[i].Click += myCustomButton_Click; |
032 | this.Controls.Add(myCustomButton[i]); |
033 | myCustomButton[i].Initialize(i); |
036 | myCustomButton[15].Visible = false; |
043 | private void myCustomButton_Click(object sender, EventArgs e) |
045 | ((CustomButton)sender).Move(myCustomButton[15]); |
052 | private void setMovable() |
054 | foreach (CustomButton allCustomButton in myCustomButton) |
056 | if ((allCustomButton.Top == myCustomButton[15].Top & Math.Abs(allCustomButton.Left - myCustomButton[15].Left) == 100 | (allCustomButton.Left == myCustomButton[15].Left & Math.Abs(allCustomButton.Top - myCustomButton[15].Top) == 100))) |
058 | allCustomButton.isMovable = true; |
062 | allCustomButton.isMovable = false; |
065 | allCustomButton.Text = allCustomButton.Name + allCustomButton.isMovable + allCustomButton.Position;//テスト用のコード |
069 | private void gameInitialize() |
071 | for (int i = 0; i < 30; i++) |
073 | myCustomButton[myRandom.Next(0, 15)].Move(myCustomButton[15]); |
078 | private void checkComplete() |
082 | foreach (CustomButton allCustomButton in myCustomButton) |
084 | if (Convert.ToInt16(allCustomButton.Name) == Convert.ToInt16(allCustomButton.Position)) |
092 | MessageBox.Show("Complete!"); |
097 | class CustomButton : Button |
099 | public string Position; |
100 | public bool isMovable; |
102 | public CustomButton() |
106 | this.Font = new Font("Arial", 20); |
107 | this.isMovable = false; |
110 | public void Initialize(int i) |
112 | this.Name = (i + 1).ToString(); |
113 | this.Position = (i + 1).ToString(); |
114 | this.Text = (i + 1).ToString(); |
116 | this.Top = (i / 4) * 100; |
117 | this.Left = (i % 4) * 100; |
118 | this.Text = this.Name + this.isMovable + this.Position;//テスト用のコード |
121 | public void Move(CustomButton cb) |
123 | if (this.isMovable == true) |
129 | tempLeft = this.Left; |
130 | tempPosition = this.Position; |
133 | this.Position = cb.Position; |
136 | cb.Position = tempPosition; |
コードを整理してパズルを完成させる
最後にデバッグ用のコードの前に「//」をつけて、次のようにコメントアウトします。もちろん、最終的にデバッグの必要がなくなれば行を消してもかまいません。
リスト7:デバッグ用コードをコメントアウト
1 | (setMovable()メソッドにあるテスト用のコード) |
3 | //allCustomButton.Text = allCustomButton.Name + allCustomButton.isMovable + allCustomButton.Position;//テスト用のコード |
5 | (Initialize()メソッドにあるテスト用のコード) |
6 | //this.Text = this.Name + this.isMovable + this.Position;//テスト用のコード |
また、開始時に位置をランダムに交換する回数をfor文で決めていますが、この数を増やしましょう。次のコードでは、デバッグ時に30回だったgameInitialize()のfor文を3000回に増やしています。
リスト8:開始時のボタン交換回数を増やす
1 | for (int i = 0; i < 3000; i++) |
最後にボタンの数字を少し大きく表示するように変えましょう。ボタンのフォントはCustomButtonクラスのthis.Font = new Font("Arial", 20);で定義しています。このコードを次のように変えて、フォントサイズを40にします。
リスト9:ボタンのフォントを大きく
1 | this.Font = new Font("Arial", 40); |
Visual Studioで緑の三角「開始」ボタンをクリックするか、「デバッグ」メニューの「デバッグの開始」でビルドしてプログラムを実行します。タイルをクリックで移動し、パズルを完成させてください。完成すると「Complete!」のメッセージボックスが出て完了です。次の画面は完成した15パズルを実行したところです。
完成版の15パズルを実行したところ
ここまでのコードは次のようになります。
リスト10:完成版のコード全体(expand sourceをクリックで表示)
002 | using System.Collections.Generic; |
003 | using System.ComponentModel; |
008 | using System.Threading.Tasks; |
009 | using System.Windows.Forms; |
011 | namespace _15puzzle_objective_Text |
013 | public partial class Form1 : Form |
015 | CustomButton[] myCustomButton; |
016 | Random myRandom = new System.Random(); |
020 | InitializeComponent(); |
023 | private void Form1_Load(object sender, EventArgs e) |
025 | this.ClientSize = new Size(400, 400); |
026 | myCustomButton = new CustomButton[16]; |
028 | for (int i = 0; i < 16; i++) |
030 | myCustomButton[i] = new CustomButton(); |
031 | myCustomButton[i].Click += myCustomButton_Click; |
032 | this.Controls.Add(myCustomButton[i]); |
033 | myCustomButton[i].Initialize(i); |
036 | myCustomButton[15].Visible = false; |
043 | private void myCustomButton_Click(object sender, EventArgs e) |
045 | ((CustomButton)sender).Move(myCustomButton[15]); |
052 | private void setMovable() |
054 | foreach (CustomButton allCustomButton in myCustomButton) |
056 | if ((allCustomButton.Top == myCustomButton[15].Top & Math.Abs(allCustomButton.Left - myCustomButton[15].Left) == 100 | (allCustomButton.Left == myCustomButton[15].Left & Math.Abs(allCustomButton.Top - myCustomButton[15].Top) == 100))) |
058 | allCustomButton.isMovable = true; |
062 | allCustomButton.isMovable = false; |
065 | //allCustomButton.Text = allCustomButton.Name + allCustomButton.isMovable + allCustomButton.Position;//テスト用のコード |
069 | private void gameInitialize() |
071 | for (int i = 0; i < 3000; i++) |
073 | myCustomButton[myRandom.Next(0, 15)].Move(myCustomButton[15]); |
078 | private void checkComplete() |
082 | foreach (CustomButton allCustomButton in myCustomButton) |
084 | if (Convert.ToInt16(allCustomButton.Name) == Convert.ToInt16(allCustomButton.Position)) |
092 | MessageBox.Show("Complete!"); |
097 | class CustomButton : Button |
099 | public string Position; |
100 | public bool isMovable; |
102 | public CustomButton() |
106 | this.Font = new Font("Arial", 40); |
107 | this.isMovable = false; |
110 | public void Initialize(int i) |
112 | this.Name = (i + 1).ToString(); |
113 | this.Position = (i + 1).ToString(); |
114 | this.Text = (i + 1).ToString(); |
116 | this.Top = (i / 4) * 100; |
117 | this.Left = (i % 4) * 100; |
118 | //this.Text = this.Name + this.isMovable + this.Position;//テスト用のコード |
121 | public void Move(CustomButton cb) |
123 | if (this.isMovable == true) |
129 | tempLeft = this.Left; |
130 | tempPosition = this.Position; |
133 | this.Position = cb.Position; |
136 | cb.Position = tempPosition; |
終わりに
いかがでしたか。オブジェクト指向を意識しなくてもVisual Studioを使ってC#のプログラムを作ることはできます。しかしこの記事で紹介した15パズル程度の簡単なプログラムでも、オブジェクト指向を意識して作ると、似たコードを繰り返し書く必要のない、合理的でわかりやすいプログラムになります。また縦横4×4のパズルを5×5など大きなサイズに変更することも簡単です。見栄えをよくするにはタイルの色を変更するなどデザインを工夫し、完成した時のメッセージを派手にするといいでしょう。またゲーム性を高めるなら、何回のクリックで完成できたかをカウントしてもよいでしょうし、時間を測って競うのもよいですね。またタイマーオブジェクトを使って、ある決めた時間内に完成させるようにしてもおもしろそうです。オブジェクト指向を身に着けて、いろいろなプログラミングにチャレンジしてください。