Tic Tac Toe resetting the board after the 3rd move - c

So everything works fine till the 4th move. It then resets the board and puts and X in the first box. What's wrong with it? Also I would prefer if I would be guided to the answer, not just given it, it's for the learning. I've also tried finding the answer without any help by cutting one part and checking what effect it does. (Don't know how to use the debugger cause it always gives out, filename has no debugging information).
#include <stdio.h>
#include <stdlib.h>
int clear(void);
int displayboard(void);
int initialize(void);
int startgame(void);
int checkwin(char);
int canwin(void);
int getmove(void);
int makemove(void);
int canblock(void);
char board[3][3];
int main()
{
int menuchoice;
while(1)
{
printf(" |\\ /| | | /\\ |\\ |\n");
printf(" | \\/ | | | /--\\ | \\ |\n");
printf(" | | | |_ / \\ | \\|\n");
printf(" Tic-tac-toe Version 1 \n\n");
printf(" [Main Menu]\n");
printf(" 1 - Start game\n");
printf(" 2 - Exit game\n");
scanf("%d",&menuchoice);
if(menuchoice==1)
{
clear();
startgame();
}
else if(menuchoice==2)
{
exit(EXIT_SUCCESS);
}
}
}
/* Prints newlines to refresh the page */
int clear(void)
{
int i;
for(i=0;i<25;i++)
{
printf("\n");
}
return 0;
}
/* Makes the board blank */
int initialize(void)
{
int numrow,numcol;
numrow=0;
numcol=0;
while(numrow<3)
{
while(numcol<3)
{
board[numrow][numcol]=' ';
numcol++;
}
numcol=0;
numrow++;
}
return 0;
}
/* Prints the board */
int displayboard(void)
{
printf(" 1 2 3\n\n\n");
printf(" 1 %c | %c | %c \n",board[0][0],board[0][1],board[0][2]);
printf(" ------------- \n");
printf(" 2 %c | %c | %c \n",board[1][0],board[1][1],board[1][2]);
printf(" ------------- \n");
printf(" 3 %c | %c | %c \n",board[2][0],board[2][1],board[2][2]);
return 0;
}
/* Function that controls the game*/
int startgame(void)
{
int movecount;
while(1)
{
movecount=0;
initialize();
displayboard();
board[1][1]='X';
clear();
displayboard();
getmove();
makemove();
movecount=3;
while(1)
{
clear();
displayboard();
getmove();
/* I believe the problem starts here */
if(checkwin('O')==1)
{
printf("\n\t\t\tYou WIN!!!!");
/*just to test*/
exit(EXIT_SUCCESS);
}
movecount++;
canwin(); /* Checks if it can make winning move */
if(canblock()==0) /*if a move to block has not been made*/
{
makemove();
movecount++;
}
else if(canblock()==1) /*if a move to block has been made*/
{
movecount++;
}
if(checkwin('X')==1)
{
printf("\n\t\t\tYou LOSE!!!");
/* just to test */
exit(EXIT_SUCCESS);
}
if(movecount==9)
{
printf(" Its a DRAW!!!");
/*Just to test */
exit(EXIT_SUCCESS);
}
}
}
}
/* Function to check win */
int checkwin(char ltr)
{
int rownumber,colnumber;
for(rownumber=0;rownumber<3;rownumber++)
{
if(board[rownumber][0]==ltr && board[rownumber][1]==ltr && board[rownumber][2]==ltr)
{
return 1;
}
}
for(colnumber=0;colnumber<3;colnumber++)
{
if(board[0][colnumber]==ltr && board[1][colnumber]==ltr && board[2][colnumber]==1)
{
return 1;
}
}
if(board[0][0]==ltr && board[1][1]==ltr && board[2][2]==ltr)
{
return 1;
}
else if(board[0][2]==ltr && board[1][1]==ltr && board[2][0]==ltr)
{
return 1;
}
else
return 0;
}
/* Function to get move */
int getmove(void)
{
int colnumber,rownumber;
printf("\n\t\t\tWhat row do you want to put your move?\n");
scanf("%d",&rownumber);
printf("\n\t\t\tWhat column do you want to put your move?\n");
scanf("%d",&colnumber);
board[rownumber-1][colnumber-1]='O';
return 0;
}
/* Function to makemove */
int makemove(void)
{
if(board[0][0]==' ')
{
board[0][0]='X';
return 0;
}
else if(board[0][2]==' ')
{
board[0][2]='X';
return 0;
}
else if(board[2][0]==' ')
{
board[2][0]='X';
return 0;
}
else if(board[2][2]==' ')
{
board[2][2]='X';
return 0;
}
else if(board[0][1]==' ')
{
board[0][1]=='X';
return 0;
}
else if(board[1][0]==' ')
{
board[1][0]='X';
return 0;
}
else if(board[1][2]==' ')
{
board[1][2]='X';
return 0;
}
else if(board[2][1]==' ')
{
board[2][1]='X';
return 0;
}
}
/* Function to make winning move */
int canwin(void)
{
int rownumber,colnumber;
for(rownumber=0;rownumber<3;rownumber++)
{
for(colnumber=0;colnumber<3;colnumber++)
{
board[rownumber][colnumber]='X';
if(checkwin('X')==1)
{
return 1;
}
board[rownumber][colnumber]=' ';
}
}
return 0;
}
/* Function to block winning move */
int canblock(void)
{
int rownumber,colnumber;
for(rownumber=0;rownumber<3;rownumber++)
{
for(colnumber=0;colnumber<3;colnumber++)
{
board[rownumber][colnumber]='O';
if(checkwin('O')==1)
{
board[rownumber][colnumber]='X';
return 1;
}
else if(checkwin('O')==0)
{
board[rownumber][colnumber]=' ';
}
}
}
return 0;
}

I think you got a problem in your canwin() function, as I understand it, you want the A.I. to test if it can make a winning move. But looking at the function
int canwin(void)
{
int rownumber,colnumber;
for(rownumber=0;rownumber<3;rownumber++)
{
for(colnumber=0;colnumber<3;colnumber++)
{
board[rownumber][colnumber]='X'; // <--- Problem here
if(checkwin('X')==1)
{
return 1;
}
board[rownumber][colnumber]=' ';
}
}
return 0;
}
You are actually overwriting current position of your board with an 'X', without checking if there already was a symbol there before! So you are essentially overwriting your board with 'X'es, checking if the X-player won and if not "resetting" to empty space ' '!
You can fix this by inserting a check before your write like this:
if (board[rownumber][colnumber] == ' ')
{
board[rownumber][colnumber]='X';
...

Related

Tic Tac Toe Minimax not working in certain placement

It would give me a board that looks like
==============
| X | 1 | O |
-------------
| 3 | X | 5 |
-------------
| O | 7 | 8 |
==============
The issue i think is that the first move is not in the middle which will cause the AI to lose.
#include <stdio.h>
#include <stdbool.h>
#define X 'X'
#define O 'O'
#define T 'T'
struct Move
{
int row;
int column;
};
void generateBoard(char board[3][3]);
bool canMakeMove(char board[3][3], struct Move move);
bool makeMove(char board[3][3], struct Move move, char moveSymbol);
void copyBoard(char originalBoard[3][3], char duplicateBoard[3][3]);
int minimax(char board[3][3], int depth, bool isMaximizing);
char generatePlayerChar(int player);
char checkWinner(char board[3][3]);
bool hasAvailableSpot(char board[3][3]);
void generateBoard(char board[3][3])
{
printf("\n"
"==============\n"
"| %c | %c | %c |\n"
"-------------\n"
"| %c | %c | %c |\n"
"-------------\n"
"| %c | %c | %c |\n"
"==============\n",
board[0][0], board[0][1], board[0][2],
board[1][0], board[1][1], board[1][2],
board[2][0], board[2][1], board[2][2]);
}
char generatePlayerChar(int player)
{
return ((player == 1) ? 'X' : 'O');
}
/// #brief Given a board, check if there's any available spot available to use
/// #param board
/// #return
bool hasAvailableSpot(char board[3][3])
{
int count = 0;
for (int rows = 0; rows < 3; rows++)
{
for (int cols = 0; cols < 3; cols++)
{
struct Move attemptedMove = {rows, cols};
if (canMakeMove(board, attemptedMove))
{
count++;
}
}
}
if (count > 0)
{
return true;
}
return false;
}
/// #brief Check for both vertical/horizontal/diagonal winner
/// #param board
/// #return Return 'X'/'O'/'T'/-1 depending on who won the game/tie
char checkWinner(char board[3][3])
{
for (int i = 0; i < 3; i++)
{
// Check horizontal winning condition
if ((board[i][0] == board[i][1]) && (board[i][1] == board[i][2]))
{
return board[i][0];
}
// Check vertical winning condition
if ((board[0][i] == board[1][i]) && (board[1][i] == board[2][i]))
{
return board[0][i];
}
}
// Check for diagonal winning condition
if ((board[0][0] == board[1][1]) && (board[1][1] == board[2][2]))
{
return board[0][0];
}
else if ((board[0][2] == board[1][1]) && (board[1][1] == board[2][0]))
{
return board[0][2];
}
// There's no winner so we check if there's any empty space left yet.
if (!hasAvailableSpot(board))
{
return 'T';
}
return -1;
}
/// #brief Place the character on the board
/// #param board
/// #param move
/// #param moveSymbol
/// #return Return true depending on whether it successfully modified the board
bool makeMove(char board[3][3], struct Move move, char moveSymbol)
{
if (canMakeMove(board, move))
{
board[move.row][move.column] = moveSymbol;
return true;
}
return false;
}
/// #brief Takes in a board and does out of bound checking as well as check on available spots on the board
/// #param board The board to check
/// #param move A single structure consisting of row,column
/// #return A boolean true/false whether you can place a move on a specific area on the board
bool canMakeMove(char board[3][3], struct Move move)
{
if ((move.row > 3) || (move.column > 3))
{
return false;
}
if ((board[move.row][move.column] != X) && (board[move.row][move.column] != O))
{
return true;
}
return false;
}
/// #brief Calls each available spot on the board and determine using minimax which is the next bestMove supposed to be
/// #param board Given a board, what's the best next move to do next
/// #return A structure which contains the best determined move to do next
struct Move getBestMove(char board[3][3])
{
int bestScore = -1000;
struct Move bestMove;
for (int rows = 0; rows < 3; rows++)
{
for (int cols = 0; cols < 3; cols++)
{
struct Move attemptedMove = {rows, cols};
if (canMakeMove(board, attemptedMove))
{
char duplicatedBoard[3][3];
copyBoard(board, duplicatedBoard);
// Attempt to put in the next possible move.
makeMove(duplicatedBoard, attemptedMove, X);
int tempScore = minimax(duplicatedBoard, 0, false);
if (tempScore > bestScore)
{
bestScore = tempScore;
bestMove = attemptedMove;
}
}
}
}
return bestMove;
}
// TODO: Include alpha beta pruning
/// #brief The code looks 90% similar to getBestMove. However, one thing that differentiates them is it goes recursively into every single board for possibility.
/// #param board
/// #param depth How deep has the recursion gone
/// #param isMaximizing Checks which player turn. AI is usually maximizing. Player is usually minimizing.
/// #return The
int minimax(char board[3][3], int depth, bool isMaximizing)
{
// Remember that if we do not calculate how to get the results somewhere in this function,
// Return bestScore would be unable to run as there is no one returning a value.
char winResult = checkWinner(board);
if (winResult == X)
{
return (10 - depth);
}
else if (winResult == O)
{
return (-10 + depth);
}
else if (winResult == T)
{
return 0;
}
if (isMaximizing)
{
int bestScore = -1000;
for (int rows = 0; rows < 3; rows++)
{
for (int cols = 0; cols < 3; cols++)
{
struct Move attemptedMove = {rows, cols};
if (canMakeMove(board, attemptedMove)) // Check for available spot in the board.
{
char duplicateBoard[3][3];
copyBoard(board, duplicateBoard);
makeMove(duplicateBoard, attemptedMove, X);
// As long as the game doesn't end recursively call it till we get an end state.
int score = minimax(duplicateBoard, depth++, false);
if (bestScore < score)
{
bestScore = score;
}
}
}
}
return bestScore;
}
else
{
int bestScore = 1000;
for (int rows = 0; rows < 3; rows++)
{
for (int cols = 0; cols < 3; cols++)
{
struct Move attemptedMove = {rows, cols};
if (canMakeMove(board, attemptedMove))
{
char duplicateBoard[3][3];
copyBoard(board, duplicateBoard);
makeMove(duplicateBoard, attemptedMove, O);
// As long as the game doesn't end recursively call it till we get an end state.
int score = minimax(duplicateBoard, depth++, true);
if (bestScore > score)
{
bestScore = score;
}
}
}
}
return bestScore;
}
}
/// #brief Duplicates a board from originalBoard to duplicateBoard which creates a exact value but different array pointer
/// #param originalBoard
/// #param duplicateBoard
void copyBoard(char originalBoard[3][3], char duplicateBoard[3][3])
{
for (int rows = 0; rows < 3; rows++)
{
for (int cols = 0; cols < 3; cols++)
{
duplicateBoard[rows][cols] = originalBoard[rows][cols];
}
}
}
void MultiplayerMode()
{
char board[3][3] = {
{'0', '1', '2'},
{'3', '4', '5'},
{'6', '7', '8'},
};
bool gameInProgress = true;
int player = 0;
while (gameInProgress)
{
char playerChar = generatePlayerChar(player);
generateBoard(board);
printf("\nCurrently player %c turn.", playerChar);
printf("\nPlease enter your desired move: ");
struct Move desiredMove;
scanf(" [%d][%d]", &desiredMove.row, &desiredMove.column);
while (!canMakeMove(board, desiredMove))
{
printf("\nInvalid Move detected.");
printf("\nPlease re-enter your desired move: ");
scanf(" [%d][%d]", &desiredMove.row, &desiredMove.column);
}
makeMove(board, desiredMove, playerChar);
int result = checkWinner(board);
if (result == X)
{
printf("\nPlayer %c has won the game!", X);
gameInProgress = false;
}
else if (result == O)
{
printf("\nPlayer %c has won the game!", O);
gameInProgress = false;
}
else if (result == T)
{
printf("\nGame has resulted in a tie!");
gameInProgress = false;
}
player = !player;
}
}
void BotsMode()
{
char board[3][3] = {
{'0', '1', '2'},
{'3', '4', '5'},
{'6', '7', '8'},
};
bool gameInProgress = true;
int player = 0;
while (gameInProgress)
{
char playerChar = generatePlayerChar(player);
printf("\nCurrently player %c turn", playerChar);
if (player == 0)
{
struct Move desiredMove;
do
{
generateBoard(board);
printf("\nPlease enter your desired move: ");
scanf(" [%d][%d]", &desiredMove.row, &desiredMove.column);
} while (!canMakeMove(board, desiredMove));
makeMove(board, desiredMove, playerChar);
}
else
{
// This belongs to the AI.
struct Move bestMove = getBestMove(board);
printf("\nBest move determined is [%d][%d]", bestMove.row, bestMove.column);
makeMove(board, bestMove, playerChar);
}
int result = checkWinner(board);
if (result == X)
{
printf("\nPlayer %c has won the game!", X);
gameInProgress = false;
}
else if (result == O)
{
printf("\nPlayer %c has won the game!", O);
gameInProgress = false;
}
else if (result == T)
{
printf("\nGame has resulted in a tie!");
gameInProgress = false;
}
// Invert the player
player = !player;
}
}
int main(void)
{
int gameSelection;
do
{
printf("\nTic Tac Toe - Main Menu");
printf("\n1. Multiplayer Mode");
printf("\n2. Bots Mode");
printf("\nPlease enter your selection: ");
scanf("%d", &gameSelection);
} while (gameSelection != 1 && gameSelection != 2);
switch (gameSelection)
{
case 1:
MultiplayerMode();
break;
case 2:
BotsMode();
break;
}
return 0;
}
Hi there, I've tried and it seems to be working in certain combinations.
To use a move, i make use of [rows][cols]
So for the cases below, it doesn't seem to be working
Instruction 1: [0][2]
Instruction 2: [2][0]

I'm getting an error that says conflicting types in a C program

I'm working on this assignment and I can't get it to run. I have tried many different things such as switching the position of the function isValid, but when I declare it before the function getGuess, the code will stop right after the function populateColorArray is called and will close the program.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define COLORS 8
#define THREE 3
#define FOUR 4
#define TEN 10
#define TRUE 1
#define FALSE 0
enum color {BLACK, GREEN, NAVY, ORANGE, PINK, RED, VIOLET, WHITE};
int main()
{
srand((time(0)));
int i;
int j;
char colors[COLORS] = {'B', 'G', 'N', 'O', 'P', 'R', 'V', 'W'};
int secretCode[FOUR];
int guesses[TEN][FOUR];
int clues[TEN][FOUR];
welcomeScreen();
clearScreen();
setCode(secretCode);
printf("\n");
clearScreen();
displayBoard();
populateColorArray(colors);
initializeArray(guesses);
getGuess(guesses, colors);
for(i = 0; i < TEN; i++)
{
for(j = 0; j < FOUR; j++)
{
printf("%c", guesses[i][j]);
}
}
return 0;
}
void welcomeScreen()
{
printf(" ###################################################################\n");
printf(" ###################################################################\n");
printf(" ######################## #####################\n");
printf(" ######################## Mastermind #####################\n");
printf(" ######################## #####################\n");
printf(" ###################################################################\n");
printf(" ###################################################################\n");
printf("Rules:\n");
printf("1. The CodeMaker sets a secret code\n");
printf("2. The CodeBreaker tries to match the code using logic and deduction\n");
printf("3. After each move, the CodeMaker gives clues to the CodeBreaker\n");
printf("4. The CodeBreaker has 10 attempts to guess the secret code\n");
printf("\n");
}
// clears the screen for the next step of the program
void clearScreen()
{
printf(" #########################\n");
printf("\n");
printf(" <Hit enter to continue>\n");
printf("\n");
printf(" #########################\n");
char key;
scanf("%c", &key);
system("cls");
}
// board of the game
void displayBoard()
{
printf("+---------------------------------------+\n");
printf("| SECRET CODE |\n");
printf("+---------------------------------------+\n");
printf("| ? ? ? ? |\n");
printf("+---------------------------------------+\n");
printf("| PLAYER GUESS | CLUES |\n");
printf("+---------------------------------------+\n");
printf("| ? ? ? ? | ? ? ? ? |\n");
printf("+---------------------------------------+\n");
printf("| ? ? ? ? | ? ? ? ? |\n");
printf("+---------------------------------------+\n");
printf("| ? ? ? ? | ? ? ? ? |\n");
printf("+---------------------------------------+\n");
printf("| ? ? ? ? | ? ? ? ? |\n");
printf("+---------------------------------------+\n");
printf("| ? ? ? ? | ? ? ? ? |\n");
printf("+---------------------------------------+\n");
printf("| ? ? ? ? | ? ? ? ? |\n");
printf("+---------------------------------------+\n");
printf("| ? ? ? ? | ? ? ? ? |\n");
printf("+---------------------------------------+\n");
printf("| ? ? ? ? | ? ? ? ? |\n");
printf("+---------------------------------------+\n");
printf("| ? ? ? ? | ? ? ? ? |\n");
printf("+---------------------------------------+\n");
printf("| ? ? ? ? | ? ? ? ? |\n");
printf("+---------------------------------------+\n");
}
//function has as an argument codeArray[] that later on it's used when calling the function convertColor
void setCode (int codeArray[])
{
int i;
printf("Integer Secret Code\n");
for(i = 0; i < 4; ++i)
{
codeArray[i] = getColor();
printf("%d ", codeArray[i]);
}
printf("\n");
printf("Color Secret Code\n");
for(i = 0; i < 4; ++i)
{
convertColor(codeArray[i]);
}
}
// function used to get the random colors
int getColor ()
{
int colorRandom = rand() %COLORS;
return colorRandom;
}
// function used to convert the numbers into an actual color string
void convertColor (int color)
{
switch (color)
{
case 0:
printf("Black ");
break;
case 1:
printf("Green ");
break;
case 2:
printf("Navy ");
break;
case 3:
printf("Orange ");
break;
case 4:
printf("Pink ");
break;
case 5:
printf("Red ");
break;
case 6:
printf("Violet ");
break;
case 7:
printf("White ");
break;
}
}
// function that receives the array color[] and prints the char equivalent to each color
void populateColorArray(char color[])
{
int i;
printf("\nCharacter colors are:\n");
for(i = 0; i < COLORS; ++i)
{
printf("%c ", color[i]);
}
printf("\n");
}
// used to set all row and columns of the array as -1
void initializeArray(int guesses[TEN][FOUR])
{
int i;
int j;
for (i = 0; i < TEN; ++i)
{
for (j = 0; j < FOUR; ++j)
{
guesses[i][j] = -1;
}
}
}
/* function that is going to use isValid function to check if the user's
guess is valid and continue the game from there*/
void getGuess(int guesses[TEN][FOUR], char colors[])
{
static int row = 0;
int col = 0;
int valid = FALSE;
char guess[TEN];
int i;
while(valid = FALSE)
{
printf("Enter your guess of four colors (no spaces):\n");
for(i = 0; i < FOUR; ++i)
{
scanf("%c", &guess[i]);
}
printf("You entered: ");
for(i = 0; i < FOUR; ++i)
{
printf("%c", guess[i]);
}
if(strlen(guess[TEN]) == 4)
{
for (i = 0; i < FOUR; ++i)
{
guess[i] = toupper(guess[i]);
if (isalpha(guess[i]) == TRUE)
{
if(isValid(colors, guess[i]) == TRUE)
{
row = guess[i];
col = guess[i];
if(col == THREE)
{
valid = TRUE;
}
}
else
{
printf("The value you entered is invalid");
valid = FALSE;
break;
}
}
else
{
printf("Invalid value entered %c, try again", guess[i]);
valid = FALSE;
break;
}
}
}
else
{
printf("Incorrect number of letters entered");
valid = FALSE;
}
}
row = row + 1;
}
// actually validates the user guess
// giving an error "conflicting types for 'isValid'
int isValid(char colors[COLORS], char color)
{
int c;
int valid = FALSE;
for(c = 0; c < COLORS; ++c)
{
if(colors[c] == color)
{
return TRUE;
}
}
return FALSE;
}
if anyone knows what else can I do to make it run, I would appreciate it.
Here, you pass a char to strlen instead of a char*:
if(strlen(guess[TEN]) == 4)
The result has undefined behavior. The char will be cast to a char* and it will start reading from that memory address. Not only that, TEN is out of bounds. The highest index you can use in guess is TEN - 1.
It should be like this instead:
if(strlen(guess) == FOUR)
Here, you assign FALSE to valid instead of checking the value:
while(valid = FALSE)
It should be:
while(valid == FALSE)
When you read the colors from the user, you do it character-by-character so guess will not be null terminated:
for(i = 0; i < FOUR; ++i)
{
scanf("%c", &guess[i]);
}
Make that into something like this instead:
if(scanf("%4s", guess) != 1) {
printf("try again\n");
continue;
}
When you use the function isalpha you assume that it will return 1 (TRUE) if the char is alphabetic. That assumption is wrong. It will return non-zero if it's alphabetic.
if(isalpha(guess[i]) == TRUE)
should be
if(isalpha((unsigned char) guess[i]))
Here you take the argument guesses, but it's not used at all in the function, which is highly suspicious:
void getGuess(int guesses[TEN][FOUR], char colors[])
Also: You've defined your functions in the wrong order. Reorder them so that they are declared before they are used:
void welcomeScreen() { ... }
void clearScreen() { ... }
void displayBoard() { ... }
int getColor() { .. }
void convertColor(int color) { ... }
void setCode(int codeArray[]) { ... }
void populateColorArray(char color[]) { ... }
void initializeArray(int guesses[TEN][FOUR]) { ... }
int isValid(char colors[COLORS], char color) { ... }
void getGuess(int guesses[TEN][FOUR], char colors[]) { ... }
int main() { ... }

How to wait an input without stop the program in Xlib

The problem is this, I, am writing a chip 8 emulator in C, and i am using a library that use Xlib, for writing sprites attending input etc, the method that the library have for wait an input is this:
char gfx_wait(){
XEvent event;
gfx_flush();
while(1) {
XNextEvent(gfx_display,&event);
if(event.type==KeyPress) {
saved_xpos = event.xkey.x;
saved_ypos = event.xkey.y;
return XLookupKeysym(&event.xkey,0);
} else if(event.type==ButtonPress) {
saved_xpos = event.xkey.x;
saved_ypos = event.xkey.y;
return event.xbutton.button;
}
}
}
when i call this method the program stops waiting for input, I, need a methods that is called just when i press or release a button.
I just solve my problem, using this function :
int gfx_event_waiting(unsigned char *ch)
{
XEvent event;
gfx_flush();
while (1) {
if(XCheckMaskEvent(gfx_display,-1,&event)) {
if(event.type==KeyPress) {
*ch = XLookupKeysym(&event.xkey,0);
return 1;
}else if(event.type==KeyRelease){
return 1;
}else if (event.type==ButtonPress) {
return 1;
} else {
return 0;
}
} else {
return 0;
}
}
}
and this is the main :
int
main(int argc, char *argv[])
{
int x;
int i;
unsigned char key_pressed,key_released;
Init();
LoadRom(SELECTED_ROM);
gfx_open(WIDTH,HEIGHT,"Chip 8 Emulator");
gfx_color(255,250,250);
for(;;){
if(!gfx_event_waiting(&key_pressed)){
opcode_cycle();
key_wait(key_released,0);
#if DEBUG
printf("# %d | %c #",x,key_pressed);
#endif
key_wait(key_pressed,1);
key_released = key_pressed;
gfx_clear();
if(DrawFlag)
Draw();
/*Big for for simulate a delay*/
for(i = 0; i <= 100000; i++)
;
}else{
x++;
}
}
}
I, am sure that there is a better way for do this , but you know, It's work...

Countries Grouping in c

People in a group are sitting in a group numbered 1 to N. It is known that people of same countries are sitting together.
Output is a single integer denoting no of distinct countries.
Input
4 (no of test cases)
2 (no of people in group)
1 1 ( in this there are 2 people from diff country)
2
1 3
7
1 1 2 2 3 3 3
7
7 7 7 7 7 7 7
Output should be
2
Invalid Data
4
1
My program:please tell me where is the error
#include<stdio.h>
#include<string.h>
int main()
{
int tcaseno,nopgrp,flag=0;
int arr[1000];
int count=0,i=0,j=0,t=0;
scanf("%d", &tcaseno);
t=tcaseno;
while(t>0)
{
scanf("%d\n", &nopgrp);
for (i = 0; i < nopgrp;i++)
{
scanf("%d", &arr[i]);
}
for (j = 0; j < nopgrp;j++)
{
if(arr[j]==1)
{
count++;
}
else if(arr[j]==2)
{
if(arr[j+1]==2)
{
count++;
}
else
{
flag=1;
}
}
else if(arr[j]==3)
{
if((arr[j+1]==3)&&(arr[j+2]==3))
{
count++;
}
else
{
flag=2;
}
}
else if(arr[j]==4)
{
if((arr[j+1]==4)&&(arr[j+2]==4)&&(arr[j+3]==4))
{
count++;
}
else
{
flag=3;
}
}
else if(arr[j]==5)
{
if((arr[j+1]==5)&&(arr[j+2]==5)&&(arr[j+3]==5)&&(arr[j+4]==5))
{
count++;
}
else
{
flag=4;
}
}
else if(arr[j]==6)
{
if((arr[j+1]==6)&&(arr[j+2]==6)&&(arr[j+3]==6)&&(arr[j+4]==6)&&(arr[j+5]==6))
{
count++;
}
else
{
flag=5;
}
}
else if(arr[j]==7)
{
if((arr[j+1]==7)&&(arr[j+2]==7)&&(arr[j+3]==7)&&(arr[j+4]==7)&&(arr[j+5]==7)&&(arr[j+6]==7))
{
count++;
}
else
{
flag=6;
}
}
else if(arr[j]==8)
{
if((arr[j+1]==8)&&(arr[j+2]==8)&&(arr[j+3]==8)&&(arr[j+4]==8)&&(arr[j+5]==8)&&(arr[j+6]==8)&&(arr[j+7]==8))
{
count++;
}
else
{
flag=7;
}
}
else if(arr[j]==9)
{
if((arr[j+1]==9)&&(arr[j+2]==9)&&(arr[j+3]==9)&&(arr[j+4]==9)&&(arr[j+5]==9)&&(arr[j+6]==9)&&(arr[j+7]==9)&&(arr[j+8]==9))
{
count++;
}
else
{
flag=8;
}
}
else if(arr[j]==0)
{
flag=9;
}
}
if(flag!=0)
{
printf("Invalid Data");
flag=0;
}
else
{
printf("%d\n",count);
count=0;
}
t--;
}
return 0;
}
if((arr[j+1]==9)&&(arr[j+2]==9)&&(arr[j+3]==9) ...)
You can simplify the above code with another for loop. Evidently you just want to see how many different numbers there are in the array.
Note that one of the main reasons to use C, or to learn C, is for efficiency. Therefore int arr[1000] is somewhat out of place because it allocates 4000 bytes. You may want to streamline that with malloc/free.
You should use printf to tell the user what to input.
I took some guesses on what you are trying achieve.
int tcaseno, nopgrp, error;
int count, i;
int *arr;
printf("no_test_cases: ");
scanf("%d", &tcaseno);
while(tcaseno > 0)
{
error = 0;
count = 1;
printf("no_people_in_group: ");
scanf("%d", &nopgrp);
if(nopgrp > 0 && nopgrp < 1000)
{
arr = malloc(nopgrp * sizeof(int));
printf("Enter %d numbers: ", nopgrp);
for(i = 0; i < nopgrp; i++)
scanf("%d", &arr[i]);
for(i = 1; i < nopgrp; i++)
{
if(arr[i - 1] > arr[i])
error = 1;
else if(arr[i - 1] != arr[i])
count++;
}
free(arr);
}
else
error = 1;
if(error)
printf("Invalid Data\n");
else
printf("Result: %d\n", count);
tcaseno--;
}

control may reach end of non-void function [-Wreturn-type]|

Ok, I have a code in C. Its noughts and crosses.
But i don't know about my 'sprawdzenie'(check).
IDE send me control may reach end of non-void function [-Wreturn-type].
I have no idea whats wrong but I know my code isn't beauty.
#include <stdio.h>
#include <stdlib.h>
char plansza[3][3];
void wczytaj()
{
printf(" %c |%c | %c\n",plansza[0][0],plansza[0][1],plansza[0][2]);
printf("-------\n");
printf(" %c |%c | %c\n",plansza[1][0],plansza[1][1],plansza[1][2]);
printf("-------\n");
printf(" %c |%c | %c\n",plansza[2][0],plansza[2][1],plansza[2][2]);
}
char sprawdzenie()
{
if((plansza[0][0]&&plansza[0][1]&&plansza[0][2] =='x' )||
(plansza[0][2]&&plansza[1][1]&&plansza[2][0]=='x') ||
(plansza[0][2]&&plansza[1][2]&&plansza[2][2]=='x') ||
(plansza[2][0]&&plansza[2][1]&&plansza[2][2]=='x') ||
(plansza[1][0]&&plansza[1][1]&&plansza[1][2]=='x') ||
(plansza[0][1]&&plansza[1][1]&&plansza[2][1]=='x') ||
(plansza[0][0]&&plansza[1][1]&&plansza[2][2]=='x') ||
(plansza[0][0]&&plansza[1][0]&&plansza[2][0]=='x'))
{
return 1;
}else if((plansza[0][0]&&plansza[0][1]&&plansza[0][2]=='o') ||
(plansza[0][0]&&plansza[1][0]&&plansza[2][0]=='o') ||
(plansza[0][0]&&plansza[1][1]&&plansza[2][2]=='o') ||
(plansza[0][1]&&plansza[1][1]&&plansza[2][1]=='o') ||
(plansza[1][0]&&plansza[1][1]&&plansza[1][2]=='o') ||
(plansza[2][0]&&plansza[2][1]&&plansza[2][2]=='o') ||
(plansza[0][2]&&plansza[1][2]&&plansza[2][2]=='o') ||
(plansza[0][2]&&plansza[1][1]&&plansza[2][0]=='o'))
{
return 2;
}
}
void gracz_x()
{
unsigned int i=3;
unsigned int j=3;
wczytaj();
printf("Podaj wiersz i kolumnę: ");
scanf("%u %u",&i,&j);
if(plansza[i][j]!='o')
plansza[i][j]='x';
else{
printf("Podaj poprawne współrzędne: ");
scanf("%u %u",&i,&j);
plansza[i][j]='x';
}
}
void gracz_o()
{
unsigned int i=3;
unsigned int j=3;
wczytaj();
printf("Podaj wiersz i kolumnę: ");
scanf("%u %u",&i,&j);
if(plansza[i][j]!='x')
plansza[i][j]='o';
else{
printf("Podaj poprawne współrzędne: ");
scanf("%u %u",&i,&j);
plansza[i][j]='o';
}
}
int main()
{
char wynik=0;
int kolejka = 0;
while(wynik==0)
{
if(kolejka==0)
{
gracz_o();
}else{
gracz_x();
}
kolejka=kolejka+1;
wynik=sprawdzenie();
if(kolejka==9){
printf("remis");
break;
}
}
wczytaj();
if(wynik==1)
{
printf("wygryw x\n");
}else if(wynik==2)
{
printf("wygryw o\n");
}
return 0;
}
It means that your function sprawdzenie is supposed to return char but it might not. You have an if and an else if. If neither of these conditions are met, the function will get to the end and not return anything. This isn't allowed because the function is expected to return char.
Add a default return value at the end or add an else block to prevent your function from ending without returning anything.

Resources