Tic Tac Toe for Windows Phone
Introduction
We are going to create a simple Tic Tac Toe game for Windows Phone. We’ll be using Visual Studio as our development environment and C# for our programming language. All the resources you need are listed below and all are free.
Resources:
VISUAL STUDIO 2010 EXPRESS FOR WINDOWS PHONE https://www.microsoft.com/visualstudio/en-us/products/2010-editions/windows-phone-developer-tools or https://bit.ly/ymbC9Q
Windows Phone for Absolute Beginners video series https://channel9.msdn.com/Series/Windows-Phone-7-Development-for-Absolute-Beginners or https://bit.ly/x72NnV
Alfred Thompson’s blog https://blogs.msdn.com/b/alfredth/ or https://bit.ly/AlfredTh
For a copy of this post in Word format, the images for the project, and code snippets used to create this lab download the PhoneTTT.zip file from https://skydrive.live.com/?cid=9a87f3a86cb0aa3e&id=9A87F3A86CB0AA3E%215413
Open Visual Studio
Find Visual Studio on the Start menu and open it up. It should look something like this.
Next we will open a new project. From the File menu select New Project. From the New Project form select Visual C# as the language Silverlight for Windows Phone under that and Windows Phone Application as the application type. Make sure you give your project a name. Something like TicTacToe followed by your initials will do nicely (TicTacToeACT)
We’ll be using the latest Windows Phone Version which is 7.1.
Our initial screen will look something like this.
We’ll come back to this in a minute.
Add Image Resources
We need to add some image files to the project. We will be adding images for an empty box , the letter O and the letter X. Right click on the Solution in the Solution viewer and select Add > Existing Item. You can download them from here if you like.
Browse to where the files for the project are (should be on the Desktop) and select the three files we need and click on add.
Design Our Form
Now let’s go back to designing our form on the mock up of the phone. Left click on where it says “page name” and select properties. The properties window will open up and we will change the Text property to Tic Tac Toe.
Next we will use the Tool box and drag an Image onto the form.
Using the properties form set the Height to 69, the width to 93 and the Source to the image file of the empty box. Use copy and paste to make a series of identical image boxes on the form. The results should look something like the image above.
Add a tenth copy below the ninth copy. Next to that draw a Text Block. Change the Text property of the Text Block to read “Next Move.” You may want to play with the font size property as well. The result will look something like this.
We’ll come back to this but now let us enter some code.
Declare some variables
Under MainPage.xaml on the Solution Explorer you will find MainPage.xaml.cs which hold our programming code. Double click on that to open the code editing window.
Above the constructor declare some variables that we will use to manage the game throughout the program.
public partial class MainPage : PhoneApplicationPage
{
// Boolean variables to track whose move it is and if the game is over
Boolean isX, GameOver;
// An array to track the contents of each box (0 = empty 1 = X 2 = O)
int[] boxValue;
// Helpful images
Image myXImage, myOimage, myEmptyImage;
// Counting moves
int MoveCount;
// Constructor
public MainPage()
Initialize Variables
Inside the constructor we will set the initial values of our variables.
Note that the resetBoxes method has not been created yet so the IDE gives us a warning. (The same sort of red squiggly live we are used to from Microsoft Word) Let’s correct that now. Also note that a common cause of problems is the wrong location in the Uri section. Change the “TicTacToe” in this sample code to match your project name.
// Constructor
public MainPage()
{
InitializeComponent();
boxValue = new int[10];
// STore the images for use in the game
myXImage = new Image();
myXImage.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("/PhoneApp3;component/x.jpg", UriKind.RelativeOrAbsolute));
myOimage = new Image();
myOimage.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("/PhoneApp3;component/o.jpg", UriKind.RelativeOrAbsolute));
myEmptyImage = new Image();
myEmptyImage.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("/PhoneApp3;component/empty.jpg", UriKind.RelativeOrAbsolute));
// Set the initial state of the game board
resetBoxes();
}
Create a Method to Set the Game Board
Our method here will have to initialize some additional variables. We do it here so that we can reset them all in just one place when we start new games.
// Set the initial state of the game board
void resetBoxes()
{
GameOver = false;
MoveCount = 0;
isX = true;
// Set all boxes to empty
for (int i = 0; i < 10; i++)
boxValue[i] = 0;
// Display empty images in all boxes on screen
image1.Source = myEmptyImage.Source;
image2.Source = myEmptyImage.Source;
image3.Source = myEmptyImage.Source;
image4.Source = myEmptyImage.Source;
image5.Source = myEmptyImage.Source;
image6.Source = myEmptyImage.Source;
image7.Source = myEmptyImage.Source;
image8.Source = myEmptyImage.Source;
image9.Source = myEmptyImage.Source;
GameOver = false;
MoveCount = 0;
textBlock1.Text = "Next Move ";
image10.Source = myXImage.Source;
}
Respond to Taps
We’ll play the game by tapping on individual boxes. For each tap we have to make sure it is a valid move (nothing in the box already), store and display the right symbol and check for a win or a tie. We’ll need a tab routine for each box but I’m only going to show one of them here. The rest is left as an exercise for the student. J
As you can see this method calls several of the methods we have not yet created. Let’s get on that.
// Respond to taps on all boxes.
// For each box:
// Check that it is empty and only act if it is
// Call UpdateBox to record move and return which symbol to display
// Check for a winner
private void image9_Tap(System.Object sender, System.Windows.Input.GestureEventArgs e)
{
if (boxValue[9] == 0)
{
boxValue[9] = updateBox();
if (boxValue[9] == 1)
{
image9.Source = myXImage.Source;
}
else
{
image9.Source = myOimage.Source;
}
if (IsWinner())
endGame();
}
}
Updating a Box
// Count move and determine which player made the move.
// Display the symbol for the next player to move
public int updateBox()
{
if (GameOver)
return 0;
MoveCount = MoveCount + 1;
if (isX)
{
isX = !isX;
image10.Source = myOimage.Source;
return 1;
}
else
{
isX = !isX;
image10.Source = myXImage.Source;
return 2;
}
}
Checking for a Winner
Checking for a winner means looking for three boxes in a row, column or diagonal that have the same value. Oh and it has to be the same not empty box value.
Getting close now. Notice the call to TieGame? Let’s create that routine after we create the winning end of a game.
// Determine if there is a winner by checking possible winning combinations
private bool IsWinner()
{
bool HaveWinner = false;
HaveWinner = false;
if (boxValue[1] != 0 & boxValue[1] == boxValue[2] & boxValue[1] == boxValue[3])
HaveWinner = true;
if (boxValue[4] != 0 & boxValue[4] == boxValue[5] & boxValue[4] == boxValue[6])
HaveWinner = true;
if (boxValue[7] != 0 & boxValue[8] == boxValue[7] & boxValue[7] == boxValue[9])
HaveWinner = true;
if (boxValue[1] != 0 & boxValue[1] == boxValue[4] & boxValue[4] == boxValue[7])
HaveWinner = true;
if (boxValue[2] != 0 & boxValue[2] == boxValue[5] & boxValue[5] == boxValue[8])
HaveWinner = true;
if (boxValue[3] != 0 & boxValue[6] == boxValue[3] & boxValue[6] == boxValue[9])
HaveWinner = true;
if (boxValue[1] != 0 & boxValue[1] == boxValue[5] & boxValue[5] == boxValue[9])
HaveWinner = true;
if (boxValue[3] != 0 & boxValue[3] == boxValue[5] & boxValue[5] == boxValue[7])
HaveWinner = true;
if (HaveWinner == true)
GameOver = true;
// if there is no winner but we have taken 9 moves declare a draw (tie)
if (MoveCount >= 9)
TieGame();
return HaveWinner;
}
Handling the End of a Game
Here we have the two routines that show the end of a game. One for a winning game and one for a tie game.
// Announce the winner
public void endGame()
{
textBlock1.Text = "The Winner is";
if (isX)
{
image10.Source = myOimage.Source;
}
else
{
image10.Source = myXImage.Source;
}
}
// Display tie game information
public void TieGame()
{
image10.Source = myEmptyImage.Source;
textBlock1.Text = "Tie Game";
}
We just have two more things to do. The first of those is that we have to “tell” the image boxes to call the tap routines when they are tapped. For this we go back to the design window.
Assigning Tap Handlers
Back on the property window you will find the Events tab. Selecting that and moving down we find an option for Tap. Selecting each image one by one we can use the drop down list to set the right handler for each image box.
Starting a New Game
All we need now is a way to start a new game. I suggest we tap on the Text Block to do that. Select the Text Block and in the properties window option for Tap enter New Game and press the enter key. This will open up the code window with a chance for use to call the ResetBoxes method we created.
private void NewGame(object sender, GestureEventArgs e)
{
resetBoxes();
}
Testing
Ok let’s run it and see how we did.
Comments
Anonymous
March 13, 2012
Well done. Thanks, for this well described Tutorial.Anonymous
March 13, 2012
Thanks Alfred. I am going to adapt it as an intro tutorial for my AP CS kids.Anonymous
March 16, 2012
I'm surprised that you didn't separate the UI from the game logic here. Not great design.Anonymous
March 16, 2012
No not the best design. I designed it mostly to be able to build it in 10 minutes or less as a demo and to make it as simple to understand as possible over showing off design.Anonymous
March 16, 2012
BTW I would love to see other designs. I see this as a starter and far from a "finished product."Anonymous
March 17, 2012
I am not a C# dude so I am interested in the logic, not the code. I would love to see other designs just to see other logic. I cannot use the C# code to teach my kids but having simple programs like this with alternate techniques is great. They do know enough so they can piece together what is going on in the C# program. It really makes them think.