// ■数当てゲーム // // label1, label2, textBox1, timer1をフォームに割り当てます。 // 背景色、文字色、文字表示位置は、好みに合わせて設定しておきます。 // timer1は、label1の文字を電光掲示板風に動かしたり、 // label2の文字をブリンキングするために用意します。 // Form1のForm1_MouseClickを設定しておきます。 // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace guessNumber { public partial class Form1 : Form { public Random rn = new Random(); // 乱数オブジェクト  public int Count = 0; // 答えた回数 public int Ans; // 解答(乱数で決める) public Image image = new Bitmap(1000, 1000); // 描画用ビットマップ public Graphics g; Brush brush = new SolidBrush(Color.LightGray); // ボタン表面 Brush bBlack = new SolidBrush(Color.Black); // 黒塗り潰し(文字用) Pen pWhite = new Pen(Color.White); // 白色ペン(ボタン上部) Pen pGray = new Pen(Color.DarkGray); // 暗い灰色ペン(ボタン陰影部) Font f = new Font(FontFamily.GenericSansSerif, 30, FontStyle.Bold);// 文字フォント public Form1() { InitializeComponent(); } protected override void OnPaint(PaintEventArgs e) // OnPaint オーバライド { base.OnPaint(e); e.Graphics.DrawImage(image, 50, 50); } private void Form1_Load(object sender, EventArgs e) // フォームのロード時処理 { g = Graphics.FromImage(image);g.Clear(this.BackColor); Initialize(); GameStart(); this.Invalidate(); } private void Initialize()//全体初期化 { label1.Text = "0 から 9 の数字を当ててください。 "; for (int i = 0; i < 10; i++) drawButtonLike(i); timer1.Enabled = true; } private void drawButtonLike(int i)//ボタン風の長方形に数字を描く { float X = i * 50, Y = 0; g.FillRectangle(brush, X, Y, 50, 50); //ボタン表面 g.DrawLine(pWhite, X, Y, X + 50, Y); //ボタン上部 g.DrawLine(pWhite, X, Y, X, Y + 50); g.DrawLine(pGray, X, Y + 49, X + 49, Y + 49); //ボタン陰影部 g.DrawLine(pGray, X + 49, Y, X + 49, Y + 49); g.DrawLine(pGray, X, Y + 48, X + 48, Y + 48); g.DrawLine(pGray, X + 48, Y, X + 48, Y + 48); g.DrawString(i.ToString(), f, bBlack, X + 5, Y + 2);//文字描画 } private void GameStart()// ゲーム開始 { Count = 0; Ans = rn.Next(0, 10); textBox1.Text = ""; label2.Text = ""; } private void Form1_MouseClick(object sender, MouseEventArgs e) { if (e.Y < 50 || e.Y >= 100) return;//ボタン表示部以外のとき取り消し int i = (int)(e.X - 50) / 50; if (i < 0 || i > 9) return; textBox1.Text=i.ToString(); if (i == Ans)// 正解のとき { label2.ForeColor = Color.Green; label2.Text = "正解!!"; MessageBox.Show("正解 " + Ans.ToString() + " です。"); GameStart(); } else if (Count >= 2) // 数字が異なっており三回目(ゲームオーバ) { label2.ForeColor = Color.Red; label2.Text = "ゲームオーバ!!"; MessageBox.Show("残念。正解は " + Ans.ToString() + " です。"); GameStart(); } else // 数字が異なっているが3回以内のとき { Count++; label2.ForeColor = Color.Black; if (Ans > i) label2.Text = "もっと大きいです。"; else label2.Text = "もっと小さいです。"; } } private void timer1_Tick(object sender, EventArgs e)// 説明を電光掲示板風に動かし { // コメントをブリンキング String s = label1.Text, sp = s.Substring(0, 1), s2 = s.Substring(1, s.Length - 1); label1.Text = s2 + sp; label2.Visible = ! label2.Visible; } } }