473,800 Members | 2,615 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

I need help w/my tic tac toe code

My code does not seem to be working properly...
The game is b/w a human and the computer. The computer always goes
first. The computer chooses the first corner in the first turn. in
the comp's 2nd turn, it chooses the opposite corner if possible, if
that corner is not availabe, the computer chooses randomly. In the
computers next turns...it does the following:
1. checks for a winning position
else
2. blocks human from a winning position
else
3. randomly chooses a position

The code is:

//Tic-Tac-Toe program

//
// The game board is a 3x3 array of ints
// board[3][3]:
// board[0][0] is upper left corner
// board[0][1] is top row, middle
// ...
// board[2][2] is bottom right

// 0 means the spot is empty
// 1 means 'X' has the spot
// 2 means 'O' has the spot
#include <iostream.h>
#include <conio.h>
#include <stdlib.h>

// drawpos will draw the right character to the screen, depending
// on the value of the parameter val.

// if val is 0, the spot is empty to draw a blank
// if val is 1, the spot belongs to player X, print 'X'
// if val is 2, the spot belongs to player O, print 'O'
void drawpos( int val ) {

if (val==0)
cout << " "; // val is 0, so draw a space
else if (val==1)
cout << "X"; // val is 1, so draw a 'X'
else if (val==2)
cout << "O"; // val is 2, so draw a 'O'
}

// drawrow gets an array of 3 ints and draw a
// row of a tic-tac-toe game using the array to determine
// what should go in each of the three squares.
//
// draws a row of the board

void drawrow( int row[3] ) {

cout << " "; // indent a space
drawpos(row[0]); // draw the leftmost spot
cout << " | "; // draw the vertial bar
drawpos(row[1]); // draw the middle
cout << " | "; // draw the vertial bar
drawpos(row[2]); // draw the rightmost spot
cout << endl; // newline (end of the line)
}
// drawgame will print out a tic-tac-toe game board
//
// the output looks something like this:
//
// | |
// ---|---|---
// X | | O
// ---|---|---
// X | O |
//
//
// the top left corner is board[0][0]
// the top middle is board[0][1]
// the bottom right corner is board[2][2]

void drawgame( int board[3][3] ) {

drawrow(board[0]); // draws the top row
cout << "---|---|---" << endl;
drawrow(board[1]); // draws the middlerow
cout << "---|---|---" << endl;
drawrow(board[2]); // draws the bottom row
}

bool checkPosition ( int board [3][3], int row, int col )
{

if ( ( row > 2 ) || ( row < 0 ) || ( col > 2 ) || ( col < 0 ) // out
of range test
|| ( board [ row ][ col ] != 0 ) ) //position is occupied
return false;

else return true;
}

bool won ( int board [3][3], int player )
{
int i, j;

// ROW TEST
for ( i = 0; i < 3; i++ )
{
for ( j = 0; j < 3; j++ )
if ( board [i][j] == player )
continue;
else
break;
if ( j == 3 )
return true;
}

// COLUMN TEST
for ( i = 0; i < 3; i++ )
{
for ( j = 0; j < 3; j++ )
if ( board [j][i] == player )
continue;
else
break;
if ( j == 3 )
return true;
}

//DIAGONAL TEST
if ( ( ( board[0][0] == player ) && ( board[1][1] == player ) &&
( board[2][2] == player ) ) || ( ( board[0][2] == player ) &&
( board[1][1] == player ) && ( board[2][0] == player ) ) )
return true;
return false;
}
void main ()
{
int board [3][3] = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
int turn = 1;
int flag = 0;
int row, col, player;
bool pos, testWin = 0;

drawgame ( board );

cout << "\nPlayer 1 is X............Co mputer is 0" << endl;
cout << "\nComputer goes first." << endl;

do
{
if ( ( turn % 2 ) == 1 ) // computer's turn
{
player = 2;
if ( turn == 1 ) // no possibility of any wins yet...choose
strategic position (CORNERS)
board[0][0] = 2;

else if ( turn == 3 ) // no possibility of any wins yet...choose
strategic position
{
if ( board[0][0] == 2 )
pos = checkPosition ( board, 2, 2 );
if ( pos )
board[2][2] = 2;

else if ( board[2][2] == 2 )
{
pos = checkPosition ( board, 0, 0 );
if ( pos )
board[0][0] = 2;

else if ( board[0][2] == 2 )
{
pos = checkPosition ( board, 2, 0 );
if ( pos )
board[2][0] = 2;

else if ( board[2][0] == 2 )
{
pos = checkPosition ( board, 0, 2 );
if ( pos )
board[0][2] = 2;
else
{
int n1, n2;
do
{
n1 = 1 + rand() % 2;
n2 = 1 + rand() % 2;

pos = checkPosition ( board, n1, n2 );
} while ( !pos );
board[n1][n2] = 2;
}
}
}
}
}

else // turn is > 5
{
//check for win situation

int i, j;
for ( i = 0; i < 3; i++ )
{
for ( j = 0; j < 3; j++ )
{
pos = checkPosition ( board, i , j );
if ( pos )
{
board[i][j] = 2;
testWin = won ( board, player );
if ( !testWin )
board[i][j] = 0;
else
break;
}
}
if ( j < 3 ) // computer won and broke from the loop
break;
}
if ( j < 3 )
{
drawgame ( board );
cout << "\nComputer WINS!";
break;
}

// block player 1 from winning
if ( j == 3 )
{
for ( i = 0; i < 3; i++ )
{
for ( j = 0; j < 3; j++ )
{
pos = checkPosition ( board, i , j );
if ( pos )
{
board[i][j] = 1;
testWin = won ( board, 1 );
if ( !testWin )
board[i][j] = 0;
else
{
board[i][j] = 2;
break;
}
}
}
if ( j < 3 )
break;
}
if ( j == 3 ) // computer chooses a random value
{
int n1, n2;
do
{
n1 = 1 + rand() % 2;
n2 = 1 + rand() % 2;
pos = checkPosition ( board, n1, n2 );
} while ( !pos );
board[n1][n2] = 2;
}

}
}
drawgame ( board );
}

else // player 1's turn
{
player = 1;
do
{
cout << "\nPlayer 1, Enter a position: ";
cin >> row >> col;

pos = checkPosition ( board, row, col );

if ( ! pos )
cout << "\nSorry...choo se a different position! " << endl;

} while ( ! pos ); // player entered a wrong position

board [ row ][ col ] = player;
drawgame ( board );
cout<<"\n";

// test for winning position
// tests only if each player has played twice already
if ( turn > 4 )
{
bool testWin = won( board, player );
if ( testWin ) // Player Won!
{
cout << "YOU WIN!" << endl;
break;
}
}

}

turn++; // counter

} while ( turn <= 9 );

if ( turn == 10 )
cout << "\nDRAW"; // no winner
getch();
}

Apr 13 '06 #1
8 3805

"sabirah" <i_*******@yaho o.com> wrote in message
news:11******** **************@ v46g2000cwv.goo glegroups.com.. .
My code does not seem to be working properly...


<snip>

What exactly is the problem you're having? Are we supposed to analyze all
your code (which really needs to be indented for us to read, by the way),
and guess where it might be going wrong? You need to tell us what the exact
problem is, what you expect to be happening, and what you are observing.
Then maybe we can concentrate on just the problem part.

-Howard
Apr 13 '06 #2
while playing...if i choose on my first turn the bottom right corner,
the computer doesnt play. So I think the problem is with this code:

else if ( turn == 3 ) // no possibility of any wins yet...choose
strategic position
{
if ( board[0][0] == 2 )
pos = checkPosition ( board, 2, 2 );
if ( pos )
board[2][2] = 2;
else if ( board[2][2] == 2 )
{
pos = checkPosition ( board, 0, 0 );
if ( pos )
board[0][0] = 2;
else if ( board[0][2] == 2 )
{
pos = checkPosition ( board, 2, 0 );
if ( pos )
board[2][0] = 2;
else if ( board[2][0] == 2 )
{
pos = checkPosition ( board, 0, 2 );
if ( pos )
board[0][2] = 2;
else
{
int n1, n2;
do
{
n1 = 1 + rand() % 2;
n2 = 1 + rand() % 2;
pos = checkPosition ( board, n1, n2 );
} while ( !pos );
board[n1][n2] = 2;
}
}
}
}
}

and i think is primarily in my use of the rand() function.

Apr 13 '06 #3
if i choose on my first turn the bottom right corner ( which is
board[2][2] ), the computer will not play his turn.

Apr 13 '06 #4
in the computer's turn 3, the computer should choose a corner...and if
the corners are occupied, then choose a random position.
if i dont choose the corner the computer, will play normally. if i
choose a corner, the computer won't play.

Apr 13 '06 #5
Thank you for making me elaborate on what my problem was...I figured
out what the problem was.

Apr 13 '06 #6
Thank you for making me elaborate on what my problem is...I figured out
what the problem was.

Apr 13 '06 #7

"sabirah" <i_*******@yaho o.com> wrote in message
news:11******** **************@ e56g2000cwe.goo glegroups.com.. .
Thank you for making me elaborate on what my problem was...I figured
out what the problem was.


I'm glad I helped. The same thing happens to me all the time... simply
describing the problem to someone helps me figure it out.

By the way, your responses should include relevant portions of the
message(s) you're responding to, so we don't have to go back and read
previous posts to know what you're talking about. Ok?

-Howard

Apr 13 '06 #8
Howard wrote:
By the way, your responses should include relevant portions of the
message(s) you're responding to, so we don't have to go back and read
previous posts to know what you're talking about. Ok?


As the OP is posting from Google (no surprise) the information below
may be of value.


Brian

--
Please quote enough of the previous message for context. To do so from
Google, click "show options" and use the Reply shown in the expanded
header.
Apr 13 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2319
by: Sparhawk | last post by:
Hi, I want to integrate a code beautifier for C++ in the development process of my company. There are many beautifiers around which would meet our formatting requirements (SourceFormatX, SourceStyler, ...) but those are based on a GUI and thus require a developer to do this extra-step before checking the code in. We planned to include the beautifier as a post build step (from MS VC++). To do this we would need a command line interface...
4
1746
by: Farina | last post by:
Hello, I have a directory on my company network that contains multiple directories that each hold different files, some are dbf files and some are xls files. I need my Access 2000 users to be able to click an Import File button on a form and then a list of the multiple directories would appear and they could open the particular directory they want and double click on whichever dbf or xls they need and it would automatically import. I...
4
2199
by: Jozef | last post by:
Hello, I'm trying to check for and add a field to a table to a back end database through code. The problem I've been faced with is changing permissions, because I have to use administer permissions to change the design, then remove the delete permissions when the design has been changed. I have to do it in code because there are several sites that need an automated update (as opposed to manually adding the field). The platform is...
1
1308
by: Nut Cracker | last post by:
Hello, If anyone can point me to a good ASP based Control Panel for IIS5, I would be much obliged. I hacked together an ASP site for file uploads and sharing. Its very simple, and basically shows the user the files that exist in one folder. I want to expand this functionallity so that they can create/delete subfolders and files under thier root folder on the webserver. And perhaps eventually allow the users to create subfolders and...
1
1924
by: Mark Smith | last post by:
Hi, I have the capture from http stream which is chunked and gzipped. I need code to de-chunk it (i.e. decode it), and then gunzip it--just like a web browser woudl do. Could someone please help me, or point me in the right direction? thanks much
6
1406
by: Tark Siala | last post by:
hi i spend more time to write the code, like VB6, VB2005, SQL Stored Procedure code. any one know good Application to Automaticaly read Database (Access or SQL), then write VB Code and Stored Procedure (if this allication free thats good :) ) -- Tarek M. Siala
1
1397
by: moty | last post by:
Do any body have a code example that illustrate the preprocessor of moving #define macro into the code. I need to replace all macro call (#define) in my code (file) with the macro code. Please help Moty
4
3961
by: not_a_commie | last post by:
I need code to peg the CPU for 10 seconds to test some background threads. Sleep obviously doesn't do that. How do I code a busy loop that won't get removed by the compiler? Thanks.
1
2430
by: RobertK | last post by:
I need to write a c# code that will open up word documents and delete all the macros in it. Can some one please give me a code example or any ideas on how to do this. I already know how to open word docs from c# but I need the code to find all macros and remove them.
1
1011
by: davidkurniawan | last post by:
Thanks b4 I need code for Hibernate, Log off, Shutdown Computer using API programming in VB.net for XP Vista and another Version Windows Operating System Is it Possibble ? david kurniawan indonesia
0
9690
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9551
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10504
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10274
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10251
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7576
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5469
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3764
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2945
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.