I wanted to create a program with what i had just learned in ncurses. With it the user should be able to draw with a # in the screen using WASD. this is the code i did:
#include<stdio.h>
#include<ncurses.h>
int main (void)
{
initscr();
noecho();
int coord_x = 10;
int coord_y = 10;
char direccion;
mvwprintw(stdscr,coord_y,coord_x,"#");
while (1)
{
refresh();
direccion = getchar();
switch (direccion)
{
case 'w':
coord_y -= 1;
case 's':
coord_y += 1;
case 'a':
coord_x -= 1;
case 'd':
coord_x += 1;
case 'q':
break;
default:
continue;
}
if (coord_x == -1 && coord_y == -1) { coord_y += 1;coord_x += 1;}
mvwprintw(stdscr,coord_y,coord_x,"#");
if (direccion == 'q') {break;}
}
endwin();
return 0;
}
But i am not really sure why does the # wont move neither up or left. I think the problem is in this part:
direccion = getchar();
switch (direccion)
{
case 'w':
coord_y -= 1;
case 's':
coord_y += 1;
case 'a':
coord_x -= 1;
case 'd':
coord_x += 1;
case 'q':
break;
default:
continue;
}
But i am really not sure, do you know why it doesnt work?
EDIT: Thanks to everybody, now i realised im just dumb and forgot how to use a switch
You need to add break
s after each assignment in your switch statement:
switch (direccion) {
case 'w':
coord_y -= 1;
break; /* <-- here */
case 's':
coord_y += 1;
break; /* <-- here */
case 'a':
coord_x -= 1;
break; /* <-- here */
case 'd':
coord_x += 1;
break; /* <-- here */
case 'q':
break;
default:
continue;
}
The default behavior of the case
is to "fall through" to the next one, so if you press w
it is going to execute all of the coord_x
and coord_y
assignments, not just the one you intend.