Monday, March 26, 2012

CIS 217: Array Assignment [Tic-Tac-Toe]

This assignment did not go as planned, to say the least.

The flow of the program was easy enough to figure out - I've done it in the past in other languages for other classes.
  1. Create a form with 9 Labels on it, a button to generate a new game, and an exit button.
  2. Create an 2D array to hold either 0s or 1s (0 = Os, 1 = Xs).  
  3. Loop through the array, then
    1. Generate a 0 or 1.
    2. Loop through the Label controls.
    3. Set the Text property of the current label to either "X" or "O", based on the generated number.
  4. Detect a winner:
    1. Search through the array for possible victories for Xs and Os:
      1. Top Row: Array locations [1,1], [1,2], and [1,3] are the same = Win.
      2. Middle Row: Array locations [2,1], [2,2], and [2,3] are the same = Win.
      3. Bottom Row: Array locations [3,1], [3,2], and [3,3] are the same = Win.
      4. Left Col: Array locations [1,1], [2,1], and [3,1] are the same = Win.
      5. Middle Col: Array locations [1,2], [2,2], and [3,2] are the same = Win.
      6. Right Col: Array locations [1,3], [2,3], and [3,3] are the same = Win.
      7. Left-Right Diag: Array locations [1,1], [2,2], and [3,3] are the same = Win.
      8. Right-Left Diag: Array locations [1,3], [2,2], and [3,1] are the same = Win.
  5. Let player click "New Game" button to generate the outcome again.

 Alas, I ran into a few snags:
  • Random numbers weren't generating, regardless of what I did.  Rebooting my PC and re-running the program fixed this.  Odd...
  • In an outcome set of 9 numbers, with 4 zeroes and 5 ones, the labels seemed to all display whatever the first number in the array was.
    • Yet, if I displayed each result (referencing the array), it showed the correct values.
    • I tested this in a ListBox as well...and sure enough, the random numbers were there.
I think my problem was that I used a control loop to display the outcomes, and might have been setting the Text property of each label to the current value of the current position in the array...so on one pass, all labels = 0.  The next, they = 1, then 0 again on the next pass, and so on...but never a mix of 1s and 0s. 

As an afterthought...I'm almost absolutely certain that this was the problem, as nothing else makes sense.

2 comments:

  1. My problem with the tic tac toe was that the random numbers were generating. So sometimes X would move a disproportional amount of times than O did. The other problem was when they both won, since I set X wins first in the long if/else statement it would show X as the winner in the event that both had won.

    ReplyDelete
  2. Did you create two arrays (one for X and one for O), or one? The book only mentioned one, so I wrote a 2D array to hold all of the moves. I just made a stupid mistake...lol.

    ReplyDelete