Why don't appear window created by ncurses? - c

A new window with input must appear. But instead just a standard ncurses's window displays.
#define _POSIX_C_SOURCE 200201L
#include <stdlib.h>
#include <curses.h>
#include <time.h>
int main () {
srand(time(NULL));
initscr();
cbreak();
noecho();
// get screen sizes
int yMax, xMax;
getmaxyx(stdscr, yMax, xMax);
//create a new window for input
int height = 10;
int width = 120;
WINDOW * inputwin = newwin(height, width, yMax/2 - 5, (xMax/2 - width/2));
box(inputwin, 0, 0);
refresh();
wrefresh(inputwin);
// get amount roads
echo();
mvwprintw(inputwin, 4, width/2 - 38, "Press key left to choose beginner level, key right - intermediate, key up - advanced.");
int amount_roads = 0;
keypad(inputwin, TRUE);
int a;
while (a != KEY_DOWN) {
int c = mvwgetch(inputwin, 5, 50);
if (c == KEY_LEFT) {
mvwprintw(inputwin, 5, 50, "You chose beginner ");
amount_roads = 2;
} else if (c == KEY_RIGHT) {
mvwprintw(inputwin, 5, 50, "You chose intermediate ");
amount_roads = 3;
} else if (c == KEY_UP) {
mvwprintw(inputwin, 5, 50, "You chose advanced ");
amount_roads = 4;
} else mvwprintw(inputwin, 5, 50, "INCORRECT INPUT. TRY AGAIN");
wrefresh(inputwin);
mvwprintw(inputwin, 6, 47, "Press key down to continue");
a = mvwgetch(inputwin, 7, 60);
}
delwin(inputwin);
wrefresh(stdscr);
//create win for game
height = yMax - 4;
width = xMax - 10;
WINDOW * gamewin = newwin(height, width, 2, 5);
box(gamewin, 0, 0);
refresh();
wrefresh(gamewin);
// draw roads
int road_width = (width - 2) / amount_roads;
for (int i = road_width; i < width - 2; i += road_width + 1) {
for (int j = 1; j < height - 1; j ++) {
mvwprintw(gamewin, j, i, "|");
}
}
//draw car
char car[8][12] =
{
{' ', ' ', ' ', '_', '_', '_', '_', '_', ' ', ' ', ' ', '\0'},
{' ', '(', ')', ' ', '|', '|', '|', ' ', '(', ')', ' ', '\0'},
{'/', ' ', '_', '_', '_', '_', '_', '_', '_', ' ', '\\', '\0'},
{'|', '/', '_', '_', '_', '_', '_', '_', '_', '\\', '|', '\0'},
{'|', ' ', ' ', '_', '_', '_', '_', '_', ' ', ' ', '|', '\0'},
{'|', ' ', ' ', '\\', '_', '_','_', '/', ' ', ' ', '|', '\0'},
{'\\', '#', '#', ' ', '|', ' ', '|', ' ', '#', '#', '/', '\0'},
{' ', ' ', '#', '_', '|', '_', '|', '_', '#', ' ', ' ', '\0'}
};
int y = height - 9; //y position
for (int i = 0; i < 8; i ++) {
int x = (road_width/2) - (11/2); // x position
for (int j = 0; j < 12; j ++) {
mvwprintw(gamewin, y, x, "%c", car[i][j]);
x ++;
}
y ++;
}
wrefresh(gamewin);
// let car moves
void delete_car() {
int yCurr, xCurr;
getyx(gamewin, yCurr, xCurr);
int yPos = height - 9; //y position
for (int i = 0; i < 8; i ++) {
int xPos = xCurr - 13; // x position
for (int j = 0; j < 12; j ++) {
mvwprintw(gamewin, yPos, xPos, "%c", ' ');
xPos ++;
}
yPos ++;
}
wrefresh(gamewin);
}
int move_car(const char direction) {
// let to move at given side
int add;
if (direction == 'l') add = -road_width;
else if (direction == 'r') add = road_width;
else return 0;
//defines a start position for car from left side
int yCurr, xCurr;
getyx(gamewin, yCurr, xCurr);
int yPos = height - 9;
for (int i = 0; i < 8; i ++) {
int xPos = (xCurr - 13) + add; // x position
for (int j = 0; j < 12; j ++) {
mvwprintw(gamewin, yPos, xPos, "%c", car[i][j]);
xPos ++;
}
yPos ++;
}
wrefresh(gamewin);
getyx(gamewin, yCurr, xCurr);
return xCurr;
}
int attempt = 0;
while (attempt < 20) {
keypad(gamewin, TRUE);
int move = mvwgetch(gamewin, y - 1, ((road_width/2) - (11/2)) + 13);
if (move == KEY_RIGHT) {
int yCurr, xCurr; // check is the road on the right
getyx(gamewin, yCurr, xCurr);
if ((xCurr - 13) > (road_width * amount_roads + (amount_roads - 1))) {
wprintw(gamewin, "There is no the road");
}
delete_car();// clear current road
move_car('r');// add car to next road
} else if (move == KEY_LEFT) {
int yCurr, xCurr; // check is the road on the left
getyx(gamewin, yCurr, xCurr);
if ((xCurr - 13) < road_width) wprintw(gamewin, "There is no the road");
delete_car(); // clear current road
move_car('l'); // add car to next road
}
}
wrefresh(gamewin);
getch();
endwin();
return EXIT_SUCCESS;
}
I'm writing a small game using ncurses, first I create a user login window, then a window for the game itself. Literally yesterday, everything was working fine, today nothing is displayed except for the standard window with the input at the very beginning. I don't understand what the matter is, maybe I accidentally deleted something, I don't know. I have read the entire code several times, and I have not found where the error is, please tell me what is wrong

A single function can be used to erase or print the car.
Use the xMax and yMax as a base for the window dimensions so the window fits in the terminal.
#include <stdlib.h>
#include <ncurses.h>
#include <time.h>
#define CAR_HEIGHT 8
#define CAR_WIDTH 12
void draw_car ( WINDOW *gamewin, char car[][CAR_WIDTH], int y, int x, int show) {
for ( int i = 0; i < CAR_HEIGHT; i ++) {
for ( int j = 0; j < CAR_WIDTH; j ++) {
if ( show) {
mvwprintw ( gamewin, y + i, x + j, "%c", car[i][j]);
} else {
mvwprintw ( gamewin, y + i, x + j, " ");
}
}
}
}
int main ( void) {
initscr ( );
cbreak ( );
noecho ( );
srand ( time ( NULL));
// get screen sizes
int yMax = 0, xMax = 0;
getmaxyx ( stdscr, yMax, xMax);
//create a new window for input
int height = yMax - 2;
int width = xMax - 2;
WINDOW *inputwin = newwin ( height, width, 1, 1);
box ( inputwin, 0, 0);
refresh ( );
wrefresh ( inputwin);
// get amount roads
echo ( );
mvwprintw ( inputwin, 1, 1, "Press key left to choose beginner level.");
mvwprintw ( inputwin, 2, 7, "key right - intermediate.");
mvwprintw ( inputwin, 3, 7, "key up - advanced.");
int amount_roads = 0;
keypad ( inputwin, TRUE);
int a = 0;
do {
a = mvwgetch ( inputwin, 7, 60);
switch ( a) {
case KEY_LEFT:
mvwprintw ( inputwin, 5, width / 2, "You chose beginner ");
amount_roads = 2;
break;
case KEY_RIGHT:
mvwprintw ( inputwin, 5, width / 2, "You chose intermediate ");
amount_roads = 3;
break;
case KEY_UP:
mvwprintw ( inputwin, 5, width / 2, "You chose advanced ");
amount_roads = 4;
break;
case KEY_DOWN:
break;
default:
amount_roads = 0;
}
if ( amount_roads) {
mvwprintw ( inputwin, 6, width / 2, "Press key down to continue");
} else {
mvwprintw ( inputwin, 5, width / 2, "INCORRECT INPUT. TRY AGAIN");
mvwprintw ( inputwin, 6, width / 2, " ");
}
wrefresh ( inputwin);
} while ( ! amount_roads || a != KEY_DOWN);
wrefresh ( inputwin);
delwin ( inputwin);
refresh ( );
//create win for game
height = yMax - 4;
width = xMax - 4;
WINDOW *gamewin = newwin ( height, width, 2, 2);
box ( gamewin, 0, 0);
keypad ( gamewin, TRUE);
refresh ( );
wrefresh ( gamewin);
// draw roads
int road_width = ( width - amount_roads) / amount_roads;
for ( int i = road_width; i < width - 2; i += road_width + 1) {
for ( int j = 2; j < height - 1; j ++) {
mvwprintw ( gamewin, j, i, "|");
}
}
char car[CAR_HEIGHT][CAR_WIDTH] = {
{ " _____ "},
{ " () ||| () "},
{ "/ _______ \\"},
{ "|/_______\\|"},
{ "| _____ |"},
{ "| \\___/ |"},
{ "\\## | | ##/"},
{ " #_|_|_# "}
};
int y = height - 9; //y position
int road_lane = 0;
int show = 1;
int x = road_lane * road_width + ( road_width / 2 - 5); // x position
draw_car ( gamewin, car, y, x, show);
wrefresh ( gamewin);
int attempt = 0;
int change = 0;
do {
change = mvwgetch ( gamewin, 1, 1);
draw_car ( gamewin, car, y, x, ! show);
switch ( change) {
case KEY_RIGHT:
if ( road_lane == amount_roads - 1) {
mvwprintw ( gamewin, 1, 2, "There is no the road");
} else {
mvwprintw ( gamewin, 1, 2, " ");
++road_lane;
x += road_width + 1; // x position
}
break;
case KEY_LEFT:
if ( road_lane == 0) {
mvwprintw ( gamewin, 1, 2, "There is no the road");
} else {
mvwprintw ( gamewin, 1, 2, " ");
--road_lane;
x -= road_width + 1; // x position
}
break;
case KEY_DOWN:
if ( y == height - 9) {
mvwprintw ( gamewin, 1, 2, "There is no the road");
} else {
mvwprintw ( gamewin, 1, 2, " ");
++y;
}
break;
case KEY_UP:
if ( y == 2) {
mvwprintw ( gamewin, 1, 2, "There is no the road");
} else {
mvwprintw ( gamewin, 1, 2, " ");
--y;
}
break;
}
draw_car ( gamewin, car, y, x, show);
} while ( attempt < 20 && change != '\n');
wrefresh ( gamewin);
// getch();
delwin ( gamewin);
endwin ( );
return EXIT_SUCCESS;
}

Related

Reaching The Goal With The Dfs Algorithm

#include <stdio.h>
char matrix[8][8];
struct coordinate {
int a;
int b;
};
void ReadFile() {
printf("\n\n\n START MAZE ");
int x, y;
FILE * file1;
file1 = fopen("NEWmaze.txt", "r");
for (x = 0; x < 8; x++) {
for (y = 0; y < 8; y++) {
fscanf(file1, " %c", & matrix[x][y]);
}
printf("\n");
}
}
void PrintMaze() {
int x, y;
for (x = 0; x < 8; x++) {
printf(" ");
for (y = 0; y < 8; y++) {
printf(" %c ", matrix[x][y]);
}
printf("\n");
}
printf("\n\n\n\n");
}
struct coordinate DFS(int x, int y) {
struct coordinate retval = {
x,
y
};
printf("%c", matrix[x - 1][y]); //saw the target but could not stop
if (matrix[x][y - 1] == '-') //WEST
{
printf("WEST");
// printf("%d %d",x,y-1); step by step
matrix[x][y - 1] = '.';
PrintMaze(); //step by step
DFS(x, y - 1);
struct coordinate retval = {
x,
y - 1
};
}
if (matrix[x][y - 2] == 'g' && matrix[x + 1][y - 2] != '#') {
// printf("%d %d ",x,y-2); step by step
return retval;
}
if (matrix[x - 1][y] == '-') //NORTH
{
// printf("%d %d",x-1,y); step by step
matrix[x - 1][y] = '.';
PrintMaze(); //step by step
DFS(x - 1, y);
struct coordinate retval = {
x - 1,
y
};
}
if (matrix[x - 2][y] == 'g' && matrix[x - 3][y] != '#') {
struct coordinate retval = {
0,
0
};
return retval;
}
if (matrix[x][y + 1] == '-') //SOUTH
{
//printf("%d %d",x,y+1); step by step
matrix[x][y + 1] = '.';
PrintMaze();
DFS(x, y + 1);
struct coordinate retval = {
x,
y + 1
};
}
if (matrix[x + 1][y + 1] == 'g' && matrix[x + 2][y + 1] != '#') {
struct coordinate retval = {
0,
0
};
return retval;
}
if (matrix[x + 1][y] == '-') { // EAST
// printf("%d %d",x+1,y);
matrix[x + 1][y] = '.';
//PrintMaze();
DFS(x + 1, y);
struct coordinate retval = {
x + 1,
y
};
}
if (matrix[x + 1][y + 1] == 'g' && matrix[x + 1][y + 2] != '#') {
struct coordinate retval = {
0,
0
};
return retval;
}
return retval;
}
void StartSearch() {
printf(" STEP BY STEP");
int x, y;
for (x = 0; x < 8; x++) {
for (y = 0; y < 8; y++) {
if (matrix[x][y] == 's') //START
{
struct coordinate coord = DFS(x, y);
}
}
printf("\n");
}
}
int main() {
ReadFile();
PrintMaze();
StartSearch();
PrintMaze();
return 0;
}
newMaze.txt file (# wall, . step, - empty , s start,g goal)
# # # # # # # #
# g - - # - - #
# - - - - - # #
# - - # - - - #
# - - # - - # #
# - - - - - - #
# - # - - - s #
# # # # # # # #
I print the steps and i can see it reaches the goal.The only problem is it doesn't stop when i reach the goal('g').When I use while break it can't get out of infinite loops. How do I make it stop when it reaches the goal('g')?
This is a follow up to ->
Maze solver with DFS (
here i tried using struct as x and y are not returning at the same time
)
UPDATE
#include <stdio.h>
char matrix[8][8];
struct coordinate {
int x, y;
};
void ReadFile()
{
printf("\n\n\n START MAZE ");
int x,y;
FILE *file1;
file1=fopen("NEWmaze.txt","r");
for(x=0; x<8; x++){
for(y=0;y<8;y++)
{
fscanf (file1, " %c", &matrix[x][y]);
}
printf("\n");
}
}
void PrintMaze()
{
int x,y;
for(x=0;x<8;x++)
{
printf(" ");
for(y=0;y<8;y++)
{
printf(" %c ",matrix[x][y]);
}
printf("\n");
}
printf("\n\n\n\n");
}
struct coordinate DFS(int x, int y)
{
struct coordinate retval = { -1, -1 };
if (matrix[x][y] == 'g')
{
retval.x = x;
retval.y = y;
}
else if (matrix[x][y] == '-' )
{
matrix[x][y] = 'o';// West North South East
PrintMaze();
retval = DFS(x, y-1); if (retval.x != -1) return retval;
retval = DFS(x-1, y ); if (retval.x != -1) return retval;
retval = DFS(x , y+1); if (retval.x != -1) return retval;
retval = DFS(x + 1, y); matrix[x][y] = '.';
}
return retval;
}
void StartSearch()
{
printf(" STEP BY STEP");
int x,y;
for(x=0;x<8;x++)
{
for(y=0;y<8;y++)
{
if(matrix[x][y] == 's')//START
{
if(matrix[x][y-1] == '-')
{
DFS(x,y-1);
}
if(matrix[x-1][y] == '-')
{
DFS(x-1,y);
}
if(matrix[x][y+1] == '-')
{
DFS(x,y+1);
}
if(matrix[x+1][y] == '-')
{
DFS(x+1,y);
}
}
}
printf("\n");
}
}
int main()
{
ReadFile();
PrintMaze();
StartSearch();
PrintMaze();
return 0;
}
UPDATE OUPUT
I wrote in order of priority and it works.
You're going about the return value in a weird way. Instead of constructing it after the recursive call, simply make it so that a valid co-ordinate is returned if the current position is the goal. Otherwise, return something invalid (e.g. {-1,-1}, or even {0,0} in your case if that will always be a wall).
Now all you need to do is store the return value of each recursive call and check if it's valid. If it is, then return it immediately. Otherwise continue processing (i.e. test other directions).
Put in terms of code, something like this:
struct coordinate {
int x, y;
};
struct coordinate DFS(int x, int y)
{
struct coordinate retval = { -1, -1 };
if (matrix[x][y] == 'g')
{
retval.x = x;
retval.y = y;
}
else if (matrix[x][y] == '-' || matrix[x][y] == 's')
{
matrix[x][y] = '.';
retval = DFS(x - 1, y); if (retval.x != -1) return retval;
retval = DFS(x, y - 1); if (retval.x != -1) return retval;
retval = DFS(x + 1, y); if (retval.x != -1) return retval;
retval = DFS(x, y + 1);
}
return retval;
}
Provided your maze always has a wall around the perimeter, you don't need to do any bounds-testing on the co-ordinates because you will never perform recursion when on the edge.
You can even slightly reorder this to draw the actual path used when you first reached the goal. It might not be the optimal path, but that requires a more advanced algorithm. Below, we use 'o' to denote a cell on the path to the goal.
struct coordinate DFS(int x, int y)
{
struct coordinate retval = { -1, -1 };
if (matrix[x][y] == 'g')
{
retval.x = x;
retval.y = y;
}
else if (matrix[x][y] == '-' || matrix[x][y] == 's')
{
matrix[x][y] = '.';
retval = DFS(x - 1, y);
if (retval.x == -1) retval = DFS(x, y - 1);
if (retval.x == -1) retval = DFS(x + 1, y);
if (retval.x == -1) retval = DFS(x, y + 1);
if (retval.x != -1) matrix[x][y] = 'o';
}
return retval;
}
And with a small tweak to the search function:
void StartSearch()
{
int x, y;
for (x = 0; x < 8; x++) {
for (y = 0; y < 8; y++) {
if (matrix[x][y] == 's')
{
DFS(x, y);
matrix[x][y] = 's';
}
}
}
}
You get this output:
# # # # # # # #
# g o o # . . #
# - - o o o # #
# - - # - o - #
# - - # - o # #
# - - - - o o #
# - # - - - s #
# # # # # # # #

finding path to all 3 corners on a chess board starting from 0,0 isn't working

#include <stdio.h>
#define SIDE 8
#define VISITED 1
#define NOT_VISITED 0
#define FALSE 0
#define TRUE !FALSE
void printBoard(int board[][SIDE]);
int goHorsie(int board[][SIDE], int x, int y, int step);
int main(void)
{
int board[SIDE][SIDE] = { NOT_VISITED };
goHorsie(board, 0, 0, 1);
printBoard(board);
getchar();
return 0;
}
int goHorsie(int board[][SIDE], int x, int y, int step)
{
int res = FALSE;
int cor1 = 0, cor2 = 0, cor3 = 0;
if (x == 7 && y == 7)
{
cor1 = 1;
}
if (x == 7 && y == 0)
{
cor2 = 1;
}
if (x == 0 && y == 7)
{
cor3 = 1;
}
if (cor1 == 1 && cor2 == 1 && cor3 == 1)
{
printf("FOUND ALL!\n");
res = TRUE;
}
else if (board[x][y] != NOT_VISITED //We were here already!
|| x >= SIDE || y >= SIDE || x < 0 || y < 0)
{
res = FALSE;
}
else
{
board[x][y] = step;
step++;
res =
goHorsie(board, x + 1, y - 2, step) ||
goHorsie(board, x + 2, y + 1, step) ||
goHorsie(board, x + 2, y - 1, step) ||
goHorsie(board, x + 1, y + 2, step) ||
goHorsie(board, x - 2, y + 1, step) ||
goHorsie(board, x - 2, y - 1, step) ||
goHorsie(board, x - 1, y + 2, step) ||
goHorsie(board, x + 1, y - 2, step);
if (!res)
{
board[x][y] = NOT_VISITED;
}
}
return res;
}
/*
Prints the chess board
*/
void printBoard(int board[][SIDE])
{
int i = 0, j = 0;
for (int i = 0; i < SIDE; i++)
{
for (int j = 0; j < SIDE; j++)
{
printf("%3d", board[i][j]);
}
printf("\n");
}
}
im using recursion to find the path to all 3 corners.
i ran the program for about 20min now and it's still didn't get to the solution.
ik why its taking too long but not sure if it will even get me to the answer.
so my question is did i make the function right and will it eventually give me the right answer (the path to all 3 corners).

How do I stop my player from leaving the grid in my game?

I have to make a dungeon like game. I've been stuck on the same problem for a while now, my player can leave the grid. Ive tried many ways but i cant figure out how to limit the grid so they cant just leave or tp in to the next column.
#include <cstdio>
#include <stdlib.h>
#include <time.h>
#include <ctime>
#include <iostream>
struct mapPosition {
int x, y;
};
struct Player
{
int gold;
int maxhealth; int health;
int maxstamina; int stamina;
int maxagility; int agility;
int maxpotions; int potions;
};
#define SIZE 5
char map[SIZE][SIZE] = { {' ',' ',' ',' ',' '},
{' ',' ',' ',' ',' '},
{' ',' ',' ',' ',' '},
{' ',' ',' ',' ',' '},
{' ',' ',' ',' ',' '} };
Player player;
int generateHP() {
return (rand() % 21 + 90); //(110 - 90 + 1)) + 90;
}
void Health(int value) {
player.health = 0;
if (player.health == 0) {
player.health += generateHP();
}
printf("Health = %d/110\n", player.health);
}
void PrintMap()
{
int value = 0;
system("cls");
printf("----- DUNGEON -----\n");
Health(value);
printf(" ___ ___ ___ ___ ___ \n");
for (int i = 0; i < 5; i++)
{
printf("| | | | | |\n");
for (int j = 0; j < 5; j++)
{
printf("| %c ", map[j][i]);
}
printf("|\n");
printf("|___|___|___|___|___|\n");
}
}
void randomEnemy() {
int row, col;
int x = 0;
while (x < 3)
{
row = rand() % SIZE;
col = rand() % SIZE;
if (map[row][col] != 'E' && map[row][col] != 'C')
{
map[row][col] = 'E';
}
else
x--;
x++;
}
}
void randomChest() {
int row, col;
int j = 0;
while (j < 2)
{
row = rand() % SIZE;
col = rand() % SIZE;
if (map[row][col] != 'E' && map[row][col] != 'C')
{
map[row][col] = 'C';
}
else
j--;
j++;
}
}
void PlayerMovement(mapPosition& _mapPos) {
char d;
printf("Where do you want to go? \n");
scanf_s("%c", &d);
map[_mapPos.x][_mapPos.y] = ' ';
switch (d) {
case 'W':
//mapPosition _Pos;
//_Pos.x = _mapPos.x;
//_Pos.y = _mapPos.y - 1;
//if (checkMovement(_Pos) == 0) {
if (_mapPos.y < 4) {
_mapPos.y -= 1;
}
else{
}
//else if (checkMovement(_Pos) == 1) {
//gamestate = 1
//}
//else if (checkMovement(_Pos) == 2) {
///gamestate = 2
//}
//_mapPos.y -= 1;
break;
case 'A':
//mapPosition _Pos;
//_Pos.x = _mapPos.x - 1;
//_Pos.y = _mapPos.y;
//if (_mapPos.x < 5)
_mapPos.x -= 1;
//else {
//}
break;
case 'S':
//mapPosition _Pos;
//_Pos.x = _mapPos.x;
//_Pos.y = _mapPos.y + 1;
_mapPos.y += 1;
break;
case 'D':
//mapPosition _Pos;
//_Pos.x = _mapPos.x + 1;
//_Pos.y = _mapPos.y;
_mapPos.x += 1;
break;
}
map[_mapPos.x][_mapPos.y] = 'P';
}
void Start(mapPosition& _playerPos) {
randomEnemy();
randomChest();
map[_playerPos.x][_playerPos.y] = 'P';
PrintMap();
}
void Update(mapPosition& _playerPos)
{
int x = 0;
while (x < 12)
{
PlayerMovement(_playerPos);
PrintMap();
x++;
}
}
void clearMap(mapPosition& _playerPos) {
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
map[i][j] = ' ';
}
}
}
/*void gameState() {
if (gameState == 0) {
//explore
}
else if (gameState == 1) {
//battle
}
else if (gameState == 2) {
}
}*/
int checkMovement(mapPosition& _pos) {
if (map[_pos.x][_pos.y] == 'E') {
return 1;
}
if (map[_pos.x][_pos.y] == 'C') {
return 2;
}
else {
return 0;
}
}
int main()
{
int x = 0;
int gameState = 0;
srand(time(NULL));
mapPosition playerPos;
playerPos.y = 3;
playerPos.x = 2;
while (x < 4) {
Start(playerPos);
Update(playerPos);
clearMap(playerPos);
}
x++;
}
I know the code is janky, but ive only been coding for two months. Any help is appreciated. Its in playerMovement, and I just cant figure out how to do it. Its also not done and has a lot of incomplete things now, but i cant move on without fixing this first.

Window resizing of c program affects element positions

I want to create a minesweeper generator in c and whenever I run the program either the window comes out oddly shaped thereby changing the positions of the elements to look incorrect, or the function I use to generate the tiles is generating them incorrectly. How would I solve either problem? My code is here:
#include <windows.h> /* for HANDLE type, and console functions */
#include <stdio.h> /* standard input/output */
#include <stdlib.h> /* included for rand */
#define WIDTH 70
#define HEIGHT 35
#define BOMBS 20
HANDLE wHnd; /* write (output) handle */
HANDLE rHnd; /* read (input handle */
void SetGrid(int grid[WIDTH][HEIGHT])
{
int bomb[2] = {abs(rand() % WIDTH),
abs(rand() % HEIGHT)};
for (int i = 0; i < BOMBS; i++)
{
while (grid[bomb[0]][bomb[1]] < -1)
{
bomb[0] = abs(rand() % WIDTH);
bomb[1] = abs(rand() % HEIGHT);
}
grid[bomb[0]][bomb[1]] = -9;
grid[bomb[0]+1][bomb[1]+1]++;
grid[bomb[0]-1][bomb[1]-1]++;
grid[bomb[0]-1][bomb[1]+1]++;
grid[bomb[0]+1][bomb[1]-1]++;
grid[bomb[0]-1][bomb[1]]++;
grid[bomb[0]+1][bomb[1]]++;
grid[bomb[0]][bomb[1]-1]++;
grid[bomb[0]][bomb[1]+1]++;
}
}
int main(void)
{
srand(time(0));
SMALL_RECT windowSize = {0, 0, WIDTH - 1, HEIGHT - 1};
COORD bufferSize = {WIDTH, HEIGHT};
COORD characterBufferSize = {WIDTH, HEIGHT};
COORD characterPosition = {0, 0};
SMALL_RECT consoleWriteArea = {0, 0, WIDTH - 1, HEIGHT - 1};
CHAR_INFO consoleBuffer[WIDTH][HEIGHT];
wHnd = GetStdHandle(STD_OUTPUT_HANDLE);
rHnd = GetStdHandle(STD_INPUT_HANDLE);
SetConsoleTitle("Our shiny new title!");
SetConsoleWindowInfo(wHnd, TRUE, &windowSize);
SetConsoleScreenBufferSize(wHnd, bufferSize);
int startGrid[WIDTH][HEIGHT] = {0};
SetGrid(startGrid);
for (int x = 0; x < WIDTH; ++x)
{
for (int y = 0; y < HEIGHT; ++y)
{
if(startGrid[x][y] > 0)
{
consoleBuffer[x][y].Char.AsciiChar = '0' + startGrid[x][y];
consoleBuffer[x][y].Attributes = FOREGROUND_GREEN | FOREGROUND_INTENSITY;
}
else
{
consoleBuffer[x][y].Char.AsciiChar = (unsigned char)219;
consoleBuffer[x][y].Attributes = (startGrid[x][y] < 0 ? FOREGROUND_RED : FOREGROUND_BLUE) | FOREGROUND_INTENSITY;
}
}
}
WriteConsoleOutputA(wHnd, consoleBuffer, characterBufferSize, characterPosition, &consoleWriteArea);
getchar();
}
You need to deal with several boundary issues.
The four corners default to -4
Except for the four corners, the border is -6(Although you did not use them)
Important:The increase at the boundary considers whether the boundary is exceeded.
Here is the code:
#include <windows.h> /* for HANDLE type, and console functions */
#include <stdio.h> /* standard input/output */
#include <stdlib.h> /* included for rand */
#define WIDTH 30
#define HEIGHT 30
#define BOMBS 10
HANDLE wHnd; /* write (output) handle */
HANDLE rHnd; /* read (input handle */
int check(int a)
{
if (a == 0 || a == WIDTH - 1 || a == HEIGHT - 1)
{
return 1;
}
else
{
return 0;
}
}
void SetGrid(int grid[WIDTH][HEIGHT])
{
int bomb[2] = { abs(rand() % WIDTH),
abs(rand() % HEIGHT) };
char t[100];
for (int i = 0; i < BOMBS; i++)
{
while (grid[bomb[0]][bomb[1]] < -1)
{
bomb[0] = abs(rand() % WIDTH);
bomb[1] = abs(rand() % HEIGHT);
}
grid[bomb[0]][bomb[1]] = -9;
if (check(bomb[0]) || check(bomb[1])) grid[bomb[0]][bomb[1]] = -6;
if (check(bomb[0]) && check(bomb[1])) grid[bomb[0]][bomb[1]] = -4;
if (bomb[0] + 1 <= WIDTH - 1 && bomb[1] + 1 <= HEIGHT - 1)
{
grid[bomb[0] + 1][bomb[1] + 1]++;
}
if (bomb[0] + 1 <= WIDTH - 1)
{
grid[bomb[0] + 1][bomb[1]]++;
}
if (bomb[1] + 1 <= HEIGHT - 1)
{
grid[bomb[0]][bomb[1] + 1]++;
}
if (bomb[0] - 1 >= 0 && bomb[1] + 1 <= HEIGHT - 1)
{
grid[bomb[0] - 1][bomb[1] + 1]++;
}
if (bomb[1] - 1 >= 0)
{
grid[bomb[0]][bomb[1] - 1]++;
}
if (bomb[1] - 1 >= 0 && bomb[0] + 1 <= WIDTH - 1)
{
grid[bomb[0] + 1][bomb[1] - 1]++;
}
if (bomb[0] - 1 >= 0 && bomb[1] - 1 >= 0)
{
grid[bomb[0] - 1][bomb[1] - 1]++;
}
if (bomb[0] - 1 >= 0)
{
grid[bomb[0] - 1][bomb[1]]++;
}
}
}
int main(void)
{
srand(time(0));
SMALL_RECT windowSize = { 0, 0, WIDTH - 1, HEIGHT - 1 };
COORD bufferSize = { WIDTH, HEIGHT };
COORD characterBufferSize = { WIDTH, HEIGHT };
COORD characterPosition = { 0, 0 };
SMALL_RECT consoleWriteArea = { 0, 0, WIDTH - 1, HEIGHT - 1 };
CHAR_INFO consoleBuffer[WIDTH][HEIGHT];
wHnd = GetStdHandle(STD_OUTPUT_HANDLE);
rHnd = GetStdHandle(STD_INPUT_HANDLE);
SetConsoleTitle("Our shiny new title!");
SetConsoleWindowInfo(wHnd, TRUE, &windowSize);
SetConsoleScreenBufferSize(wHnd, bufferSize);
int startGrid[WIDTH][HEIGHT] = { 0 };
SetGrid(startGrid);
for (int x = 0; x < WIDTH; ++x)
{
for (int y = 0; y < HEIGHT; ++y)
{
if (startGrid[x][y] > 0)
{
consoleBuffer[x][y].Char.AsciiChar = '0' + startGrid[x][y];
consoleBuffer[x][y].Attributes = FOREGROUND_GREEN | FOREGROUND_INTENSITY;
}
else
{
consoleBuffer[x][y].Char.AsciiChar = (unsigned char)111;
consoleBuffer[x][y].Attributes = (startGrid[x][y] < 0 ? FOREGROUND_RED : FOREGROUND_BLUE) | FOREGROUND_INTENSITY;
}
}
}
WriteConsoleOutputA(wHnd, consoleBuffer, characterBufferSize, characterPosition, &consoleWriteArea);
printf("\n\n");
getchar();
}

Ncurses WINDOW not refreshing properly

i'm trying to increment and decrement values on an ncurses window using mouse clicks, everything is working fine, but if i decrement up till the point where the number is negative then try to increment again (like -1), the second character (the 1) will stay showing on the WINDOW and the main character in the position where i change the number (-) will change, i realise that the problem is that i am changing only in the position event.x event.y with mvwprintw
so the question is, what is the most simple way (an ncurses function maybe) that allows me to delete that.
while((ch = getch()) != KEY_F(2)) {
switch(ch) {
case KEY_MOUSE :
if (getmouse(&event) == OK) {
if (event.y == 39 && event.x >= 1 && event.x <= 10) {
item_actif = PLUS;
mvwprintw(fen_outils, 0, 1, "X");
mvwprintw(fen_outils, 1, 1, " ");
wrefresh(fen_outils);
}
else if (event.y == 40 && event.x >=1 && event.x <= 10) {
item_actif = MINUS;
mvwprintw(fen_outils, 0, 1, " ");
mvwprintw(fen_outils, 1, 1, "X");
wrefresh(fen_outils);
}
else if (event.y > 0 && event.y < NB_LIGNES_SIM + 1 && event.x > 0 && event.x < NB_COL_SIM + 1) {
switch (item_actif) {
case PLUS :
k=0;
l=0;
for(i = 0;i<36;i+=4){
k++;
l=0;
for(j=19;j<129;j+=11){
if((event.y==i+1 && event.x==j+1)){
++tab[k][l];
sprintf(tabChar[k][l],"%d",tab[k][l]);
mvwprintw(fen_sim, event.y - 1, event.x - 1, tabChar[k][l]);
wrefresh(fen_sim);
refresh();
break;
}
l++;
}
}
break;
case MINUS :
k=0;
l=0;
for(i = 0;i<36;i+=4){
k++;
l=0;
for(j=19;j<129;j+=11){
if((event.y==i+1 && event.x==j+1)){
--tab[k][l];
sprintf(tabChar[k][l],"%d",tab[k][l]);
mvwprintw(fen_sim, event.y - 1, event.x - 1, tabChar[k][l]);
wrefresh(fen_sim);
refresh();
break;
}
l++;
}
}
}
}
}
}
}
Control PANEL ncurses
i found the simplest (but not the best) answer which is to add in both cases an :
if(tab[k][l] < 0){
mvwprintw(fen_sim, event.y -1, event.x -1, " ");
wrefresh(fen_sim);
}

Resources