C: Comparing two elements not producing correct results? - c

My code is below, most of which may not be helpful, but maybe the problem lies outside of where I think it is. That being said, please read the following first because it gives the rundown of my code and states where I think the problem lies.
I'm trying to create a Battleship game in C. I first create two two-dimensional arrays, one representing the player's board and one representing the enemy's board. I fill both of them with periods. I print them out with numbers along the sides to make things look nice (using my initialPrintBoards function). I then set the locations of the enemy's ships by replacing some of the periods in the enemy's array with 's' and print it out to make sure they are where I want them to be. They are, which is great. I then have the player "fire" at the enemy's ship. This is done by replacing 's' in the enemy's array with 'x' (which represents a hit) or replacing '.' with 'o' (which represents a miss). I print this out, and everything works well.
Now, here's where I hit a problem. Up to this point, for the sake of testing, the enemy's ships have been completely visible to the player via my print method. I don't want that. So, what I figured I'd do is create a new print function (called printBoards) that does exactly what my previous print function does except it prints '.' on the board when it encounters 's' as an element in the enemy's array. My initial thought in accomplishing this was to use comparisons. Basically, if the element stored in the enemy's array at location whatever is 's', print '.', otherwise print out what's stored at that location in the array (which would be '.', 'x', or 'o'). Unfortunately, all it does is print all periods, even if there's an 'x' or 'o' stored at that location in the array. I'm at a loss as to why this is. I'm quite new to C (I've studied Java in the past), so maybe there's something about comparisons in C that I don't know about. But that's assuming the problem is with the comparisons, which it might not be.
Any help or hints would be greatly appreciated.
#include <stdio.h>
char playerBoard[8][8];
char enemyBoard[8][8];
void fillBoards()
{
int a;
for (a = 0; a < 8; a++)
{
int b;
for (b = 0; b < 8; b++)
{
enemyBoard[a][b] = '.';
}
}
int x;
for (x = 0; x < 8; x++)
{
int y;
for (y = 0; y < 8; y++)
{
playerBoard[x][y] = '.';
}
}
}
void initialPrintBoards()//This is used before the enemy's ships are set.
{
printf("Enemy Board\n*12345678\n");
int a;
for (a = 0; a < 8; a++)
{
printf("%d", a + 1);
int b;
for (b = 0; b < 8; b++)
{
printf("%c", enemyBoard[a][b]);
}
printf("\n");
}
printf("\n");
printf("Player Board\n*12345678\n");
int x;
for (x = 0; x < 8; x++)
{
printf("%d", x + 1);
int y;
for (y = 0; y < 8; y++)
{
printf("%c", playerBoard[x][y]);
}
printf("\n");
}
printf("\n");
}
void printGreeting()
{
printf("\nWelcome to Battleship!\n\n");
}
void setEnemyShips()
{
// Ship 1.
enemyBoard[3][2] = 's';
enemyBoard[4][2] = 's';
enemyBoard[5][2] = 's';
// Ship 2.
enemyBoard[1][1] = 's';
enemyBoard[1][2] = 's';
enemyBoard[1][3] = 's';
// Ship 3.
enemyBoard[6][5] = 's';
enemyBoard[6][6] = 's';
enemyBoard[6][7] = 's';
}
void playerFire()
{
if (enemyBoard[2][2] == 's')
{
enemyBoard[2][2] = 'x';
}
else
{
enemyBoard[2][2] = 'o';
}
}
void printBoards()//This is used after the enemy's ships are set.
{
printf("Enemy Board\n*12345678\n");
int a;
for (a = 0; a < 8; a++)
{
printf("%d", a + 1);
int b;
for (b = 0; b < 8; b++)
{
if (enemyBoard[1][0] == 's')
{
printf("%c", '.');
}
else
{
printf("%c", enemyBoard[1][0]);
}
}
printf("\n");
}
printf("\n");
printf("Player Board\n*12345678\n");
int x;
for (x = 0; x < 8; x++)
{
printf("%d", x + 1);
int y;
for (y = 0; y < 8; y++)
{
printf("%c", playerBoard[x][y]);
}
printf("\n");
}
printf("\n");
}
int main()
{
fillBoards();
printGreeting();
initialPrintBoards(); //This will print the boards before the enemy's ships are set.
setEnemyShips();
initialPrintBoards(); //This will end up printing the enemy ships' locations. Need a different print method.
playerFire();
initialPrintBoards(); //This prints to see if a hit or miss is properly printed.
printBoards(); //This prints to see if the ships are hidden and a hit or miss is properly printed.
return 0;
}

regarding this code, found in the printBoards() function:
if (enemyBoard[1][0] == 's')
{
printf("%c", '.');
}
else
{
printf("%c", enemyBoard[1][0]);
}
This always looks at the second row, first column to determine what is printed. As you saw, that is an error.
Suggest:
if (enemyBoard[a][b] == 's')
{
printf("%c", '.');
}
else
{
printf("%c", enemyBoard[a][b]);
}

Let the Board[][] variables contain the state '.' (water) or 'A', 'B' ... 'E' for the 5 ships.
When a ship is hit, change 'A' to 'a', etc.
When printing, pass in a control variable to control how the view is rendered: Enemy View, Player View, Programmer View.

Related

My dynamically allocated 2d array print random gibberish with no meaning

This code can get the first row to print, but for some reason will not get the first column to print. If this clarifies the question a bit the x values print but the y value barely does, I get some weird characters instead.
char** GenerateLand(int width, int height) {
char** GenLand;
int i;
GenLand = malloc(width * sizeof(char*));
for(i = 0; i < width; i++) {
GenLand[i] = malloc(sizeof(char) * height);
}
char RandChar = PickLandType();
int x, y;
for(x = 0; x < width; x++) {
if(x == 0) {
GenLand[x][0] = RandChar;
} else {
char RandChar1 = GenerateNeighbor(RandChar);
GenLand[x-1][0] = GenerateNeighbor(RandChar1);
for( y = 0; y < height ; y++){
if(y == 0){
GenLand[x][y] = RandChar;
} else {
char RandChar2 = GenerateNeighbor(RandChar);
GenLand[0][y-1] = GenerateNeighbor(RandChar2);
}
}
}
return GenLand;
for(i = 0; i < width; i++) {
free(GenLand[i]);
}
free(GenLand);
}
char GenerateNeighbor(char item)
{
switch(item)
{
case 'R':
return NewFromRuralLand();
break;
case 'F':
return NewFromForest();
break;
case 'T':
return NewFromTown();
break;
case 'W':
return NewFromWater();
break;
case 'C':
return NewFromCity();
break;
case 'M':
return NewFromMountain();
break;
default:
printf("Error!");
break;
}
}
char PickLandType()
{
int typeOfLand = rand()%5;
if(typeOfLand == 0){
return 'R';
} else if(typeOfLand == 1){
return 'F';
} else if(typeOfLand == 2){
return 'T';
} else if(typeOfLand == 3){
return 'W';
} else if(typeOfLand == 4){
return 'C';
} else if(typeOfLand == 5){
return 'M';
}
}
void PrintLand(char** Land, int width, int height) {
int x, y;
for( x = 0; x < width; x++){
for( y = 1; y < height ; y++){
printf("%c", Land[x][y]);
}
}
}
https://i.stack.imgur.com/t6Fec.png ^ Picture of error, was hoping someone could tell me why I keep getting these cryptic unreadable values. Sorry I don't have enough reputation points to directly embed the picture. I checked my NewFrom() functions and they all work so I do not believe they are the issue. The output is supposed to be organized by row and column:
I don't have enough reputation to comment, hence I have to write this as an answer.
Your freeing code at the end of GenerateLand will never run, there is an unconditional return statement prior to it. (NB: You shouldn't be freeing it regardless as you want to return GenLand, just remove the freeing code)
Without giving us the PickLandType and GenerateNeighbor functions, we can't tell you why your code returns a garbled mess of letters. Please edit and attach these functions.
This is the exact same question you asked before, except now you've attached different output - have you changed the code inbetween? If so, please attach the updated code.
This is bad code, the first iteration will access GenLand[0][-1]:
for(y = 0; y < height; y++) {
GenLand[0][y-1] = GenerateNeighbor(RandChar1);
}
Please try and keep your code nicely formatted to that it's easier for everyone to read.
If you want an answer that can actually help, give the GenerateNeighbor and PickLandType functions, and also give us an expected output.
Edit:
As Paul Ogilvie pointed out, the code in point 4 will also only ever generate the 0th column (the left most column). You probably meant for this to be GenLand[x][y] (but once again, see point 4)

Replace a character with another character + Setting a tie game

This is for Homework
I have to create a game of TicTacToe for a project and I have two issues. Also I apologize if I'm violating a rule by having two questions within one post, If it's not allowed then I'd appreciate someone notifying me in the comments and I'll go ahead and break this into two separate posts. I'll post my code then ask my questions following the code.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
char table[3][3];
void clear_table();
void player1_move();
void player2_move();
void the_matrix(); // Like the movie
char check_three();
int main() {
srand(time(NULL));
char win;
printf("This program plays the game of Tic Tac Toe.\n");
win = ' ';
clear_table();
do {
the_matrix(); // Like the movie
player1_move();
win = check_three(); // Check win for player 1
if (win != ' ')
break;
player2_move();
win = check_three(); // Check win for player 2
}
while (win == ' ');
the_matrix(); // Shows the final move+Like the movie
if (win == 'O')
printf("Congratulations, Player 1 wins!\n");
else
printf("Congratulations, Player 1 lost!\n");
// the_matrix (); //Shows the final move+Like the movie
return 0;
}
void clear_table() {
// Creates empty spaces for the user and computer to enter stuff in
int i, j, k;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++)
// for(l = 0; k < 3; j++)
table[i][j] = ' ';
}
}
void player1_move() {
// Moves that player 1 can and can't make
int x, y, z;
printf("Player 1 enter your selection[row, col]: ");
scanf("%d, %d", &x, &y);
x--;
y--;
// z--;
if (table[x][y] != ' ') {
printf("Space already taken, please try again.\n");
player1_move();
}
else
table[x][y] = 'O'; // O goes first for some reason
}
void player2_move() {
// Needs work!!
// Call srand in the main
int a = rand() % 3;
int b = rand() % 3;
// Make it so the game would end in a tie when possible
for (a = rand() % 3; a < 3; a++) {
for (b = rand() % 3; b < 3;
b++) // For loops causing issues in randomization?
// for(c = 0; c < 3; c++)
if (table[a][b] == ' ')
break;
if (table[a][b] == ' ') // Checks the rows and columns
break;
}
if (a * b == 9)
**Kinda works ? ** {
printf("Game Over, No Player Wins\n");
exit(0);
}
else
table[a][b] = 'X';
}
void the_matrix() { // Like the movie
**Get rid of the underscores **
int m;
printf("The current state of the board:\n");
for (m = 0; m < 3; m++) {
printf("%c_ %c_ %c_\n", table[m][0], table[m][1], table[m][2]);
}
printf("\n");
}
char check_three() {
int w;
// char table[3][3];
for (w = 0; w < 3; w++) {
if (table[w][0] == table[w][2] && table[w][0] == table[w][1])
return table[w][0]; // Row Check
}
for (w = 0; w < 3; w++) {
if (table[0][w] == table[2][w] && table[0][w] == table[1][w])
return table[0][w]; // Col Check
}
if (table[0][0] == table[1][1] && table[1][1] == table[2][2])
return table[0][0];
if (table[0][2] == table[1][1] && table[1][1] == table[2][0])
return table[0][2]; // Diag Check
return ' ';
}
First Question
So my first question is with a draw game. On the player two function I have a snip of code set to determine a draw game. Initially I assumed that if the X's and O's were to multiply to 9 then that would mean that the board would be filled up then that would result in a draw game. [This is within my third function - player2_move near the end of the function] It kind of works, but sometimes the program just preemptively ends the game. It's a bit hard to test it because the computers moves are randomized and most of the times I've tried, I ended up winning accidentally. My question is what would I need to do to set up my program to essentially have a better way of determining a draw game.
Second Question
On my 4th function called the_matrix I need help with formatting. The assignment requires the format to be a little like this where if I were to enter in the coordinates 1,1 then the board would look like this:
O _ _ with the proceeding lines near the bottom to be blank. However as my program is right now, it looks like this:
O_ _ _
What I want to do is swap or replace the underscore with the user's input. Not entirely sure how to do that and any help would be appreciated.
I apologize if I violated any rules for stackoverflow by having two questions in one and I'm also sorry for this huge post.

Printing out mandlebrot in ascii

I'm trying to print out the ASCII version of mandlebrot in C and it doesn't seem to be working. The main thing is changing the complex c in escapeSteps as the grid changes.
Expected result:
This is my current code for printing out the result. I think the complex c changing is the reason why it's not working but its just printing out all spaces.
The escapeSteps function checks to see if its in the mandlebrot. C is a complex struct with real and imaginary values.
//TILE_SIZE = 512 pixels
int x = 0;
int y = 0;
for (y = 0; y < TILE_SIZE; y++) {
for (x = 0; x < TILE_SIZE; x++) {
complex(c) = {(x),(y)};
if (escapeSteps(c) == 256) {
printf("*");
} else {
printf(" ");
}
}
printf("\n");
}
return 0;
}

Tortoise and the Hare Pointers

I'm building a program that simulates the tortoise and the hare race. The way I'm doing it is I create a SIZE 70 array of '_' to simulate the racetrack. Then I create 2 pointers, char *harePtr and char *tortoisePtr, that point to elements in that array (each one starting at [0]) The elements in the array that the pointers point to I'm also trying to change to 'T' and 'H' to simulate their locations on the track.
From there I've algorithms developed to determine, based on a random number generator, the action each would take.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 70
enum winner {TORTOISE, HARE};
int raceRunner (char wRaceTrack[], void (*moveHare)(char *harePtr, int i), void (*moveTortoise)(char *tortoisePtr, int i));
void moveHare (char *harePtr, int i);
void moveTortoise ( char *tortoisePtr, int i);
int main() {
char racetrack [SIZE];
size_t i;
for (i = 0; i < SIZE; i++)
racetrack[i] = '_';
int winner;
winner = raceRunner(racetrack, moveHare, moveTortoise);
if (winner == 1)
printf("The hare won!");
if (winner == 2)
printf("The tortoise won!");
}
int raceRunner (char wRaceTrack[], void (*moveHare)(char *harePtr, int i), void (*moveTortoise)(char *tortoisePtr, int i)){
srand(time(NULL));
int move = 1 + rand() %10;
char *harePtr = wRaceTrack;
char *tortoisePtr = wRaceTrack;
size_t i;
for (i = 0; i < SIZE; i++)
printf("%c,", wRaceTrack[i]);
printf("\n\n");
moveHare(harePtr, move);
moveTortoise(tortoisePtr, move);
i = 0;
for (i = 0; i < SIZE; i++)
printf("%c,", wRaceTrack[i]);
printf("\n\n");
if (harePtr = tortoisePtr)
printf("OUCH! Damn tortoise bit the hare!\n\n");
if (harePtr[69])
return 1;
else if (tortoisePtr[69])
return 2;
else
raceRunner(wRaceTrack, moveHare, moveTortoise);
}
void moveHare ( char *harePtr, int i) {
if (i == 1) {
*harePtr = '_';
harePtr - 12;
*harePtr = 'H';
}
if (2 <= i <= 3) {
return;
}
if (4 <= i <= 5){
*harePtr = '_';
harePtr + 9;
*harePtr = 'H';
}
if (6 <= i <= 8) {
*harePtr = '_';
harePtr + 1;
*harePtr = 'H';
}
if (9 <= i <= 10) {
*harePtr = '_';
harePtr - 2;
*harePtr = 'H';
}
}
void moveTortoise ( char *tortoisePtr, int i) {
if (1 <= i <= 5) {
*tortoisePtr = '_';
tortoisePtr + 3;
*tortoisePtr = 'T';
}
if (6 <= i <= 7){
*tortoisePtr = '_';
tortoisePtr - 6;
*tortoisePtr = 'T';
}
if (8 <= i <= 1) {
*tortoisePtr = '_';
tortoisePtr + 1;
*tortoisePtr = 'T';
}
}
What I'm trying to do is to then first set their CURRENT position back to '_', then increment each pointer to move up or down along the array accordingly, depending on what the random generator comes up with, and change that value to 'T' or 'H'. First pointer that points to the last element in the array, [69], wins the race.
When I run the program however, it consistently produces the same result each time, without the hare marker making an appearance anywhere on the array. I'm positive this is because I've my pointers set up improperly, as I'm still trying to wrap my head around the whole concept. Is it not possible to set up pointers to the same array? Or am I accessing the array in the wrong way through incorrect use of * and &? I'm honestly lost when it comes to using those operands to properly integrate pointers with arrays, so any and all help is appreciated. Thank you!
In your code, There are many issues.
First,
harePtr - 12;
...
harePtr + 9;
...
tortoisePtr + 3;
etc. statements are essentially useless. They do not affect harePtr or tortoisePtr, as you might have thought. The result of the opration is lost, unless you collect the same in some variable.
You can make use of += or -= in this regard, to modify the LHS operand value.
Second
regarding the chaining of relational operators, like
if (1 <= i <= 5)
see this answer to find out why it surprises you. is logically wrong.
Third
In your code
if (harePtr = tortoisePtr) –
does not compare the values, instead assigns it. You need to use == for comparison.
Fourth
srand() is used to seed the random number generator. You need to call srand() only once from the main(). You may want to refer to the related answer.
First of all, subtracting a number from a pointer will return a new value, not modify the existing one. Use the -= and += operators to actually change something.
Secondly, randomly changing a pointer and then using it without first checking whether it is still inside the valid range means the operating system will bite your program long before either animal manages to bite the other.

Saving Data in a Basic Tic-Tac-Toe Game

I'm relatively new to C. In Kochan's "Programming in C" I'm currently on if-else statements. I'm trying to program a basic tic-tac-toe game but I've run into some difficulty. I'm not sure how to save the board once a player has placed an x or an o. Here's the code I have so far:
#include <stdio.h>
int main (void)
{
int board = "_|_|_\n
_|_|_\n
| | \n";
int player1, player2;
printf ("Print %i", board)
printf("Player 1, it's your move:")
scanf("%i", player1)
if(player1 == "upLeft")
printf("x|_|_\n
_|_|_\n
_|_|_\n
etc.
Am I still too much of a beginner to implement this feature?
First of all, this doesn't make sense:
int board = "_|_|_\n
_|_|_\n
| | \n";
An int is not a string, and you can't assign a string to an int. In C, strings are arrays of characters:
char board[] = "_|_|_\n_|_|_\n | | \n";
That makes more sense. But it's really not a good way to store the state of a tic tac toe board. What you should do instead is store some value for each position on the board. Don't worry about the actual format of the board, you can format it as you like when you display it. So store your board this way:
char board[9] = "---------";
where a "-" means the space is empty. When the player moves, you replace the character at the appropriate position in the array with an "X" or an "O" (or 1 and 2, or any other values that work for you). When you get some input from the user, you'll change just the corresponding value in the board array. If you number the positions 0-8 starting from the top left corner, the rightmost position in the middle row would be position 5, for example. (Remember, C arrays are zero-based, so the first index is 0.) So if the user wants to put an X at that spot, you'd say:
board[5] = 'X';
Next, you might want to write a function that prints the board. That is where you'll insert whatever characters you like to draw the board.
Finally, you're going to want to use some sort of loop to repeatedly read the user's input, modify the state of the board, print the board, and maybe display a prompt.
First-things-first, you cannot store
"_|_|_\n
_|_|_\n
| | \n";
in an integer variable. You need variables of other types (like char *, char a[][], etc).
OTOH, the pseudocode is as follows. Please try and follow this to write a C program on your own.
Let row = 3 and column = 3
Declare an array[row][column] and fill it all with 0
Let 1 represent the input of user-1 and 2 represent the input of user-2 (in the array)
i.e. if a[2][2] = 1 means, user-1 marked that location.
while ( ! all_locations_filled() ) {
take input from user-1
if user-1 chooses a valid_location(location) to mark, then mark_location(user-1, location)
check if user-1 won_the_game(user-1), if so break and congratulate user-1!
take input from user-2
if user-2 chooses a valid_location(location) to mark, then mark_location(user-2, location)
check if user-2 won_the_game(user-2), if so break and congratulate user-2!
}
valid_location(location l)
{
return array[l.row][l.column] == 0;
}
mark_location(user u, location l)
{
array[l.row][l.column] = (u==user-1) ? 1 : 2;
}
display_board()
{
for i=0 to row
for j=0 to col
if array[i][j] == 0 print ""
else print array[i][j]
/* print blank when that location is not yet marked */
}
all_locations_filled()
{
for i=0 to row
for j=0 to col
if array[i][j] == 0
return false
return true
}
won_the_game(user u)
{
/* You need to write the logic here */
:P
}
You can use a 2d array to represent the board, and maybe some small int, with 0 as nothing there, 1 as X and 2 as 0.
You cant save the like that
int board = "X|_|_\n
_|_|_\n
| | \n";
you can have something like board[0][0]=1;
then you can iterate that array and if its 1 print the X.
It's a bit of a beginner question, but you're a beginner, so that's okay! Let's go with some leading questions:
So, you're saying you want to save the board state. What do you want to save? At any point in the program, what do you want to be able to look up? The history of the moves? What the board looks like? What each corner contains? Each of these suggests a different way to change a variable when you get some input from the user.
As other people have said, you can't do all those things with int type, and even if you could, this program is still way too hard and frustrating until you have a few more tools in your toolbox. Chapter 7 is Arrays, which will be very useful, and Chapter 10 is Character Strings, which will show you how to deal with all these strings the right way in C. So my suggestion to you is go through a few more chapters of the book and the big picture will start to make a bit more sense. Happy hacking!
Here is a small template like thing I have given write your own logic inside the GetBestMove() function for the computers move (if you are building AI) else replace the call for the GetBestMove by GetMove function in the StartGame function
#include<stdio.h>
#define HUMAN_WIN 1
#define DRAW 0
#define HUMAN_LOSE -1
#define HUMAN_COIN 'X'
#define COMP_COIN 'O'
#define DEFAULT 0xFFF
int main(void)
{
StartGame();
}
enum turnOf{ Human = 0, Computer};
enum gameEndState{Lose = -1, Draw, Win};
int humanMove = 1;
int computerMove = 1;
char _board[3][3] = {'-', '-', '-', '-', '-', '-', '-', '-', '-'};
void StartGame()
{
enum turnOf turn = 0;
enum gameEndState state = -2;
while(1)
{
turn = 1 - turn;
if(turn == Human)
{
GetMove();
UpdateBoard(humanMove, turn);
}
else if(turn == Computer)
{
GetBestMove(turn);
UpdateBoard(computerMove, turn, _board);
}
state = win(_board);
switch(state)
{
case Win:
NotifyUser("You win.");exit(0);
case Draw:
NotifyUser("Match draw.");exit(0);
case Lose:
NotifyUser("You Lose.");exit(0);
}
}
}
int depth = 0;
int GetBestMove(enum turnOf turn, int *x, int *y)
{
depth++;
int i, j, MOV = -10, BESTMOVx, BESTMOVy;
enum turnOf now = turn;
char pebble = (now == Human) ? HUMAN_COIN : COMP_COIN;
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
if(_board[i][j] == '-')
{
_board[i][j] = pebble;
now = 1 - now;
int condition = win(_board);
if(condition != DRAW || condition != DEFAULT)
{
return (condition == HUMAN_LOSE) ? (depth - 10) : (10 - depth);
}
else
{
int state = GetBestMove(now, BESTMOVx, BESTMOVy);
if(state > MOV)
{
MOV = state;
}
}
}
}
}
}
int win(char a[3][3])
{
char pebble = HUMAN_COIN;
int i, j, p = 0;
i=0;
for(j = 0; j < 3; j++)
if(a[i][j] == pebble && a[i+1][j] == pebble && a[i+2][j] == pebble) return HUMAN_WIN;
j=0;
for(i = 0; i < 3; i++)
if(a[i][j] == pebble && a[i][j+1] == pebble && a[i][j+2] == pebble) return HUMAN_WIN;
if(a[0][0] == pebble && a[1][1] == pebble && a[2][2] == pebble) return HUMAN_WIN;
else if(a[0][2] == pebble && a[1][1] == pebble && a[2][0] == pebble) return HUMAN_WIN;
/// Recheck for lose
pebble = COMP_COIN;
i=0;
for(j = 0; j < 3; j++)
if(a[i][j] == pebble && a[i+1][j] == pebble && a[i+2][j] == pebble) return HUMAN_LOSE;
j=0;
for(i = 0; i < 3; i++)
if(a[i][j] == pebble && a[i][j+1] == pebble && a[i][j+2] == pebble) return HUMAN_LOSE;
if(a[0][0] == pebble && a[1][1] == pebble && a[2][2] == pebble) return HUMAN_LOSE;
else if(a[0][2] == pebble && a[1][1] == pebble && a[2][0] == pebble) return HUMAN_LOSE;
for(i = 0; i < 3; i++)
for(j = 0; j < 3; j++)
if(a[i][j] == '-') p++;
if(p == 0) return DRAW;
return DEFAULT;
}
void GetMove()
{
int x, y;
LoadFrame(_board);
printf("\nEnter your move : ");
humanMove = getche() - 48;
if(!(humanMove > 0 && humanMove < 10))
{
NotifyUser("Enter a valid location.");
GetMove();
}
GetCordinates(&x, &y, humanMove);
if(_board[x][y] != '-')
{
NotifyUser("The place is nonEmpty.");
GetMove();
}
}
void UpdateBoard(int move, enum turnOf player, char board[3][3])
{
int x, y;
char pebble = (player == Human) ? HUMAN_COIN : COMP_COIN;
GetCordinates(&x, &y, move);
board[x][y] = pebble;
LoadFrame(board);
}
void LoadFrame(char board[3][3])
{
int x, y;
system("cls");
for(x = 0; x < 3; x++)
{
printf("\n\t ");
for(y = 0; y < 3; y++)
{
printf(" %c ", board[x][y]);
}
}
}
void GetCordinates(int *x, int *y, int move)
{
switch(move)
{
case 1: *x = 0; *y = 0; break;
case 2: *x = 0; *y = 1; break;
case 3: *x = 0; *y = 2; break;
case 4: *x = 1; *y = 0; break;
case 5: *x = 1; *y = 1; break;
case 6: *x = 1; *y = 2; break;
case 7: *x = 2; *y = 0; break;
case 8: *x = 2; *y = 1; break;
case 9: *x = 2; *y = 2; break;
}
}
void NotifyUser(const char* message)
{
printf("\n\n%s\a", message);
getch();
system("cls");
LoadFrame(_board);
}

Resources