C# C#應用 十五字小遊戲
阿新 • • 發佈:2018-12-14
1.用C#編輯出來一個小遊戲,和小時玩的拼圖遊戲有些類似,還是蠻有趣得到,來和大家分享一下。 2.該十五字遊戲下面有三個按鈕,作用分別為:亂序:打亂上面十五個數字的順序;提交:當你把遊戲恢復到原位後,點提交按鈕,會判斷你的順序對不對,若是正確的,出現“你真棒”字樣,若不正確,不會出現;排序:自動把十五個數字順序排好。 3.程式程式碼如下:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace 十五字遊戲 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } const int N = 4; Button [,] buttons = new Button[N,N]; private void Form1_Load(object sender, EventArgs e) { //產生所有按鈕 GenerateAllButtons(); } void GenerateAllButtons() { int x0 = 100, y0 = 50, w = 45, d = 50; for (int i=0;i<N;i++) { for (int j = 0; j < N; j++) { int number = i * N + j; Button btn = new Button(); btn.Text = (number+1).ToString(); btn.Top = y0 + i*d; btn.Left = x0 + j*d; btn.Width = w; btn.Height = w; btn.Tag = i * N + j; btn.Visible = true; buttons[i, j] = btn; //註冊事件 btn.Click += new EventHandler(btn_Click); this.Controls.Add(btn); } } buttons[N - 1, N - 1].Visible = false; } void btn_Click(Object sender, EventArgs e) { Button btn = sender as Button; Button blank = FindHiddenButton(); //判斷是否相鄰 if (IsNeighbor(btn, blank)) { Swap(btn, blank); blank.Focus(); } } //交換兩個按鈕 void Swap(Button btna,Button btnb) { string s = btna.Text; btna.Text = btnb.Text; btnb.Text = s; bool b = btna.Visible; btna.Visible = btnb.Visible; btnb.Visible = b; } //判斷是否相鄰的函式 bool IsNeighbor(Button btn,Button blank) { int a = (int)btn.Tag; int b = (int)blank.Tag; int c1 = a / N; int d1 = a % N; int c2 = b / N;int d2 = b % N; if ((c1 == c2 && ((d1 == d2 - 1) || (d1 == d2 + 1)))||(d1==d2&&((c1==c2-1)||(c1==c2+1)))) { return true; } return false; } Button FindHiddenButton() { for(int i=0;i<N;i++) { for(int j=0;j<N;j++) { if (buttons[i, j].Visible == false) { return buttons[i, j]; } } } return null; } private void button3_Click(object sender, EventArgs e) { //點選後自動排序 Sort(); GenerateAllButtons(); } void Sort() { Button btn = new Button(); btn.Visible = false; for(int i=0;i<N;i++) { for(int j=0;j<N;j++) { buttons[i, j].Visible = btn.Visible ; } } } private void button1_Click(object sender, EventArgs e) { //點選後隨機亂序 Shuffle(); } void Shuffle() { //多次交換兩個按鈕 Random r = new Random(); for(int i=0;i<100;i++) { int a = r.Next(N); int b = r.Next(N); int c = r.Next(N); int d = r.Next(N); Swap(buttons[a, b], buttons[c, d]); } } private void button2_Click(object sender, EventArgs e) { //判斷是否找回正確順序 if(ResultIsOk()) { MessageBox.Show("你真棒"); } } bool ResultIsOk() { for(int i=0;i<N;i++) { for (int j = 0; j < N; j++) { if (int.Parse(buttons[i, j].Text) != (i*N+j+1)) { return false; } } } return true ; } } }