标签:
推方块小游戏 很有意思的小游戏 mooc 有代码 我还是自己打了一遍 熟悉下C#
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows.Forms; 10 11 namespace WindowsFormsApplication4 12 { 13 public partial class Form1 : Form 14 { 15 public Form1() 16 { 17 InitializeComponent(); 18 } 19 const int N = 4; 20 Button[,] buttons = new Button[N, N]; 21 private void Form1_Load(object sender, EventArgs e) 22 { 23 GenerateAllButtons();//产生按钮 24 } 25 26 private void button1_Click(object sender, EventArgs e) 27 { 28 Shuffle(); //打乱 29 } 30 void GenerateAllButtons() 31 { 32 int X = 130, Y = 50, W = 45, D = 50; 33 for(int r=0;r<N;r++) 34 { 35 for (int c = 0; c < N; c++) 36 { 37 int num = r * N + c; 38 Button btn = new Button(); 39 btn.Text = (num + 1).ToString(); 40 btn.Top = Y + r * D; 41 btn.Left = X + c * D; 42 btn.Width = W; 43 btn.Height = W; 44 btn.Visible = true; 45 btn.Tag = r * N + c; 46 47 btn.Click += new EventHandler(btn_Click); 48 buttons[r, c] = btn; 49 this.Controls.Add(btn); 50 } 51 } 52 buttons[N - 1, N - 1].Visible = false; 53 } 54 55 void Shuffle() 56 { 57 Random ran = new Random(); 58 for(int i=0;i <100;i++) 59 { 60 int a = ran.Next(N); 61 int b = ran.Next(N); 62 int c = ran.Next(N); 63 int d = ran.Next(N); 64 swap(buttons[a, b], buttons[c, d]); 65 } 66 } 67 void swap(Button a,Button b) 68 { 69 string t = a.Text; 70 a.Text = b.Text; 71 b.Text = t; 72 73 bool v = a.Visible; 74 a.Visible = b.Visible; 75 b.Visible = v; 76 } 77 void btn_Click(object sender, EventArgs e) 78 { 79 Button btn = sender as Button; 80 Button blank = FindBlank(); 81 if (IsNear(btn, blank)) 82 { 83 swap(btn, blank); 84 blank.Focus(); 85 } 86 if (resultIsOk()) 87 { 88 MessageBox.Show("congratulation!"); 89 } 90 91 } 92 Button FindBlank() 93 { 94 for (int r = 0; r < N; r++) 95 for (int c = 0; c < N; c++) 96 { 97 if (!buttons[r, c].Visible) 98 { 99 return buttons[r, c]; 100 } 101 } 102 return null; 103 } 104 bool IsNear(Button a, Button b) 105 { 106 int x = (int)a.Tag; 107 int y = (int)b.Tag; 108 if (x / N == y / N && (x % N + 1 == y % N || x % N - 1 == y % N)) 109 return true; 110 if( x % N == y % N && (x/N+1==y/N||x/N-1==y/N)) 111 return true; 112 return false; 113 } 114 bool resultIsOk() 115 { 116 for (int r = 0; r < N; r++) 117 for (int c = 0; c < N; c++) 118 { 119 if (buttons[r, c].Text != (r * N + c + 1).ToString()) 120 { 121 return false; 122 } 123 } 124 return true; 125 } 126 } 127 }
标签:
原文地址:http://www.cnblogs.com/threezj/p/4592567.html