Struggles with TicTacToe - c

I have written a program in C, that when runs, is supposed to allow the user to play a game of tic tac toe - or noughts and crosses, whether it be against the computer, or another user. I have nearly completed it, and it prints the grid out perfectly fine. However, when I go to input which row/column I want to place the symbol in, instead of inserting the symbol, it just removes a space in the grid, aligning it incorrectly. I have tried to put a loop in the main method which fills the grid in with spaces to try and prevent null values.
If anyone could suggest anything it would be much appreciated. Thanks in advance!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void user_prompt();
void clear_board(char gameBoard[3][3]);
void display_board(char gameboard[3][3]);
void user_move(char gameBoard[3][3]);
void computer_move(char gameBoard[3][3]);
int detect_win(char gameBoard[3][3]);
int gameMode;
char symbol1;
char symbol2;
char nickname1[10];
char nickname2[10] = "TicTacBot";
char gameBoard[3][3];
char playerTurn[10];
int main(void){
int i, j;
char gameBoard [3][3];
clear_board(gameBoard);
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
gameBoard[i][j] = ' ';
}
}
i = 0;
j = 0;
user_prompt();
display_board(gameBoard);
if(gameMode == 2){
for(i = 0; i < 9; i++){
user_move(gameBoard);
display_board(gameBoard);
if(detect_win(gameBoard) == 1){
printf("The winner is %s!!!\n", nickname1);
}
if(detect_win(gameBoard) == 2){
printf("The winner is %s!!!\n", nickname2);
}
}
}
else{
user_move(gameBoard);
display_board(gameBoard);
for(i = 0; i < 4; i++){
printf("TicTacBot's move.\n");
computer_move(gameBoard);
display_board(gameBoard);
if(detect_win(gameBoard) == 1){
printf("The winner is %s!!!\n", nickname1);
}
user_move(gameBoard);
display_board(gameBoard);
if(detect_win(gameBoard) == 1){
printf("The winner is %s!!!\n", nickname2);
}
}
}
if(detect_win(gameBoard) == 0){
("The game ended in stalemate!\n");
}
return 0;
}
/*
Prompts the user to enter a nickname, what symbol they would like to use, and whether they'd rather play against the computer or another user.
*/
void user_prompt(void){
printf("Please choose whether you would rather play against the computer (enter '1'),or another user (enter '2'): \n");
scanf("%d", &gameMode);
getchar();
while(gameMode != 1 && gameMode != 2){
printf("Please enter a valid digit: \n");
scanf("%d", &gameMode);
getchar();
}
if(gameMode == 1){
printf("Please choose whether you would rather play as 'X' (enter 'x') or as 'O' (enter 'o'): \n");
scanf(" %c", &symbol1);
getchar();
if(symbol1 == 'x') {
symbol2 == 'o';
}
else{
symbol2 == 'x';
}
}
else{
printf("Player 1, would you like to play as 'X' (enter 'x') or as 'O' (enter 'o'): \n");
scanf(" %c", &symbol1);
getchar();
while(symbol1 != 'x' && symbol1 != 'o'){
printf("Please enter a valid symbol: \n");
scanf(" %c", &symbol1);
getchar();
}
if(symbol1 == 'x'){
symbol2 == 'o';
}
else{
symbol2 == 'x';
}
}
if(gameMode == 1){
printf("Please enter a nickname: \n");
fgets(nickname1, 10, stdin);
getchar();
}
else{
printf("Please enter a nickname for player 1: \n");
fgets(nickname1, 10, stdin);
getchar();
printf("Please enter a nickname for player 2: \n");
fgets(nickname2, 10, stdin);
getchar();
}
}
/*
Resets the game board.
*/
void clear_board(char gameBoard[3][3]){
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
gameBoard[i][j] = 0;
}
}
}
/*
Displays the game board and all symbols within it.
*/
void display_board(char gameBoard[3][3]){
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
printf(" %c ", gameBoard[i][j]);
if(j == 2){
printf("\n");
}
if(j != 2){
printf("|");
}
}
if(i != 2){
printf("---+---+---\n");
}
}
}
/*
Takes input of a position on the board from the user, then places the user's symbol into that space on the game board.
*/
void user_move(char gameBoard[3][3]){
int row;
int column;
if(playerTurn == nickname1){
printf("Would you like to enter your %c in row 1, 2 or 3? \n", symbol1);
scanf("%d", &row);
getchar();
printf("Would you like to enter your %c in column 1, 2 or 3? \n", symbol1);
scanf("%d", &column);
getchar();
}
else{
printf("Would you like to enter your %c in row 1, 2 or 3? \n", symbol2);
scanf("%d", &row);
getchar();
printf("Would you like to enter your %c in column 1, 2 or 3? \n", symbol2);
scanf("%d", &column);
getchar();
}
if(row < 1 || row > 3){
printf("Please enter a valid row number: \n");
scanf("%d", &row);
getchar();
}
if(column < 1 || column > 3){
printf("Please enter a valid column number: \n");
scanf("%d", &row);
getchar();
}
if(gameBoard[row-1][column-1] != ' '){
printf("The position you entered is already taken. Try again! \n");
display_board(gameBoard);
user_move(gameBoard);
}
else if(gameBoard[row-1][column-1] != ' '){
printf("The position you entered is already taken. Try again! \n");
display_board(gameBoard);
user_move(gameBoard);
}
else{
if(playerTurn == nickname1){
gameBoard[row-1][column-1] = symbol1;
}
else{
gameBoard[row-1][column-1] = symbol2;
}
}
printf("%c", symbol2);
if(gameMode == 2){
return;
}
if(strcmp(playerTurn, nickname1)==0){
strcpy(playerTurn, nickname2);
}
else if(strcmp(playerTurn, nickname2)==0){
strcpy(playerTurn, nickname1);
}
}
/*
Automates a strategic move from the computer, aiming to win the game, or at the least prevent the user from winning
*/
void computer_move(char gameBoard[3][3]){
int row;
int column;
int endTurn = 0;
row = rand() % 3 + 0;
column = rand() % 3 + 0;
if(gameBoard[row][column] != symbol1 && gameBoard[row][column] != symbol2){
gameBoard[row][column] = symbol2;
endTurn = 1;
}
}
/*
Detects a win on the game board. Checks if there are three identical symbols in a row, or if there are no more spaces on the game board.
*/
int detect_win(char gameBoard[3][3]){
for(int row = 0; row < 3; row++){
if(gameBoard[row][0] == gameBoard[row][1] && gameBoard[row][1] == gameBoard[row][2]){
if(gameBoard[row][0] == symbol1){
return 1;
}
if(gameBoard[row][0] == symbol2){
return 2;
}
}
}
for(int column = 0; column < 3; column++){
if(gameBoard[0][column] == gameBoard[1][column] && gameBoard[1][column] == gameBoard[2][column]){
if(gameBoard[0][column] == symbol1){
return 1;
}
if(gameBoard[0][column] == symbol2){
return 2;
}
}
}
if(gameBoard[0][0] == gameBoard[1][1] && gameBoard[1][1] == gameBoard[2][2]){
if(gameBoard[1][1] == symbol1){
return 1;
}
if(gameBoard[1][1] == symbol2){
return 2;
}
}
if(gameBoard[0][2] == gameBoard [1][1] && gameBoard[1][1] == gameBoard[2][0]){
if(gameBoard[1][1] == symbol1){
return 1;
}
if(gameBoard[1][1] == symbol2){
return 2;
}
}
return 0;
}

There's a small logical error:
In line 98, 101, 117, and 121, (and perhaps other places - please check) you have used == (operator for equality check) instead of the = used for assignment.
For example,
symbol2 == 'o';
should be replaced with
symbol2 = 'o';
Hence, it just checks for equality, throws away the result, and continues; with no changes made to symbol2.

Related

How can I search a part of a string and display it?

I have this code here to search a string in a file and display it. How can I edit this piece of code to make it possible to search just a part of this string?
say, the file contains the author "dennis zill", if I search "zill" I want the code to display "dennis zill".
int searchauthor(FILE *ptr) //searching starts
{
int save;
char de;
char in_name[30];
int flag = 1;
save = readbooks();
ptr = fopen("books info.txt", "r");
fflush(stdin);
printf("\n Enter the name of the author: ");
gets(in_name);
printf("-------------------------------------------------");
for(int i = 0; i < save; i++){
if(strcmpi(in_name, info[i].bauthor) == 0){
printf("\n Book name: %s\n Price: %u\n Number of books available: %u\n Number of pages: %u\n-------------------------------------------------", info[i].bname, info[i].price, info[i].numavail, info[i].bpages);
flag = 0;
}
}
if (flag == 1){
printf("\n Not found.\n Do you want to try another search [Y/N]? ");
scanf("%c", &de);
if(de == 'y' || de == 'Y'){
system("cls");
in_name[MAX] = reset(in_name);
fclose(ptr);
return 2;
}
else if(de == 'n' || de == 'N'){
printf("\n You will be redirected to main menu");
for(int k = 1; k <= 5; k++){
Sleep(300);
printf(".");
}
system("cls");
return 1;
}
}
printf("\n\n Do you want to try another search [Y/N]? ");
scanf("%c", &de);
if (de == 'y' || de == 'Y') {
system("cls");
in_name[MAX] = reset(in_name);
return 2; //return 2 to case 3 to search again
}
else if (de == 'n' || de == 'N') {
system("cls");
printf("\n You will be redirected to main menu");
for(int k = 1; k <= 5; k++){
Sleep(300);
printf(".");
}
system("cls");
return 1;
}
} //searching ends
The problem is the line:
if(strcmp(in_name, info[i].bauthor) == 0){
It will succeed only on a full match.
Rather that using strcmp use strstr (or its case-insensitive variant strcasestr() if it's available).
char *strstr(const char *haystack, const char *needle);
The haystack is the full authors name, needle the user's input.
Function returns NULL on failure so it's enough to check if non-NULL was returned.
if(strstr(info[i].bauthor, in_name) != NULL){

Counting Dashes to Exit a While Loop in C

I made a hangman game using a while loop. I want to use the number of dashes == 0 to break the loop so the player knows that they won. The word is hidden behind "-"s. My word is coding, so it has 6 dashes.
When I run the program, the first guess at the word is an accurate number of dashes. But after the second guess, and so on, it is adding all of the dashes from all the guesses together, not just from that one turn. By the third turn it says I have 9 dashes because that's how many is left over in all of the turns. Any ideas on how to fix?
char word[] = { "Coding" };
char dash[] = {"------"};
char guess;
int numguesses = 10;
int count;
int loopcount;
int i;
int dashcount;
int main()
{
printf("Your Word Is: %s", &dash);
//printf("\nWord: %c", &dash);
loopcount = 10;
count = 1;
while (count <= loopcount)
{
printf("\n\nPick a letter to guess: ");
scanf(" %c", &guess);
printf("\n\nYour Guess Was %c. ", guess);
count = count + 1;
if (guess == 'c')
{
dash[0] = 'c';
printf("\n\n %s", dash);
}
else if (guess == 'o')
{
dash[1] = 'o';
printf("\n\n %s", dash);
}
else if (guess == 'd')
{
dash[2] = 'd';
printf("\n\n %s", dash);
}
else if (guess == 'i')
{
dash[3] = 'i';
printf("\n\n %s", dash);
}
else if (guess == 'n')
{
dash[4] = 'n';
printf("\n\n %s", dash);
}
else if (guess == 'g')
{
dash[5] = 'g';
printf("\n\n %s", dash);
}
else
printf("That Letter Is Not Apart of this Word");
printf("\n\nYou are at Guess Number %d, Your word is at %s", count, dash);
for (i = 0; dash[i]; i++)
{
if (dash[i] == '-')
{
dashcount++;
}
}
printf("\n\nDoes it work ?: %d", dashcount);
}
if (count < numguesses)
{
printf("\n\n\nYou Won the Game, Your Awesome!!");
}
else
{
printf("\n\n\nI'm Sorry, the word was %s.", word);
}
printf("\n\n");
return 0;
}
The issue is that you are not resetting the dashcount variable, so every time it starts with previous value and adds the dashes left
for (i = 0; dash[i]; i++)
{
if (dash[i] == '-')
{
dashcount++;
}
}
You can easily fix this in this way
dashcount=0;
for (i = 0; dash[i]; i++)
{
if (dash[i] == '-')
{
dashcount++;
}
}

Repeat the Program for again Search Array Element

Repeat the Program for again Search Array Element.
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int arr[MAX_SIZE];
int size, i, toSearch, found;
char repeat;
printf("Enter the size of an array\n");
scanf("%d", &size);
printf("Enter the array elements\n");
for (i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
do{
printf("\nEnter element to search: ");
scanf("%d", &toSearch);
found = 0;
for(i=0; i<size; i++)
{
if(arr[i] == toSearch)
{
found = 1;
break;
}
}
if(found == 1)
{
printf("\n%d is found at position %d", toSearch, i + 1);
}
else
{
printf("\n%d is not found in the array \n", toSearch);
}
printf("\n \n \nPress Y to again Search Any Element in Array\n \nPress Any other Key to Exit the Program\n\n");
scanf(" %c \t",&repeat);
}
while(repeat == 'y' || repeat == 'Y' );
return 0;
}
I want to repeat my program when user give the input of Y || y otherwise it'll exit the program.
In this code i want to make an array then search the element after this show's the results and in last repeat the code from the search the element block.
I ran your code and everything seems to be working properly except for this line:
scanf(" %c \t",&repeat);
Remove the \t from the scanf and it should work properly. You don't want to scan for a tab character, just the 'Y' or 'y' character.
Also, your use of newlines is a bit unusual. Try putting newline characters at the end of your strings as opposed to the beginning.
Updated code:
#include <stdio.h>
#define MAX_SIZE 100
int main() {
int arr[MAX_SIZE];
int size, i, toSearch, found;
char repeat = ' ';
printf("Enter the size of an array\n");
scanf("%d", &size);
printf("Enter the array elements\n");
for (i = 0; i < size; i++)
scanf("%d", &arr[i]);
do{
printf("Enter element to search: \n");
scanf("%d", &toSearch);
found = 0;
for(i=0; i<size; i++) {
if(arr[i] == toSearch) {
found = 1;
break;
}
}
if(found == 1)
printf("%d is found at position %d\n", toSearch, i + 1);
else printf("%d is not found in the array\n", toSearch);
printf("Press Y to again Search Any Element in Array\nPress Any other Key to Exit the Program\n");
scanf(" %c",&repeat);
}
while(repeat == 'y' || repeat == 'Y' );
return 0;
}
Enclose the block of code you want to repeat in a while loop, something like
bool flag = false;
while(flag==true) {
//Code block
scanf("%c",&input)
if((input == 'y') || (input == 'Y')) {flag = true;}
else {flag = false;}
}
The first method that came to my mind :
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int arr[MAX_SIZE];
int size, i, toSearch, found;
char repeat;
printf("Enter the size of an array\n");
scanf("%d", &size);
printf("Enter the array elements\n");
for (i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
do
{
printf("\nEnter element to search: ");
scanf("%d", &toSearch);
found = 0;
for (i = 0; i < size; i++)
{
if (arr[i] == toSearch)
{
found = 1;
break;
}
}
if (found == 1)
{
printf("\n%d is found at position %d", toSearch, i + 1);
}
else
{
printf("\n%d is not found in the array \n", toSearch);
}
printf("\n \n \nPress Y to again Search Any Element in Array\n \nPress Any other Key to Exit the Program\n\n");
repeat = getchar();
repeat = getchar();
if(repeat == 'y' || repeat == 'Y') {
continue;
}
else {
break;
}
} while (1);
return 0;
}

How to Fix the Logic Errors in My "Guess the Movie" Game as a C Program

I have written a Guess the Movie game in the C programming language. My logic seems to be correct but whenever I run the program, it doesn't work as expected.
Here is my code
#include <stdio.h>
#include <stdlib.h>
int main()
{
int ran = 1;
int l, j = 0, i = 0, total = 0, d = 0;
char b;
char a[20];
char s[1000];
int z;
FILE *my;
printf("Enter your name:\n ");
scanf("%s", s);
ran = rand() % 6;
if (ran == 1)
{
my = fopen("my1.txt", "r");
}
else if (ran == 2)
{
my = fopen("my.txt", "r");
}
else if (ran == 3)
{
my = fopen("my2.txt", "r");
}
else if (ran == 4)
{
my = fopen("my3.txt", "r");
}
else if (ran == 5)
{
my = fopen("my4.txt", "r");
}
for (d = 0; d < 20; d++)
fscanf(my, "%c", &a[d]);
fclose(my);
printf("GUESS THE MOVIE GAME\n");
for (j = 0; j < 7; j++)
{
if (a[j] == 'm')
{
printf("M ");
}
else
{
printf("_ ");
}
}
printf("\n");
printf("Let's begin the game\n");
for (i = 0; i < 7;)
{
if (a[i] != 'm')
{
printf("enter character number %d\n",i+1);
scanf("%c", &b);
if (b == a[i])
{
printf("its a right guess\n");
total = total + 4;
i++;
}
else if (b != a[i])
{
printf("Wrong choice\n");
if (total == 1 || total == 0)
{
total=0;
}
else
{
total = total - 2;
}
}
}
}
printf("You have guessd the movie\n");
printf("The movie name is: ");
for (i = 0; i < 7; i++)
{
printf("%c",a[i]);
}
printf("Your score is %d\n",total);
}
This is the program output that I get each time I run the above code:
Enter your name:
raj
GUESS THE MOVIE GAME
_ _ _ _ M _ _
Let's begin the game
Enter character number 1
Wrong choice
Enter character number 1
I
Wrong choice
Enter character number 1
Wrong choice
Enter character number 1
Besides the deficiencies pointed out in comments, there's this major logic error:
for (i = 0; i < 7;)
{
if (a[i] != 'm')
{
…
}
}
If the loop encounters an m, it repeats endlessly. Eliminate the if (a[i] != 'm') or add an else ++i.

Connecting Random number in 2d array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have generated random number into a 2d array.What I want now is to connect the same number by moving it inside the game board.The problems is it doesn't move.
I really need help!!! I am new to c programming btw. Thanks in advance.
Here's my code:
void playgame(char box[ROW][COL])
{
int x, y, choice2,num,direction=0;
char input;
do{
printf("Please select a number (1-7) : \n");
scanf("%i",&num);
if(x==0 || x==ROW-1 ||y==0 || y==COL-1)
{
printf("Invalid!\n");
}
else
{
printf("Numer %i is currently selected!\n", num);
}
}while(x==0 || x==ROW-1 ||y==0 || y==COL-1);
printf("[1]Move\n[2]Sign out\n");
printf("Enter choice: ");
scanf("%d", &choice2);
switch(choice2)
{
case 1:
{
printf("Press 'E' to go up\n");
/*codes for moving the character up.....*/
}
{
printf("Press 'D' to go right\n");
/*codes for moving the character down.....*/
}
{
printf("Press 'S' to go left\n");
/*codes for moving the character left.....*/
}
{
printf("Press 'X' to go down\n");
/*codes for moving the character up.....*/
}
{
printf("Press 'R' to remove the existing path\n");
}
fflush(stdin);
scanf("%c", &input);
break;
case 2: printf("Bye!\n");
}
for(x=0; x<9; x++)
for(y=0; y<9; y++)
{
if(input == 'E')
if(box[x][y]==num)
{
box[--x][y]==num;
}
if(input == 'D')
if(box[x][y]==num)
{
box[x][y++]==num;
}
if(input == 'S')
if(box[x][y]== num)
{
box[x][--y]== num;
}
if(input == 'X')
if(box[x][y]==num)
{
box[--x][y]==num;
}
}
}
try this:
#include <stdio.h>
#include <stdlib.h>
#define ROW 9
#define COL 9
void display(char box[ROW][COL]);
int validMove(int r, int c, char box[ROW][COL]);
void playgame(char box[ROW][COL]){
int r, c, num;
int choice, nr, nc;
char input, n;
for(;;){
printf("Please select a number (1-7) : \n");
if(1 == scanf("%i", &num) && 1<= num && num <= 7)
break;
printf("Invalid!\n");
while(getchar() != '\n');
}
printf("Numer %i is currently selected!\n", num);
n = num + '0';
for(r = 1; r < ROW-1; ++r)
for(c = 1; c < COL-1; ++c)
if(box[r][c] == n)
goto find;
find:
for(;;){
printf("[1]Move\n"
"[2]Sign out\n"
"Enter choice: ");
scanf("%d", &choice);
switch(choice){
case 1:
printf("Press 'E' to go up\n"
"Press 'D' to go right\n"
"Press 'S' to go left\n"
"Press 'X' to go down\n"
"Press 'R' to remove the existing path\n");
scanf(" %c", &input);
nr = r;
nc = c;
switch(input){
case 'E':
nr = r - 1;
break;
case 'D':
nc = c + 1;
break;
case 'S':
nc = c - 1;
break;
case 'X':
nr = r + 1;
break;
case 'R':
break;
default:
break;
}
if(validMove(nr, nc, box)){
box[nr][nc] = box[r][c];
box[r][c] = ' ';
r = nr;
c = nc;
display(box);
} else if(input != 'R'){
printf("invalid move!\n");
}
break;
case 2: printf("Bye!\n");
exit(0);
}
}
}
int validMove(int r, int c, char box[ROW][COL]){
if(r == 0 || r == ROW-1 || c == 0 || c == COL-1)
return 0;
if(box[r][c] != ' ')
return 0;
return 1;
}
void initBoard(char box[ROW][COL]){
int r, c;
for(r = 0; r < ROW; ++r){
for(c = 0; c < COL; ++c){
if(r == 0 || r == ROW-1 || c == 0 || c == COL-1)
box[r][c] = '#';
else
box[r][c] = ' ';
}
}
for(int i = 1; i <= 7; ++i){
int r = rand() % (ROW-1-1) + 1;
int c = rand() % (COL-1-1) + 1;
if(box[r][c] == ' ')
box[r][c] = i + '0';
else
--i;
}
}
void display(char box[ROW][COL]){
for(int r = 0; r < ROW; ++r){
for(int c = 0; c < COL; ++c){
putchar(box[r][c]);
}
putchar('\n');
}
}
int main(void){
char board[ROW][COL];
initBoard(board);
display(board);
playgame(board);
return 0;
}

Resources