Tic Tac Toe game - c

I was working on learning c code and was making a tic-tac-toe game. The Boolean issue was fixed. Now the issue is that it is looping the printf("There is no empty space!"); and prinf("Invalid !!!"); after it take the player1 name. I also wanted to know if the line where I printed the array with the grid is correct or not.
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
char space[3][3] = {
{'1', '2', '3'},
{'4', '5', '6'},
{'7', '8', '9'},
};
int row;
int column;
char token = 'x';
bool tie = false;
char n1[256];
char n2[256];
void functionboard()
{
char space[3][3] = {
{'1', '2', '3'},
{'4', '5', '6'},
{'7', '8', '9'},
};
printf(" | | \n");
printf(" ", space[0][0], "| ", space[0][1], "| ", space[0][2], " \n");
printf("______|________|_____\n");
printf(" | | \n");
printf(" ", space[1][0], " | ", space[1][1], " | ", space[1][2], " \n");
printf("______|________|_____\n");
printf(" | | \n");
printf(" ", space[2][0], " | ", space[2][1], " | ", space[2][2], " \n");
printf(" | | \n");
}
void functionOne()
{
int dight;
if (token == 'x')
{
printf(n1, "please enter");
scanf("&d", &dight);
}
if (token == '0')
{
printf(n2, "please enter");
scanf("&d", &dight);
}
if (dight == 1)
{
row = 0;
column = 0;
}
if (dight == 2)
{
row = 0;
column = 1;
}
if (dight == 3)
{
row = 0;
column = 2;
}
if (dight == 4)
{
row = 1;
column = 0;
}
if (dight == 5)
{
row = 1;
column = 1;
}
if (dight == 6)
{
row = 1;
column = 2;
}
if (dight == 7)
{
row = 2;
column = 0;
}
if (dight == 8)
{
row = 2;
column = 1;
}
if (dight == 9)
{
row = 2;
column = 2;
}
else if (dight < 1 || dight > 9)
{
prinf("Invalid !!!");
}
if (token == 'x' && space[row][column] != 'x' && space[row][column] != '0')
{
space[row][column] = 'x';
token = '0';
}
else if (token == '0' && space[row][column] != 'x' && space[row][column] != '0')
{
space[row][column] = '0';
token = 'x';
}
else
{
printf("There is no empty space!");
functionboard();
}
functionOne();
}
bool functionDraw()
{
for (int i = 0; i < 3; i++)
{
if (space[i][0] == space[i][1] && space[i][0] == space[i][2] || space[0][i] == space[1][i] && space[0][i] == space[2][i])
return true;
}
if (space[0][0] == space[1][1] && space[1][1] == space[2][2] || space[0][2] == space[1][1] && space[1][1] == space[2][0])
{
return true;
}
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (space[i][j] != 'x' && space[i][j] != '0')
{
return false;
}
}
}
tie = true;
return false;
}
int main()
{
printf("Enter the name of the first player : \n");
scanf("%c", n1);
printf("Enter the name of the second player : \n");
scanf("%c", n2);
printf("%c is player1 so he/she will play first \n", n1);
printf("%c is player2 so he/she will play first \n", n2);
while (!functionDraw())
{
functionboard();
functionOne();
functionDraw();
}
if (token == 'x' && tie == false)
{
printf("%c Wins!!\n", n2);
}
else if (token == '0' && tie == false)
{
printf("%c Wins!!\n", n1);
}
else
{
printf("its a draw!!");
}
}

If the error you're getting is about the type bool and not the variable itself, see this question: you need to also include <stdbool.h> to be able to use the bool type.

There's no built-in bool type in classic C. You can use it though by using #include <stdbool.h>. The other solution is replacing it with an int since it can be used like a bool

Related

Wrong output (C)

I'm getting the wrong output. The black screen is my output and the white screen is the right output. In my output the "V" is always in the right placement but the symbols under that line is always in the wrong placement.
: (hyphen) represents undiscovered locations
! : represents bombs
$ : represents treasure
& : represents both a bomb and treasure
. : represents a visited location that had neither a bomb nor a treasure
Check for BOTH a bomb AND a treasure
Check both the bomb and treasure member arrays to see if a value of 1 is set for both at the same
location
Update the player’s counters accordingly (bomb: reduce lives, treasure: increase treasure counter)
Display an appropriate message (use symbol: [&] to denote a bomb AND treasure, the treasure is
considered a “life insurance payout”)
If there is no bomb or treasure at the location entered by the user
Display an appropriate message (use symbol: [.] to denote nothing found)
This is my code:
do
{
printf(" ");
for (lives = 1; lives < (playerData.currentMove + 1); lives++)
{
if (lives != playerData.currentMove)
{
printf(" ");
}
else if (playerData.currentMove == 0)
{
printf(" ");
}
else
{
printf("%c\n", playerData.playerSym);
}
}
if (gameSettings.bombInput[playerData.currentMove] == 1 && gameSettings.treasureInput[playerData.currentMove] == 0)
{
gameSettings.revealedPosition[playerData.currentMove] = '!';
}
else if (gameSettings.treasureInput[playerData.currentMove] == 1 && gameSettings.bombInput[playerData.currentMove] == 0)
{
gameSettings.revealedPosition[playerData.currentMove] = '$';
}
else if (gameSettings.bombInput[playerData.currentMove] == 1 && gameSettings.treasureInput[playerData.currentMove] == 1)
{
gameSettings.revealedPosition[playerData.currentMove] = '&';
}
else if (gameSettings.bombInput[playerData.currentMove] == 0 && gameSettings.treasureInput[playerData.currentMove] == 0)
{
gameSettings.revealedPosition[playerData.currentMove] = '.';
}
if (playerData.currentMove == 0)
{
for (lives = 0; lives < (gameSettings.gameLength); lives++)
{
printf("%c", hiddenPosition);
gameSettings.revealedPosition[lives] = hiddenPosition;
}
}
else {
printf(" ");
for (lives = 0; lives < (gameSettings.gameLength); lives++)
{
printf("%c", gameSettings.revealedPosition[lives]);
}
}
printf("\n ");
for (lives = 1, z = 1; lives <= gameSettings.gameLength; lives++)
{
if (lives % 10 == 0)
{
printf("%d", z);
z++;
}
else {
printf("|");
}
}
printf("\n ");
for (lives = 1, z = 1; lives <= gameSettings.gameLength; lives++)
{
if (lives % 10 == 0)
{
printf("0");
z = 1;
}
else
{
printf("%d", z);
z++;
}
}
printf("\n");
printf("+---------------------------------------------------+\n");
printf(" Lives: %2d | Treasures: %2d | Moves Remaining: %2d\n", playerData.playerLives, playerData.treasureNum, gameSettings.gameMoves);
printf("+---------------------------------------------------+\n");
do
{
lives = 0;
printf("Next Move [1-%d]: ", gameSettings.gameLength);
scanf("%d", &playerData.currentMove);
if (playerData.currentMove >= 1 && playerData.currentMove <= gameSettings.gameLength)
{
printf("\n");
lives++;
}
else
{
printf(" Out of Range!!!\n");
}
} while (lives < 1);
if (gameSettings.revealedPosition[playerData.currentMove] == hiddenPosition)
{
if (gameSettings.bombInput[playerData.currentMove] == 0 && gameSettings.treasureInput[playerData.currentMove] == 0)
{
printf("===============> [.] ...Nothing found here... [.]\n\n");
gameSettings.gameMoves -= 1;
}
else if (gameSettings.bombInput[playerData.currentMove] == 1 && gameSettings.treasureInput[playerData.currentMove] == 0)
{
printf("===============> [!] !!! BOOOOOM !!! [!]\n\n");
playerData.playerLives -= 1;
gameSettings.gameMoves -= 1;
}
else if (gameSettings.treasureInput[playerData.currentMove] == 1 && gameSettings.bombInput[playerData.currentMove] == 0)
{
printf("===============> [$] $$$ Found Treasure! $$$ [$]\n\n");
playerData.treasureNum += 1;
gameSettings.gameMoves -= 1;
}
else if (gameSettings.bombInput[playerData.currentMove] == 1 && gameSettings.treasureInput[playerData.currentMove] == 1)
{
printf("===============> [&] !!! BOOOOOM !!! [&]\n");
printf("===============> [&] $$$ Life Insurance Payout!!! [&]\n\n");
gameSettings.gameMoves -= 1;
playerData.treasureNum += 1;
playerData.playerLives -= 1;
}
}
else
{
printf("===============> Dope! You've been here before!\n\n");
}
} while (playerData.playerLives != 0 && gameSettings.gameMoves != 0);
printf("No more LIVES remaining!\n\n");
printf(" ");
for (lives = 1; lives < (playerData.currentMove + 1); lives++)
{
if (lives != playerData.currentMove)
{
printf(" ");
}
else if (playerData.currentMove == 0)
{
printf(" ");
}
else
{
printf("%c\n", playerData.playerSym);
}
}
if (gameSettings.bombInput[playerData.currentMove] == 1 && gameSettings.treasureInput[playerData.currentMove] == 0)
{
gameSettings.revealedPosition[playerData.currentMove] = '!';
}
else if (gameSettings.treasureInput[playerData.currentMove] == 1 && gameSettings.bombInput[playerData.currentMove] == 0)
{
gameSettings.revealedPosition[playerData.currentMove] = '$';
}
else if (gameSettings.bombInput[playerData.currentMove] == 1 && gameSettings.treasureInput[playerData.currentMove] == 1)
{
gameSettings.revealedPosition[playerData.currentMove] = '&';
}
else if (gameSettings.bombInput[playerData.currentMove] == 0 && gameSettings.treasureInput[playerData.currentMove] == 0)
{
gameSettings.revealedPosition[playerData.currentMove] = '.';
}
if (playerData.currentMove == 0)
{
for (lives = 1; lives < (gameSettings.gameLength + 1); lives++)
{
printf("%c", hiddenPosition);
gameSettings.revealedPosition[lives] = hiddenPosition;
}
}
else {
printf(" ");
for (lives = 1; lives < (gameSettings.gameLength + 1); lives++)
{
printf("%c", gameSettings.revealedPosition[lives]);
}
}
printf("\n ");
for (lives = 1, z = 1; lives <= gameSettings.gameLength; lives++)
{
if (lives % 10 == 0)
{
printf("%d", z);
z++;
}
else {
printf("|");
}
}
printf("\n ");
for (lives = 1, z = 1; lives <= gameSettings.gameLength; lives++)
{
if (lives % 10 == 0)
{
printf("0");
z = 1;
}
else {
printf("%d", z);
z++;
}
}
printf("\n");
printf("+---------------------------------------------------+\n");
printf(" Lives: %2d | Treasures: %2d | Moves Remaining: %2d\n", playerData.playerLives, playerData.treasureNum, gameSettings.gameMoves);
printf("+---------------------------------------------------+\n\n");
printf("##################\n# Game over! #\n##################\n\n");
printf("You should play again and try to beat your score!!\n");
return 0;

Some Errors in my X and O game ( C language)

What I'm trying to do here is a tie toe game, but when my code enters the do - while part, it ends the process by itself. Since I could not solve this part, I did not have a chance to try whether there are other problems with the code, unfortunately, I would be glad if you could help with this issue.
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
char box_area[] = { '0','1','2','3','4','5','6','7','8','9' };
struct Player {
bool turn;
char mark;
int ID;
};
int main()
{
int return_result;
int player_number;
struct Player player1;
struct Player player2;
struct Player users[2];
users[0] = player1;
users[1] = player2;
(player1.mark = 'X') && (player2.mark = 'O');
(player1.turn = true) && (player2.turn = false);
(player1.ID = 1) && (player2.ID = 2);
do
{
box_creat();
for (int i = 0; i < 2; i++) {
if (users[i].turn == true)
{
make_move(users[i].ID);
box_creat();
users[i].turn = false;
users[i + 1].turn = true; \\ I made the logic of this section wrong
\\I will try to fix it, I realized after I sent the question
}
}
return_result = check_the_winner();
} while (return_result == 1 || return_result == -1);
return 0;
}
void box_creat(void) {
printf("| %c | %c | %c |", box_area[0], box_area[1], box_area[2]);
printf("\n\n");
printf("| %c | %c | %c |", box_area[3], box_area[4], box_area[5]);
printf("\n\n");
printf("| %c | %c | %c |", box_area[6], box_area[7], box_area[8]);
}
void make_move(int Player_ID)
{
int choice;
printf("Please select a area between 0-9 ");
scanf("%d", choice);
if (choice == '0' && box_area[0] == '0')
{
if (Player_ID == 1) {
box_area[0] = 'X';
}
else {
box_area[0] = 'O';
}
}
else if (choice == '1' && box_area[1] == '1')
{
if (Player_ID == 1) {
box_area[1] = 'X';
}
else {
box_area[1] = 'O';
}
}
else if (choice == '2' && box_area[2] == '2')
{
if (Player_ID == 1) {
box_area[2] = 'X';
}
else {
box_area[2] = 'O';
}
}
else if (choice == '3' && box_area[3] == '0')
{
if (Player_ID == 1) {
box_area[3] = 'X';
}
else {
box_area[3] = 'O';
}
}
else if (choice == '4' && box_area[4] == '0')
{
if (Player_ID == 1) {
box_area[4] = 'X';
}
else {
box_area[4] = 'O';
}
}
else if (choice == '5' && box_area[5] == '0')
{
if (Player_ID == 1) {
box_area[5] = 'X';
}
else {
box_area[5] = 'O';
}
}
else if (choice == '6' && box_area[6] == '0')
{
if (Player_ID == 1) {
box_area[6] = 'X';
}
else {
box_area[6] = 'O';
}
}
else if (choice == '7' && box_area[7] == '0')
{
if (Player_ID == 1) {
box_area[7] = 'X';
}
else {
box_area[7] = 'O';
}
}
else if (choice == '8' && box_area[8] == '0')
{
if (Player_ID == 1) {
box_area[8] = 'X';
}
else {
box_area[8] = 'O';
}
}
}
int check_the_winner(void)
{
if (box_area[0] && box_area[1] && box_area[2] == 'X' || 'O') {
return 1;
}
else if(box_area[3] && box_area[4] && box_area[5] == 'X' || 'O') {
return 1;
}
else if (box_area[6] && box_area[7] && box_area[8] == 'X' || 'O') {
return 1;
}
else if (box_area[2] && box_area[4] && box_area[6] == 'X' || 'O') {
return 1;
}
else if (box_area[0] && box_area[3] && box_area[6] == 'X' || 'O') {
return 1;
}
else if (box_area[2] && box_area[8] && box_area[5] == 'X' || 'O') {
return 1;
}
else if (box_area[0] && box_area[4] && box_area[8] == 'X' || 'O') {
return 1;
}
else if (box_area[1] && box_area[4] && box_area[7] == 'X' || 'O') {
return 1;
}
else {
return -1;
}
}
I tried out your program and found a few glitches that needed revision as well as adding in some additional bits of code just to neaten things up a bit. Following is your code with those revisions.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
char box_area[] = { '0','1','2','3','4','5','6','7','8','9' };
struct Player
{
bool turn;
char mark;
int ID;
};
void box_creat(void)
{
printf("| %c | %c | %c |", box_area[0], box_area[1], box_area[2]);
printf("\n\n");
printf("| %c | %c | %c |", box_area[3], box_area[4], box_area[5]);
printf("\n\n");
printf("| %c | %c | %c |", box_area[6], box_area[7], box_area[8]);
printf("\n"); /* Added for aesthetics */
}
void make_move(int Player_ID)
{
int choice;
printf("Player %d - please select a area between 0-9 ", Player_ID);
scanf("%d", &choice); /* Corrected missing ampersand */
printf("Player: %d makes a move\n", Player_ID);
if (choice == 0 && box_area[0] == '0') /* FYI - '0' is equivalent to integer value 48 */
{
if (Player_ID == 1)
{
box_area[0] = 'X';
}
else
{
box_area[0] = 'O';
}
}
else if (choice == 1 && box_area[1] == '1')
{
if (Player_ID == 1)
{
box_area[1] = 'X';
}
else
{
box_area[1] = 'O';
}
}
else if (choice == 2 && box_area[2] == '2')
{
if (Player_ID == 1)
{
box_area[2] = 'X';
}
else
{
box_area[2] = 'O';
}
}
else if (choice == 3 && box_area[3] == '3')
{
if (Player_ID == 1)
{
box_area[3] = 'X';
}
else
{
box_area[3] = 'O';
}
}
else if (choice == 4 && box_area[4] == '4')
{
if (Player_ID == 1)
{
box_area[4] = 'X';
}
else
{
box_area[4] = 'O';
}
}
else if (choice == 5 && box_area[5] == '5')
{
if (Player_ID == 1)
{
box_area[5] = 'X';
}
else
{
box_area[5] = 'O';
}
}
else if (choice == 6 && box_area[6] == '6')
{
if (Player_ID == 1)
{
box_area[6] = 'X';
}
else
{
box_area[6] = 'O';
}
}
else if (choice == 7 && box_area[7] == '7')
{
if (Player_ID == 1)
{
box_area[7] = 'X';
}
else
{
box_area[7] = 'O';
}
}
else if (choice == 8 && box_area[8] == '8')
{
if (Player_ID == 1)
{
box_area[8] = 'X';
}
else
{
box_area[8] = 'O';
}
}
}
int check_the_winner(void)
{
if ((box_area[0] == box_area[1]) && (box_area[1] == box_area[2]) && (box_area[0] != '0')) /* Corrected the testing for proper "and" conditioning */
{
return 1;
}
else if ((box_area[3] == box_area[4]) && (box_area[4] == box_area[5]) && (box_area[3] != '3'))
{
return 1;
}
else if ((box_area[6] == box_area[7]) && (box_area[7] == box_area[8]) && (box_area[6] != '6'))
{
return 1;
}
else if ((box_area[2] == box_area[4]) && (box_area[4] == box_area[6]) && (box_area[2] != '2'))
{
return 1;
}
else if ((box_area[0] == box_area[3]) && (box_area[3] == box_area[6]) && (box_area[0] != '0'))
{
return 1;
}
else if ((box_area[2] == box_area[5]) && (box_area[5] == box_area[8]) && (box_area[2] != '2'))
{
return 1;
}
else if ((box_area[0] == box_area[4]) && (box_area[4] == box_area[8]) && (box_area[4] != '4'))
{
return 1;
}
else if ((box_area[1] == box_area[4]) && (box_area[4] == box_area[7]) && (box_area[1] != '1'))
{
return 1;
}
else
{
return -1;
}
}
int main()
{
int return_result;
//int player_number; /* Compiler said that this wasn't being used */
int swap = 1;
int i;
struct Player player1;
struct Player player2;
struct Player *users[2]; /* Used these as address pointers to player "1" and player "2" */
users[0] = &player1; /* Before making these pointers, the users array just contained copies of the player structures */
users[1] = &player2;
(player1.mark = 'X') && (player2.mark = 'O');
(player1.turn = true) && (player2.turn = false);
(player1.ID = 1) && (player2.ID = 2);
do
{
box_creat();
swap += 1;
i = swap % 2;
if (i == 1)
{
make_move(users[1]->ID);
//box_creat(); /* Being performed at the top of the loop */
users[0]->turn = false;
users[1]->turn = true;
}
else
{
make_move(users[0]->ID);
//box_creat();
users[1]->turn = false;
users[0]->turn = true;
}
return_result = check_the_winner();
if (check_the_winner() == 1) /* Added when a winner has been sensed */
{
box_creat();
if (i == 1)
{
printf("Player 2 won!\n");
}
else
{
printf("Player 1 won!\n");
}
}
}
while (return_result != 1);
return 0;
}
I added comments to most of the places I had tweaked, but here are the highlights:
I shuffled some of the functions around so that the "main" function followed all of the helper functions (the compiler was giving warnings about the original sequence of the function positions).
I corrected the "choice" tests as "choice" is an integer, so the test of "choice" needed to be compared to an integer value (e.g. zero) as opposed to character '0' (which actually has a value of 48).
The tests for three letters in a row for either player do not work in that manner. Either a test needed to be made for each box for a certain row needed to tested for an "X" or an "O", and then if that test was true the test needed to be continued for the next box in the row, and then again for the third box in the row. In lieu of that route, the test was revised to basically say "if the character in the first box in the row is the same as the character in the second box in the row, and the character in the second box in the row is the same as the character in the third box in the row, and the first box does not contain a digit character (which means is contains an "X" or an "O"), then there is a winner.
It appears that an attempt was made to mirror the contents of "Player1" and "Player2" into an array of player structures. Although initially, structure "users[0]" contained the same data as "Player1" and structure "users[1]" contained the same data as "Player2", once the data in "Player1" and "Player2" were updated, those changes did to propagate over to the "users" array. So to utilize "users" in the spirit of this program, they were defined as pointers to their respective player structures.
Those were the most significant bits. The other bits were added for a logical conclusion of the game. Note that no logic was added for a draw.
Give that a test and see if that clarifies things and follows the spirit of the project.

Movement for game character doesn't work at all

Here is the .c code from start to finish. I suspect it's an order of operations issue or something else.
The code is supposed to have a title screen where you can exit or play. If you hit play it renders a new char array in which you can move either left, right, or down (a/d/s). You get points for going down a row each time as well as going over 'P' spots on the array.
Once you hit y-coordinate 202 on the array as well as have positive points, you win and it renders a congrats char array. If you go negative in points (by hitting the '#' paces or the 'L' wall that goes down a row every 1/2 second) then you will lose and be told you lost in a new char array as well as be asked if you want to exit or play again.
And as mentioned before, the movement for the 'L's and the play character 'O' simply doesn't move.
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <fcntl.h>
#include <unistd.h>
char quickchar(float delay);
void render();
void titleRender();
void renderLoss();
void renderWin();
int score();
char titlescreen[20][59] = { };
char diffdiff[20][46] = {
(Grid removed due to char limit)
};
char gameover[20][50] = {
(Grid removed due to char limit)
};
char gameboard[203][26] = {
(Grid removed due to char limit)
};
int playerx;
int playery;
int pts;
void entryRender();
void gameRender();
int main() {
int input;
char replay;
int lx;
int ly;
char walkin;
int gaming;
char titlechoice;
int diff;
int running;
lx = 0;
ly = 0;
running = 1;
playerx = 13;
playery = 5;
pts = 25;
gaming = 0;
while (gaming == 0) {
titleRender();
printf("\033[1;32m");
printf("\nPress 'p' to play or 'x' to exit!");
printf("\033[0m");
scanf(" %c", &titlechoice);
if (titlechoice == 'p') {
gaming += 4;
}
if (titlechoice == 'x') {
return 0;
}
}
while (gaming == 4) {
system("stty -echo raw");
render();
printf("\033[1;35m");
printf("Choose a direction: s/Down, a/Left, d/Right.\n\r");
printf("\033[0m");
walkin = quickchar(0.5);
scanf("%c", &walkin);
//obj behaviour
if (walkin == 's' &&
gameboard[playery +1][playerx] != '#' &&
gameboard[playery + 1][playerx] != '+' &&
gameboard[playery + 1][playerx] != '|' &&
gameboard[playery + 1][playerx] != '-') {
playery++;
pts += 5;
if (gameboard[playery + 1][playerx] == '#') {
pts -= 25;
}
if (gameboard[playery + 1][playerx] == 'P') {
printf("Points increased!\n\r");
pts += 50;
gameboard[playery + 1][playerx] = '_';
}
}
else if (walkin == 'a' &&
gameboard[playery][playerx - 1] != '#' &&
gameboard[playery][playerx - 1] != '+' &&
gameboard[playery][playerx - 1] != '|' &&
gameboard[playery][playerx - 1] != '-') {
playerx--;
if (gameboard[playery][playerx - 1] == '#') {
pts -= 25;
}
if (gameboard[playery][playerx - 1] == 'P') {
printf("Points increased!\n\r");
pts += 50;
gameboard[playery][playerx - 1] = '_';
}
}
else if (walkin == 'd' &&
gameboard[playery][playerx + 1] != '#' &&
gameboard[playery][playerx + 1] != '+' &&
gameboard[playery][playerx + 1] != '|' &&
gameboard[playery][playerx + 1] != '-') {
playerx++;
if (gameboard[playery][playerx + 1] == '#') {
pts -= 25;
}
if (gameboard[playery + 1][playerx] == 'P) {
printf("Points increased!\n\r");
pts += 50;
gameboard[playery][playerx + 1] = '_';
}
}
if (walkin == 'a' || walkin == 's' || walkin == 'd' ||
walkin != 'a' || walkin != ' ' || walkin != 'd' ) {
for (ly = 0; ly = 202; ly++) {
for (lx = 1; lx = 25; lx++) {
gameboard[ly][lx] = 'L';
}
}
}
if (pts <= 0) {
system("clear");
renderLoss();
scanf("%c", replay);
if (replay == 'Y') {
gaming = 3;
}
if (replay == 'N') {
gaming = 5;
}
}
if (playery == 202) {
renderWin();
printf("");
printf("Congrats! You got a score of %d !", pts);
printf("");
scanf("%c", &replay);
if (replay == 'Y') {
gaming = 4;
}
if (replay == 'N') {
gaming = 5;
}
}
//player postion == 203y, then congrta screen
//ask player to set gaming to 4(replay) or none (exit program)
}
system("stty echo -raw");
return 0;
}
void render() {
int y,x,k;
system("clear");
printf("\033[01;33m");
printf("||POINTS: %d||\r\n", pts);
printf("\033[0m");
for (y = 0; y < 203; y++) {
for (x = 0; x < 26; x++) {
if (y == playery && x == playerx) {
printf("\033[0;32m");
printf("O");
printf("\033[0m");
}
else {
printf("\033[1;36m");
printf("%c", gameboard[y][x]);
printf("\033[0m");
}
}
printf("\r\n");
}
}
void titleRender() {
int y, x;
system("clear");
for (y = 0; y < 20; y++) {
for (x = 0; x < 59; x++) {
printf("\033[0;32m");
printf(" %c", titlescreen[y][x]);
printf("\033[0m");
}
printf("\r\n");
}
}
void renderLoss() {
int y, x;
system("clear");
for (y = 0; y < 26; y++) {
for (x = 0; x < 50; x++) {
printf("\033[0;31m");
printf(" %c", gameover[y][x]);
printf("\033[0m");
}
printf("\r\n");
}
}
void renderWin() {
int y, x;
system("clear");
for (y = 0; y < 20; y++) {
for (x = 0; x < 46; x++) {
printf("\033[0;33m");
printf(" %c", diffdiff);
printf("\033[0m");
}
printf("\r\n");
}
}
char quickchar(float delay) {
int flags;
char c;
usleep((int)(delay*1000000));
flags = fcntl(0, F_GETFL, 0);
fcntl(0, F_SETFL, flags | O_NONBLOCK);
c = getchar();
fcntl(0, F_SETFL, flags ^ O_NONBLOCK);
return c;
}

Struggling programming TicTacToe in C

I'm new to C and programming and I tried to code a simple TicTacToe game. I new that I defintaly did many dumb things.
So I have a main .c file and two header files, which I will post here:
main.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "game.h"
#include "random.h"
#define NAMELENGTH 20
int main(void) {
char names[2][NAMELENGTH];
// field positions
char field[9];
int winner = -2;
getnames(names);
printf("\n\n");
initField(field);
// set field positions to 'empty'
char actualPlayer = (char)(get_random_number()*10.0) % 2;
while (1) {
drawField(field);
turn(actualPlayer, names, field);
winner = isWinner(actualPlayer, field);
drawField(field);
if (winner >= 0) {
printwinner(winner, names);
return 0;
}
else if (winner == -1) {
printDrawGame(names);
return 0;
}
actualPlayer = (actualPlayer + 1) % 2;
system("cls");
}
return 0;
}
game.h:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NAMELENGTH 20
#pragma warning(disable:4996)
void drawField(char *field) {
printf("________________________\n");
printf("| | | |\n");
printf("| %c | %c | %c |\n", field[1], field[2], field[3]);
printf("|_______|_______|______|\n");
printf("| | | |\n");
printf("| %c | %c | %c |\n", field[4], field[5], field[6]);
printf("|_______|_______|______|\n");
printf("| | | |\n");
printf("| %c | %c | %c |\n", field[7], field[8], field[9]);
printf("|_______|_______|______|\n");
}
void getnames(char nameField[][NAMELENGTH]) {
printf("Name of the first player: ");
scanf("%s", &nameField[0]);
printf("Name of the second player: ");
scanf("%s", &nameField[1]);
}
void initField(char *field) {
for (int i = 1; i < 10; i++)
{
field[i] = i+48;
}
}
void turn(char actualPlayer, char names[][NAMELENGTH], char *field) {
char symbol = ' ';
int k;
int m;
if (actualPlayer == 1)
{
do {
printf("\nIts Player %s's turn.", names[0]);
char symbol = 'X';
printf("\nNumber of the field which you want to put your symbol in: ");
scanf("%i", &k);
if (field[k] == 'X' || field[k] == 'O')
{
printf("\nField is already occupied!");
k = 10;
}
} while (k < 1 || k > 9);
field[k] = 'X';
}
else {
do {
printf("\nIts Player %s's turn.", names[1]);
char symbol = 'O';
printf("\nNumber of the field which you want to put your symbol in: ");
scanf("%i", &m);
if (field[m] == 'X' || field[m] == 'O')
{
printf("\nField is already occupied!");
m = 10;
}
} while (m < 1 || m > 9);
field[m] = 'X';
}
}
int isWinner(char actualPlayer, char *field) {
int w = 2;
if (((field[1] = 'O') && (field[2] = '0') && (field[3] = '0')) || (field[4] = '0') && (field[5] = '0') && (field[6] = '0') || (field[7] = '0') && (field[8] = '0') && (field[9] = '0') || (field[1] = '0') && (field[5] = '0') && (field[9] = '0') || (field[3] = '0') && (field[5] = '0') && (field[7] = '0') || (field[1] = '0') && (field[4] = '0') && (field[7] = '0') || (field[2] = '0') && (field[5] = '0') && (field[8] = '0') || (field[3] = '0') && (field[6] = '0') && (field[9] = '0'))
{
int w = 1;
}
if (((field[1] = 'X') && (field[2] = 'X') && (field[3] = 'X')) || (field[4] = 'X') && (field[5] = 'X') && (field[6] = 'X') || (field[7] = 'X') && (field[8] = 'X') && (field[9] = 'X') || (field[1] = 'X') && (field[5] = 'X') && (field[9] = 'X') || (field[3] = 'X') && (field[5] = 'X') && (field[7] = 'X') || (field[1] = 'X') && (field[4] = 'X') && (field[7] = 'X') || (field[2] = 'X') && (field[5] = 'X') && (field[8] = 'X') || (field[3] = 'X') && (field[6] = 'X') && (field[9] = 'X'))
{
int w = 0;
}
else
{
int w = -1;
}
return w;
}
void printwinner(char winnerNumber, char names[][NAMELENGTH]) {
if (winnerNumber == 0)
{
printf("Player %s won!", names[0]);
system("exit");
}
else if (winnerNumber == 1)
{
printf("Player %s won!", names[1]);
system("exit");
}
}
void printDrawGame(char names[][NAMELENGTH]) {
printf("Draw!");
system("exit");
}
and random.h:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
static int _initialized;
void init() {
srand(time(NULL));
_initialized = 1;
}
double get_random_number() {
init();
if (!_initialized)
printf("Warning: init() should be called first!\n");
double random;
random = (double)rand() / ((double)(RAND_MAX)+1);
return random;
}
So the Program itself runs till I type in which field I want to put in the symbol. I get a weird error ("Stack around the variable 'field' was corrupted.") and also the random function doesnt work like I want. Would be happy and thankful for you help guys :)
You declared field to be an array of 9 elements. The indices will be 0 to 8. In game.h you have a function initField in which you do:
for (int i = 1; i < 10; i++)
{
field[i] = i+48;
}
This will produce indices 1 to 9, which steps out of bounds for the array.
You reinitialize the random number generator each time it is called. You pseudo random values will not be very random I'm afraid.
Fix it this way:
static int _initialized;
double get_random_number() {
if (!_initialized) {
srand(time(NULL));
_initialized = 1;
}
return = (double)rand() / ((double)(RAND_MAX)+1);
}
You should not write code in header files. Declarations belong in header files, code belongs in source files with the extension .c.

Printing string pointers in c

So, essentially I have two files:
File 1:
//
// main.c
// frederickterry
//
// Created by Rick Terry on 1/15/15.
// Copyright (c) 2015 Rick Terry. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int size (char *g) {
int ofs = 0;
while (*(g+ofs) != '\0') {
++ofs;
}
return ofs;
}
int parse(char *g) {
// Setup
char binaryConnective;
int negated = 0;
// Looking for propositions
int fmlaLength = size(g);
if(fmlaLength == 0) {
return 1;
}
if(fmlaLength == 1) {
if(g[0] == 'p') {
return 1;
} else if (g[0] == 'q') {
return 1;
} else if (g[0] == 'r') {
return 1;
} else {
return 0;
}
}
// Now looking for negated preposition
if(fmlaLength == 2) {
char temp[100];
strcpy(temp, g);
if(g[0] == '-') {
negated = 1;
int negatedprop = parse(g+1);
if(negatedprop == 1) {
return 2;
}
}
}
// Checking if Binary Formula
char arrayleft[50];
char arrayright[50];
char *left = "";
char *right = "";
int numLeft = 0;
int numRight = 0;
int bclocation = 0;
int binarypresent = 0;
if(fmlaLength != 1 && fmlaLength != 2) {
if(g[0] == '-') {
int negatedBinary = parse(g+1);
if(negatedBinary == 1 || negatedBinary == 2 || negatedBinary == 3) {
return 2;
} else {
return 0;
}
}
int i = 0;
int l = 0;
int p = strlen(g);
for(l = 0; l < strlen(g)/2; l++) {
if(g[l] == '(' && g[p-l-1] == ')') {
i++;
}
}
for(int q = i; q < strlen(g); q++) {
if(g[q] == '(') {
numLeft++;
} else if(g[q] == ')') {
numRight++;
}
arrayleft[q] = g[q];
//printf("%c", arrayleft[i]);
//printf("%s", left);
if((numRight == numLeft) && (g[q+1] == 'v' || g[q+1] == '>' || g[q+1] == '^')) {
arrayleft[q+1] = '\0';
bclocation = q+1;
binaryConnective = g[q+1];
binarypresent = 1;
// printf("The binary connecive is: %c\n", binaryConnective);
break;
}
}
if(binarypresent == 0) {
return 0;
}
int j = 0;
for(int i = bclocation+1; i < strlen(g)-1; i++) {
arrayright[j] = g[i];
j++;
}
arrayright[j] = '\0';
left = &arrayleft[1];
right = &arrayright[0];
//printf("Printed a second time, fmla 1 is: %s", left);
int parseleft = parse(left);
// printf("Parse left result: %d\n", parseleft);
if(parseleft == 0) {
return 0;
}
int parseright = parse(right);
if(parseright == 0) {
return 0;
}
// printf("Parse right result: %d\n", parseleft);
if(negated == 1) {
return 2;
} else {
return 3;
}
}
return 0;
}
int type(char *g) {
if(parse(g) == 1 ||parse(g) == 2 || parse(g) == 3) {
if(parse(g) == 1) {
return 1;
}
/* Literals, Positive and Negative */
if(parse(g) == 2 && size(g) == 2) {
return 1;
}
/* Double Negations */
if(g[0] == '-' && g[1] == '-') {
return 4;
}
/* Alpha & Beta Formulas */
char binaryConnective;
int numLeft = 0;
int numRight = 0;
int bclocation = 0;
int binarypresent = 0;
int i = 0;
if(g[0] == '(') {
i++;
}
if(g[0] == '-') {
i++;
if(g[1] == '(') {
i++;
}
}
for(i; i < strlen(g); ++i) {
if(g[i] == '(') {
numLeft++;
} else if(g[i] == ')') {
numRight++;
}
if(numRight == numLeft) {
if(g[i+1] == 'v' || g[i+1] == '>' || g[i+1] == '^') {
bclocation = i+1;
binaryConnective = g[i+1];
binarypresent = 1;
break;
}
}
}
/* Connective established */
if(binaryConnective == '^') {
if(g[0] == '-') {
return 3;
} else {
return 2;
}
} else if(binaryConnective == '>') {
if(g[0] == '-') {
return 2;
} else {
return 3;
}
} else if (binaryConnective == 'v') {
if(g[0] == '-') {
return 2;
} else {
return 3;
}
}
}
return 0;
}
char bin(char *g) {
char binaryConnective;
char arrayLeft[50];
int numLeft = 0;
int numRight = 0;
int bclocation = 0;
int i = 0;
if(g[0] == '(') {
i++;
}
if(g[0] == '-') {
i++;
if(g[1] == '(') {
i++;
}
}
for(i; i < strlen(g); ++i) {
if(g[i] == '(') {
numLeft++;
} else if(g[i] == ')') {
numRight++;
}
int j = 0;
arrayLeft[j++] = g[i];
if(numRight == numLeft) {
if(g[i+1] == 'v' || g[i+1] == '>' || g[i+1] == '^') {
arrayLeft[i+1] = '\0';
bclocation = i+1;
binaryConnective = g[i+1];
return binaryConnective;
}
}
}
return binaryConnective;
}
char *partone(char *g) {
char binaryConnective;
char arrayLeft[50];
char arrayRight[50];
int numLeft = 0;
int numRight = 0;
int bclocation = 0;
int i = 0;
if(g[0] == '(') {
i++;
}
if(g[0] == '-') {
i++;
if(g[1] == '(') {
i++;
}
}
int j = 0;
for(i; i < strlen(g); ++i) {
if(g[i] == '(') {
numLeft++;
} else if(g[i] == ')') {
numRight++;
}
arrayLeft[j] = g[i];
if(numRight == numLeft) {
if(g[i+1] == 'v' || g[i+1] == '>' || g[i+1] == '^') {
arrayLeft[j+1] = '\0';
bclocation = i+1;
binaryConnective = g[i+1];
break;
}
}
j++;
}
int m = 0;
for(int k = bclocation+1; k < strlen(g)-1; k++) {
arrayRight[m] = g[k];
m++;
}
arrayRight[m] = '\0';
char* leftSide = &arrayLeft[0];
// printf("%s\n", leftSide);
// printf("%s\n", rightSide);
int k = 0;
k++;
return leftSide;
}
char *parttwo(char *g) {
char binaryConnective;
char arrayLeft[50];
char arrayRight[50];
int numLeft = 0;
int numRight = 0;
int bclocation = 0;
int i = 0;
if(g[0] == '(') {
i++;
}
if(g[0] == '-') {
i++;
if(g[1] == '(') {
i++;
}
}
int j = 0;
for(i; i < strlen(g); ++i) {
if(g[i] == '(') {
numLeft++;
} else if(g[i] == ')') {
numRight++;
}
arrayLeft[j] = g[i];
if(numRight == numLeft) {
if(g[i+1] == 'v' || g[i+1] == '>' || g[i+1] == '^') {
arrayLeft[j+1] = '\0';
bclocation = i+1;
binaryConnective = g[i+1];
break;
}
}
j++;
}
int m = 0;
int n = size(g) - 1;
if(g[strlen(g)-1] != ')') {
n++;
}
for(int k = bclocation+1; k < n; k++) {
arrayRight[m] = g[k];
m++;
}
arrayRight[m] = '\0';
char* leftSide = &arrayLeft[0];
char* rightSide = &arrayRight[0];
// printf("%s\n", leftSide);
// printf("%s\n", rightSide);
return rightSide;
}
char *firstexp(char *g) {
char* left = partone(g);
char leftArray[50];
int i = 0;
for(i; i < strlen(left); i++) {
leftArray[i] = left[i];
}
leftArray[i] = '\0';
char binConnective = bin(g);
int typeG = type(g);
if(typeG == 2) {
if(binConnective == '^') {
return &leftArray;
} else if(binConnective == '>') {
return &leftArray;
}
} else if(typeG == 3) {
if(binConnective == 'v')
return &leftArray;
}
char temp[50];
for(int i = 0; i < strlen(leftArray); i++) {
temp[i+1] = leftArray[i];
}
temp[0] = '-';
char* lefttwo = &temp[0];
if(typeG == 2) {
if(binConnective == 'v') {
return lefttwo;
}
} else if(typeG == 3) {
if(binConnective == '>' || binConnective == '^') {
return lefttwo;
}
}
return "Hello";
}
char *secondexp(char *g) {
// char binaryConnective = bin(g);
// char* right = parttwo(g);
// char rightArray[50];
// int i = 0;
// for(i; i< strlen(right); i++) {
// rightArray[i+1] = right[i];
// }
// rightArray[i] = '\0';
// int typeG = type(g);
// if(type(g) == 2) {
// if(binaryConnective == '^') {
// return &rightArray;
// }
// } else if(type(g) == 3) {
// if(binaryConnective == 'v' || binaryConnective == '>') {
// return &rightArray;
// }
// }
return "Hello";
}
typedef struct tableau tableau;
\
\
struct tableau {
char *root;
tableau *left;
tableau *right;
tableau *parent;
int closedbranch;
};
int closed(tableau *t) {
return 0;
}
void complete(tableau *t) {
}
/*int main(int argc, const char * argv[])
{
printf("Hello, World!\n");
printf("%d \n", parse("p^q"));
printf("%d \n", type("p^q"));
printf("%c \n", bin("p^q"));
printf("%s\n", partone("p^q"));
printf("%s\n", parttwo("p^q"));
printf("%s\n", firstexp("p^q"));
printf("Simulation complete");
return 0;
}*/
File 2:
#include <stdio.h>
#include <string.h> /* for all the new-fangled string functions */
#include <stdlib.h> /* malloc, free, rand */
#include "yourfile.h"
int Fsize = 50;
int main()
{ /*input a string and check if its a propositional formula */
char *name = malloc(Fsize);
printf("Enter a formula:");
scanf("%s", name);
int p=parse(name);
switch(p)
{case(0): printf("not a formula");break;
case(1): printf("a proposition");break;
case(2): printf("a negated formula");break;
case(3): printf("a binary formula");break;
default: printf("what the f***!");
}
printf("\n");
if (p==3)
{
printf("the first part is %s and the second part is %s", partone(name), parttwo(name));
printf(" the binary connective is %c \n", bin(name));
}
int t =type(name);
switch(t)
{case(0):printf("I told you, not a formula");break;
case(1): printf("A literal");break;
case(2): printf("An alpha formula, ");break;
case(3): printf("A beta formula, ");break;
case(4): printf("Double negation");break;
default: printf("SOmewthing's wrong");
}
if(t==2) printf("first expansion fmla is %s, second expansion fmla is %s\n", firstexp(name), secondexp(name));
if(t==3) printf("first expansion fmla is %s, second expansion fmla is %s\n", firstexp(name), secondexp(name));
tableau tab;
tab.root = name;
tab.left=0;
tab.parent=0;
tab.right=0;
tab.closedbranch=0;
complete(&tab);/*expand the root node then recursively expand any child nodes */
if (closed(&tab)) printf("%s is not satisfiable", name);
else printf("%s is satisfiable", name);
return(0);
}
If you look at the first file, you'll see a method called * firstexp(char * g).
This method runs perfectly, but only if another method called * secondexp(char * g) is commented out.
If * secondexp(char * g) is commented out, then *firstexp runs like this:
Enter a formula:((pvq)>-p)
a binary formula
the first part is (pvq) and the second part is -p the binary connective is >
A beta formula, first expansion fmla is -(pvq), second expansion fmla is Hello
((pvq)>-p) is satisfiableProgram ended with exit code: 0
otherwise, if *secondexp is not commented out, it runs like this:
Enter a formula:((pvq)>-p)
a binary formula
the first part is (pvq) and the second part is -p the binary connective is >
A beta formula, first expansion fmla is \240L, second expansion fmla is (-
((pvq)>-p) is satisfiable. Program ended with exit code: 0
As you can see, the outputs are completely different despite the same input. Can someone explain what's going on here?
In the commented-out parts of secondexp and in parttwo, you return the address of a local variable, which you shouldn't do.
You seem to fill a lot of ad-hoc sized auxiliary arrays. These have the problem that they might overflow for larger expressions and also that you cannot return them unless you allocate them on the heap with malloc, which also means that you have to free them later.
At first glance, the strings you want to return are substrings or slices of the expression string. That means that the data for these strings is already there.
You could (safely) return pointers into that string. That is what, for example strchr and strstr do. If you are willing to modify the original string, you could also place null terminators '\0' after substrings. That's what strtok does, and it has the disadvantage that you lose the information at that place: If you string is a*b and you modify it to a\0b, you will not know which operator there was.
Another method is to create a struct that stores a slice as pointer into the string and a length:
struct slice {
const char *p;
int length;
};
You can then safely return slices of the original string without needing to worry about additional memory.
You can also use the standard functions in most cases, if you stick to the strn variants. When you print a slice, you can do so by specifying a field width in printf formats:
printf("Second part: '%.*s'\n", s->length, s->p);
In your parttwo() function you return the address of a local variable
return rightSide;
where rightSide is a pointer to a local variable.
It appears that your compiler gave you a warning about this which you solved by making a pointer to the local variabe arrayRight, that may confuse the compiler but the result will be the same, the data in arrayRight will no longer exist after the function returns.
You are doing the same all over your code, and even worse, in the secondexp() function you return a the address of a local variable taking it's address, you are not only returning the address to a local variabel, but also with a type that is not compatible with the return type of the function.
This is one of many probable issues that your code may have, but you need to start fixing that to continue with other possible problems.
Note: enable extra warnings when compiler and listen to them, don't try to fool the compiler unless you know exactly what you're doing.

Resources