I am trying to get familiar with ncurses and I have a problem - the constants such as KEY_LEFT seem to be wrong.
For example, I'm trying to catch keyboard arrows. Should be as simple as
while (ch = getch()){
if (ch == KEY_LEFT)
foo();
}
But that does not work. I had the ch written out and it says this - left arrow is 68, right 67, up 65, down 66.
That wouldn't be such a problem, but when trying to catch mouse events, it goes bad. Leftclicking the terminal gives me values from 33 to 742, least when clicking upper left corner, most when clicking bottom right corner. What the hell?
This is my whole main, just in case
int main(void){
initscr();
start_color();
init_pair(1, COLOR_YELLOW, COLOR_WHITE);
init_pair(2, COLOR_RED, COLOR_RED);
cbreak();
//printw("Hai!\n");
noecho();
int width;
int height;
getmaxyx(stdscr, height, width);
int posx = 30;
int posy = 30;
const char* str = " ";
const char* hint = "ch = %d";
curs_set(0);
mousemask(BUTTON1_CLICKED, NULL);
unsigned int ch = 0;
while (ch = getch()) {
attron(COLOR_PAIR(1));
mvprintw(0, 0, hint, ch);
mvdelch(posy,posx);
mvdelch(posy, posx);
mvdelch(posy, posx);
switch (ch) {
case 68:
if (posx > 0) posx--;
//mvprintw(1,0,"LEFT");
break;
case 67:
if (posx < width) posx++;
break;
case 65:
if (posy > 0) posy--;
break;
case 66:
if (posy < height) posy++;
break;
case KEY_MOUSE:
MEVENT event;
if (getmouse(&event)==OK){
posx = event.x;
posy = event.y;
}
}
attron(COLOR_PAIR(2));
mvprintw(posy, posx, str);
refresh();
}
endwin();
return 0;
}
As (almost) always a look in the manual helps. Taking a look at man getch
Function Keys
The following function keys, defined in curses.h, might be returned by getch
if keypad has been enabled. Note that not all of these are necessarily supportā
ed on any particular terminal.
it seems you missed
keypad (stdscr, TRUE);
in your program. At least it doesn't occur in the snippet you posted.
Related
I am pretty new to c++ and ncurses, so sorry if my question is weird or obvious.
I managed to make a simple tui program that will do various tasks, my problem is that I have no back functionality or something that would loop the program.
I want to be able to go back to the main menu after accessing one of the submenus and I want to make the program repeat after it's done so I won't have to keep opening it over and over, so do you have any solutions that I can apply?
Thank you in advance
This is my code:
int main(int argc, char ** argv)
{
int i=0;
string input;
initscr();
noecho();
cbreak();
curs_set(0);
int yMax, xMax;
getmaxyx(stdscr, yMax, xMax);
WINDOW * menuwin = newwin (0, xMax, 0, 0);
leaveok(menuwin, true);
refresh();
wrefresh(menuwin);
keypad(menuwin, true);
string choices[4] = {"Youtube","Music","Anime","Games"};
int choice;
int highlight = 0;
int option = 0;
while(1)
{
for (i=0;i < 4; i++)
{
if(i == highlight)
wattron(menuwin, A_REVERSE);
mvwprintw(menuwin, i+1, 1, choices[i].c_str());
wattroff(menuwin, A_REVERSE);
}
choice = wgetch(menuwin);
switch(choice)
{
case KEY_UP:
highlight--;
if(highlight == -1)
highlight = 3;
break;
case KEY_DOWN:
highlight++;
if(highlight == 4)
highlight = 0;
break;
default:
break;
}
if(choice == 10)
{
break;
}
}
werase(menuwin);
switch(highlight)
{
case 0:
{
menu2();
break;
}
case 1:
{
menu3();
break;
}
case 2:
{
menu4();
break;
}
case 3:
{
menu2();
}
default:
break;
}
endwin();
return 0;
}
I'm writing a programm that's using getch() to scan for arrow keys. My code so far is:
switch(getch()) {
case 65: // key up
break;
case 66: // key down
break;
case 67: // key right
break;
case 68: // key left
break;
}
Problem is that when I press 'A', 'B', 'C' or 'D' the code will also executed, because 65 is the decimal code for 'A', etc...
Is there a way to check for an arrow key without call others?
Thanks!
By pressing one arrow key getch will push three values into the buffer:
'\033'
'['
'A', 'B', 'C' or 'D'
So the code will be something like this:
if (getch() == '\033') { // if the first value is esc
getch(); // skip the [
switch(getch()) { // the real value
case 'A':
// code for arrow up
break;
case 'B':
// code for arrow down
break;
case 'C':
// code for arrow right
break;
case 'D':
// code for arrow left
break;
}
}
getch () function returns two keycodes for arrow keys (and some other special keys), as mentioned in the comment by FatalError. It returns either 0 (0x00) or 224 (0xE0) first, and then returns a code identifying the key that was pressed.
For the arrow keys, it returns 224 first followed by 72 (up), 80 (down), 75 (left) and 77 (right). If the num-pad arrow keys (with NumLock off) are pressed, getch () returns 0 first instead of 224.
Please note that getch () is not standardized in any way, and these codes might vary from compiler to compiler. These codes are returned by MinGW and Visual C++ on Windows.
A handy program to see the action of getch () for various keys is:
#include <stdio.h>
#include <conio.h>
int main ()
{
int ch;
while ((ch = _getch()) != 27) /* 27 = Esc key */
{
printf("%d", ch);
if (ch == 0 || ch == 224)
printf (", %d", _getch ());
printf("\n");
}
printf("ESC %d\n", ch);
return (0);
}
This works for MinGW and Visual C++. These compilers use the name _getch () instead of getch () to indicate that it is a non-standard function.
So, you may do something like:
ch = _getch ();
if (ch == 0 || ch == 224)
{
switch (_getch ())
{
case 72:
/* Code for up arrow handling */
break;
case 80:
/* Code for down arrow handling */
break;
/* ... etc ... */
}
}
So, after alot of struggle, I miraculously solved this everannoying issue !
I was trying to mimic a linux terminal and got stuck at the part where it keeps a command history which can be accessed by pressing up or down arrow keys. I found ncurses lib to be painfuly hard to comprehend and slow to learn.
char ch = 0, k = 0;
while(1)
{
ch = getch();
if(ch == 27) // if ch is the escape sequence with num code 27, k turns 1 to signal the next
k = 1;
if(ch == 91 && k == 1) // if the previous char was 27, and the current 91, k turns 2 for further use
k = 2;
if(ch == 65 && k == 2) // finally, if the last char of the sequence matches, you've got a key !
printf("You pressed the up arrow key !!\n");
if(ch == 66 && k == 2)
printf("You pressed the down arrow key !!\n");
if(ch != 27 && ch != 91) // if ch isn't either of the two, the key pressed isn't up/down so reset k
k = 0;
printf("%c - %d", ch, ch); // prints out the char and it's int code
It's kind of bold but it explains alot. Good luck !
The keypad will allow the keyboard of the user's terminal to allow for function keys to be interpreted as a single value (i.e. no escape sequence).
As stated in the man page:
The keypad option enables the keypad of the user's terminal. If
enabled (bf is TRUE), the user can press a function key (such as an
arrow key) and wgetch returns a single value representing the function
key, as in KEY_LEFT. If disabled (bf is FALSE), curses does not treat
function keys specially and the program has to interpret the escape
sequences itself. If the keypad in the terminal can be turned on (made
to transmit) and off (made to work locally), turning on this option
causes the terminal keypad to be turned on when wgetch is called. The
default value for keypad is false.
Actually, to read arrow keys one need to read its scan code.
Following are the scan code generated by arrow keys press (not key release)
When num Lock is off
Left E0 4B
Right E0 4D
Up E0 48
Down E0 50
When Num Lock is on these keys get preceded with E0 2A
Byte E0 is -32
Byte 48 is 72 UP
Byte 50 is 80 DOWN
user_var=getch();
if(user_var == -32)
{
user_var=getch();
switch(user_var)
{
case 72:
cur_sel--;
if (cur_sel==0)
cur_sel=4;
break;
case 80:
cur_sel++;
if(cur_sel==5)
cur_sel=1;
break;
}
}
In the above code I have assumed programmer wants to move 4 lines only.
how about trying this?
void CheckKey(void) {
int key;
if (kbhit()) {
key=getch();
if (key == 224) {
do {
key=getch();
} while(key==224);
switch (key) {
case 72:
printf("up");
break;
case 75:
printf("left");
break;
case 77:
printf("right");
break;
case 80:
printf("down");
break;
}
}
printf("%d\n",key);
}
int main() {
while (1) {
if (kbhit()) {
CheckKey();
}
}
}
(if you can't understand why there is 224, then try running this code: )
#include <stdio.h>
#include <conio.h>
int main() {
while (1) {
if (kbhit()) {
printf("%d\n",getch());
}
}
}
but I don't know why it's 224. can you write down a comment if you know why?
for a solution that uses ncurses with working code and initialization of ncurses see getchar() returns the same value (27) for up and down arrow keys
I have written a function using getch to get arrow code. it's a quick'n'dirty solution but the function will return an ASCII code depending on arrow key :
UP : -10
DOWN : -11
RIGHT : -12
LEFT : -13
Moreover,with this function, you will be able to differenciate the ESCAPE touch and the arrow keys. But you have to press ESC 2 time to activate the ESC key.
here the code :
char getch_hotkey_upgrade(void)
{
char ch = 0,ch_test[3] = {0,0,0};
ch_test[0]=getch();
if(ch_test[0] == 27)
{
ch_test[1]=getch();
if (ch_test[1]== 91)
{
ch_test[2]=getch();
switch(ch_test[2])
{
case 'A':
//printf("You pressed the up arrow key !!\n");
//ch = -10;
ch = -10;
break;
case 'B':
//printf("You pressed the down arrow key !!\n");
ch = -11;
break;
case 'C':
//printf("You pressed the right arrow key !!\n");
ch = -12;
break;
case 'D':
//printf("You pressed the left arrow key !!\n");
ch = -13;
break;
}
}
else
ch = ch_test [1];
}
else
ch = ch_test [0];
return ch;
}
I'm Just a starter, but i'v created a char(for example "b"), and I do b = _getch(); (its a conio.h library's command)
And check
If (b == -32)
b = _getch();
And do check for the keys (72 up, 80 down, 77 right, 75 left)
void input_from_key_board(int &ri, int &ci)
{
char ch = 'x';
if (_kbhit())
{
ch = _getch();
if (ch == -32)
{
ch = _getch();
switch (ch)
{
case 72: { ri--; break; }
case 80: { ri++; break; }
case 77: { ci++; break; }
case 75: { ci--; break; }
}
}
else if (ch == '\r'){ gotoRowCol(ri++, ci -= ci); }
else if (ch == '\t'){ gotoRowCol(ri, ci += 5); }
else if (ch == 27) { system("ipconfig"); }
else if (ch == 8){ cout << " "; gotoRowCol(ri, --ci); if (ci <= 0)gotoRowCol(ri--, ci); }
else { cout << ch; gotoRowCol(ri, ci++); }
gotoRowCol(ri, ci);
}
}
Try this...
I am in Windows 7 with Code::Blocks
while (true)
{
char input;
input = getch();
switch(input)
{
case -32: //This value is returned by all arrow key. So, we don't want to do something.
break;
case 72:
printf("up");
break;
case 75:
printf("left");
break;
case 77:
printf("right");
break;
case 80:
printf("down");
break;
default:
printf("INVALID INPUT!");
break;
}
}
In my game right now I am trying to make a menu you can access when you press 'q', but currently I am having some issues. I think it switches to the CompScreen view and then back to the currentroom view quickly, I may be wrong. I am getting the cout CompMenu, HELP, and hello readings so I know it is running through the programs, but when I press q I remain in the same spot, nothing happening.
EventManager.h
#ifndef EventManager_h
#define EventManager_h
#endif /* EventManager_h */
int windowWidth = 5000;//width of window
int windowHeight = 5000;//height of window
sf::View leveltwo(sf::FloatRect(x, y, 5000, 5000));
sf::View start(sf::FloatRect(0, 0, 2500, 1500));
sf::View ComputerScreen(sf::FloatRect(50000, 50000, 5000, 5000));
sf::RenderWindow window(sf::VideoMode(windowWidth, windowHeight ), "Awesome Game" );
Character player("/Users/danielrailic/Desktop/Xcode /NewGame/ExternalLibs/Sprites/Player.png");
bool InMenu = false;
enum Levels{
StartRoom, LevelTwo
};
Levels room = StartRoom;
int currentroom;
void WhatRoom(int TheLevel){
switch (room){
case StartRoom:
currentroom = 1;
window.setView(start);
if (TheLevel == 2){
room = LevelTwo;
}
break;
case LevelTwo:
currentroom = 2;
window.setView(leveltwo);
break;
}
};
enum States{
compmenu, mainmenu, NoMenu
};
States menu = NoMenu;
void CompMenu(){
window.setView(ComputerScreen);
cout << "HELP";
InMenu = true;
}
void WhatMenu(int TheMenu){
switch (menu){
case compmenu:
cout << "CompMenu";
CompMenu();
break;
case mainmenu:
break;
case NoMenu:
if (TheMenu == 2){
menu = compmenu;
}
break;
if (TheMenu == 3){
menu = mainmenu;
}
break;
}
}
main.cpp (inside int main)
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Q) and InMenu == false){
WhatMenu(2);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Q) and InMenu == true){
InMenu = false;
WhatRoom(currentroom);
cout << "hello";
}
If you have any questions or need to see more of the code let me know. Thanks.
I think you've missed else after first if block so it may be executed immediately because InMenu may be changed to true at that point:
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Q) and InMenu == true){
Also you should handle the situation when key is pressed for a long time (to react only when it enters pressed state) and get rid of all the global variables because they are already creating quite a mess.
I am trying to create a program that response to keyboard input. At the moment the menu below functions correctly but upon pressing enter I am running into issues. When I press enter nothing happens. I am just wondering why this is happening?
Many thanks!
#include <ncurses.h>
#define MENUMAX 6
void drawmenu(int item)
{
int c;
char mainmenu[] = "Menu";
char menu[MENUMAX] [10] = {
"1",
"2",
"3",
"4",
"5",
"6"
};
clear();
attron(A_BOLD | A_UNDERLINE);
addstr(mainmenu);
attroff(A_BOLD | A_UNDERLINE);
for( c = 0; c < MENUMAX; c++)
{
if( c == item)
attron(A_REVERSE);
attron(A_BOLD);
mvaddstr(3 + (c * 2), 20, menu[c]);
attroff(A_BOLD);
attroff(A_REVERSE);
}
refresh();
}
int main(int argc, char *argv[])
{
int key, menuitem;
menuitem = 0;
initscr();
drawmenu(menuitem);
keypad(stdscr, TRUE);
noecho();
do
{
raw();
nonl();
key = getch();
switch(key)
{
case KEY_DOWN:
menuitem++;
if(menuitem > MENUMAX - 1) menuitem = 0;
break;
case KEY_UP:
menuitem--;
if(menuitem < 0) menuitem = MENUMAX - 1;
break;
case KEY_ENTER:
mvaddstr(17, 25, "Test mesage!");
refresh();
break;
default:
break;
}
drawmenu(menuitem);
} while(key != '~');
echo();
endwin();
return 0;
}
The program has not provided for character-at-a-time (unbuffered) input, as described in the Initialization section of the ncurses manual page. Since it looks for special keys such as KEY_UP, that means it should use cbreak (rather than raw, which prevents ncurses from decoding special keys).
I'm new to ncurses and we have a project to create a game of our choice.
The idea of my game is to have a spaceship and have enemies attack from the top.
I only started the code and I already ran into a problem, when i use the space bar to shoot a bullet, the bullet will travel, however i am unable to move my ship at the same time the bullet is moving.
#include<ncurses.h>
typedef struct
{/*define a structure for player information*/
int row;
int col;
}playerinfo;
int changeRow(int x,int m, int c)
{
if(x+m==22 || x+m==0 )
{
beep();
return x;
}
return x+m;
}
int changeColumn(int y,int n, int r)
{
if(y+n==72 || y+n==0 )
{
beep();
return y;
}
return y+n;
}
int main(){
initscr();
start_color();
assume_default_colors(COLOR_GREEN, COLOR_BLACK);
noecho();
cbreak();
curs_set(0); /* turn cursor display off */
timeout(0);
keypad(stdscr,TRUE); /* allow keypad keys to be used */
playerinfo playership;
playership.row= 10;
playership.col= 15;
char player[] =" X ";
char player2[]=" |o| ";
char player3[]=" xX| |Xx ";
char player4[]=" X | | X ";
char player5[]=" X__-|-__X ";
char bullet = '.';
int key = 0;
int i=0;
bool moving= false;
mvprintw(playership.row,playership.col,player);
mvprintw(playership.row+1,playership.col,player2);
mvprintw(playership.row+2,playership.col,player3);
mvprintw(playership.row+3,playership.col,player4);
mvprintw(playership.row+4,playership.col,player5);
timeout(0);
while(key!='q'){
usleep(17000);
mvprintw(playership.row,playership.col," ");
mvprintw(playership.row+5,playership.col," ");
key = getch ();
switch(key){
case KEY_UP: playership.row=changeRow(playership.row,-1,playership.col); /* move up */
break;
case KEY_DOWN: playership.row=changeRow(playership.row,+1,playership.col); /* move down */
break;
case KEY_LEFT:playership.col=changeColumn(playership.col,-1,playership.row); /* move left */
break;
case KEY_RIGHT:playership.col=changeColumn(playership.col,+1,playership.row); /* move right */
break;
case ' ': moving=true; break;
default: break; /* do nothing if other keys */
}
mvprintw(playership.row,playership.col,player);
mvprintw(playership.row+1,playership.col,player2);
mvprintw(playership.row+2,playership.col,player3);
mvprintw(playership.row+3,playership.col,player4);
mvprintw(playership.row+4,playership.col,player5);
if (moving==true){
for( i=0; i <24; i++){
refresh; mvprintw(playership.row-i-2,playership.col+5,"%c", bullet); mvprintw(playership.row,playership.col,player);
refresh();usleep(12000); mvprintw(playership.row-i-1,playership.col+5," ");} moving=false; }
refresh();
}
echo(); /* turn echo back on */
endwin(); /* End curses mode */
return 0;
}
That is because you nested the "firing" code inside your game loop, so all input stops while you do that animation. You need to change your logic to a kind of state machine:
switch(key)
{
// ...
case ' ':
if( !bullet_active )
{
bullet_active = true;
bullet_pos = 0;
}
break;
}
if( bullet_active ) {
// TODO: Draw bullet at bullet_pos
if( ++bullet_pos == 24 ) bullet_active = false;
}