C#實(shí)現(xiàn)十五子游戲
更新時間:2017年05月09日 08:42:10 作者:vettel_wang
這篇文章主要為大家詳細(xì)介紹了C#實(shí)現(xiàn)十五子游戲的相關(guān)代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下
最近由于工作需要,做一個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ù)字編號
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位置
//注冊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;
}
//交換兩個按鈕
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)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#使用SqlSugarClient進(jìn)行數(shù)據(jù)訪問并實(shí)現(xiàn)了統(tǒng)一的批量依賴注入(示例代碼)
M為 BaseDto 請用C# 給出一個案例,支持不同表對應(yīng)不同的業(yè)務(wù)邏輯層,然后不同倉儲實(shí)例,不同表的業(yè)務(wù),都實(shí)現(xiàn)統(tǒng)一的批量依賴注入,下面通過示例給大家演示如何使用SqlSugarClient進(jìn)行數(shù)據(jù)訪問,并實(shí)現(xiàn)了統(tǒng)一的批量依賴注入,感興趣的朋友跟隨小編一起看看吧2024-05-05
C#/VB.NET實(shí)現(xiàn)在 Word 中插入水印?
這篇文章主要介紹了C#/VB.NET實(shí)現(xiàn)在 Word 中插入水印,水印是指在 Word 文檔的背景中以淡色或灰色顯示的文本或圖像。文章圍繞主題展開介紹,需要的朋友可以參考一下2022-08-08
C#構(gòu)造函數(shù)在基類和父類中的執(zhí)行順序
這篇文章介紹了C#構(gòu)造函數(shù)在基類和父類中的執(zhí)行順序,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-04-04

