Lost Password?


  #1 (permalink)  
Old 06-16-2008, 01:04 AM
gaylo565's Avatar   
gaylo565 gaylo565 is offline
Programmer
 
Join Date: May 2007
Location: flagstaff, az
Posts: 187
Last Blog:
String Manipulation wi...
Rep Power: 9
gaylo565 is a jewel in the roughgaylo565 is a jewel in the roughgaylo565 is a jewel in the rough
Default C# memory game tutorial

This is a simple C# memory game where the user selects tiles two at a time in order to come up with matches. It is made on a 7x6 grid with 7 different pictures. It has a high scores option but other than that it is very basic.

GUI design
*I started with a basic widows form and added a menu strip, 42 buttons in a grid pattern and 5 labels to display game information.

*Next we need to add a File and Help option to the main menu. Under the File option we need a New Game, Reset Scores, and Exit options. Under Help all we need is an About option to show information about the programmer.

*After all of the added options have been named appropriately we double click on the New Game, Reset Scores, Exit, and About options to add click handlers for our menu. Now we are ready to start coding. We also need to double click the form its self in order to create a form load event.

Coding
*First we need to add our references to the very top section of the code. Add the following:
Code:
using System.IO;
using System.Threading;
using Microsoft.VisualBasic;
*We need to add the Visual Basic reference manually. Select Add Reference under Project on the main menu. Scroll down until you find Microsoft.VisualBasic and select ok. This is so we can use a visual basic input box for a user name input when a user gets a high score.

*Now we can declare our class level arrays. We need one integer type array for storing random #’s from our random #’s function, one to store our 42 non-repeating #’s for randomizing pictures, and one to store our 3 high scores. We also need a string type array for the names that go with the high scores.

*Next we need to declare 2 booleen type class level variables. One for keeping track of which guess the user is on. One for keeping track of matches.

*We also need to declare 6 integer type class level variables. We will need 4 to hold values for checking matches and storing button value, one for keeping track of number of guesses left, and one for keeping track of users score.

*We also need to declare a random number object before we start coding our methods

*In our methods section we will need 5 methods plus the ones we already have for our menu and form load. First we need a new game method:
Code:
private void newGame()
		{
			intScore = 0;
			bln_isFirst = true; 
			bln_isMatch = false; 
			//create bln variable to check if random #'s exist in board array already
            bool bln_isSame = false;
            
            //display the score and guesses left
            lblGuess.Text = "Trys Left: " + intGuess.ToString();
            lblScore.Text = "Score: " + intScore.ToString();
			

			//set high scores arrays from high scores file and display on label
			try
			{
                StreamReader highScoresStreamReader = new StreamReader(Directory.GetCurrentDirectory() + @"\Pictures\HighScores.txt");
				while(highScoresStreamReader.Peek() !=-1)
				{
					for(int a=0; a < 3; a++)
					intHighScores[a] = int.Parse(highScoresStreamReader.ReadLine());
				}
				highScoresStreamReader.Close();
			}
			catch
			{
				MessageBox.Show("File Reading Error1");
			}

			//set user array from user file and display on label
			try
			{
                StreamReader userStreamReader = new StreamReader(Directory.GetCurrentDirectory() + @"\Pictures\User.txt");
				while(userStreamReader.Peek() !=-1)
				{
					for(int a=0; a < 3; a++)
						strUser[a] = userStreamReader.ReadLine();
				}
				userStreamReader.Close();
			}
			catch
			{
				MessageBox.Show("File Reading Error1");
			}	
            lblHighScore.Text = "HighScores:    "+ strUser[0]+"..."+intHighScores[0];
			lblHighScore2.Text = strUser[1]+"..."+intHighScores[1];
			lblHighScore3.Text = strUser[2]+"..."+intHighScores[2];

			//set number of guesses
			intGuess = 13;
			
            //seed the random number function
			DateTime dtmCurrent = DateTime.Now;
            generateRandom = new Random(dtmCurrent.Millisecond);
            _buttonArray = new Button[42] {
											  btn0, btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9,btn10, 
											  btn11, btn12, btn13, btn14, btn15, btn16, btn17, btn18, btn19,
											  btn20, btn21, btn22, btn23, btn24, btn25, btn26, btn27, btn28,
											  btn29,btn30, btn31, btn32, btn33, btn34, btn35, btn36, btn37,
											  btn38, btn39, btn40, btn41};
            for (int i = 0; i < 42; i++)
            {
                //ensure that the event only called once
                this._buttonArray[i].Click -= this.ClickHandler;
                
                //set new click handler
                this._buttonArray[i].Click += new System.EventHandler(this.ClickHandler);
                
                //enable all buttons and set images to null
                _buttonArray[i].Enabled = true;
                _buttonArray[i].Image = null;
            }
			//fill array with random #'s from 1 to 42
			int intAdd = 0, intCount1;
			for(int r=0; r < 200; r++)
			{
				intStorage[r] = generateRandom.Next(1,43);
			}
			for(intCount1=0; intCount1 < 250; intCount1++)
			{
				bln_isSame = false;
				if(intAdd < 43)
				{
					//check to see if array already contains generated #
					foreach(int intBoard1 in intBoard)
					{
						if(intStorage[intCount1] == intBoard1)
						{
							bln_isSame = true;
						}
					}
					//fill board array with random non matching #'s
					if(bln_isSame == false && intStorage[intCount1] != 0)
					{
						intBoard[intAdd] = intStorage[intCount1];
						intAdd++;
					}
				}
			}
		}
*next we need a click handler for our buttons and a button events method
Code:
private void ClickHandler(object sender, System.EventArgs e)
		{
            	        //button handler...temporarily set button to false visibility and not enabled
		        Button tempButton = (Button)sender;
            	        intCount4 = (tempButton.TabIndex - 42);
			
			//store last int Count2 for checking match and button use.
			intCount3 = intCount2;
			
            	        //set random number for passing to find file name
			intCount2 = intBoard[intCount4];
			ImgLocation = checkNumbers(intCount2);
			tempButton.Image = Image.FromFile(ImgLocation);
			tempButton.Enabled = false;
			buttonEvents(tempButton, intCount2, intCount3, intCount4);
            
            	        //set pause for second turn so player can see pictures
            	        for (int i = 0; i < 10; i++)
            	        {
                		System.Threading.Thread.Sleep(100);
            	        }
		}
private void buttonEvents(Button tempButton, int intCount2, int intCount3, int intCount4)
        	{
            	if(bln_isFirst == true)
				{
					bln_isFirst = false;
					intCount5 = intCount4;
				}
				else
				{
					bln_isFirst = true;				
					bln_isMatch = checkMatch(intCount2, intCount3);
					// if not a match refresh buttons
					if(bln_isMatch == false)
					{
						tempButton.Enabled = true;
						tempButton.Image = null;
						_buttonArray[intCount5].Enabled = true;
						_buttonArray[intCount5].Image = null;
						intGuess -= 1;
					}
					else
					{
						intScore += 10;
					}
				}
            	if (intGuess <= 0)
            	{
               		MessageBox.Show("game over");
                		for (int r = 0; r < 42; r++)
                		{
                    		_buttonArray[r].Enabled = false;
                		}
                		if (intScore > intHighScores[0])
                		{
                    		//move old high scores down one spot
                    		intHighScores[2] = intHighScores[1];
                    		intHighScores[1] = intHighScores[0];
                    		intHighScores[0] = intScore;
                    		//show the User Input Form
                    		strUser[0] = Interaction.InputBox("Congratulations", "New High Score", "Please enter your name:", 10, 10);
                    
                		}
                		else if (intScore > intHighScores[1] && intScore <=intHighScores[0])
                		{
                    		//move middle high score down one spot
                    		intHighScores[2] = intHighScores[1];
                    		intHighScores[1] = intScore;
                    		//show the User Input Form
                   		 strUser[1] = Interaction.InputBox("Congratulations", "New High Score", "Please enter your name:", 10, 10);
                		}
                		else if (intScore > intHighScores[2] && intScore <= intHighScores[1])
                		{
                    		intHighScores[2] = intScore;
                    		//show the User Input Form
                    		strUser[2] = Interaction.InputBox("Congratulations", "New High Score", "Please enter your name:", 10, 10);
                		}
                		//write new high scores strings to the highscores file
                		StreamWriter HighScoreStreamWriter = new StreamWriter(Directory.GetCurrentDirectory()+@"\Pictures\HighScores.txt", false);
                		for (int g = 0; g < 3; g++)
                		{
                    HighScoreStreamWriter.WriteLine(intHighScores[g]);
                		}
                		HighScoreStreamWriter.Close();
                		//write new names strings to the user file
                		StreamWriter NamesStreamWriter = new StreamWriter(Directory.GetCurrentDirectory() + @"\Pictures\User.txt", false);
                		for (int b = 0; b < 3; b++)
                		{
                    		NamesStreamWriter.WriteLine(strUser[b]);
                		}
                		NamesStreamWriter.Close();
            	}
            	else
            	{
                	//display the score and guesses left
                	lblGuess.Text = "Trys Left: " + intGuess.ToString();
                	lblScore.Text = "Score: " + intScore.ToString();
            	}
		}
*The final two user added methods will be a checkMatch method to check for matches and a checkNumbers method to translate our random #’s file paths for our pictures.
Code:
private void ClickHandler(object sender, System.EventArgs e)
		{
            //button handler...temporarily set button to false visibility and not enabled
			Button tempButton = (Button)sender;
            intCount4 = (tempButton.TabIndex - 42);
			
			//store last int Count2 for checking match and button use.
			intCount3 = intCount2;
			
            //set random number for passing to find file name
			intCount2 = intBoard[intCount4];
			ImgLocation = checkNumbers(intCount2);
			tempButton.Image = Image.FromFile(ImgLocation);
			tempButton.Enabled = false;
			buttonEvents(tempButton, intCount2, intCount3, intCount4);
            
            //set pause for second turn so player can see pictures
            for (int i = 0; i < 10; i++)
            {
                System.Threading.Thread.Sleep(100);
            }
		}
		private void buttonEvents(Button tempButton, int intCount2, int intCount3, int intCount4)
        {
            if(bln_isFirst == true)
			{
				bln_isFirst = false;
				intCount5 = intCount4;
			}
			else
			{
				bln_isFirst = true;				
				bln_isMatch = checkMatch(intCount2, intCount3);
				// if not a match refresh buttons
				if(bln_isMatch == false)
				{
					tempButton.Enabled = true;
					tempButton.Image = null;
					_buttonArray[intCount5].Enabled = true;
					_buttonArray[intCount5].Image = null;
					intGuess -= 1;
				}
				else
				{
					intScore += 10;
				}
			}
            if (intGuess <= 0)
            {
                MessageBox.Show("game over");
                for (int r = 0; r < 42; r++)
                {
                    _buttonArray[r].Enabled = false;
                }
                if (intScore > intHighScores[0])
                {
                    //move old high scores down one spot
                    intHighScores[2] = intHighScores[1];
                    intHighScores[1] = intHighScores[0];
                    intHighScores[0] = intScore;
                    //show the User Input Form
                    strUser[0] = Interaction.InputBox("Congratulations", "New High Score", "Please enter your name:", 10, 10);
                    
                }
                else if (intScore > intHighScores[1] && intScore <=intHighScores[0])
                {
                    //move middle high score down one spot
                    intHighScores[2] = intHighScores[1];
                    intHighScores[1] = intScore;
                    //show the User Input Form
                    strUser[1] = Interaction.InputBox("Congratulations", "New High Score", "Please enter your name:", 10, 10);
                }
                else if (intScore > intHighScores[2] && intScore <= intHighScores[1])
                {
                    intHighScores[2] = intScore;
                    //show the User Input Form
                    strUser[2] = Interaction.InputBox("Congratulations", "New High Score", "Please enter your name:", 10, 10);
                }
                //write new high scores strings to the highscores file
                StreamWriter HighScoreStreamWriter = new StreamWriter(Directory.GetCurrentDirectory()+@"\Pictures\HighScores.txt", false);
                for (int g = 0; g < 3; g++)
                {
                    HighScoreStreamWriter.WriteLine(intHighScores[g]);
                }
                HighScoreStreamWriter.Close();
                //write new names strings to the user file
                StreamWriter NamesStreamWriter = new StreamWriter(Directory.GetCurrentDirectory() + @"\Pictures\User.txt", false);
                for (int b = 0; b < 3; b++)
                {
                    NamesStreamWriter.WriteLine(strUser[b]);
                }
                NamesStreamWriter.Close();
            }
            else
            {
                //display the score and guesses left
                lblGuess.Text = "Trys Left: " + intGuess.ToString();
                lblScore.Text = "Score: " + intScore.ToString();
            }
		}
*finally we will need to define our methods for the menu bar and our form load event
Code:
private void mnuNewGame_Click_1(object sender, System.EventArgs e)
		{
			//call newGame method
            	newGame();
		}
		
private void mnuResetScore_Click(object sender, System.EventArgs e)
		{
			//write name string to the user file
            	StreamWriter NameStreamWriter = new StreamWriter(Directory.GetCurrentDirectory() + @"\Pictures\User.txt", false);
			for(int p=0; p<3; p++)
			{
				NameStreamWriter.WriteLine("NAME");
			}
			NameStreamWriter.Close();
			
			//write 0 strings to the highscores file
			StreamWriter hScoreStreamWriter = new StreamWriter(Directory.GetCurrentDirectory() + @"\Pictures\HighScores.txt",false);
			for(int p=0; p<3; p++)
			{
				hScoreStreamWriter.WriteLine("0");
			}
			hScoreStreamWriter.Close();
		}

private void mnuExit_Click_1(object sender, System.EventArgs e)
		{
			//close this application
			this.Close();
		}

private void mnuAbout_Click(object sender, System.EventArgs e)
		{
			//display 'programmed by' message
			MessageBox.Show("Programmed by: Galen Goforth");
		}
private void frmMain_Load(object sender, System.EventArgs e)
		{
			newGame();
		}
*and there it is You will need to add the pictures to your /bin/debug folder for your project as well as a high scores and user text file to hold high score information. I have attached a working copy(hopefully). This is my first tutorial so suggestions and criticism are more than welcome. I know I didn't explain everything here but my comments are fairly explanatory.
Attached Files To view attachments in this forum your post count must be 1 or greater. You currently have 0 posts.

Last edited by gaylo565; 06-16-2008 at 09:54 AM.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote

Sponsored Links
  #2 (permalink)  
Old 06-16-2008, 08:15 PM
gaylo565's Avatar   
gaylo565 gaylo565 is offline
Programmer
 
Join Date: May 2007
Location: flagstaff, az
Posts: 187
Last Blog:
String Manipulation wi...
Rep Power: 9
gaylo565 is a jewel in the roughgaylo565 is a jewel in the roughgaylo565 is a jewel in the rough
Default Re: C# memory game tutorial

Just some thoughts now that I posted this.
First I got a little happy with the if else statements. I probably should have used a couple of switch statements for the checkNumbers method and the checkMatch method. Also I think I declared a couple of the variables with the private modifier for no real reason. I was gonna make my own input form for the high scores name, but the visual basic form seemed an easier way to go.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 06-16-2008, 08:49 PM
Jordan's Avatar   
Jordan Jordan is offline
Administrator
 
Join Date: Nov 2005
Location: Hendersonville, NC
Posts: 9,224
Last Blog:
Ext JS or Ext GWT
Rep Power: 20
Jordan is just really niceJordan is just really niceJordan is just really niceJordan is just really nice
Send a message via ICQ to Jordan Send a message via AIM to Jordan Send a message via MSN to Jordan
Default Re: C# memory game tutorial

Nice tutorial! +rep
__________________
CodeCall Blog | CodeCall Wiki | Shareware Site | Linux Forum | Write a Blog
The CodeCall Wiki is now fully integrated with vBulletin users! Check it out and add some new pages!
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #4 (permalink)  
Old 06-17-2008, 10:29 AM
gaylo565's Avatar   
gaylo565 gaylo565 is offline
Programmer
 
Join Date: May 2007
Location: flagstaff, az
Posts: 187
Last Blog:
String Manipulation wi...
Rep Power: 9
gaylo565 is a jewel in the roughgaylo565 is a jewel in the roughgaylo565 is a jewel in the rough
Default Re: C# memory game tutorial

Thank-You. Hope this helps all the folks out there with memory questions. Was also hoping for some suggestions...anybody?
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #5 (permalink)  
Old 06-30-2008, 01:27 AM
gimmo gimmo is offline
Newbie
 
Join Date: Jun 2008
Posts: 1
Rep Power: 0
gimmo is on a distinguished road
Default Re: C# memory game tutorial

Thanks alot!
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote

Sponsored Links
  #6 (permalink)  
Old 08-21-2008, 01:19 PM
Healncrush's Avatar   
Healncrush Healncrush is offline
Newbie
 
Join Date: Aug 2008
Posts: 12
Rep Power: 0
Healncrush is on a distinguished road
Default Re: C# memory game tutorial

you lost me at:
*In our methods section we will need 5 methods plus the ones we already have for our menu and form load. First we need a new game method:

Code:

Where should i put the following code at?
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #7 (permalink)  
Old 08-21-2008, 01:45 PM
Xav's Avatar   
Xav Xav is offline
Code Warrior
 
Join Date: Mar 2008
Location: On God's Planet
Posts: 9,589
Last Blog:
Web slideshow in JavaS...
Rep Power: 76
Xav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud ofXav has much to be proud of
Send a message via MSN to Xav
Default Re: C# memory game tutorial

Somewhere inside the code file, outside another method. In short, open the form, double click on it. The code window will appear and there will be some code that says "Form1_Load" or whatever you called it. As a guide, you can put the code just above this.
__________________


Mr. Xav | Website | Forums | Blog
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #8 (permalink)  
Old 08-22-2008, 06:50 AM
bennysachdev bennysachdev is offline
Newbie
 
Join Date: Aug 2008
Posts: 1
Rep Power: 0
bennysachdev is on a distinguished road
Default Re: C# memory game tutorial

thnx for the code
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #9 (permalink)  
Old 09-24-2008, 05:40 PM
walshi2k8 walshi2k8 is offline
Newbie
 
Join Date: Sep 2008
Posts: 1
Rep Power: 0
walshi2k8 is on a distinguished road
Default Re: C# memory game tutorial

Great tutorial!
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #10 (permalink)  
Old 10-20-2008, 01:09 AM
switchoff switchoff is offline
Newbie
 
Join Date: Oct 2008
Posts: 1
Rep Power: 0
switchoff is on a distinguished road
Default Re: C# memory game tutorial

Extremely helpful, thanks!
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote

Sponsored Links
Reply



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
C# Memory Game Reilly911 C# Programming 12 06-04-2008 11:21 AM
help finishing memory game gaylo565 C# Programming 2 05-08-2008 11:16 PM
John's Java Tutorial Index John Java Tutorials 0 01-11-2007 04:05 PM


All times are GMT -5. The time now is 12:09 PM.

Contest Stats

WingedPanther ........ 2753.6
Xav ........ 2704
Brandon W ........ 1702.32
John ........ 1207.73
marwex89 ........ 1175.24
morefood2001 ........ 966.05
dcs ........ 655.75
Steve.L ........ 475.59
orjan ........ 418.58
Aereshaa ........ 383.54

Contest Rules

CodeCall Goal

Goal: 100,000 Posts
Complete: 98%

Ads