C# Logical Game


Source Code:

using System;
using System.Windows.Forms;
using System.Drawing;
class MainForm : Form
{
private const int BUTTON_COUNT=25; //count of buttons (exact square 16,25,36,49,...)
private int SQUARE_ROOT=Convert.ToInt32(Math.Sqrt(BUTTON_COUNT)); //the square root of the count
private int PART_COUNT=2*Convert.ToInt32(Math.Sqrt(BUTTON_COUNT))+1;
private Button[] btn=new Button[BUTTON_COUNT]; //the array of buttons
private Label lblAim; //the label in the upper left part of the form
public MainForm()
{
//do some form settings
this.Left=0;
this.Top=0;
this.MaximizeBox=false;
this.FormBorderStyle=FormBorderStyle.Fixed3D;
this.Text = "The PressAll GAME";
//make the buttons and put them on the form
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.SeaGreen;
btn[i].Text=Convert.ToString(i+1);
btn[i].Click+=
new EventHandler(btn_Click);
btn[i].Tag=0;
this.Controls.Add(btn[i]);
}
//make the label and put it on the form
lblAim=new Label();
lblAim.Width=
this.ClientSize.Width;
lblAim.Text="All buttons must become RED!";
this.Controls.Add(lblAim);
}
//this function activates when the user clicks on a button
public void btn_Click(object sender, EventArgs eArgs)
{
int i=Convert.ToInt32(((Button)sender).Text)-1;
ChangeButtonState(i);
//pressed button
ChangeButtonState((i/SQUARE_ROOT)*SQUARE_ROOT+(i+1)%QUARE_ROOT); //right button
ChangeButtonState((i/SQUARE_ROOT)*SQUARE_ROOT+(i+SQUARE_ROOT-1)%SQUARE_ROOT); //left button
ChangeButtonState((i+SQUARE_ROOT)%BUTTON_COUNT); //down button
ChangeButtonState((i-SQUARE_ROOT+BUTTON_COUNT)%BUTTON_COUNT); //up button
if (CheckForWin()==true) WonTheGame(); //check whether all the buttons have become RED
}
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()
{
lblAim.Text="Congratulations!!!";
for (int i=0;i<BUTTON_COUNT;i++)
{
btn[i].Click-=
new EventHandler(btn_Click);
}
}
public static void Main(string[] args)
{
Application.Run(
new MainForm());
}
}


Similar Articles