Window 7 Phone , Programming a Tic Tac Toe part 1

I am excited to see Windows 7 phone coming to live slowly. And as always I wanted to play with this new toy and make something to get my feet wet. After watching the introductory videos, I figured out that I will make a simple game. Well Tic Tac Toe was my choice.  I tried to stay away from complex logic and class seperation at this point. This is a Introductory project and just want it to work. So without any delay I will walk you through the process.

 

First of all, if you haven’t downloaded the Developer tools you can go here and download it. You will also find useful documentations. If you just want to watch few videos, go to Windows Phone 7 in 7 Minutes! (Beta) site.

 

  1. Fire up your Visual Studio 2010.
  2. Select Visual C# node (I used C#)
  3. Select Windows Phone Application
  4. I named my project TicTacToe ( you can name it whatever you want). (Don’t get confused if you see TicTacToe2 on the pictures. It is just for the pics).

CreateProject

 

Now you are on the Mainpage.xaml. You can items on your xaml and graphically as you want.

  • Click on Page Name.
  • On the right hand side (properties window), find Text and change it to Tic Tac Toe.
  • You can Change the Application Name from My Application to whatever you want.

FirstChange

 

  • On your left click on ToolBox and Drag 9 textboxes on the canvas.  I named them TopLeft1, TopMiddle1, TopRight1, MiddleLeft1, MiddleMiddle1, MiddleRight1, BottomLeft1, BottomMiddle1, BottomRight1. You can do this right on the xaml or properties.
  • Size them into squares.
  • Click on each button to generate the click events.
  • Add a TextBox on the bottom and change text to “Game On!!!”
  • One you are done your xaml’s <Grid> segment  should look like below.

 

<Grid x:Name="ContentGrid" Grid.Row="1">
            <Button Content=" " Height="82" HorizontalAlignment="Left" Margin="107,150,0,0" Name="TopLeft1" VerticalAlignment="Top" Width="89" Click="TopLeft1_Click" Background="#00EF0303" />
            <Button Content=" " Height="82" HorizontalAlignment="Left" Margin="299,150,0,0" Name="TopRight1" VerticalAlignment="Top" Width="89" Click="TopRight1_Click" />
            <Button Content=" " Height="82" HorizontalAlignment="Right" Margin="0,150,190,0" Name="TopMiddle" VerticalAlignment="Top" Width="89" Click="TopMiddle_Click" />
            <Button Content=" " Height="82" HorizontalAlignment="Left" Margin="299,326,0,0" Name="BottomRight1" VerticalAlignment="Top" Width="89" Click="BottomRight1_Click" />
            <Button Content=" " Height="82" HorizontalAlignment="Left" Margin="201,326,0,0" Name="BottomMiddle1" VerticalAlignment="Top" Width="89" Click="BottomMiddle1_Click" />
            <Button Content=" " Height="82" HorizontalAlignment="Left" Margin="106,326,0,0" Name="BottomLeft1" VerticalAlignment="Top" Width="89" Click="BottomLeft1_Click" />
            <Button Content=" " Height="82" HorizontalAlignment="Left" Margin="299,238,0,0" Name="buMiddleRight1" VerticalAlignment="Top" Width="89" Click="buMiddleRight1_Click" />
            <Button Content="" Height="82" HorizontalAlignment="Left" Margin="201,238,0,0" Name="MiddleMiddle1" VerticalAlignment="Top" Width="89" Click="MiddleMiddle1_Click" />
            <Button Content="" Height="82" HorizontalAlignment="Left" Margin="106,238,0,0" Name="MiddleLeft1" VerticalAlignment="Top" Width="89" Click="MiddleLeft1_Click" />
            <TextBox Height="72" HorizontalAlignment="Left" Margin="36,479,0,0" Name="textBox1" Text="Game On !!!!" VerticalAlignment="Top" Width="383"  />
        </Grid>

 

Now your UI is all set.

We will define a value for each button on the canvas.

 

 

1  2  3

4  5  6

7  8  9

 

There are few winning combinations

Horizontally

123, 321

456, 654

789, 987

 

Vertically

147 , 741

258 , 852

369 , 963

 

Diagonally

159 , 951

357 , 753

 

Well, if we just can sort and go one way we can eliminate the reverse order so our logic segment will have to only work half as hard. You can call me lazy if you want.

 

Now what other logic can I find in there. hmmm.

Well when all the lines match except for the top (lowest value number) and bottom (most valued numbers) it all equals to 15. 

The top if matches equal to 6 and bottom equals to 24.

Also left vertical will equals to 12 and right vertical equals to 18.

We will  have special cases for these two since 12 and 18 can be in few different ways

12 = (3, 4, 5 ) (2,3,7) (1,3,8) (1,4,7)

18 = (3,6,9) ( 1,8,9) (2,7,9) (4,5,9)

(I have left this logic out for now for simplicity and will implement the login on Part 3)

 

Wait, there are more. To have this logic actually work for us, we have to make sure that there are 3 numbers that comes together for that sum of values.

 

 

 

So here is the logic for the core

  1. If there are 3 numbers
  2. That equals to 15
  3. Or 24
  4. or 6

Then we have a winner. Simple isn’t it? Feel free to improve it if you want or point out the flaws in this logic.

 

Now we also need to keep track of players and boxes that are checked

  • Since they will alternate after each move. That’s easy to do, just have identifier to identify the whose move is next.
  • and create a list<int> where you can store all the values that are selected so far.
  • I also have Hard coded player name as ”Player 1” and “Player 2”. You can use input box to create dynamic names if you want.
  • Also to keep track of each players moves I have created 2 List<int> where I keep track of each player moves.

Ok Back to Programming.

 

Code Snippet
  1. private const string _player1 = "Player 1";
  2.         private const string _player2 = "Player 2";
  3.  
  4.         private List<int> player1Moves;
  5.         private List<int> player2Moves;
  6.  
  7.         private int _nextMoveFor;
  8.         private List<int> _notAvailablePositions;

 

You need to instantiate the list at the startup and  identify the first players move. Do this on the constructor

Code Snippet
  1. // Constructor
  2.         public MainPage()
  3.         {
  4.             InitializeComponent();
  5.  
  6.             player1Moves = new List<int>();
  7.             player2Moves = new List<int>();
  8.             
  9.             _notAvailablePositions = new List<int>();
  10.  
  11.             _nextMoveFor = (int)Players.Player1;
  12.             
  13.         }

 

You will have to create a method that will handle your Button Selection. You need to pass the button that was selected and number for that button.

I called this HandleBoxSelection

 

Code Snippet
  1. /// <summary>
  2.         /// Handles the box selection.
  3.         /// </summary>
  4.         /// <param name="buttonId">The button id.</param>
  5.         private void HandleBoxSelection(int buttonId, object sender)
  6.         {
  7.             if (IsPositionAvailable(buttonId) == true)
  8.             {
  9.                 if (_nextMoveFor == (int)Players.Player1)
  10.                 {
  11.  
  12.                     ChangeForSelected(Players.Player1, buttonId,sender);
  13.                 }
  14.                 else
  15.                 {
  16.                     ChangeForSelected(Players.Player2, buttonId, sender);
  17.  
  18.                 }
  19.  
  20.                 _notAvailablePositions.Add(buttonId);
  21.             }
  22.         }

 

This is a very simple method. It Checks If the position is available for that button. If it is then checks who is changing the move and changes for the person. You got introduced to 3 new things here. 2 Methods IsPositionAvailable and ChangeForSelected and a enum called Players. They are below.

 

Code Snippet
  1. public enum  Players
  2. {
  3.     Player1 = 1, Player2 = 2
  4. }

 

Is PositionAvailable is very simple. Just goes through the list of already selected values and if there are no match it means the position is still available.

Code Snippet
  1. /// <summary>
  2.         /// Determines whether [is position available] [the specified position].
  3.         /// </summary>
  4.         /// <param name="position">The position.</param>
  5.         /// <returns>
  6.         ///     <c>true</c> if [is position available] [the specified position]; otherwise, <c>false</c>.
  7.         /// </returns>
  8.         private bool IsPositionAvailable(int position)
  9.         {
  10.             bool retVal = true;
  11.             if (_notAvailablePositions.Count > 0)
  12.             {
  13.                 foreach (int item in _notAvailablePositions)
  14.                 {
  15.                     if (position == item)
  16.                     {
  17.                         retVal = false;
  18.  
  19.                     }
  20.  
  21.                 }
  22.             }
  23.  
  24.             return retVal;
  25.         }

 

Change for Selected has few things.

  • Adding the move to appropriate player.
  • Setting the flag for move to the next player.
  • Changing the Button que to “X” or “O”.
  • Checking the GameLogic to see if we have a winning number.
Code Snippet
  1.     /// <summary>
  2.     /// Changes for selected.
  3.     /// </summary>
  4.     /// <param name="player">The player.</param>
  5.     /// <param name="buttonId">The button id.</param>
  6.     private void ChangeForSelected(Players player, int buttonId, object sender)
  7.     {
  8.         bool isWinner = false;
  9.         string winner = string.Empty;
  10.         if (player == Players.Player1)
  11.         {
  12.             player1Moves.Add(buttonId);
  13.             _nextMoveFor = (int) Players.Player2;
  14.             ((ContentControl) (sender)).Content = "X";
  15.             isWinner = GameLogic.IsWinningNumbers(player1Moves);
  16.             winner = _player1;
  17.         }
  18.         else
  19.         {
  20.             player2Moves.Add(buttonId);
  21.             _nextMoveFor = (int) Players.Player1;
  22.             ((ContentControl) (sender)).Content = "O";
  23.             isWinner = GameLogic.IsWinningNumbers(player2Moves);
  24.             winner = _player2;
  25.  
  26.         }
  27.  
  28.         if (isWinner)
  29.         {
  30.             textBox1.Text = winner + " wins the game";
  31.         }
  32. }

 

GameLogic is where we are implementing all the predefined GameLogic.

 

Code Snippet
  1. public static class GameLogic
  2.     {
  3.         //Possible Win
  4.         //123, 456,789,
  5.         //369,258,147,
  6.         //159,753
  7.         /// <summary>
  8.         /// Determines whether [is winning numbers] [the specified numbers list].
  9.         /// </summary>
  10.         /// <param name="numbersList">The numbers list.</param>
  11.         /// <returns>
  12.         ///     <c>true</c> if [is winning numbers] [the specified numbers list]; otherwise, <c>false</c>.
  13.         /// </returns>
  14.         public static bool IsWinningNumbers(List<int> numbersList)
  15.         {
  16.             bool retVal = false;
  17.             if (numbersList != null)
  18.             {
  19.                 numbersList.Sort();
  20.  
  21.                 retVal = IsWinningCombination(numbersList);
  22.         
  23.             }
  24.  
  25.             return retVal;
  26.         }
  27.  
  28.         /// <summary>
  29.         /// Gets the winner with3 numbers.
  30.         /// </summary>
  31.         /// <param name="numbersList">The numbers list.</param>
  32.         /// <returns></returns>
  33.         private static bool GetWinnerWith3Numbers(List<int> numbersList)
  34.         {
  35.             bool retVal = false;
  36.             var total = numbersList[0] + numbersList[1] + numbersList[2];
  37.             if (total == 15 || total == 24 || total == 6) // we have a winner
  38.             {
  39.                 retVal = true;
  40.             }
  41.  
  42.             return retVal;
  43.         }
  44.  
  45.         /// <summary>
  46.         /// Determines whether [is winning combination] [the specified my list].
  47.         /// </summary>
  48.         /// <param name="myList">My list.</param>
  49.         /// <returns>
  50.         ///     <c>true</c> if [is winning combination] [the specified my list]; otherwise, <c>false</c>.
  51.         /// </returns>
  52.         private static bool IsWinningCombination(List<int> myList)
  53.         {
  54.             List<int> v1 = new List<int>();
  55.             List<int> v2 = new List<int>();
  56.             List<int> v3 = new List<int>();
  57.  
  58.             //horizontal items
  59.             List<int> h1 = new List<int>();
  60.             List<int> h2 = new List<int>();
  61.             List<int> h3 = new List<int>();
  62.  
  63.             //Diagonal
  64.             List<int> d1 = new List<int>();
  65.             List<int> d2 = new List<int>();
  66.             bool Retval = false;
  67.             if (myList != null)
  68.             {
  69.                 myList.Sort();
  70.                 foreach (int item in myList)
  71.                 {
  72.                     switch (item)
  73.                     {
  74.                         case 1:
  75.                             v1.Add(1);
  76.                             h1.Add(1);
  77.                             d1.Add(1);
  78.                             break;
  79.                         case 2:
  80.                             v1.Add(2);
  81.                             h2.Add(2);
  82.                             break;
  83.                         case 3:
  84.                             v1.Add(3);
  85.                             h3.Add(3);
  86.                             d2.Add(3);
  87.                             break;
  88.                         case 4:
  89.                             v2.Add(4);
  90.                             h1.Add(4);
  91.                             break;
  92.                         case 5:
  93.                             v2.Add(5);
  94.                             h2.Add(5);
  95.                             d1.Add(5);
  96.                             d2.Add(5);
  97.                             break;
  98.                         case 6:
  99.                             v2.Add(6);
  100.                             h3.Add(6);
  101.                             break;
  102.                         case 7:
  103.                             v3.Add(7);
  104.                             h1.Add(7);
  105.                             d2.Add(7);
  106.                             break;
  107.                         case 8:
  108.                             v3.Add(8);
  109.                             h2.Add(8);
  110.                             break;
  111.                         case 9:
  112.                             v3.Add(9);
  113.                             h3.Add(9);
  114.                             d1.Add(9);
  115.                             break;
  116.                     }
  117.                 }
  118.  
  119.                 
  120.                 //add these to a list
  121.                 var allItems = new List<List<int>>();
  122.                 //check each items
  123.                 allItems.Add(v1);
  124.                 allItems.Add(v2);
  125.                 allItems.Add(v3);
  126.                 allItems.Add(h1);
  127.                 allItems.Add(h2);
  128.                 allItems.Add(h3);
  129.                 allItems.Add(d1);
  130.                 allItems.Add(d2);
  131.  
  132.                 foreach (var item in allItems)
  133.                 {
  134.                     if (item.Count == 3)
  135.                     {
  136.                         if (GetWinnerWith3Numbers(item))
  137.                         {
  138.                             Retval = true;
  139.                             break;
  140.                         }
  141.                     }
  142.                 }
  143.  
  144.  
  145.             }
  146.  
  147.             return Retval;
  148.         }
  149.     }

 

As you can see the method IsWinningNumber is the only call you make and that will do all the work for you.

  • It calls IsWinningCombination and sends it the list of sorted numbers.
  • Winning Combination creates 8 List<int> and keeps 8 possible winning list.  Each list will have 3 numbers (well at least one of them will have 3 number in case of a win).
  • We take the list of the lists and call GetWinnerWith3Numbers ( this is where the “Sum” of number are checked.

image

 

You will see the game will show “Player 1 wins the game” or “Player 2 wins the game”  in the textbox once someone wins. Thats it folks.

 

Here is the source codes Download Source

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *