Thursday, September 27, 2012

Beginner in C#: Helper methods

What's a helper method?

Well, a helper method is a statement that carries with it a big or small piece of code, created by you, to execute them easily in your program

Why to use helper methods in C#?

Using helper method can help you to save time, for example if you need to get the factorial of an integer more than one time in your code, it's better for  you to create a method and call it something like getFact(uint n), with a parameter an unsigned integer.

What are the types of helper methods?

  1. Methods that don't return a value (of type void).
  2. Methods that returns value (of type int, string, Button, bool, etc... it depends on your needs)

Example on C# helper methods:


Number factorial function C#

You can do this function in two ways , using a recursive method or not.

Recursive method C#:

        public static uint getFact(uint n)
        {
            if (n <2) 
                return 1;
           //you don't have to use 'else' here
            return n * getFact(n - 1);
        }

Non-recursive method C#:

        public static uint getFact(uint n)
        {
            uint ans=1;
            for (uint i = 2; i <= n; i++)
                ans *= i;
            return ans;
        }
So now you are ready to create your own helper methods! have a question? Comment on this post.

Tuesday, September 25, 2012

Beginner in C#: using fixed one dimensional Arrays

What is an Array?

An array is simply a place to store an amount of items, that can be used later easily.

Defining a fixed Array

First, you must specify the type of items to store in your array, lets say for example you want to store a list of integers. Then, the number of items (integers) you want to store.
The following code snippet creates an array of 4 integers.
int[] myFirstIntArray = new int[4];

Storing items in your array

In C#, an array index starts at 0, and ends at the array length minus one.
To store data in a predefined array, the basic way, just set the value of each item in your array, using the equal sign!
Let's consider our previous example. we want to store in it the following information:
  1. my age.
  2. my birth-year.
  3. my birth-month.
  4. my birth-day.
The code below will do the task.

myFirstIntArray[0] = 19 ; //19 years old
myFirstIntArray[1] = 1993 ;
myFirstIntArray[2] = 7 ; //July
myFirstIntArray[3] = 21 ;

Of course, you may need to store a big amount of items and you're not gonna put them all one by one, so in this case we usually use the Loops.

A good example: Let's say we want to get the list of the first 100 prime numbers. Here we are going to use a do-While loop.

            int[] primeNbrs = new int[100];
            int number = 2;
            int index=0;
            do
            {
                int i = 2;
                while ((i < number) && (number % i != 0)) i++;
                if (i == number)
                {
                    primeNbrs[index] = number;
                    index++;
                }
                number++;
            } while (index < 100);
If you have any questions, COMMENT!

Friday, September 21, 2012

Beginner in C#: using StreamReader and StreamWriter

Brief Definition

StremReader: used to Read data from a file, such as .txt files.
StremWriter: used to Write data on a file, or even create a new file.

Example

To make things simple lets consider a simple example.
We want to write a C# console application that will EDIT a text file.
The process is as the following:
  1. Reading the old text file
  2. Writing a new one (edited one)
  3. Deleting the original.
Before you start make sure you've added this line above the namespace:
using System.IO;
In the following we suppose that you have a text file in the Debug directory of your project with name "file.txt".

Declarations:
            StreamReader sR = new StreamReader("file.txt");
            StreamWriter sW = new StreamWriter("new.txt");

Writing data in the new.txt file while reading from the file.txt file at the same time.
            while (sR.Peek() != -1) // stops when it reachs the end of the file
            {
                string line = sR.ReadLine();
                // "line" EDITING GOES HERE
                sW.WriteLine(line); // writing the edited line as a new line in the new.txt file
            }

Deleting the old file and rename the new file as the old file's name.
            File.Delete("file.txt");
            File.Move("new.txt", "file.txt");

Finally close the initially declared StreamReader and StreamWriter.
                sR.Close();
                sW.Close();
And that's it! leave your comments.

Beginner in C#: The if statement

The if statement is one of the most important statement in almost all programming languages and in C#.

The main use of it is to specify an action to do but only when a condition of type bool is true.


For example lets make a simple console application that asks the user for an integer number and determines if the number given is an even number or an odd number.

        static void Main(string[] args)
        {
            Console.Write("Enter a number: ");//asking the user to enter a number
            int number = int.Parse(Console.ReadLine());//reading the given number
            if (number % 2 == 0)//if 'number' is a multiple of two
                Console.WriteLine("It's an even number");//Writing the result
            else //this means "if not, do the following.."
                Console.WriteLine("It's an odd number");//Writing the result
            Console.Read();
        }

If (you have a question)
    Leave a comment and I'll answer!

Wednesday, September 19, 2012

Beginner in C#: Understanding loops


What is a loop in programming?


A loop is as statement that helps you to execute a piece of code repeatedly, a known number of times or until a certain condition become true.
For example, if I said I'm going to walk exactly 500 steps, I'm making a loop about one step repeated 500 times. But if I said I'm going to walk until my dad calls me, here I don't know when exactly my dad will calls me, so this is a loop depending on a particular condition: "my dad is calling me", when it becomes true I will stop walking.

Loops in C#


The 3 most frequently used loops in C# are the following:

the "for" loop

The for loop is usually used to repeat a code N times, N could be a variable or a fixed integer (int).
here's how you write it:

int i; // Declaring an integer with the name 'i'
for(i=0;i<N;i++)
{
// YOUR CODE HERE
}

the "while" loop

The while loop is used to repeat an action until the condition (of type bool) becomes true. 
usage:
while(!condition)
{
// YOUR CODE HERE
}

the "do-while" loop

The do-while loop is just like the while, the only difference is that by its usage we ensure that your CODE is executed at least once.
usage:
do
{
// CODE
}while(!condition);
Its equivalent to:
// CODE
while(!condition)
{
// CODE
}

Sunday, September 16, 2012

Date to Date Calculator - Download!

Date to Date Calculator, is a freeware tool that calculates the time duration between two given dates.
You will have the ability to choose the suitable time unit from 7 different units.
  1. Seconds
  2. Minutes
  3. Hours
  4. Days
  5. Weeks
  6. Months
  7. Years

Application's screen-shots


Calculating in days

Calculating in weeks

As you can see, it's very simple to use. Just select the two dates and let the tool do the rest of the work!
I hope you like it my friends..

Download it now!
Download Date-to-Date Calculator

So did you like it? do you have any suggestion? Don't hesitate to leave your comment!

Saturday, September 15, 2012

Creating Tic-Tac-Toe with C# - Part 3 (Final part)

So now we will finalize our project.
In part 2, we created the computer role in the Tic Tac Toe game, but as a dumb.
So now we are going to program the smart playing algorithm in C#.
We will consider two main points in the algorithm:

  1. Do we have a winning play? if yes lets play it and win! No? proceed to step 2.
  2. Check if the opponent has a winning move, block it if yes, continue to step 3 if no.
  3. Play like our old friend from part 2, yes it's the dumb.


HELPER METHODS

the NormalPCWrite method is not that easy, so we are going to create four helper methods.

Get Coordinates

        private void getCoordinates(int p, out int x, out int y)
        {//change the variables x and y to the correct coordinate
            switch (p)
            {
                case 1: x = 0; y = 0; break;
                case 2: x = 0; y = 1; break;
                case 3: x = 0; y = 2; break;
                case 4: x = 1; y = 0; break;
                case 5: x = 1; y = 1; break;
                case 6: x = 1; y = 2; break;
                case 7: x = 2; y = 0; break;
                case 8: x = 2; y = 1; break;
                default: x = 2; y = 2; break;
            }
        }

Clicked (+1 overload)

private bool clicked(int index)
        {//true if it was clicked, false if it's still clickable
            return (ButtonsIndexs.IndexOf(index.ToString()) == -1);
        }
private bool clicked(int index,string p)
        {//checks if "p" is written on the button with index "index"
            int a,b;
            switch(index){
                case 1:a=0;b=0;break;
                case 2:a=0;b=1;break;
                case 3:a=0;b=2;break;
                case 4:a=1;b=0;break;
                case 5:a=1;b=1;break;
                case 6:a=1;b=2;break;
                case 7:a=2;b=0;break;
                case 8:a=2;b=1;break;
                default:a=2;b=2;break;
                    }
            if (p == "X")
                return (X[a, b]);
            return (O[a, b]);
        }

Write_buttonIndex

private void Write_buttonIndex(int index, string toWrite)
        {//Writing 'toWrite' in a button by knowing its index p
            switch (index)
            {
                case 1: Write(toWrite, button1); break;
                case 2: Write(toWrite, button2); break;
                case 3: Write(toWrite, button3); break;
                case 4: Write(toWrite, button4); break;
                case 5: Write(toWrite, button5); break;
                case 6: Write(toWrite, button6); break;
                case 7: Write(toWrite, button7); break;
                case 8: Write(toWrite, button8); break;
                default: Write(toWrite, button9); break;
            } 
        }

check

        private bool check(int i, int k, string toCheck,string toWrite)
        {
            //k=1 for rows, k=3 for columns, k=5-i for diagonals
            string P = (toWrite == "X") ? "O" : "X";
            if ((clicked(i,toCheck) && clicked(i+k,toCheck) && !clicked(i + k + k)))
            {
                getCoordinates(i + k + k, out x, out y);
                Write_buttonIndex(i + k + k, toWrite);
                return true;
            }
            if ((clicked(i,toCheck) && clicked(i+k+k,toCheck) && !clicked(i + k)))
            {
                getCoordinates(i + k, out x, out y);
                Write_buttonIndex(i + k, toWrite);
                return true;
            }
            if ((clicked(i+k,toCheck) && clicked(i+k+k,toCheck) && !clicked(i)))
            {
                getCoordinates(i, out x, out y);
                Write_buttonIndex(i, toWrite);
                return true;
            }
            return false;
        }

Please read the helper methods carefully to understand well how they work. Now Finally lets write the NormalPCWrite method!

Normal level method

private void NormalPCWrite(string p)
        { 
            string q = (p == "X") ? "O" : "X";
            //Lets check if we can win
            if (!check(1, 1, p, p))
                if (!check(4, 1, p, p))
                    if (!check(7, 1, p, p))
                        if (!check(1, 3, p, p))
                            if (!check(2, 3, p, p))
                                if (!check(3, 3, p, p))
                                    if (!check(1, 4, p, p))
                                        if (!check(3, 2, p, p))
                                            if (!check(1, 1, q, p))
                                                //It seems that we can't, let's defend
                                                if (!check(4, 1, q, p))
                                                    if (!check(7, 1, q, p))
                                                        if (!check(1, 3, q, p))
                                                            if (!check(2, 3, q, p))
                                                                if (!check(3, 3, q, p))
                                                                    if (!check(1, 4, q, p))
                                                                        if(!check(3, 2, q, p))
                                                                            //play randomly
                                                                        EasyPCWrite(p);   
        }
Note: this is not the best playing, as we can create a more smarter algorithm, which will avoid and even try to create TRAPS. Maybe you can do it? try to add one more difficulty, the Unbeatable.

For the best performance, please edit some of our previously created methods.

EDIT: resetVars()

private void resetVars()
        {
            ButtonsIndexs = "123456789";
            finished = false;
            rnd = new Random();
            O = new bool[3, 3];
            X = new bool[3, 3];
        }

EDIT: Form3_Load()

        private void Form3_Load(object sender, EventArgs e)
        {
            difficulity = 0;
            resetVars();
        }

EDIT: back_Click()

private void back_Click(object sender, EventArgs e)
        {
            if (difficulity == 0)
                easyRB.Checked = true;
            else
                normalRB.Checked = true;
            playAgainButton.PerformClick();
            xLabel.Text = oLabel.Text = "0";
            tableLayoutPanel1.Visible = false;
            this.Size = new Size(229, 300);
        }
If you are working  with me, you probably noticed while debugging, that if you click the close button (X) of the form, the debugger doesn't stop.
That's because you are closing a single form, while previous ones are hidden.
To solve this and to end the application process when the user click the (X) button, go to each form, look for an event called Form closing. double click it and add this line of code:
Application.Exit();
Finally we are done! I wish you enjoyed this tutorial, go play some Tic Tac Toe now ;) see you later..

Friday, September 14, 2012

Creating Tic-Tac-Toe with C# - Part 2

In the previous part of this tutorial, we created the Tic Tac Toe game for two players.
Now in Part-2 we will add the option to let the user Play against the computer.
So open your project and let's continue building..

Create a new form

Add a new Form to your project.
Tic Tac Toe
Leave its name to Form3, If you don't know how to add a new form check this: Creating Tic-Tac-Toe with C# - Part 1

Design

Add buttons, labels, radioButtons to make it look close to the picture on the right.

Naming:

change the name of your created buttons and radioButtons to:
XButtonOButtoneasyRBnormalRB, backButton.
We are going to use these names in our code later..

You can customize the design as you want, but here I just want to make a practical game, i'm not a Designer.

I forgot to change the Text property of the form,  change it to Tic Tac Toe or something else...
Tic Tac Toe


Now go to Form2 Design, select the tableLayoutPanel1 copy it to your clipboard, then paste it in Form3 Design.

The form will  look like the second picture.

Now look at the properties window, and find the Visible property, set it to False. 
Also change the button text from "Reset" to "Play again", it makes more sense, and its name to playAgainButton.

This will hide the game until the user select one of the two Buttons created previously.

In this part, I'm going to write only the Easy difficulty mode.

Coding

Declare some variables in the class of Form3
        bool[,] X, O;
        string player;
        bool finished; // true when the game finish
        int difficulity;
        string ButtonsIndexs; //Indexs of remaining buttons
        int x, y; //coordinate of button
        Random rnd; 
Lets write some helper methods now.

Reset Variables

        private void resetVars()
        {
            ButtonsIndexs = "123456789";
            finished = false;
            rnd = new Random();
            difficulity = 0;
            O = new bool[3, 3];
            X = new bool[3, 3];
        }

Writing on a Button

private void Write(string p, Button targetButton)
        {
            if (p == "O")
            {
                targetButton.ForeColor = Color.Red;
                O[x, y] = true; //the place (x,y) is occupied by an 'O'
            }
            else
            {
                targetButton.ForeColor = Color.Blue;
                X[x, y] = true; //the place (x,y) is occupied by an 'X'
            }
            targetButton.Text = p; //Writing X or O

            //Removing the index of the clicked button from ButtonIndexs
            if (targetButton == button1) 
ButtonsIndexs=ButtonsIndexs.Remove(ButtonsIndexs.IndexOf('1'), 1);
            if (targetButton == button2)
ButtonsIndexs=ButtonsIndexs.Remove(ButtonsIndexs.IndexOf('2'), 1);
            if (targetButton == button3)
ButtonsIndexs=ButtonsIndexs.Remove(ButtonsIndexs.IndexOf('3'), 1);
            if (targetButton == button4)
ButtonsIndexs=ButtonsIndexs.Remove(ButtonsIndexs.IndexOf('4'), 1);
            if (targetButton == button5)
ButtonsIndexs=ButtonsIndexs.Remove(ButtonsIndexs.IndexOf('5'), 1);
            if (targetButton == button6)
ButtonsIndexs=ButtonsIndexs.Remove(ButtonsIndexs.IndexOf('6'), 1);
            if (targetButton == button7)
ButtonsIndexs=ButtonsIndexs.Remove(ButtonsIndexs.IndexOf('7'), 1);
            if (targetButton == button8)
ButtonsIndexs=ButtonsIndexs.Remove(ButtonsIndexs.IndexOf('8'), 1);
            if (targetButton == button9)
ButtonsIndexs=ButtonsIndexs.Remove(ButtonsIndexs.IndexOf('9'), 1);
        }

Easy difficulity, Computer turn

        private void EasyPCWrite(string p)
        {
            // a Random button index (to chose a random free button)
            int index = int.Parse(ButtonsIndexs[rnd.Next(ButtonsIndexs.Length)].ToString());
            switch (index)
            {
                case 1: x = y = 0; Write(p, button1); break;
                case 2: x = 0; y = 1; Write(p, button2); break;
                case 3: x = 0; y = 2; Write(p, button3); break;
                case 4: x = 1; y = 0; Write(p, button4); break;
                case 5: x = 1; y = 1; Write(p, button5); break;
                case 6: x = 1; y = 2; Write(p, button6); break;
                case 7: x = 2; y = 0; Write(p, button7); break;
                case 8: x = 2; y = 1; Write(p, button8); break;
                case 9: x = 2; y = 2; Write(p, button9); break;
            }
        }

Normal difficulty, Computer turn

        private void NormalPCWrite(string p)
        { 
           //Coming in Part 3
        }

Checking if any diagonal wins

        private bool Diagonals(bool[,] current)
        {
            return (
                (current[0, 0] && current[1, 1] && current[2, 2])
                ||
                (current[0, 2] && current[1, 1] && current[2, 0])
                );
        }

Checking if any row wins

        private bool Row(int p, bool[,] current)
        {
            return (current[p, 0] && current[p, 1] && current[p, 2]);
        }

Checking if any column wins

        private bool Column(int p, bool[,] current)
        {
            return (current[0, p] && current[1, p] && current[2, p]);
        }

Checking for win or Draw

 
private bool CheckForWinOrDraw(bool[,] current)
        {
            if (Row(0, current) || Row(1, current) || Row(2, current) || Column(0, current) || Column(1, current) || Column(2, current) || Diagonals(current))
            {
                //updating score
                if (current == X)
                    xLabel.Text = (int.Parse(xLabel.Text) + 1).ToString();
                else
                    oLabel.Text = (int.Parse(oLabel.Text) + 1).ToString();
                //game finished
                finished = true;
                MessageBox.Show(string.Format("{0} Wins", (ButtonsIndexs.Length%2==0)?"X":"O"));//showing result
            }
            else
            {
                if (ButtonsIndexs=="")
                {
                    //game finished
                    finished = true;
                    MessageBox.Show("Draw");
                }

            }
            return finished;
        }

Checking if the button was clicked before (by PC or player)

        private bool wasClickedBefore(Button button, out int x, out int y)
        {
            x = y = 0;
            switch (button.Name)
            {
                case "button1": x = 0; y = 0; break;
                case "button2": x = 0; y = 1; break;
                case "button3": x = 0; y = 2; break;
                case "button4": x = 1; y = 0; break;
                case "button5": x = 1; y = 1; break;
                case "button6": x = 1; y = 2; break;
                case "button7": x = 2; y = 0; break;
                case "button8": x = 2; y = 1; break;
                case "button9": x = 2; y = 2; break;
            }
            return (X[x, y] || O[x, y]);
        }

only one helper method left, it's the computer turn in Normal mode. I will leave it to the third part of this tutorial.
Now lets write the code to the buttons.

Play again button event

private void playAgianButton_Click(object sender, EventArgs e)
        {
            resetVars();
            button1.Text =
            button2.Text =
            button3.Text =
            button4.Text =
            button5.Text =
            button6.Text =
            button7.Text =
            button8.Text =
            button9.Text =
            "";
            if (player == "O") player = "X";
            else
            {
                player = "O";
                if (difficulity == 0)
                    EasyPCWrite("X");
                else
                    NormalPCWrite("X");
            }

        }

Game buttons Click(the 9 buttons)

private void gameButtons_Click(object sender, EventArgs e)
        {
            if(!wasClickedBefore(sender as Button,out x, out y)&&!finished)
            {
                if(player=="O")
                {
                    //The user turn
                    Write("O",sender as Button);
                    if (!CheckForWinOrDraw(O))
                    {
                        //PC turn
                        if (difficulity == 0)
                            EasyPCWrite("X");
                        else
                            NormalPCWrite("X");
                        CheckForWinOrDraw(X);
                    }
                }
                else
                {
                    //The user turn
                    Write("X",sender as Button);
                    if(!CheckForWinOrDraw(X))
                    {
                        //PC turn
                        if(difficulity==0)
                            EasyPCWrite("O");
                        else
                            NormalPCWrite("O");
                        CheckForWinOrDraw(O);
                    }
                }
            }
        }

The back button (second one)

        private void back_Click(object sender, EventArgs e)
        {
            easyRB.Checked = true;
            playAgainButton.PerformClick();
            xLabel.Text = oLabel.Text = "0";
            tableLayoutPanel1.Visible = false;
            this.Size = new Size(229, 300);
        }

Radio buttons checked

        private void easyRB_Click(object sender, EventArgs e)
        {
            difficulity = 0; //Easy level
        }
        private void normalRB_CheckedChanged(object sender, EventArgs e)
        {
            difficulity = 1; //Normal Level
        }

Main buttons (XButton and OButton)

        private void mainButtons(object sender, EventArgs e)
        {
                        player = (sender as Button).Text; //user choice, X or O
            this.Size = new Size(382, 300); //changes form size
            tableLayoutPanel1.Visible = true;
            if (difficulity == 0)
                if (player == "O")
                    EasyPCWrite("X");
                else
                    return;
            else
                if (player == "O")
                    NormalPCWrite("X");
        }

Back button

        private void backButton_Click(object sender, EventArgs e)
        {
            Form1 f1 = new Form1();
            this.Hide();
            f1.Show();
        }

Form3_Load event

        private void Form3_Load(object sender, EventArgs e)
        {
            resetVars();
        }

Last step, go to Form1 and double click the PC vs Player button..

Player vs PC button

        private void playerVsPC_Click(object sender, EventArgs e)
        {
            Form3 f3 = new Form3();
            this.Hide();
            f3.Show();
        }
We've created today the Easy PC mode of player vs PC option in Tic Tac Toe game.
It's almost done, Last part of this tutorial will include the Normal PC mode, and some other final touches for your game to be ready!
Stay tuned, if you have any question post it to my Facebook page and I'll try to help, see you later.

>>CLICK FOR THE NEXT PART OF THIS TUTORIAL

Wednesday, September 12, 2012

Creating Tic-Tac-Toe with C# - Part 1

Today we'll start a new tutorial about creating the Tic Tac Toe game, or XO game.
Open visual studio, create a new windows form application project, name it Tic Tac Toe or something..

Right now we are going to use only 2 forms.
create Tic Tac Toe gameTo add another form, right click on your project, select Add, then choose Windows Form.

a new form with the name of Form2 will appear. In this form we are going to place the game.
you may ask but Form1 for what? we will create a menu with two buttons, to choose between 2-Player mode or 1-player vs computer.

In this part of the tutorial, we will build the 2-Player mode.

create Tic Tac Toe game

Form1 design


we only need two buttons, to select the game mode.
okay, this form will look something like this:
I used a TableLayoutPanel to centralize the buttons. Click to see this tutorial if you're not sure how to use it.







Form1 Coding

double click the 2-Player button and write this code:
Form2 f2= new Form2();
this.Hide();
f2.Show();
This code will hide the current form, and open the second form.
I will leave the second button "Player cs PC" for the Part 2 of this tutorial.

Form2 design



create Tic Tac Toe game
  • Create a tableLayoutPanel, set the Dock property to Fill, divide it to 4 columns with percentage 25% of each, and 4 rows with the percentages: 33.33%, 16.66%, 16.66%, 33.33%.
  • Add a button with the Dock property set to Fill and an empty Text property. Copy and paste until you have 9 buttons filling the cells: (0,0) ; (0,1) ;  (0,2) ;  (1,0) ; (1,1) ; (1,2) ; (3,0) ; (3,1) ; (3,2) ; 
  • Select the 3 middle small height buttons and change their RowSpan property to 2.
  • Select all created buttons and set their Font property to: Tahoma; 36pt.
  • Fill the last column with 2 buttons and two labels as the picture above shows, change their names to: resetButton, xLabel(blue), oLabel(red), backButton. We will use these names in our code.

Form2 Coding

Declarations

        Button btn; //to get the clicked button data
        int turn/*to determine wich turn*/,counter/*for the played turns*/; 
        bool[,] X/*X player buttons*/, O/*O player buttons*/, cells/*Occupied cells*/, current/*X or O*/; //using 3x3 coordinate system
        string player; //X or O
        bool finished; // true when the game finish

Reset button and Form load

 
private void resetButton_Click(object sender, EventArgs e)
        {
           //clear buttons text property
           button1.Text =
           button2.Text =
           button3.Text =
           button4.Text =
           button5.Text =
           button6.Text =
           button7.Text =
           button8.Text =
           button9.Text =
           "";
            resetVariables();
        }

private void Form2_Load(object sender, EventArgs e)
        {
            resetVariables();
        }
you can notice that I used a helper method in the last line to reset the variables. I'm resetting variables on both events. I'm going to write the code of all helper methods after finishing the main ones.

Back button

private void backButton_Click(object sender, EventArgs e)
        {
            this.Hide();
            Form1 f1 = new Form1();
            f1.Show();
        }
This code will take us back to the menu (Form1).

Gaming buttons (9 buttons)EXPLAINED (Improved, thanks to Yahia)

private void gamePlayButtons_Click(object sender, EventArgs e)
        {
            int x,y;
            //ensure that the user is clicking a button, if yes give me its coordinate (x,y)
            //ensure that the game has not finished yet
            if (!wasClickedBefore(sender as Button, out x, out y)&&!finished)
            {
                counter ++;
                btn = (sender as Button); //the clicked button from the 9 buttons
                
                if (turn == 0)
                {
                    (sender as Button).ForeColor = Color.Blue;//changing color to Blue
                    player = "X";
                    X[x,y]=true;//the position(x,y) is occupied now by an X
                    current = X;
                }
                else
                {
                    (sender as Button).ForeColor = Color.Red;//changing color to Red
                    player = "O";
                    O[x, y] = true;//the position(x,y) is occupied now by an O
                    current = O;
                }
                (sender as Button).Text = player;//writing text property

                
                cells[x,y]=true; // this cell is no longer empty
                turn = (turn + 1) % 2; //switching turns, this will switch between 0 and 1
             //a Win occurs when at least 5 turns are played
             if(counter>=5)
                //Check for a win 
                if (Row(0) || Row(1) || Row(2) || Column(0) || Column(1) || Column(2) || Diagonals())
                {
                    //updating score
                    if(player=="X")
                        xLabel.Text=(int.Parse(xLabel.Text)+1).ToString();
                    else
                        oLabel.Text=(int.Parse(oLabel.Text)+1).ToString();

                    finished = true;//game finished
                    MessageBox.Show(string.Format("{0} Wins", player));//showing result
                }

             if (counter==9&&!finished)//It's a draw here
             {
                  finished = true;
                  MessageBox.Show("Draw");
             }

            }
        }
Now we still have to write five helper methods, that we used earlier but we didn't write their codes.

Check the win on diagonals

        private bool Diagonals()
        {
            return (
                (current[0, 0] && current[1, 1] && current[2, 2])
                ||
                (current[0, 2] && current[1, 1] && current[2, 0])
                );
        }

Check the win on a Row/Column

private bool Row(int p)
        {
            return (current[p, 0] && current[p, 1] && current[p, 2]);
        }
        private bool Column(int p)
        {
            return (current[0, p] && current[1, p] && current[2, p]);
        }

Was it clicked before?

private bool wasClickedBefore(Button button, out int x, out int y)
        {
            x = y = 0;
            switch (button.Name)
            {
                case "button1": x = 0;y=0 ; break;
                case "button2": x = 0;y=1 ; break;
                case "button3": x = 0;y=2 ; break;
                case "button4": x=1;y= 0; break;
                case "button5": x=1;y= 1; break;
                case "button6": x=1;y= 2; break;
                case "button7": x=2;y=0; break;
                case "button8": x=2;y= 1; break;
                case "button9": x = 2;y= 2; break;
            }
            return (X[x, y]||O[x,y]);
        }

Reset Variables

private void resetVariables()
        {
            finished = false;
            turn = 0;
            O = new bool[3, 3];
            X = new bool[3, 3];
            cells = new bool[3, 3];
counter=0;
        }

Testing application

create Tic Tac Toe game
Now your 2-Player game is ready to test. It looks good right?

If you have any problems with it you can Download the solution from here.
Okay so today we've made a simple Tic Tac Toe game between two players. In the coming parts we are going to add the Player vs PC option.

>>CLICK FOR THE NEXT PART OF THIS TUTORIAL

Tuesday, September 11, 2012

Simple Calculator tutorial Part 2 of 2 - Visual C# - Windows forms applications

The previous part of this tutorial was about how to create correctly the design for a simple calculator.
In this part we are going to write some code. I will try to explain everything step by step.

Because we are creating a simple calculator, we are only interested in operations such as 7*3=21
and we are not considering the PEMDAS rule. so the answer to 4+3*4 will be 28 instead of 16. We'll create a more advanced calculator later, but now our goal is to learn the basics.

In the design mode press F7 to switch to the c# code.
First of all we are gonna declare some variables to use, write the declarations in the Form1 class.

Declarations:
        string text; //The text that will show in the textBox
        double operand_1, operand_2, solution;
        char Operator;

From the design mode, double click on the Form, this will generate an event called Form1_Load, this event will launch when your form is loaded.
Generally we put the initial values of our variables in this event.

Form1_Load method
 private void Form1_Load(object sender, EventArgs e)
        {
            operand_1 = operand_2 = solution = 0;
            text = "0";
            Operator = '=';
        }

we will create two main methods, one for the numbers and the other for the operators (+, -, *, /, =).

Numbers method:
 private void numbers_Click(object sender, EventArgs e)  
     {  
       Button button=(Button)sender;  
       text += button.Text;  
       while (text != "0" && text[0] == '0' && text[1] != '.')  
           text = text.Substring(1);  
       textBox1.Text = text;  
     }

This code will execute only when the user click one of the 10 numeric buttons or the point button.

  • In the first line I'm declaring a Button (which would not appear) I name it button. My goal here is just to know which button from the 11 was pressed, this would be the sender of type object.
  • The second line is adding the Text property of the sender button (button) to the variable text.
  • We don't want to allow user to write for example 0001 or maybe 00.1, the while loop will automatically convert them to the appropriate form 1 or 0.1
  • Finally we show the text in textBox1 (the default name of the created TextBox)
Now we have to tell VS when to launch this method. Go back to design view, hold Ctrl key and select the 11 buttons, then click on Events tab in the properties window, look for the Click event, assign number_Click method to it.

Operators method:
private void operators_Click(object sender, EventArgs e)
        {
            if (Operator!='=')
            {
                operand_2 = double.Parse(textBox1.Text);

                switch (Operator)
                {
                    case '+': solution=operand_1+operand_2; break;
                    case '-': solution=operand_1-operand_2; break;
                    case '*': solution=operand_1*operand_2; break;
                    case '/': solution=operand_1/operand_2; break;
                }
                Operator = '=';
                textBox1.Text = solution.ToString();
            }
            operand_1 = double.Parse(textBox1.Text);
            Operator=char.Parse(((Button)sender).Text);
            text = "0";
        }
The first line will check if there's a previous operation to complete, if yes we complete it and set the Operator value back to '=' and print the result in the textBox.
Next, the number in the textBox (whether it was written or calculated) is ready for a new operation with the operator Operator, which is the Text property value of the clicked button from the operators buttons.

Don't forget to assign this method to the appropriate buttons from the design tab.

Testing
Calculator

Now your application is ready to test, press F5 to start the debugger.
I suggest you to add some more features to this calculator.

If you have any questions leave a comment here or on my facebook page.

Monday, September 10, 2012

Simple Calculator tutorial Part 1 of 2 - Visual C# - Windows forms applications

If you're a beginner in programming with Visual C#, then I think this tutorial is very helpful for you.

So we're going to create a very simple calculator, you'll see how much easy it is.
Our target is to create a working calculator similar to this one:

Simple Calculator tutorial


In this part of tutorial we'll build the design of the application.


Open Visual Studio, select "New Project", choose "Visual C#" (you may find it in the Other languages listing), select Windows Forms Application, choose a suitable name like Easy-Calculator.

Edit Form1 Properties. 
  • Size: "300; 240".
  • BackColor: "GradientInactiveCaption", I like this color.
  • MaximumSize: "300; 240", not allowing user to increase the size of the our form.
  • MinimumSize: "300; 240", the minimum size of the form set to its actual size.
  • MaximizeBox: "False", this is important to add so the user don't click the Maximize button.
  • Text: "Easy Calculator", or anything you want.
Add a TextBox from the ToolBox list, and change its properties as following:
  • Dock: "Top", this will place it in the top of the form.
  • Font: "Tahoma; 18pt", making numbers a little bigger. 
  • BackColor: "GradientInactiveCaption", same as the form background color.
  • ReadOnly: "True", since we don't the user to edit the TextBox with his keyboard. 
  • Text: "0".
Add a TableLayoutPanel.
  • We'll place our buttons in this panel. 
  • Change the Dock property to "Bottom".
  • Cick on the upper right corner arrow to show the TableLayoutPanel Tasks, check the picture below.

Simple Calculator tutorial
Click on Edit Rows and Columns...

We need to have 4 Rows and 5 Columns, let the percent value to every row be 20%, and 25% for columns.

Simple Calculator tutorial
Simple Calculator tutorial

Click OK, now extend the TableLayoutPanel height. the results should be like this:

Simple Calculator tutorial

Adding buttons
  • Drag and drop a button to the cell 0,0 (The first row and the first column). Change its Dock property to Fill. Select it and press Ctrl+C. Now press 19 times  Ctrl+V. you should get this:
    Simple Calculator tutorial
  • Remove the following buttons: button17,button10,button15,button20.
  • Set the RowSpan property for button16 to 2, and set the ColumnSpan property for button5 to 4.
  • Finally edit the text property so finally you get this result:
    Simple Calculator tutorial
Save your project so we can continue the next time the programming part, believe me, you'll find it easier than the design. if you have any question Leave a comment and I'll help you. See you next time.

CLICK HERE TO VIEW THE PART 2 OF THIS TUTORIAL

Saturday, September 8, 2012

Hangman - The Instructive Game!

Hangman

Previously I published the Guess the Word console game. under the title of Words games, I'm presenting now the Hangman game.
Hangman is one of the awesome games that we used to play in our childhood, I programmed this app over 3 days using Visual Studio windows forms applications, language used is C#. It was really challenging, I added some interesting features to the classic hangman game that we used to play on a sheet of paper.

After you start the application, you will be asked to choose one of 7 different categories of words to guess, which are:

  1. Cars brands.
  2. Movies.
  3. Celebrities.
  4. World countries.
  5. Girls names.
  6. Boys names.
  7. Animals.
In the example below, I chose the Cars brands category, so the word to guess seems to be consisted of 3 letters, You must guess it letter by letter. you can have a maximum of 9 wrong guesses
As you can see, the Progress bar is 9% filled, this means that you've already successfully guessed 9% of the words of the current category. can you reach 100% of each ? Animals one is the hardest !

Hangman


If you guessed right.. 
Hangman


If you run out of tries, the correct word will appear in red.
Click the "New Word" button to start again with a new word.

Hangman


In addition you can notice the "What's this word?" link button below the back button, this appears when you fail in guessing certain word. Click on it to view images of the Pierce Arrow brand via google images search.



Enjoy this instructive game, Download it now:

Hangman.rar
Hangman.zip

(NOTE: For the best performance do not change the installation location to Program Files)

Hope you like it! :) give me your thoughts in comments..

Do you want the source code of this app? just Follow me by email and I'll send it to you.

Friday, September 7, 2012

Guess the Word - Console application game

In my previous posts I published two windows forms applications, Password and Serial Generator and Simple Units Converter, now in this article I'm presenting a Console application.

It's a simple game, you will be given a word such as "VLOE", your mission is to guess that this word is "LOVE", just try to rearrange letters in a correct way to win!

screen-shots:

Select between 3 difficulties.


If you can't find the correct word just enter "0".

The correct word was "BECAUSE", it seemed hard at first.
Like it? you can't decide until your try it!

Download now (rar)
Download now (zip)

Want the source code? leave a comment.

Wednesday, September 5, 2012

Simple Units Converter (SUC) Download

Simple Units Converter

In my previous post I introduced the Password and Serial Generator. Now we have a new Utility application for today..
Simple Units Converter is a powerful and user-friendly tool, it helps you to convert over 8 kinds of units.
It is a simple windows forms application, made by me using Visual Studio 2010.
It combines 8 converters in just one:
  • Weight converter.
  • Length converter.
  • Area converter.
  • Time converter.
  • Volume converter.
  • Speed (Velocity) converter.
  • Pressure converter.
  • Power converter.
Here's a screen-shot of the application:
Simple Units Converter
It's pretty easy to use, just choose the conversion type by clicking on its corresponding button from the 8 buttons listed.

For example, let's click on the "Time" button, now start writing in any of the box's to convert the amount to the other box's unit.
If you write "3" in one box, the number in other box will change to 1095, that means 3 years=1095 days.
You can also write in the right box as well.. 
Simple Units Converter


You are free to chose between 6 different units of every Measurement.
Simple Units Converter

Download it now:


Please give me your opinion about this tool, and if you like it share it.

Do you want the source code of this app? just Follow me by email and I'll send it to you.

Monday, September 3, 2012

Password and Serial Generator Download - Create a strong password


Password and Serial Generator

Have you ever wanted to create a powerful password for you email or Facebook account?
If yes then this is the right place for you!
Have you ever be a victim of hackers?
well one of the main causes of hacking your email or Facebook account is actually the weakness of the password that you have chosen.

Password and Serial Generator is a simple windows forms application, made by me using Visual Studio 2010.

OK so let's take a closer look at this tool.

Password Generator
When you run the application it would look like the above screen-shot.
As you can see, you have the ability to toggle between a Password Generator and a Serial Generator.
In the password generator you can choose the length in characters of you desired password, also you can decide if you want numbers or special characters such as: ",./?;! etc.."

Serial Generator
The serial generator have also its options, first you must choose the number of quads in you serial, a serial with 5 quads looks like this: Q1HU-9AJT-1LZK-V29D-P8UD.
Another option is to generate a Numbers-Only serial.

Below an example of a generated serial:
Serial Generator

And here another example of a generated password:
Password Generator

you can download Password and Serial Generator from the following links:

Download Password and Serial Generator (zip)
Download Password and Serial Generator (rar)

Please give me your opinion about this tool, and if you like it share it.

Do you want the source code of this app? just Follow me by email and I'll send it to you.

Visual Studio Applications

Hello and welcome to my blog, you can call me ABR, one of my hobbies is to create some useful windows programs using Visual Studio.

Most of the time, I use the C# language to create my applications. This language is pretty easy to learn and a very good one to start with if you want to be a windows applications developer.

I created this blog to share some of my work on Visual Studio with people who are interested in programming or not. Feel free to ask for the code of any application that I share, just leave a comment with your email on the corresponding article, and I'll send it to you.

My regards.