Tic Tac Toe invincible AI code issue - c

I have decided to make a C program of Tic-Tac-Toe. I am trying to make the AI invincible at the moment but I have encountered a problem.
And I wrote this:
int getFutureScoreOfMove(char square[][columns], char turn)
{
int row, column, curBestScore, score;
if(turn == 'C') curBestScore = -100;
else curBestScore = 100;
for(i = 0; i < 3; i ++)
{
for(j = 0; j < 3; j++)
{
if(square[i][j] == ' ')
{
if(turn == 'C')
{
square[i][j] = 'X';
score = getFutureScoreOfMove(board, 'U');
square[i][j] = ' ';
}
else
{
square[i][j] = 'O';
score = getFutureScoreOfMove(board, 'C');
square[i][j] = ' ';
}
if(turn == 'C' && score > curBestScore) curBestScore = score;
if(turn == 'U' && score < curBestScore) curBestScore = score;
}
}
}
return(curBestScore);
}
There is something wrong in the code, as it is NOT invincible AI, and is ineffective. Why? And how can I fix it?
Thank you :)

getFutureScoreOfMove calls itself, but it never modifies board with the move you're checking. This means it finds the same move again, resulting in infinite recursion. When calculating the outcome, you need to fill in the move on the board before recursing.

The pseudo-code just implements a min/max strategy without actually computing anything to do with tic-tac-toe. Your code just recursively calls itself infinitely.

Related

Conway's game of life with C. Command terminated when calling function to generate new generation and update "board"

I'm writing Conway's game of life in C. I understand that the rules of the game are:
Any live cell with 2 or 3 live neighbours survives.
Any dead cell with 3 live neighbours becomes a live cell.
All other live cells die in the next generation.
'#' symbolises a live cell and '.' symbolises a dead one
The code to my function to generate and update the universe "board" for every generation is written below. It takes in the universe (A 2d array which I dynamically allocated memory for in the main function), the no of rows and no of columns of the 2d array. All other functions (such as alive_neighbour) are correct and the program runs smoothly to the point this function is called. Afterwhich the terminal just prints "command terminated". I can't seem to figure out which part of the function causes the program to crash. Help will be greatly appreciated. Thank you!
void next_generation(char **universe, long row, long column)
{
for (long i = 1; i <= (row - 1); i += 1) {
for (long j = 1; j <= (column - 1); j += 1) {
//a = no of alive neighbours surrounding universe[i][j]
long a = alive_neighbour(universe, i, j);
if (universe[i][j] == '#') {
if (a == 2 || a == 3) {
universe[i][j] = '#';
}
}
else if (universe[i][j] == '.') {
if (a == 3) {
universe[i][j] = '#';
}
}
else {
universe[i][j] = '.';
}
}
}
}
long alive_neighbour(char **universe, long row, long column)
{
long count = 0;
for (long i = -1; i <= 1; i += 1) {
for (long j = -1; j <= 1; j += 1) {
if (universe[row + i][column + j] == '#') {
count += 1;
}
}
}
if (universe[row][column] == '#') {
count -= 1;
}
return count;
}
How I declared universe in the main function:
universe = (char **)malloc((size_t) row * sizeof(char *));
for (long i = 0; i < row; i += 1) {
universe[i] = (char *)malloc((size_t) column * sizeof(char));
}

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.

3D arrays and member functions to check winner to 3D tic-tac-toe

first post here. I'm creating a 3D tic-tac-toe c++ program. My checkWin member function is causing problems. I am curious as to why the test rows nested for loops do not give a winner when the if statement has been satisfied but the test colums and diagonals work fine for layer0. Thanks
void TicTacToe::checkWin(void) {
char returnValue = ' ';
//test for X or O win
//test rows, does not work
for (int k=0; k<=2; k++){
for (int i=0; i<=2; i++){
if ( (space[i][0][k] == space[i][1][k]) && (space[i][0][k] == space[i][2][k]) ){
returnValue = space[i][0][k];
}
}
}
int k=0; //test layer 0 only
//test columns
if ( (space[0][0][k] == space[1][0][k]) && (space[0][0][k] == space[2][0][k]) )
returnValue = space[0][0][k];
else if ( (space[0][1][k] == space[1][1][k]) && (space[0][1][k] == space[2][1][k]) )
returnValue = space[0][1][k];
else if ( (space[0][2][k] == space[1][2][k]) && (space[0][2][k] == space[2][2][k]) )
returnValue = space[0][2][k];
//test diagonals
else if ( (space[0][0][k] == space[1][1][k]) && (space[0][0][k] == space[2][2][k]) )
returnValue = space[0][0][k];
else if ( (space[0][2][k] == space[1][1][k]) && (space[0][2][k] == space[2][0][k]) )
returnValue = space[0][2][k];
if ( returnValue == ' ' ) { //then test for cat
int i, j, k, catCheck=0;
for (i=0; i<=2; i++) {
for (j=0; j<=2; j++) {
for (k=0; k<=2; k++) {
if (space[i][j][k] == ' ' )
catCheck++;
}
}
}
if ( catCheck == 0 )
returnValue = 'C';
}
winner = returnValue;
}
Probably because you should break out of that loop when you find a winner (all three equal to eachother, but not equal to ' '). Even if you find a winner first, if an empty set of three occurs after that, it satisfies the condition but stores a blank in returnvalue, overwriting the previously found winning x or o. Or you could add ... != ' ' to your condition there, because you really don't care if all three are empty at that point. Stepping through a debugger or adding temporary diagnostics print outs could really help you here.
Just a guess at a glance.

C: Comparing two elements not producing correct results?

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.

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