Array for TicTacToe (2D)

Pages: 12
I have been working on this program for a while, and trying to get help from many different sources. I have a math disability and have a hard time with some of the concepts in C++. Even though I have been able to figure most of the assignments out, I am having trouble when the teacher introduces new techniques. I have asked for help before on the forum, and everyone was very helpful, but I didn't understand what I was told to do, because she has not yet covered the information that was suggested here in the forum. We are 13 weeks into a 15 week class, and I feel totally lost with this concept. She wants us to use a 2D array, and make a physical board in the code. I have spent the last week and a half trying to research on the web and in my book how to do arrays for this, but most of what is being used in code on the web is beyond me.

The Assignment is:

write a two player Tic Tac Toe game. The user should enter the row and column (1,2,or 3) for the cell that they want to place their piece in. Every time through the grid should be redrawn to show the current layout. After each play, the computer should check to see if someone won the game. Then users should be able to start a new game.

I have drawn the grid, but there is an error that is shifting it sideways, and I can't find it. I played with it a bit. Can anyone tell me the error so I can continue to try to figure the coding out? Any other help would also be appreciated. What I have so far is how she said to do it.

Here is my code:



#include <iostream>

using namespace std;

int main()
{
const int ROWS = 3;
const int COLS = 3;
char board[ROWS][COLS] = {' '};


cout << "| " << board[0][0] << " | " << board[0][1] << " | " << board[0][2] << "|\n";
cout << "|____|____|____|\n";
cout << "| " << board[1][0] << " | " << board[1][1] << " | " << board[1][2] << "|\n";
cout << "|____|____|____|\n";
cout << "| " << board[2][0] << " | " << board[2][1] << " | " << board[2][2] << "|\n";
cout << "|____|____|____|\n";






return 0;
}


Thanks,
Miscue
Last edited on
Hi Miscue. I'm a beginner at c++ like yourself but just completed this same TicTacToe assignment for my Intro C++ class so I think I can help.

Currently the issue with your board is caused because there is an uneven number of spaces.

1
2
3
cout << "| " << board[0][0] << " | " << board[0][1] << " | " << board[0][2] << "|\n";

cout << "|____|____|____|\n";


In line 1 you have a "|" and then 3 spaces before the next one - one space is in the quotes with the |. The next space is pulled from board[0][0], and the 3rd space comes from the next set of quotes, " | ". But in the 2nd line you have 4 spaces between each |.

You could fix it as follows:

1
2
3
cout << "| " << board[0][0] << " | " << board[0][1] << " | " << board[0][2] << " |\n";

cout << "|___|___|___|\n";


But in the long run it's preferable to use a function containing a "for" loop to output an array's contents.

You want to display this board every time a user makes a move, and you don't want to have to retype (or copy/paste) all this code every time you redisplay it.

So you want to make a void function that displays the current board each time it is called. If your class is structured like mine you've probably done a chapter on functions recently, yes?
Sorry about the repeating posts...
Last edited on
no, she didn't teach functions until a week after she gave us this assignment. Even so, I am so confused by her lack of linking her actual examples to anything we need to use. She doesn't want us to use functions for this. She suggested that it be typed it like that.

I am not sure I really understand functions either. What I got out of functions, was that you can make any word do anything if you use the appropriate code after.

I see what is different in line three, but I can't see it in line 1....

I am not sure how to code the rest. I was just worrying right now about the grid. Thank you for responding! I will try to change what you suggested about the lines
Last edited on
Sorry about the repeating posts...
Last edited on
Sorry about the repeating posts...
Last edited on
Sorry about the repeating posts...
Last edited on
In the first line I added a space in << " |\n"; because there wasn't a space before the |.

You would want to change the spacing the same way on your other lines of code.

I am happy to explain functions more if you would like, but I won't force it either if you aren't supposed to use functions on this assignment. :) I thought they were VERY useful because they allow you to type code once and then use it as many times as you want.

For a start on coding the rest - you are going to need 2 variables to store the user's 'move' temporarily. Then you will have a loop that checks the input to see if it's valid - what if the user tried to go in space [4][1]? Your loop should detect input that's out of bounds and tell the user to enter it again. You may also want to make a loop that checks if that space is empty or filled to prevent a person going in a place where there's already an x or y.

You will also need a loop or loops to check for wins after each play. Of course if someone wins, you want to end the game, but if nobody has won, the game should end when the board is full.
sorry about the extra posts, my computer's graphics card decided to die and I couldn't tell if the post had gone through.
I would love to hear about functions, I think that I am supposed to use them in this week's assignment:

A choose your own adventure story.

Thank you for your help!
Functions are a way of making sets of instructions (code) for the program. One analogy I saw compared it to baking. If you were going to bake several recipes of cookies, you could write out the instructions and ingredient list 5 times - or you could write it once, and then follow the same instructions again for each batch.

Functions in C++ are set up like

1
2
3
4
5
returntype functionName (datatype inputvariable, datatype inputvariable2)
{
instructions that do things to input variables;
return something;
}


They are defined OUTSIDE the main, either inside a Class definition, or globally.

It's a bit confusing to explain because many of these function parts are optional. For example, a function does not have to 'return' anything, in which case the returntype would be void. It also doesn't have to accept any information in the input.

Suppose you just wanted to display something - heck, a TicTacToe board - over and over. Since the purpose of that function is just to cout an array, it doesn't need any input and it doesn't need to 'return' anything. We will use "void" as the return type because no return is needed. The parenthesis at the function beginning will be empty since it doesn't need any input.

Your function would look as follows.

1
2
3
4
5
6
7
8
9
10
void displayBoard()
{
cout << "| " << board[0][0] << " | " << board[0][1] << " | " << board[0][2] << " |\n";
cout << "|___|___|___|\n";
cout << "| " << board[1][0] << " | " << board[1][1] << " | " << board[1][2] << " |\n";
cout << "|___|___|___|\n";
cout << "| " << board[2][0] << " | " << board[2][1] << " | " << board[2][2] << " |\n";
cout << "|___|___|___|\n";
return 0;
}


Any time you wanted to redisplay the board again in your main() (which by this time you might have noticed is a function itself!) you would do

displayBoard();

and the program would find that function, go through the steps in it, and then return to the main and continue with whatever you've programmed next.



I also want to show you a function that accepts arguments (data sent in via the brackets) and returns something. Suppose you have a date stored in int variables. Let's say it is stored in

1
2
3
int day;
int month;
int year;


Since the datatype is int, these are stored as numbers. But what if you want to let the user enter any date, and then later cout that date with the month written as a word, like "January 4, 2012"? How do you convert the int month to the correct string - January, February, etc - automatically?

Well you have a function like so. In this function the return type is "string" because it's going to give us a string of characters. The argument it takes (int m) is an integer. Whatever integer we send in when we call the function will be stored in "m". Then it declares a string variable named "mw" to store the word in.

Please note that any variable declared inside a function only exists inside that function. So it doesn't matter if 2 different functions use the same variable names, so long as it doesn't confuse you when you're programming it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
string wordMonth(int m)
	{
		string mw;
		if (m==1)
			{mw="January";}
		else if (m==2)
			{mw="February";}
		else if (m==3)
			{mw="March";}
		else if (m==4)
			{mw="April";}
		else if (m==5)
			{mw="May";}
		else if (m==6)
			{mw="June";}
		else if (m==7)
			{mw="July";}
		else if (m==8)
			{mw="August";}
		else if (m==9)
			{mw="September";}
		else if (m==10)
			{mw="October";}
		else if (m==11)
			{mw="November";}
		else if (m==12)
			{mw="December";}
		return mw;
	}


At the end there it says "return mw;" which means the function is going to return whatever it just stored in the string variable 'mw'.

You could just call this function by saying

wordMonth(month);

which will take whatever info is currently stored in int month, and send it in to the variable m in the function. The function will then store the appropriate word in mw, and return that. But when it returns that information, nothing is really done with it. It's not being stored in a variable in main. It's not being output with cout. So instead we will do

cout << wordMonth (month) << " " << day << ", " << year << endl;

Yes... you can call the function inside a cout statement! This will send the numeric month in and output whatever string is returned, followed by a space, the numeric day, a comma, and the numeric year.


I hope this helps.. making any sense so far?
Yes, although being a bit slow with this course, I may need to re-read it several times, but I don't mind. I will try this out and practice it.

Do you know how to tell it which coordinates to find inside the grid without using functions, or how to tell it to pick the Y and the X axis for choices? I'm sorry if my questions seem silly...

I printed the notes from here on arrays and I see that it says to access an array you should frame it this way:

name [index]

How does that translate into telling it which box is being entered on which axis?

Thank you for the time you have taken to help me!

Miscue
name[index] works perfectly for a one dimensional array, but for 2 dimensional arrays you will use arrayname[row][column] to access the contents.

And of course remember that both the row numbering and the column numbering in arrays start with 0!
here is what I tried since last night, and it runs, but there is a logic error in the output. I commented out the things I was unsure of. Have you any Idea what I did wrong?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>

using namespace std;
int main() 
{
	
		const int ROW = 3;
		const int COL = 3;
		char board[ROW][COL] = {' '};
		//char location[ROW][COL]; not sure about this either
		int playerName1;
		int playerName2;


			cout << "Let's Play Tic Tac Toe!\n\n";
			cout << "Player 1, enter your name: ";
			cin >> playerName1;
			cout << "Your Letter is x, .\n\n" << playerName1;
			
			cout << "Player 2, enter your name: ";
			cin >> playerName2;
			cout << "Your Letter is o, .\n\n" << playerName2;
			cout << "Enter the numbers for rows first, and then the columns to choose a square to occupy.\n\n";
			//cin >> location[" "] [" "]; not sure-- is this what you meant by arrayname[row][col]

			cout << "  _O___1___2_\n";
			cout << "0| " << board[0][0] << " | " << board[0][1] << " | " << board[0][2] << " |\n";
			cout << " |___|___|___|\n";
			cout << "1| " << board[1][0] << " | " << board[1][1] << " | " << board[1][2] << " |\n";
			cout << " |___|___|___|\n";
			cout << "2| " << board[2][0] << " | " << board[2][1] << " | " << board[2][2] << " |\n";
			cout << " |___|___|___|\n";
	




return 0;
}





it outputs a bunch of numbers instead of the player's name.

Thank you for your help!
Miscue
Last edited on
You will need to store the user's input in temp variables before putting it in the array. Also you want to check that it's in bounds.

So, in pseudocode...

Declare two integer variables to store user input - x and y, or row and column, whatever you want to call them.

Ask user to input the row and column.

cin row variable & column variable

use a for loop to check if the output is within bounds (within 1 and 3, they can't go in row 4 obviously)

use another loop to check that the requested space is empty and not already occupied
(while array[row][column] != blank, have the user enter again)

after you have verified that the input is OK, you can store it in the array with a statement like array[row][column] = player;
You're code is outputting numbers because the variables "playerName1" and "playerName2" are declared as type int. (Which is designed to hold a number between roughly +2 million and -2 million.) You'll want to make them of type string instead. (A string holds an infinite amount of characters.)

Whether you use functions or not, (which the teacher really should let you, otherwise it's going to make coding it a LOT more difficult,) the TicTacToe game is going to require loops. (For example, determining if Player1 or Player2 has gotten 3 in a row.)

For quick starters, this is what I would use to set the initial values for the 2D array: (If you need more help on loops feel free to ask.)
1
2
3
4
5
6
7
8
9
for(int row = 0; row < ROW; row++ ) { /* This is a for loop, "int row = 0" starts a counter at 0, 
the second part checks if the int row is less than the constant ROW (3)
and the last part increases row by 1.*/
		
	for(int col = 0; col < COL; col++) { // Same thing here, except it's for the column.
		array[row][col] = ' '; // This will set the element (eg. board[0][0]) to a space. 
	}

}

What this will do is it will start at the first row (0), then loop through each column in row 0, after it has reached the last colulmn (2), it will go to the next row and start again.

You could also set it up as:
char board[ROW][COL] = { {' ',' ',' '}, {' ',' ',' '}, {' ',' ',' '} };
(You're going to need to initialize the 2D array so that the program can tell if the element (eg; board[1][1]) has a value or not. You have it partly initialized, but the single space { ' ' } will only set the first element. (board[0][0]) )


You've got the right idea on line 24, (where you're inputting the location.) But a second 2D array isn't necessary. Instead, you could do something like the following: (This code assumes you've already declared int row, int col, and char player. )
1
2
3
4
5
6
cin >> row >> col; // Gets row and column from Player.

if( board[row][col] == ' ' ) // if the specified element (eg; 0 0) is empty,
	board[row][col] = player; // assign the player's symbol. (eg; X or O.)
else
	cout << "Already taken!" << endl; // else, notify the spot is taken. (endl is the same as "\n") 



Is there anyone taking the class with you that would be willing to help you out? Someone who's willing to go through it with you? I'm not saying you shouldn't try to get help online, (we are happy to help!) But someone helping in person would be a lot more beneficial. (Or maybe a Math Tutor who knows programming, if your college provides free tutoring.)

Anyway, hope this helps. (Sometimes I have difficulty simplifying things. If you need a more detailed explanation on something, don't hesitate to ask. ;) )
Last edited on
At this point, I have been seeking tutoring from one of the guys in the student resource center (who also happens to be in my class) since the first week of class. When Skyrim came out last month, he told me he hadn't done the work and couldn't help me. He hasn't been able to help since.

I have asked everyone in the class so far, but most are still stuck somewhere between assignment 2 and assignment 8, and we are in week 13. The one kid who does know what he is doing I asked last week to help, and he said he couldn't--the tutor says he likes to figure it out completely before he shows anyone else. I am one of a small group of people who are doing this assignment because I am behind just two assignments. The whole class is behind. Thank you for your advice!

I will put this to work, and probably post again.
Thank you Emilya and benjamin d. Your explanations have been much clearer and easier to understand than what I have been reading in the book I bought, and what the teacher has been saying at school. :-)

Miscue
I give credit to my instructor, and the book he chose for the class: http://www.amazon.com/Programming-Program-Design-Including-Structures/dp/0538798092/ref=dp_ob_title_bk

Sounds like the teacher might be going too fast, not giving enough time for the students to understand a concept before moving to the next. (Not meaning to sound judgmental or anything.) You seem do be doing really good so far, despite your "math disability." (My sister struggles in math as well, she and I joke that she has M.A.D. Math Anxiety Disorder. :P )

Anyway, glad we were able to help. If you have anymore questions feel free to ask.
Last edited on
I'm glad to help miscue. I am glad you have found some real life help too as sometimes things are more easily explained in person. Feel free to ask if you hit another stumbling block.
Pages: 12