代码改变世界

C#游戏满堂红

2012-04-08 18:45  精诚所至 金石为开  阅读(695)  评论(0编辑  收藏  举报

本实例创建一个类似于扫雷的小游戏,将途中所有方格变成红色,可赢得胜利,程序运行窗口如下所示。

20120409184306

程序CS文件代码如下。

using System;
using System.Windows.Forms;
using System.Drawing;
using System.IO;
class MainForm:Form
{
	private const int BUTTON_COUNT=25;
	private int SQUARE_ROOT=Convert.ToInt32(Math.Sqrt(BUTTON_COUNT));
	private int PART_COUNT=2*Convert.ToInt32(Math.Sqrt(BUTTON_COUNT));
	private Button[] btn=new Button[BUTTON_COUNT];
	private Label lblAim;
	private int count=0;
	private string step="";
	public MainForm()
	{
		this.Left=0;
		this.Top=0;
		this.MaximizeBox=false;
		this.FormBorderStyle=FormBorderStyle.Fixed3D;
		this.Text="满堂红";
		for(int i=0;i<BUTTON_COUNT;i++)
		{
			btn[i]=new Button();
			btn[i].Width=this.ClientSize.Width/PART_COUNT;
			btn[i].Height=this.ClientSize.Height/PART_COUNT;
			btn[i].Left=this.ClientSize.Width/PART_COUNT+2*(i%SQUARE_ROOT)*this.ClientSize.Width/PART_COUNT;
			btn[i].Top=this.ClientSize.Height/PART_COUNT+2*(i/SQUARE_ROOT)*this.ClientSize.Height/PART_COUNT;
			btn[i].BackColor=Color.Blue;
			btn[i].Text=Convert.ToString(i+1);
			btn[i].Click+=new EventHandler(btn_Click);
			btn[i].Tag=0;
			this.Controls.Add(btn[i]);
		}
		lblAim=new Label();
		lblAim.Width=this.ClientSize.Width;
		lblAim.Text="请把所有按钮变红!,要快哦!";
		this.Controls.Add(lblAim);
	}
	public void btn_Click(object sender,EventArgs eArgs)
	{
		int i=Convert.ToInt32(((Button)sender).Text)-1;
		ChangeButtonState(i);
		ChangeButtonState((i/SQUARE_ROOT)*SQUARE_ROOT+(i+1)%SQUARE_ROOT);
		ChangeButtonState((i/SQUARE_ROOT)*SQUARE_ROOT+(i+SQUARE_ROOT-1)%SQUARE_ROOT);
		ChangeButtonState((i-SQUARE_ROOT+BUTTON_COUNT)%BUTTON_COUNT);
		count++;
		if(CheckForWin()==true)
		{
			WonTheGame();
		}
	}
	private void ChangeButtonState(int i)
	{
		if(Convert.ToInt32(btn[i].Tag)==0)
		{
			btn[i].Tag=1;
			btn[i].BackColor=Color.Red;
		}
		else
		{
			btn[i].Tag=0;
			btn[i].BackColor=Color.SeaGreen;
		}
	}
	private bool CheckForWin()
	{
		for (int i=0;i<BUTTON_COUNT;i++)
		{
			if (Convert.ToInt32(btn[i].Tag)==0)
			{
				return false;
			}
		}
		return true;
	}
	private void WonTheGame()
	{
		MessageBox.Show("恭喜,你赢了!真聪明!\n共用了"+count.ToString()+"步\n步骤为"+step,"恭喜!!!",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
		for(int i=0;i<BUTTON_COUNT;i++)
		{
			btn[i].Click+=new EventHandler(btn_Click);
		}
		FileStream outputfile=null;
		outputfile=new FileStream("step.txt",FileMode.Create,FileAccess.Write);
		StreamWriter writer=new StreamWriter(outputfile);
		writer.BaseStream.Seek(0,SeekOrigin.End);
		writer.WriteLine(step);
		writer.Flush();
		writer.Close();
	}
	public static void Main(string[] args)
	{
		Application.Run(new MainForm());
	}
}