C#實(shí)現(xiàn)十五子游戲
更新時(shí)間:2017年05月09日 08:42:10 作者:vettel_wang
這篇文章主要為大家詳細(xì)介紹了C#實(shí)現(xiàn)十五子游戲的相關(guān)代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
最近由于工作需要,做一個(gè)C#的簡單程序。學(xué)習(xí)了一些基礎(chǔ)東西先記下來。
主要有:
1.生成初始框架
2.打亂順序
3.游戲部分,點(diǎn)擊按鈕后與空白部分交換的只是Text和Visible部分
const int N = 4; //行列數(shù) Button[,] buttons = new Button[N, N]; private void Form1_Load(object sender, EventArgs e) { //產(chǎn)生所有按鈕 GenerateAllButtons(); } private void button1_Click(object sender, EventArgs e) { //打亂順序 Shuffle(); } //生成按鈕 void GenerateAllButtons() { int x0 = 100, y0 = 10, w = 45, d = 50; for( int row = 0; row < N; row++ ) for ( int col = 0; col < N; col++ ) { int num = row * N + col; //數(shù)字編號(hào) Button btn = new Button(); btn.Text = (num + 1).ToString(); btn.Top = y0 + row * d; btn.Left = x0 + col * d; btn.Width = w; btn.Height = w; btn.Visible = true; btn.Tag = row * N + col; //button位置 //注冊(cè)button點(diǎn)擊事件 btn.Click += new EventHandler(btn_Click); buttons[row, col] = btn; this.Controls.Add(btn); } buttons[N - 1, N - 1].Visible = false; } void Shuffle() { Random rnd = new Random(); for (int i = 0; i < 100; i++ ) { int a = rnd.Next(N); int b = rnd.Next(N); int c = rnd.Next(N); int d = rnd.Next(N); Swap(buttons[a, b], buttons[c, d]); } } // 進(jìn)行游戲 private void btn_Click(object sender, EventArgs e) { Button btn = sender as Button; Button blank = FindHiddenButton(); // 判斷是否相鄰 if ( IsNeighbor(btn, blank) ) { Swap(btn, blank); blank.Focus(); } // 判斷是否完成 if ( ResultIsOk() ) { MessageBox.Show("OK!"); } } // 查找空白按鈕 Button FindHiddenButton() { for (int row = 0; row < N; row++) for (int col = 0; col < N; col++) { if (!buttons[row,col].Visible) { return buttons[row, col]; } } return null; } // 判斷是否相鄰 bool IsNeighbor(Button btnA, Button btnB) { int a = (int)btnA.Tag; int b = (int)btnB.Tag; int r1 = a / N, c1 = a % N; int r2 = b / N, c2 = b % N; if ( (r1 == r2 && (c1 == c2 + 1 || c1 == c2 - 1)) || (c1 == c2 && (r1 == r2 + 1 || r1 == r2 - 1)) ) return true; return false; } //檢查是否完成 bool ResultIsOk() { for (int r = 0; r < N; r++) for (int c = 0; c < N; c++) { if (buttons[r, c].Text != (r * N + c + 1).ToString()) { return false; } } return true; } //交換兩個(gè)按鈕 void Swap(Button btna, Button btnb) { string t = btna.Text; btna.Text = btnb.Text; btnb.Text = t; bool v = btna.Visible; btna.Visible = btnb.Visible; btnb.Visible = v; }
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Unity游戲開發(fā)實(shí)現(xiàn)背包系統(tǒng)的示例詳解
這篇文章主要為大家介紹了Unity游戲開發(fā)實(shí)現(xiàn)背包系統(tǒng)的示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08c#獲取字符串寬度的示例代碼(字節(jié)數(shù)方法)
本篇文章主要介紹了c#獲取字符串寬度的示例代碼(字節(jié)數(shù)方法)。需要的朋友可以過來參考下,希望對(duì)大家有所幫助2014-01-01