標籤:c#
一個小時候經常玩的遊戲:
通過只移動空白處周圍的小方塊 最終將所有方塊移動到目標位置即完成遊戲
程式的邏輯並不難:
1.初始化所有(4X4)按鈕屬性(位置 ,大小,標號,是否可見) 和方法(點擊按鈕 交換),並按順序排列
2.點擊洗牌 開始遊戲 (通過隨機交換任意兩個按鈕X次)
3.每次點擊某個按鈕 判斷是否在隱藏按鈕周圍,在周圍則交換這兩個按鈕,否則無反應
4.每次點擊按鈕 判斷所有按鈕是否達到目標位置,達到則彈出訊息視窗
Project是 Windows form Application
代碼:
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 WindowsFormsApplication3{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } const int N = 4; Button[,] buttons = new Button[N, N]; //建立N X N大小的按鈕數組 void swap(Button btn1, Button btn2) //交換兩個按鈕 實際上只需要交換兩個屬性(顯示的標號Text,是否可見Visible)即可 { string str1 = btn1.Text; btn1.Text = btn2.Text; btn2.Text = str1; bool a = btn1.Visible; btn1.Visible = btn2.Visible; btn2.Visible = a; } private void button1_Click(object sender, EventArgs e) //點擊開始按鈕 { for (int i = 0; i < 1000; i++) //隨機交換兩個按鈕 1000次實現洗牌 { Random rnd = new Random(); int a, b, c, d; a = rnd.Next(N); //產生四個不大於N的隨機數 b = rnd.Next(N); c = rnd.Next(N); d = rnd.Next(N); swap(buttons[a, b], buttons[c, d]); } } Button FindHiddenButton() //找到那個沒顯示的按鈕 { int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) if (buttons[i, j].Visible == false) return buttons[i, j]; 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 btn_Click(object sender, EventArgs e) //點擊某個按鈕 { Button btn = sender as Button; //當前點中的按鈕 Button blank = FindHiddenButton(); if (IsNeighbor(btn, blank)) { swap(btn, blank); blank.Focus(); //duang 給"移動"的格子加特效 } //判斷是否完成了 if (ResultIsOk()) { MessageBox.Show("You Win"); //彈出訊息窗 } } void GenerateAllButtons() //產生所有按鈕 { int x0 = 100, y0 = 10, wid1 = 50, wid2 = 45; for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) { Button btn = new Button(); btn.Top = y0 + i * wid1; btn.Left = x0 + j * wid1; btn.Width = wid2; btn.Height = wid2; btn.Visible = true; btn.Text = (i * N + j + 1).ToString(); //初始化按鈕所有屬性 btn.Tag = i * N + j; //儲存行號 列號 btn.Click += new EventHandler(btn_Click); buttons[i, j] = btn; //放到數組上 this.Controls.Add(btn); //加到介面上 } buttons[N - 1, N - 1].Visible = false; } private void Form1_Load(object sender, EventArgs e) //初始化 { GenerateAllButtons(); } }}
排塊遊戲 (c#實現)