I've created a program for the Tic Tac Toe game. I'm working on an exercise posted on the cplusplus.com website. Here is the exercise:
Code:
Requires:
variables, data types, and numerical operators
basic input/output
logic (if statements, switch statements)
loops (for, while, do-while)
arrays
Make a two player tic tac toe game.
★ Modify the program so that it will announce when a player has won the game (and which player won, x or o)
★★ Modify the program so that it is a one player game against the computer (with the computer making its moves randomly)
★★★★ Modify the program so that anytime the player is about to win (aka, they have 2 of 3 x's in a row, the computer will block w/ an o)
I have so far reached the one star ★ part of the exercise and noticed that the program requires arrays, which I have not used. I'm not exactly sure how to use arrays to do the exercise. Could someone point me in the right direction ans well as critiquing my existing code? Here's my code so far:
Try to rewrite your printBoard() function using loops. You will of course need to pass in the board array as a parameter.
It says that arrays are required in the 'Requires' part of the question. I cant see how arrays will make this simpler. From the sample code that you have posted, it would look almost similar to the original code without arrays. Could you elaborate on this?
What is the difference in all of those if-else statements? They are all the same thing except the number. What if it this were "super" tic-tac-toe board, say a 36x36 board? Would you write 36 if() statements to see which cell gets the mark? (I use 36 if you allow 0-9, A-Z for valid input moves).
Here is an obvious place where an array and looping makes a difference.
That one piece of code above where cell is a 1D array is equivalent to that entire repeated code you wrote. Note the usage of a string that has "123456789", and all I'm doing is looping through the string, seeing if any of the items is equal to one of the characters.
As a matter of fact, here is an even shorter version, without having to write a loop:
Code:
#include <string.h>
//...
cin >> move;
const char* allMoves = "123456789";
const char* pStr = strchr(allMoves, (int)move);
if ( pStr ) // move has been found
cell[pStr - allMoves] = mark; // this marks the correct cell with the mark
else
{
// invalid move
}
Anytime you see code that has a repeated pattern, it can be rewritten using loops, arrays, calling a function that does the looping internally, containers, or if its a difference in type, then a template class or function can be written.
I didn't do the 2d version as Lindley suggested (which I would have suggested also) -- I took the code you did write to show how even a simple change to a 1d array makes the code much shorter.
Regards,
Paul McKenzie
Last edited by Paul McKenzie; October 28th, 2011 at 12:23 AM.
Bookmarks