Get Key State in linux C - c

OK ive searched about for quite some time now but i simply cannot find a replacement for the GetKeyState() function in linux. All i need and want is to simply poll the arrow keys, and if they are pressed, execute something. My home PC is linux based and my students' PC is windows based, so when i worked in that, i wrote this code:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <dos.h>
#include <windows.h>
int x; int y, redraw;
int i; int l, xm, ym, op, as, b, ab;
short int display[10][10];
void draw() {
if (redraw == 1) {
system("cls");
while (l < 10) {
while (i<10) {
if (display[i][l] == 0) { printf("="); }
if (display[i][l] == 1) { printf("X"); }
if (display[i][l] == 2) { printf("w"); }
if (display[i][l] == 3) { printf("0"); }
if (display[i][l] == 4) { printf("#"); }
if (display[i][l] == 5) { printf("M"); }
if (display[i][l] == 6) { printf("H"); }
if (display[i][l] == 7) { printf("8"); }
printf("|");
i++;
}
i = 0;
printf("\n");
printf("-+-+-+-+-+-+-+-+-+-+");
printf("\n");
l++;
}
l = 0;
redraw = 0;
}
}
void getkeys() {
while (b == 0) {
if (GetKeyState(VK_LEFT) & 0x8000)
{
xm = -1;
b = 1;
}
if (GetKeyState(VK_RIGHT) & 0x8000)
{
xm = 1;
b = 1;
}
if (GetKeyState(VK_UP) & 0x8000)
{
ym = -1;
b = 1;
}
if (GetKeyState(VK_DOWN) & 0x8000)
{
ym = 1;
b = 1;
}
if (GetKeyState(VK_BACK) & 0x8000)
{
op = -1;
b = 1;
}
if (GetKeyState(VK_RETURN) & 0x8000)
{
op = 1;
b = 1;
}
} b = 0; redraw = 1;
}
void cursor() {
display[x][y] = as;
x = x + xm;
xm = 0;
y = y + ym;
ym = 0;
if (x >9) { x = 0; }
if (y >9) { y = 0; }
if (x <0) { x = 9; }
if (y <0) { y = 9; }
ab = display[x][y];
as = ab;
if (as == 0) {
display[x][y] = 4;
}
if (as == 1) {
display[x][y] = 5;
}
if (as == 2) {
display[x][y] = 6;
}
if (as == 3) {
display[x][y] = 7;
}
Sleep(100);
}
void main()
{
while (i < 10) {
while (l<10) { display[l][i] = rand() % 4; l++; } l = 0; i++;
}
redraw = 1;
while (1) {
draw();
getkeys();
b = 0;
cursor();
}
}
now this basically prints an array and a cursor on it, but it does use the GetKeyState() function and i just can not find an alternative to it on linux. So is there any simple alternative to the mentioned function and is it possible to make the source code multiplatform somehow? Thanks in advance.

Related

Variably modified at file scope [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
How can I fix this error? It is caused by initializing my arrays pgAccess, pgArray, and pgRequest to variable sizes that are all global variables used throughout the program. I know there may be some undeclared variables in some of the methods but I would like to focus on the problem with these arrays. I'm working with virtual memory algorithms here.
int flag = 0, var, currFrame = 0, numFault, currRequest, request;
int numPages, numFrames, numRequest, fc =0, go =0, c =0;
int pgAccess[numRequest], pgArray[numPages], pgRequest[numRequest];
void runningMessage(int, int, int);
void fifo();
void lru();
void opt();
void runningMessage(int pg, int frame, int msg){
if(msg == 1)
{
printf("Page %d already in Frame %d\n",pg, frame);
}
if(msg == 2)
{
printf("Page %d loaded into Frame %d\n",pg, frame);
}
if(msg == 3)
{
printf("Page %d unloaded from Fram %d\n",pg, frame);
}
}
int main(int argc, char *argv[])
{
FILE *fp;
fp = fopen(argv[1], "r");
int x =0;
fscanf(fp, "%d %d %d", &numPages, &numFrames, &numRequest);
while(!feof(fp))
{
fscanf(fp, "%d", &pgAccess[x]);
x++;
}
fclose(fp);
printf("Algorithm: %s\n\n", argv[2]);
if(argv[2] == "FIFO")
{
fifo();
}
if(argv[2] == "LRU")
{
lru();
}
if(argv[3] == "OPT")
{
opt();
}
}
void fifo(){
int i, x;
for(i = 0; i < numFrames; i++)
{
pgArray[i] = -1;
}
while(x < numRequest)
{
flag =0;
var = pgAccess[x];
for(i = 0; i < numFrames; i++)
{
if(var == pgArray[i])
{
flag = 1;
x++;
runningMessage(pgArray[i], i, 1);
break;
}
}
if(flag == 0)
{
if(currFrame < numFrames)
{
pgArray[currFrame] = pgAccess[x];
runningMessage(pgAccess[x], currFrame, 2);
currFrame++;
x++;
numFault++;
}
else if( y < numFrames)
{
runningMessage(pgArray[y], y, 3);
pgArray[y] = pgAccess[x];
runningMessage(pgAccess[x], y, 2);
x++;
y++;
numFault++;
else
{
y =0;
}
}
}
}
printf(" %d Page Faults\n\n", numFault);
}
void lru(){
int i, x, y, a, b, j;
y = numFrames;
for(i = 0; i < y; i++)
{
pgRequest[i] = 0;
pgArray[i] = -1;
}
for(i = 0; i < numRequest; i++)
{
flag = 0;
a = pgAccess[i];
for(j = 0; j < y; j++)
{
if(a == pgArray[j])
{
flag = 1;
pgRequest[j] = i;
runningMessage(pgArray[j], j, 1);
break;
}
}
if((flag == 0) && (b < y))
{
fc++;
pgArray[b] = a;
pgRequest[b] = i;
runningMessage(pgArray[b], b, 2);
b++;
}
else if((flag == 0) && (b == y))
{
fc++;
minRequest = pgRequest[0];
for(currRequest = 0; currRequest < y; currRequest++)
{
if(pgRequest[currRequest] < minRequest)
{
minRequest = pgRequest[currRequest];
request = currRequest;
}
}
pgArray[request] = a;
pgRequest[request] = i;
runningMessage(pgAccess[request], request, 3);
runningMessage(pgArray[request], request, 2);
request =0;
}
}
printf(" %d Page Faults\n\n", fc);
}
void opt(){
int i, x, y, a;
for(i = 0; i < numFrames; i++)
{
pgRequest[i] = 0;
pgArray[i] = -1;
}
for(i = 0; i < numRequest; i++)
{
flag = 0;
a = pgAccess[i];
for(y = 0; y < numFrames, y++)
{
if(a == pgArray[y])
{
flag = 1;
runningMessage(pgArray[y], y, 1);
break;
}
}
if((flag == 0) && (x < numFrames))
{
fc++;
pgArray[x] = a;
runningMessage(pgArray[x], x, 2);
x++;
}
else if((flag == 0) && (x == numFrames))
{
fc++;
for(go = 0; go < numFrames; go++)
{
pgRequest[go] = 0;
}
for(currRequest = 0; currRequest < numFrames; currRequest++)
{
c = 0;
for(currFrame = i + 1; currFrame < numRequest; currFrame++);
{
if(pgArray[currRequest] == pgAccess[currFrame])
{
if(pgRequest[currRequest] == 0)
{
pgRequest[currRequest] = currFrame;
c = 1;
}
}
}
if(c != 1)
{
pgRequest[currRequest] = numRequest + 1;
}
}
request = 0;
maxRequest = pgRequest[0];
for(go = 0; go < numFrames; go++)
{
if(pgRequest[go] > maxRequest)
{
maxRequest = pgRequest[go];
runningMessage(pgArray[go], go, 3);
request = go;
}
}
pgArray[request] = a;
runningMessage(pgArray[request], request, 2);
}
}
printf(" %d Page Faults\n\n", fc);
}
Here, you have not initialized the variable numRequest and numPages, and you are passing it inside the initialization of an array. This might be causing the error in your code. Because numRequest and numPages might have some random garbage values as they are not initialized.
So either you declare the array after setting those numRequest and numPages or take the pointer instead of array as mentioned in this answer.
You still have to use malloc(), just make sure that you used it the correct way.
Declare your arrays as pointers,
int *pgAccess, *pgArray, *pgRequest;
when allocating,
pgAccess=malloc(sizeof(int)*numRequest);
Notice that this is not the only issue in your program.

How to replace goto in my code while searching for a road in C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SPECKLE '.'
#define WALL '#'
/*char a[1000][1000] = {
{'#','.','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#'},
{'#','.','.','.','#','.','.','.','.','.','.','.','.','.','.','.','#'},
{'#','.','#','#','#','.','#','#','#','#','#','.','#','.','#','#','#'},
{'#','.','.','.','.','.','.','.','.','.','#','.','#','.','.','.','#'},
{'#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','.','#'},
};*/
#define SIZE 1000
void print_arr()
{
char a[SIZE][SIZE];
for (int i = 0; i < 5; ++i)
{
for (int j = 0; j < 7; ++j)
{
printf("%c",a[i][j]);
}
printf("\n");
}
}
int main(int argc, char const *argv[])
{
int x = 0, y = 1;
char a[SIZE][SIZE];
for(int i=0;i<SIZE;i++)
{
scanf("%s",&a[i]);
}
continue_in_road:
while(1)
{
if(y == 16 && x == 4)
break;
if(a[x][y] == SPECKLE)
{
a[x][y] = '1';
y++;
continue;
}
else if(a[x][y] == WALL)
{
y--;
goto go_back_and_check;
}
go_back_and_check:
while(1)
{
if(a[x+1][y] == SPECKLE)
{
x++;
goto continue_in_road;
}
else if(a[x-1][y] == SPECKLE)
{
x--;
goto continue_in_road;
}
else if(a[x][y-1] == WALL)
{
a[x][y] = '2';
x--;
continue;
}
else if(a[x][y-1] == '1')
{
a[x][y] = '2';
y--;
continue;
}
else if(a[x][y-1] == SPECKLE)
{
y--;
goto switch_to_left;
}
}
switch_to_left:
while(1)
{
if(a[x][y] == SPECKLE)
{
a[x][y] = '1';
y--;
continue;
}
else if(a[x][y] == WALL)
{
y++;
goto go_back_and_check;
}
}
}
//print_arr();
for (int i = 0; i < 5; ++i)
{
for (int j = 0; j < 18; ++j)
{
if(a[i][j] == '1')
a[i][j] = '*';
if(a[i][j] == '2')
a[i][j] = '.';
printf("%c",a[i][j]);
}
printf("\n\n");
}
// print_arr();
return 0;
}
The code is for finding the path or the road in the graph, which looks like :
Input:
Output:
I'm searching for an alternative to goto command as I would like to teach more than this command how to jump in loops. I was told that goto command is ugly and so on, so I would be happy if any of you will help me with this one.
THANKS GUYS !
Using functions is the best way to get rid of those gotos. However don't dislike gotos just because someone told you so.
Here is a good reading about goto which enlighted me about goto when I was convinced by teachers and the internet that they were the Evil. Now I love goto; it just has it's applications on which it is the best tool available:
https://koblents.com/Ches/Links/Month-Mar-2013/20-Using-Goto-in-Linux-Kernel-Code/
Great power comes with great responsibility :)
Now your code:
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SPECKLE '.'
#define WALL '#'
#define SIZE 1000
#if 01
static char aa[1000][1000] = {
{'#','.','#','#','#','#','#','#','#','#','#','#','#','#','#','#','#'},
{'#','.','.','.','#','.','.','.','.','.','.','.','.','.','.','.','#'},
{'#','.','#','#','#','.','#','#','#','#','#','.','#','.','#','#','#'},
{'#','.','.','.','.','.','.','.','.','.','#','.','#','.','.','.','#'},
{'#','#','#','#','#','#','#','#','#','#','#','#','#','#','#','.','#'}
};
#endif
static int x, y;
static void print_arr(void);
static void continue_in_road(char a[SIZE][SIZE]);
static bool check(char a[SIZE][SIZE]);
static void switch_to_left(char a[SIZE][SIZE]);
/*
* Note that int main(void) is completely valid, and in fact is what you need,
* because you're not using the arguments.
*/
int main(void)
{
int i, j;
// char a[SIZE][SIZE];
x = 0;
y = 1;
// for (i = 0; i < SIZE; i++)
// scanf(" %s", &a[i]);
continue_in_road(aa);
print_arr();
for (i = 0; i < 5; i++) {
for (j = 0; j < 18; j++) {
if(aa[i][j] == '1')
aa[i][j] = '*';
if(aa[i][j] == '2')
aa[i][j] = '.';
printf("%c",aa[i][j]);
}
printf("\n\n");
}
print_arr();
return 0;
}
static void continue_in_road(char a[SIZE][SIZE])
{
bool initial_chk = true;
while (1) {
if (initial_chk) {
if ((y == 16) && (x == 4))
return;
if (a[x][y] == SPECKLE) {
a[x][y] = '1';
y++;
continue;
} else if (a[x][y] == WALL) {
y--;
}
}
if (check(a)) {
initial_chk = true;
continue;
}
initial_chk = false;
switch_to_left(a);
}
}
static bool check(char a[SIZE][SIZE])
{
while (1) {
if (a[x+1][y] == SPECKLE) {
x++;
return true;
} else if (a[x-1][y] == SPECKLE) {
x--;
return true;
} else if (a[x][y-1] == WALL) {
a[x][y] = '2';
x--;
} else if (a[x][y-1] == '1') {
a[x][y] = '2';
y--;
} else if (a[x][y-1] == SPECKLE) {
y--;
return false;
}
}
}
static void switch_to_left(char a[SIZE][SIZE])
{
while (1) {
if (a[x][y] == SPECKLE) {
a[x][y] = '1';
y--;
} else if(a[x][y] == WALL) {
y++;
return;
}
}
}
/* What is this supposed to do? */
static void print_arr(void)
{
char a[SIZE][SIZE];
int i, j;
for (i = 0; i < 5; ++i) {
for (j = 0; j < 7; ++j)
printf("%c",a[i][j]);
printf("\n");
}
}
It runs if you compile it just like that. I have commented the input loop to use the static const array initializer you've created, so that it was easy to test.
However I think you should reconsider changing the structure of the functions, because it is difficult to understand what it is doing. If I had understood what it does, I could have improved more the code, but as I didn't understand it so much, I limited myself to get rid of those gotos.

loop not completing its iteration in C

I am however having trouble with my game loop! Currently when an invalid move is made, the loop iterates correctly. However when a valid move is made, my program displays the changed board, however appears to freeze in the middle of the loop! i have the location where it freezes (Test Spot 2 in the code), but i have no clue why. The desired output of my code is to keep on iterating until there are no moves available. (I haven't created the check for no moves yet as I cannot get my code to run in a normal counted loop!)
The code working when it is Invalid and not when it is valid is shown below.
here
Main Function where the issue occurs
int main(void)
{
int n;
int p;
char oppChar;
char playChar;
int i;
int pTurn;
int deltaRow;
int deltaCol;
int endGame = 999;
printf("Enter the board dimension: ");
fflush(stdout);
scanf("%d", &n);
printf("Computer plays (B/W) ");
fflush(stdout);
scanf(" %c", &oppChar);
if (oppChar == 'B') {
pTurn = 0;
playChar = 'W';
} else {
pTurn = 1;
playChar = 'B';
}
char board[n][26];
int movesAvalB[n][26];
int movesAvalW[n][26];
int AIBoard[n][26];
for (i = 0; i < n; i++) {
for (p = 0; p < n; p++) {
board[i][p] = 'U';
}
}
board[(n / 2) - 1][(n / 2) - 1] = 'W';
board[(n / 2) - 1][(n / 2)] = 'B';
board[(n / 2)][(n / 2) - 1] = 'B';
board[n / 2][n / 2] = 'W';
printBoard(board, n);
int q = 0;
do {
q++;
// testing
printf(" \n");
printf("Turn Number %d \n", pTurn);
// variable decleration
int k = 0;
int y = 0;
int x = 0;
int max = 0;
int temp = 0;
char c[3] = " ";
// arrays are all 0
for (i = 0; i < n; i++) {
for (p = 0; p < n; p++) {
AIBoard[i][p] = 0;
movesAvalB[i][p] = 0;
movesAvalW[i][p] = 0;
}
}
// moves avaliable to W
for (y = 0; y < n; y++) {
for (x = 0; x < n; x++) {
if (moves(n, x, y, board, 'W')) {
movesAvalW[y][x] = 1;
}
}
}
printf("Test Spot 1\n");
// moves avaliable to B
for (y = 0; y < n; y++) {
for (x = 0; x < n; x++) {
if (moves(n, x, y, board, 'B')) {
printf("Test Spot 1.5\n");
movesAvalB[y][x] = 1;
}
}
}
fflush(stdout);
printf("Test Spot 2\n");
// pTurn = pTurn%2;
fflush(stdout);
printf("Enter a move for colour %c (RowCol): \n", playChar);
fflush(stdout);
scanf("%s", &c);
if (positionInBounds(n, c[0], c[1])) {
int y = c[0] - 97;
int x = c[1] - 97;
if (playChar == 'B') {
if (movesAvalB[y][x] == 1) {
for (deltaRow = -1; deltaRow <= 1; deltaRow++) {
for (deltaCol = -1; deltaCol <= 1; deltaCol++) {
if (positionIntBounds(n, (x + deltaRow), (y + deltaCol))) {
i = 1;
while ((positionIntBounds(n, (y + (i * deltaRow)), (x + (i * deltaCol)))) &&
(board[y + (i * deltaRow)][x + (i * deltaCol)] == 'W')) {
i++;
if ((positionIntBounds(n, (y + (i * deltaRow)), (x + (i * deltaCol)))) &&
(board[y + (i * deltaRow)][x + (i * deltaCol)] == 'B')) {
while (i != 0) {
i--;
board[y + (i * deltaRow)][x + (i * deltaCol)] = 'B';
}
}
}
}
}
}
for (deltaRow = -1; deltaRow <= 1; deltaRow++) {
for (deltaCol = -1; deltaCol <= 1; deltaCol++) {
if (board[y + deltaRow][x + deltaCol] == 'W') {
board[y + deltaRow][x + deltaCol] == 'B';
}
}
}
printBoard(board, n);
} else {
printf("Invalid Move.");
}
}
if (playChar == 'W') {
if (movesAvalW[y][x] == 1) {
for (deltaRow = -1; deltaRow <= 1; deltaRow++) {
for (deltaCol = -1; deltaCol <= 1; deltaCol++) {
if (positionIntBounds(n, (x + deltaRow), (y + deltaCol))) {
i = 1;
while ((positionIntBounds(n, (y + (i * deltaRow)), (x + (i * deltaCol)))) &&
(board[y + (i * deltaRow)][x + (i * deltaCol)] == 'B')) {
i++;
if ((positionIntBounds(n, (y + (i * deltaRow)), (x + (i * deltaCol)))) &&
(board[y + (i * deltaRow)][x + (i * deltaCol)] == 'W')) {
while (i != 0) {
i--;
board[y + (i * deltaRow)][x + (i * deltaCol)] = 'W';
}
}
}
}
}
}
for (deltaRow = -1; deltaRow <= 1; deltaRow++) {
for (deltaCol = -1; deltaCol <= 1; deltaCol++) {
if (board[y + deltaRow][x + deltaCol] == 'B') {
board[y + deltaRow][x + deltaCol] == 'W';
}
}
}
printBoard(board, n);
} else {
printf("Invalid Move.");
}
}
} else {
printf("Invalid Move.");
}
pTurn++;
} while (q <= 5);
printf("were out");
}
Secondary Functions which you probably don't need but maybe
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
void printBoard(char board[][26], int n)
{
int i;
char alpha[27] = "abcdefghijklmnopqrstuvwxyz";
printf(" ");
for (i = 0; i < n; i++) {
printf("%c", alpha[i]);
}
int p;
int q;
for (p = 0; p < n; p++) {
printf("\n");
printf("%c", alpha[p]);
for (q = 0; q < n; q++) {
printf("%c", board[p][q]);
}
}
}
bool positionInBounds(int n, char row, char col)
{
int p = row - 97;
int d = col - 97;
if (p > n) {
return false;
}
if (d > n) {
return false;
}
if (0 > p) {
return false;
}
if (0 > d) {
return false;
}
return true;
}
bool positionIntBounds(int n, int row, int col)
{
if (row > n) {
return false;
}
if (col > n) {
return false;
}
if (0 > row) {
return false;
}
if (0 > col) {
return false;
}
return true;
}
bool checkLegalInDirection(char board[][26], int n, char row, char col, char colour, int deltaRow, int deltaCol)
{
int i = 0;
while ((positionIntBounds(n, (row + (i * deltaRow)), (col + (i * deltaCol)))) &&
(board[row + (i * deltaRow)][col + (i * deltaCol)] != colour) &&
(board[row + (i * deltaRow)][col + (i * deltaCol)] != 'U')) {
i++;
if ((positionIntBounds(n, (row + (i * deltaRow)), (col + (i * deltaCol)))) &&
(board[row + (i * deltaRow)][col + (i * deltaCol)] == colour)) {
return true;
}
}
return false;
}
bool moves(int n, int x, int y, char board[][26], char colour)
{
int deltaRow;
int deltaCol;
if (board[y][x] == 'U') {
for (deltaRow = -1; deltaRow <= 1; deltaRow++) {
for (deltaCol = -1; deltaCol <= 1; deltaCol++) {
if (positionIntBounds(n, (x + deltaRow), (y + deltaCol))) {
if (checkLegalInDirection(board, n, (x + deltaRow), (y + deltaCol), colour, deltaRow, deltaCol)) {
return true;
}
}
}
}
}
return false;
}
(I was told to put fflush(stdout) before my scanf statements but this didnt fix the problem)

C - Function to see if a game reached the "GameOver" point. (2048 copy)

I'm programing a 2048 game copy in C. But I can't figure out the game over function. I've this struct:
typedef struct struct_BLOCO
{
int valor;
int cor;
int x, y;
} BLOCO;
And this is the function I give the board its coordinates:
void GiveBlocksCoordinates(BLOCO bloco[16])
{
int i, j, cont = 0;
for (i = 0; i < MAX; i++)
{
for (j = 0; j < MAX; j++)
{
bloco[cont].x = (j * 8) + X_INI;
bloco[cont].y = (i * 4) + Y_INI;
cont++;
}
}
}
And just put them on screen using a function using the values bloco[i].[x]/[y].
This is my "GameOver" function, in its current state:
PS: The "quant" integer recivies the 16 value. If a block is empty, it has 0 value in it. If is "Game Over", the function return 1.
int acabouJogo(BLOCO vec[], int quant)
{
int i, j, x, y, cont = 0, BlocosOcupados = 1;
for (i = 0; i < quant; i++)
if (vec[i].valor != 0)
BlocosOcupados++;
if (BlocosOcupados == quant)
{
for (x = 0; x != 16; x = x + 4)
{
while (cont < 3)
{
if (vec[x + cont].valor != vec[(x + cont) + 1].valor)
cont++;
else
return 0;
}
cont = 0;
}
for (x = 0; x < 4; x++)
{
while ( (cont + x) != (12 + x) )
{
if (vec[x + cont].valor != vec[(x + cont) + 4].valor)
cont = cont + 4;
else
return 0;
}
cont = 0;
}
}
else
return 0;
return 1;
}
Can you guys help me?
Sorry for my english.
Thanks.

Pointers Binary Tree Maze Solver in C

I need to create a Robot Simulator programmed in C. The Robot has to find the Exit of a 2d labirinth using a Recursive Backtracker algorithm, i understood how does this algorithm work but i don't know how to implement it. I Think i can use a Binary Tree using Pointers but i don't know how to do this, can you try to explain it to me?
This is the program that i've created, now the Robot is entering a loop because of the method that changes direction
#ifdef __unix__
#include <unistd.h>
#elif defined _WIN32
#include <windows.h>
#define sleep(x) Sleep(1000 * x)
#endif
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
void goUp();
void goDown();
void goLeft();
void goRight();
typedef struct robot {
int direction;
bool is_moving;
}robot;
typedef struct room {
robot robot;
bool is_robot;
int obstacle;
}room;
room Room[20][20];
int r = 12;
int c = 10;
void generation(room matrix[20][20])
{
srand(time(NULL));
int x,i,j;
x=0;
for(i=0;i<20;i++)
{
for(j=0;j<20;j++)
{
matrix[i][j].is_robot=false;
x=rand()%100+1;
if(x==1||x==50||x==100)
{
matrix[i][j].obstacle=1;
}
else
{
matrix[i][j].obstacle=0;
}
}
}
}
void print_matrix(room matrix[20][20])
{
int i,j;
for(i=0;i<20;i++)
{
for(j=0;j<20;j++)
{
if(matrix[i][j].obstacle==0)
{
if(matrix[i][j].is_robot==true)
{
printf("I");
}
else
{
printf(" ");
}
}
else
{
if(matrix[i][j].is_robot==true)
{
printf("I");
}
else
{
printf("o");
}
}
}
printf("\n");
}
}
bool changeDirection(room Room[20][20],int i,int j)
{
if(Room[i][j].robot.direction == 1)
{
if(Room[i-1][j].obstacle == 1 || i-1 == 0)
{
if(Room[i+1][j].obstacle == 1 || i+1 == 19)
{
Room[i][j].robot.direction = 2;
return true;
}
else
{
Room[i][j].robot.direction = 4;
return true;
}
}
else
{
Room[i][j].robot.direction = 3;
return true;
}
}
if(Room[i][j].robot.direction == 2)
{
if(Room[i-1][j].obstacle == 1 || i-1 == 0)
{
if(Room[i+1][j].obstacle == 1 || i+1 == 19)
{
Room[i][j].robot.direction = 1;
return true;
}
else
{
Room[i][j].robot.direction = 4;
return true;
}
}
else
{
Room[i][j].robot.direction = 3;
return true;
}
}
if(Room[i][j].robot.direction == 3)
{
if(Room[i][j+1].obstacle == 1 || j+1 == 19)
{
if(Room[i][j-1].obstacle == 1 || j-1 == 0)
{
Room[i][j].robot.direction = 4;
return true;
}
else
{
Room[i][j].robot.direction = 2;
return true;
}
}
else
{
Room[i][j].robot.direction = 1;
return true;
}
}
if(Room[i][j].robot.direction == 4)
{
if(Room[i][j+1].obstacle == 1 || j+1 == 19)
{
if(Room[i][j-1].obstacle == 1 || j-1 == 0)
{
Room[i][j].robot.direction = 3;
return true;
}
else
{
Room[i][j].robot.direction = 2;
return true;
}
}
else
{
Room[i][j].robot.direction = 1;
return true;
}
}
}
void goRight()
{
c=c+1;
Room[r][c].robot.direction=1;
Room[r][c].is_robot=true;
Room[r][c-1].is_robot=false;
}
void goLeft()
{
c=c-1;
Room[r][c].robot.direction=2;
Room[r][c].is_robot=true;
Room[r][c+1].is_robot=false;
}
void goUp()
{
r=r-1;
Room[r][c].robot.direction=3;
Room[r][c].is_robot=true;
Room[r+1][c].is_robot=false;
}
void goDown()
{
r=r+1;
Room[r][c].robot.direction=4;
Room[r][c].is_robot=true;
Room[r-1][c].is_robot=false;
}
int main()
{
generation(Room);
Room[r][c].robot.direction = 1;
Room[r][c].robot.is_moving = true;
Room[r][c].is_robot = true;
do
{
Room[r][c].robot.is_moving = true;
if (Room[r][c].robot.direction == 1 && Room[r][c].robot.is_moving == true) // destra
{
if(Room[r][c +1].obstacle == 1 || c+1 == 19)
{
changeDirection(Room,r,c);
}
else
{
goRight();
}
}
if (Room[r][c].robot.direction == 2 && Room[r][c].robot.is_moving == true) // sinistra
{
if(Room[r][c -1].obstacle == 1 || c-1 == 0)
{
changeDirection(Room,r,c);
}
else
{
goLeft();
}
}
if (Room[r][c].robot.direction == 3 && Room[r][c].robot.is_moving == true) // su
{
if(Room[r-1][c].obstacle == 1 || r-1 == 0)
{
changeDirection(Room,r,c);
}
else
{
goUp();
}
}
if (Room[r][c].robot.direction == 4 && Room[r][c].robot.is_moving == true) // giu
{
if(Room[r+1][c].obstacle == 1 || r+1 == 19)
{
changeDirection(Room,r,c);
}
else
{
goDown();
}
}
print_matrix(Room);
sleep(0.1);
system("cls");
}
while(1);
print_matrix(Room);
}
I'm having a hard time understanding how a binary tree would be useful in finding a path in a labyrinth (maybe it's used to represent the labyrinth?) but maybe I'm blind. I would simply make a 2d int array and let 0 mean the position is blocked (there's a wall there or something) and 1 mean it's open (you can move there). The brute force backtrack procedure, going off orthogonal movement (left, right, up, down) would be:
f(x,y){
// you found the place your want to go to
if (x,y) is (destinationX,destinationY)
return true
block the position (x,y) // i.e. mark current position as visited
if there is an open spot at (x,y-1) AND f(x,y-1)
return true
if there is an open spot at (x,y+1) AND f(x,y+1)
return true
if there is an open spot at (x-1,y) AND f(x-1,y)
return true
if there is an open spot at (x+1,y) AND f(x+1,y)
return true
return false
}
Suppose you had the labyrinth looking like:
"+" is where you start ([1][1])
"-" is your destination ([3][1])
"#" is a blocked region
===========
|#|#|#|#|#|
|#|+| |#|#|
|#|#| |#|#|
|#|-| | |#|
|#|#|#|#|#|
===========
Using the above idea I have:
#include <stdio.h>
#define width 5
#define height 5
// print maze
void print(char arr[][width]){
for (int i = 0; i < 2*width+1; i++) printf("=");
printf("\n");
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
printf("|%c",arr[i][j]);
}
printf("|\n");
}
for (int i = 0; i < 2*width+1; i++) printf("=");
}
// starting from (x,y) to (destX,destY)
int path(int arr[][width],int x,int y,int destX,int destY,char toDest[][width]){
if (x==destX && y==destY) {
toDest[y][x] = '*';
print(toDest);
return 1;
}
// mark current position as visited
arr[y][x] = 0;
toDest[y][x] = '*';
// left
if (arr[y][x-1] && path(arr,x-1,y,destX,destY,toDest))
return 1;
// right
if (arr[y][x+1] && path(arr,x+1,y,destX,destY,toDest))
return 1;
// up
if (arr[y-1][x] && path(arr,x,y-1,destX,destY,toDest))
return 1;
// down
if (arr[y+1][x] && path(arr,x,y+1,destX,destY,toDest))
return 1;
return 0;
}
int main () {
// use this to store path
// and then print it out if found
char toDest[height][width] = {
{'#','#','#','#','#'},
{'#',' ',' ','#','#'},
{'#','#',' ','#','#'},
{'#',' ',' ',' ','#'},
{'#','#','#','#','#'}
};
// 0 -> position is blocked
// 1 -> position is open
int maze[height][width] = {
{0,0,0,0,0},
{0,1,1,0,0},
{0,0,1,0,0},
{0,1,1,1,0},
{0,0,0,0,0}
};
path(maze,1,1,1,3,toDest);
}
Output:
===========
|#|#|#|#|#|
|#|*|*|#|#|
|#|#|*|#|#|
|#|*|*| |#|
|#|#|#|#|#|
===========
In output the path is designated by the *s

Resources