Windows Phone 7 : Part 2. Adding application Bar for the Tic Tac Toe game

This is the second part where I will add the Application bar (programatically) to the Tic Tac Toe game to start a new game after the game is over.  We will add a simple Application bar button. This is part 2 of the blog. If you are not familiar with this, please check out the Programming Tic Tac Toe Part 1.

 

This a very simple step. On Mainpage I will add a Application bar and create a button with a Icon. then I will add a click event handler to the button. When the button is clicked, the StartGame() method will run and it will reinitialize everything and you will have a new game. Very Short and Sweet.

Code Snippet
  1. public MainPage()
  2.         {
  3.             InitializeComponent();
  4.  
  5.             //add the application bar
  6.             ApplicationBar = new ApplicationBar();
  7.  
  8.             ApplicationBarIconButton button1 = new ApplicationBarIconButton(new Uri("/images/NewGame.ico", UriKind.Relative));
  9.             button1.Text = "New Game";
  10.  
  11.             ApplicationBar.Buttons.Add(button1);
  12.             button1.Click += new EventHandler(button1_Click);
  13.            
  14.             //Starts the game
  15.             StartGame();
  16.  
  17.         }

Here is the Click event handler

Code Snippet
  1. void button1_Click(object sender, EventArgs e)
  2.         {
  3.             StartGame();
  4.         }

And here is the StartGame method.

 

Code Snippet
  1. /// <summary>
  2.         /// Starts the game.
  3.         /// </summary>
  4.         private void StartGame()
  5.         {
  6.             player1Moves = new List<int>();
  7.             player2Moves = new List<int>();
  8.             _isGameOver = false;
  9.             _notAvailablePositions = new List<int>();
  10.  
  11.             _nextMoveFor = (int)Players.Player1;
  12.             this.TopLeft1.Content = string.Empty;
  13.             TopMiddle1.Content = string.Empty;
  14.             TopRight1.Content = string.Empty;
  15.             MiddleLeft1.Content =  string.Empty;
  16.             MiddleMiddle1.Content = string.Empty;
  17.             buMiddleRight1.Content = string.Empty;
  18.             BottomLeft1.Content = string.Empty;
  19.             BottomMiddle1.Content = string.Empty;
  20.             BottomRight1.Content = string.Empty;
  21.  
  22.             textBox1.Text = "New Game";
  23.  
  24.  
  25.         }

 

So now when you plug all these codes in you will get this.

 

image

 

See that little application bar on the bottom, that is what we added. When you click on that, it starts a new game.

Leave a Reply

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