Computer Science Teacher

# March, 2012

• #### Wouldn’t It Be Cool If…

Interesting new student competition from Time Warner Cable (TWC). As part of Connect a Million Minds (CAMM), the company’s five-year, \$100 million commitment to science, technology, engineering and math (STEM) education, TWC has launched Wouldn’t It Be Cool If…. This new STEM ideation competition challenges youth to use creativity and imagination to develop ideas that could make a difference in their lives, communities and even the world, and then show how STEM can make them a reality.

Wouldn’t It Be Cool If… is jointly presented by i.am FIRST, founded by artist, entertainer and entrepreneur will.i.am. FIRST is a key partner in this effort, along with the Boys & Girls Clubs of America and Fahrenheit 212, a leading innovation firm.

Kids ages of 10-15 can submit their ideas online at www.wouldntitbecoolif.com between February 21 and March 28. Four finalists will have the chance to travel to the FIRST Robotics Championship in St. Louis to pitch their ideas to will.i.am, Dean Kamen and other guest judges. One grand prize winner will develop their idea with Fahrenheit 212.

• #### It Doesn’t Pay To Be Too Clever

Recently someone posted the following question and bit of code to the Advanced Placement Computer Science teacher mailing list:

Assuming that all values are ints that have been properly initialized, which two of the following three lines of code are equivalent?

`//choice A`
`result1 -= result1 + x;`
` `
`//choice B`
`result2 = result2 - result2 + x;`
` `
`//choice C`
`result3 = result3 - (result3 + x);`

This is a simple (well reasonably simple) question of precedence. The tricky part for most students is the first statement which includes –= . Tricky because a) it is easy to miss (I did on first reading) and b) people often either forget where that fits in the order of precedence or think that it doesn’t matter. OK probably solid professionals don’t mess this up but for beginners it is a landmine.

Choices B and C are pretty straight forward.In the first case subtracting result2 from itself leaves zero which added to x results in x. In the second case adding x to results3 and then subtracting the result from result3 leaves you with -x. Assuming you remember that these results don’t change the value of result2 until all the operations are finished. Choice C wisely uses parenthesis to make the desired order of operations crystal clear. Without the parenthesizes the computer will move from left to right doing the subtraction first. Yet another good example of why you want to use parenthesis. Which brings us back to choice A.

The –= has a lower precedence than the +. Remember that? Ok then realize that result1 + x does not change the value of result1 immediately. Rather it is held and then subtracted from result1 (its original value) before being reset to the result of this final operation. So choice A and C return the same result. Great!

The problem in my mind is that choice A is just too darn clever. Nothing of value is saved by not doing tings the way choice C is done. No operations are removed. Not registers are being saved. No extra value at all really. But it does add to the possible confusion and make understanding the program harder. The positives would have to really outweigh the negatives to make choice A a good implementation choice. Showing everyone how clever you are is not a positive BTW.

# 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:

Windows Phone Development SDK

VISUAL STUDIO 2010 EXPRESS FOR WINDOWS PHONE

Windows Phone for Absolute Beginners video series

Alfred Thompson’s blog

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.

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.

Page 1 of 8 (22 items) 12345»