I am a beginner in C. I wanted to make a game but I'm stuck and I come to ask you for help.
I created a main window and another smaller one in main window: sub window in main window
And I would like to move this second small window with the keys of the keyboard, that's why I made the functions move and destroy_win. Except that when I run the program, it just shows me the small window without the main window: no main window...
My code :
#include <ncurses.h>
#include <unistd.h>
WINDOW *create_newwin(int height, int width, int y, int x);
void deplacement(int height, int width, int x, int y);
void destroy_win(WINDOW *local_win);
WINDOW* mainwin;
WINDOW* my_win;
int main() {
// Initialisation de ncurses
initscr();
cbreak();
noecho();
keypad(stdscr, TRUE);
curs_set(0);
// Calcul des positions et tailles des fenêtres
int height = 30;
int width = 80;
int y = (LINES - height) / 2;
int x = (COLS - width) / 2;
// Calcul des positions du carré controlé par le Joueur
int square_height = 2;
int square_width = 4;
int square_y = y + (height - square_height) / 2;
int square_x = x + (width - square_width) / 2;
// Création de la fenêtre principale
mainwin = newwin(height, width, y, x);
box(mainwin, 0 , 0);
mvwprintw(mainwin, 0, 2, " Score : 0 ");
mvwprintw(mainwin, 0, 20, " Temps restant : 5.0s ");
wrefresh(mainwin);
// Création de la fenêtre du carré
my_win = create_newwin(square_height, square_width, square_y, square_x);
wrefresh(my_win);
sleep(3);
deplacement(square_height, square_width, square_x, square_y);
wgetch(my_win);
// Libération de la mémoire et fermeture de ncurses
delwin(my_win);
delwin(mainwin);
endwin();
return 0;
}
WINDOW *create_newwin(int height, int width, int y, int x)
{
WINDOW *local_win;
local_win = newwin(height, width, y, x);
box(local_win, 0 , 0);
wrefresh(local_win);
return local_win;
}
void deplacement(int height, int width, int x, int y) {
int ch = getch();
while((ch = getch()) != KEY_F(2))
{
switch(ch)
{
case KEY_LEFT:
destroy_win(my_win);
my_win = create_newwin(height, width, y,--x);
break;
case KEY_RIGHT:
destroy_win(my_win);
my_win = create_newwin(height, width, y,++x);
break;
case KEY_UP:
destroy_win(my_win);
my_win = create_newwin(height, width, --y,x);
break;
case KEY_DOWN:
destroy_win(my_win);
my_win = create_newwin(height, width, ++y,x);
break;
}
wrefresh(my_win);
}
}
void destroy_win(WINDOW *local_win)
{
wborder(local_win, ' ', ' ', ' ',' ',' ',' ',' ',' ');
wrefresh(local_win);
delwin(local_win);
}
So I wanted to know how I could fix this error by displaying the main window with the borders, please and thanks.
when I run the program, it just shows me the small window without the main window
So I wanted to know how I could fix this error by displaying the main window
The calls of getch()
in deplacement
implicitly refresh stdscr
, overwriting your windows; use wgetch(my_win)
instead. Then we also need keypad(local_win, TRUE);
in create_newwin
.