• 0

[C++] Tic Tac Toe with Variable Size Board


Question

We've just started learning arrays and the what-not in my C++ class. Our assignment is to create a tic tac toe program that has a user-set variable size board (3x3, 4x4, 9x9, etc). He gave us an example 3x3 tic tac toe program listed below a week back or so and told us to play around with it to make it multi-sized. I've started playing with it slightly, but for the most part, am I just going to change the constant values of 3 to variables? I thought you could not set an array to size variable?

#include <stdio.h>
#include <stdlib.h>

char matrix[3][3];  /* the tic tac toe matrix */

char check(void);
void init_matrix(void);
void get_player_move(void);
void get_computer_move(void);
void disp_matrix(void);

int main(void)
{
  char done;

  printf("This is the game of Tic Tac Toe.\n");
  printf("You will be playing against the computer.\n");

  done =  ' ';
  init_matrix();

  do {
	disp_matrix();
	get_player_move();
	done = check(); /* see if winner */
	if(done!= ' ') break; /* winner!*/
	get_computer_move();
	done = check(); /* see if winner */
  } while(done== ' ');

  if(done=='X') printf("You won!\n");
  else printf("I won!!!!\n");
  disp_matrix(); /* show final positions */

  return 0;
}

/* Initialize the matrix. */
void init_matrix(void)
{
  int i, j;

  for(i=0; i<3; i++)
	for(j=0; j<3; j++) matrix[i][j] =  ' ';
}

/* Get a player's move. */
void get_player_move(void)
{
  int x, y;

  printf("Enter X,Y coordinates for your move: ");
  scanf("%d%*c%d", &x, &y);

  x--; y--;

  if(matrix[x][y]!= ' '){
	printf("Invalid move, try again.\n");
	get_player_move();
  }
  else matrix[x][y] = 'X';
}

/* Get a move from the computer. */
void get_computer_move(void)
{
  int i, j;
  for(i=0; i<3; i++){
	for(j=0; j<3; j++)
	  if(matrix[i][j]==' ') break;
	if(matrix[i][j]==' ') break;
  }

  if(i*j==9)  {
	printf("draw\n");
	exit(0);
  }
  else
	matrix[i][j] = 'O';
}

/* Display the matrix on the screen. */
void disp_matrix(void)
{
  int t;

  for(t=0; t<3; t++) {
	printf(" %c | %c | %c ",matrix[t][0],
			matrix[t][1], matrix [t][2]);
	if(t!=2) printf("\n---|---|---\n");
  }
  printf("\n");
}

/* See if there is a winner. */
char check(void)
{
  int i;

  for(i=0; i<3; i++)  /* check rows */
	if(matrix[i][0]==matrix[i][1] &&
	   matrix[i][0]==matrix[i][2]) return matrix[i][0];

  for(i=0; i<3; i++)  /* check columns */
	if(matrix[0][i]==matrix[1][i] &&
	   matrix[0][i]==matrix[2][i]) return matrix[0][i];

  /* test diagonals */
  if(matrix[0][0]==matrix[1][1] &&
	 matrix[1][1]==matrix[2][2])
	   return matrix[0][0];

  if(matrix[0][2]==matrix[1][1] &&
	 matrix[1][1]==matrix[2][0])
	   return matrix[0][2];

  return ' ';
}

9 answers to this question

Recommended Posts

  • 0

Yes, you could start with a maximum size matrix and the jsut replace the 3's by a variable N (which would be the size)

also you'll need a double loop in

for(i=0; i<3; i++)  /* check rows */
	if(matrix[i][0]==matrix[i][1] &&
	   matrix[i][0]==matrix[i][2]) return matrix[i][0];

  for(i=0; i<3; i++)  /* check columns */
	if(matrix[0][i]==matrix[1][i] &&
	   matrix[0][i]==matrix[2][i]) return matrix[0][i];

  /* test diagonals */
  if(matrix[0][0]==matrix[1][1] &&
	 matrix[1][1]==matrix[2][2])
	   return matrix[0][0];

  if(matrix[0][2]==matrix[1][1] &&
	 matrix[1][1]==matrix[2][0])
	   return matrix[0][2];

which will allow you to check the entire row or column

  • 0

You could also use the STL (standard template library) vector class for a dynamic array size based on user input. There's plenty of examples online (cplusplus.com for instance). Consider it if you absolutely have to have a dynamic size board that could be any size - otherwise, the past comments about a max size would work too and probably be more familiar to you.

  • 0
  rpgfan said:
Or if you feel experienced enough, you could always create it dynamically yourself... Just remember that the amount of memory available is finite. In other words, don't forget to delete[] what you allocate! ^_^

Good tip! :) It is very important to take care of the garbage collection functionality (e.g. cleanup any unneeded resources). It is a good habit to get into.

Also, for this task couldn't you simply create a variable called "rows" and a variable called "columns" and have the user enter the number for each? Then, if I am correct, you would simply pass the array that you create the values that were entered.

Edited by winlonghorn
  • 0

Thanks for all the replies guys...considering my experience and the scope of the course, I believe I'll stick with setting a constant for the matrix. Now I'm trying to actually get the matrix to display correctly.

char matrix[26][26];  // the tic tac toe matrix

char check(void);
void init_matrix(int BOARD_SIZE);
void get_player_move(void);
void get_computer_move(void);
void disp_matrix(int BOARD_SIZE);
void get_player2_move(void);
void get_computer2_move(void);

/* Initialize the matrix. */
void init_matrix(int BOARD_SIZE)
{
  int i, j;

  for(i=0; i<BOARD_SIZE; i++)
	for(j=0; j<BOARD_SIZE; j++) matrix[i][j] =  ' ';
}

//Display the matrix
void disp_matrix(int BOARD_SIZE)
{
int t; int u;
//Cosmetic bar above |---|---|---|
	printf("|");
	for (t=0; t<BOARD_SIZE; t++)
	do{
	if (t != BOARD_SIZE) printf("---|");}
	while(t>BOARD_SIZE);

//Bar t
	printf("\n|");
	do{
	for (u=0; u<BOARD_SIZE; u++)
	printf(" %c |", matrix [0][u]);
	}while(u>BOARD_SIZE);


//Cosmetic bar below |---|---|---|
	printf("\n|");
	for (t=0; t<BOARD_SIZE; t++)
	do{
	if (t != BOARD_SIZE) printf("---|");}
	while(t>BOARD_SIZE);
	printf("\n");

}

I'm slowly getting it. This will display only one vertical bar, but with the correct amount of spaces horizontally. I believe I just need to add another for loop....for (t=0, t<BOARD_SIZE; t++)....is this correct?

Edited by entropypl
  • 0

Take the habit of typing your loops in full, it'll save you a lot of subtle bugs. Later when you feel very confident and are working alone on a project, you can do one-line loops with no brackets.

When you write a for loop, for instance, start by writing :

for ([initialization]; [break condition]; [increment]) {

}

Next, write what's inside the loop :

for ([initialization]; [break condition]; [increment]) {
	[statement 1];
	[statement 2];
	....
}

The same goes for if statements, functions, classes, while loops, anything that has a body. Except maybe individual cases in a switch statement.

I say this because your code is pretty hard to understand as it is, and it could break the minute you do any kind of modification to it. Take for instance this :

  for(i=0; i&lt;BOARD_SIZE; i++)
	for(j=0; j&lt;BOARD_SIZE; j++) matrix[i][j] =  ' ';

Let's say you have a second matrix, overlayed upon the first, which you'll want to initialize in the same spot. You might want to write :

  for(i=0; i&lt;BOARD_SIZE; i++)
	for(j=0; j&lt;BOARD_SIZE; j++) matrix1[i][j] =  ' '; matrix2[i][j] = ' ';

If this compiles, it will not do what you want. Can you tell why? Actually, the compiler will save you there, but it can't do the guesswork all the time. Just write the loops properly :

for(i=0; i&lt;BOARD_SIZE; i++) {
	for(j=0; j&lt;BOARD_SIZE; j++) { 
		matrix1[i][j] =  ' ';
		matrix2[i][j] = ' ';
	}
}

  • 0
  Dr_Asik said:
Take the habit of typing your loops in full, it'll save you a lot of subtle bugs. Later when you feel very confident and are working alone on a project, you can do one-line loops with no brackets.

I understand. Sometimes I guess I get excited and get ahead of myself :rolleyes:. I also need to start practicing proper indentation much more. I'll go through my project and clean it up after this post.

  Quote
We will play on a variable-size board. Your program should define the following integer constants:

BOARD_SIZE

determines both the width and height of the game board (which is always square)

WIN_LENGTH

determines the number of Xs or Os in a row (either horizontally, vertically, or diagonally) that a player needs in order to win

so that the game can be played on different size boards simply by changing these values.

I've completed my disp_matrix function and it works flawlessly, now onto the hardest part, checking for a winner with a variable sized board AND variable sized WIN_LENGTH. Will a double loop work for the check() function? I was thinking I would have to totally butcher it and start anew.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • It's an improvement overall but I'm also of the idea that they should just give users more options and let them have the menu they like instead of just going with one outline and some minor options (though finally getting rid of recommended is great). I know people who don't want pins and would rather it all be just the list/grid of apps. Others just want pins, others want them side by side and not up on top of each other. Have more layout options and let people mix and match, problem solved.
    • Hi all, I've got a Pioneer VSX 815-k receiver. Love this thing, however, my cat did his business on top of it and kinda recked it... Only analog works (5.1 surround RCA inputs). Normally I'd use toslink from mobo to digital in on the receiver, but the result is a ton of loud white noise over the music. Analog works just fine, so I'm forced to use the 3.5mm jacks on the rear of the mobo to the RCA inputs on the receiver. The issue I face is that there is no DTS or anything fun.. Originally, I could play all my MP3s or watch YouTube etc, and the subwoofer would be booming as I like because of the mixing from the DAC. Now with the analog, none of that is happening  I'm wondering if there's some kind of software solution for Windows to get the subwoofer to play as it did when I had it hooked up through toslink, but for analog out instead. As of now, only audio files that were encoded specifically to produce sound to the sub, will work, but nothing else. As to which onboard sound solution my mobo has, this from the website's description: 121dB SNR AMP-UP Audio with ALC1220 & High-End ESS SABRE 9018 DAC with WIMA audio capacitors Sound BlasterX 720°, the top-of-the-line audio engine solution for 4K gaming and entertainment  yea it uses that wonky SBx 720 app to change the audio effects n stuff.. but doesn't help with my issue Eventually yea, I wanna buy a new one. They're about $80 on ebay after shipping, but that will have to wait.
    • Serious question here. Why is the start menu such a heated topic? I can't remember the last time that I used the start menu for anything at all other than it pops up when I hit the WIN key on my keyboard before I type for the program I want to run and then hit Enter or to restart my machine. I honestly wish it would just go away, and it just be replaced with the PowerToys Run menu. Am I missing something with the Start menu? I see people always talking about installing third party replacements and such, but I just wonder what some are actually using the Start menu for that I might be missing out on. Genuine question. Hopefully not offending anyone as I know everyone has their own way to work and access things in the OS.
    • These are the Apple Watch models that support watchOS 26 by Aditya Tiwari Apple has announced the latest operating system upgrade for its smartwatch lineup, called watchOS 26, not watchOS 12, as many expected a while ago. The Cupertino giant has unified the software experience across its platforms by introducing the "Liquid Glass" software design and renaming all the operating systems to version 26. That said, the next question is which Apple Watch models will support watchOS 26. Apple has shared the official list of devices: Apple Watch Ultra 2 Apple Watch Ultra Apple Watch Series 10 Apple Watch Series 9 Apple Watch Series 8 Apple Watch Series 7 Apple Watch Series 6 Apple Watch SE (2nd Generation) The upcoming Apple Watch update brings several new features to your wrist. Liquid Glass design gives a fresh look to the UI with updated Control Center and translucent buttons within apps. It's new Workout Buddy feature can use an Apple Intelligence-enabled iPhone nearby to provide personalized, spoken motivation during workouts. Building on the Double Tap feature, you can now flick your wrist to perform actions like muting incoming calls, silencing timers, and dismissing notifications when your hands are full. It is available on Apple Watch Ultra 2 and Apple Watch Series 9 (or later). watchOS 26 is currently available for testing through the Apple Developer Program. It will roll out to general users during the fall season, when Apple is expected to refresh the Ultra and SE models. Note that your Apple Watch must be paired with an iPhone 11 (or later) or iPhone SE (2nd generation or later) running iOS 26. While the list of Apple Watch models that support watchOS 26 remains the same, it won't work with iPhone Xs/Xs Max and iPhone Xr, which were previously supported on watchOS 11. You can check out the respective lists of supported devices for iOS 26, iPadOS 26, and macOS 26 Tahoe.
  • Recent Achievements

    • Explorer
      MusicLover2112 went up a rank
      Explorer
    • Dedicated
      MadMung0 earned a badge
      Dedicated
    • Rookie
      CHUNWEI went up a rank
      Rookie
    • Enthusiast
      the420kid went up a rank
      Enthusiast
    • Conversation Starter
      NeoToad777 earned a badge
      Conversation Starter
  • Popular Contributors

    1. 1
      +primortal
      501
    2. 2
      ATLien_0
      268
    3. 3
      +FloatingFatMan
      257
    4. 4
      Edouard
      201
    5. 5
      snowy owl
      170
  • Tell a friend

    Love Neowin? Tell a friend!