Lets start with what my code looks like then I will explain my problem:
int main {
char ch; //Stores key presses
initscr();
raw();
nonl();
keypad(stdscr, TRUE);
noecho();
//Some code
ch = getch();
switch (ch) {
case KEY_UP:{
//Code that works
break;
}
case KEY_ENTER:{
//Some code- that doesn't work problem being the above
break;
}
//Other case statements
}
Now the problem:
The problem I run into if you haven't already worked it out is that when ever I press the enter/return key on my keyboard absolutely nothing happens.
I have tried changing the KEY_ENTER to '\n' - didn't work - even changed the char ch which when through multiple iterations including int and wchar_t.
All to no avail, and before you say search for answers and send me packing my bags to go onto a perilous adventure through every corner of the interwebs, I have already tried that, if I hadn't I wouldn't have ventured here, in search of aid.
So now my search has brought me here and I ask of you - the lovely people of the interwebs - to help me in my search of the answer I have been looking for
And to who ever may be valiant enough to answer it I give you my up most gratitude and thanks
Try case '\r':. (For good measure, you could do case '\r': case '\n': case KEY_ENTER:, as is basically done in testcurs.c, to capture all possibilities.) The call to nonl() is why you're getting '\r' instead of '\n'.
As for KEY_ENTER, my only excuse is that it's marked "not reliable" in the PDCurses comments. I could pretend that it's meant to represent the keypad's "Enter" key, rather than the key usually marked "Return" in the main part of the keyboard... except that PDCurses also has PADENTER, specifically for that purpose. In truth, like a lot of things in PDCurses, the reason KEY_ENTER is there, and defined the way it is, is a bit of a historical mess.
Related
I'm working on a little project to improve my coding skills and I have a problem. I'm doing a console version of Flappy Bird. So i have a map which is a two-dimensional array of chars and this map have to move to the left. I am moving all elements of an array one place to the left and after that, clearing console and showing moved map. And here is problem, map has to move constantly but player have to control a bird while map is moving. I wanted to use _getch() but it pausing a program. A question is: Can i read a keyboard input without pausing program? I mean that the map will still moving and when i press for example Space in any moment the bird position will change. I'm working on Windows 10
Even if beginners hope it to be a simple operation, inputting a single character from the keyboard is not, because in current Operating Systems, the keyboard is by default line oriented.
And peeking the keyboard (without pausing the program) is even harder. In a Windows console application, you can try to use functions from user32, for example GetAsyncKeyState if you only need to read few possible keys: you will know if the key is currently pressed and whether if was pressed since the last call to GetAsyncKeyState.
But beware: these are rather advanced system calls and I strongly advise you not to go that way if you want to improve your coding skills. IMHO you'd better learn how to code Windows GUI applications first because you will get an event loop, and peeking for events is far more common and can be used in real world applications. While I have never seen a real world console application trying to peek the keyboard. Caveat emptor...
Including conio.h
you can use this method:
#define ARROW_UP 72
#define ARROW_DOWN 80
#define ARROW_LEFT 75
#define ARROW_RIGHT 77
int main(){
int key;
while( true ){
if( _kbhit() ){ // If key is typed
key = _getch(); // Key variable get the ASCII code from _getch()
switch( key ){
case ARROW_UP:
//code her...
break;
case ARROW_DOWN:
//code her...
break;
case ARROW_LEFT:
//code her...
break;
case ARROW_RIGHT:
//code her...
break;
default:
//code her...
break;
}
}
}
return 0;
}
The upper code is an example, you can do this for any key of keyboard. In this sites you can find the ASCII code of keys:
http://www.jimprice.com/jim-asc.shtml#keycodes
https://brebru.com/asciicodes.html
Say me if it has help you!
Trying to make a program using switch case (nested switch) my system alerted me that my program has a virus (trojan). How is it even possible? I am new to programming (complete novice) so I would be grateful for any help.
The task - to make automated telephonic reply system based upon requirements (just something I wanted to try).
#include<iostream>
using namespace std;
void customer_service()
{
cout<<"Kindly wait for our employees to contact you";
}
void feedback()
{
cout<<"Kindly record your feedback after the beep";
}
void offer()
{
cout<<"You are entitled to accept our one-time offer. You will be directed to one of our employees shortly\n";
}
void satisfied()
{
cout<<"Thanks a lot for calling. Have a great day ahead";
}
int main()
{
int input,yes_no;
cout<<"\nPress 1 if you would want to directly contact our employee\n";
cout<<"\nPress 2 if you wan to give a feedback\n";
cout<<"\nPress 3 if ypu would want to know about our offers\n";
cout<<"\nPress 4 if you are satisfied with our service\n";
cout<<"\nKindly press the required key\n";
cin>>input;
switch (input)
{
case 1:
customer_service();
break;
case 2:
feedback();
break;
case 3:
offer();
cout<<"Would you like to accept our one time offer? You will get a 50% decrease in tariff";
cin>>yes_no;
switch (yes_no)
{
case 1:
cout<<"Congratulations! You have won our one time offer";
break;
default:
cout<<"Guess you didn't like our offer";
break;
}
break;
case 4:
satisfied();
break;
default:
cout<<"Kindly press either one of '1, 2, 3 or 4' keys. Thankyou.";
}
cin.get();
return 0.00;
}
This is the indication of Trojan and the program not executing
It's a false positive.
You may be able to help the situation by initialising your variables. As it is, you do not check that reading into yes_no succeeded, so your program has undefined behaviour. That could make your AV think that you are trying to write a memory exploit.
Otherwise, get better AV!
Some anti virus programs simply have false positives. Just whitelist in this case or get another anti virus.
OR your toolchain itself is infected and you compile bad stuff into your programs (then it's time to clean up your OS)
There is nothing wrong with your code.
Programs like 360 total security are anti-malware products that are designed to run on your mother's machine. They are not appropriate on a programmer's machine. They deal poorly with an executable file that appears from nowhere. Uninstall and consider something less aggressive, Windows Defender for example.
Nested switch cases will work work for sure.
First try like instead of using second switch case use if else condition if still it shows TROJAN thing then its a problem with your compiler.
So I'm working on a simple little text-based game in D to gain some experience working with the language. Here is a do-while loop that I'm currently struggling with:
do{
writeln("a. Advance 1 year\tc. Advance 10 years\tq. Quit");
writeln("b. Advance 5 years\td. Modify faction");
input = chomp(stdin.readln());
switch(input){
...
default:
break;
}
writeln(input[0]);
}while(input[0] != 'q');
Now the problem I'm running into is that when I hit q and enter the loop doesn't exit. It just keeps going. But then after the first time q is input, another q will terminate the loop. The writeln is in there as a sanity check, and it prints out the characters I type in exactly as typed. I feel like I'm going crazy, but it's probably just a simple type-o or something you guys will spot instantly. Nothing in the switch statement modifies 'input'.
EDIT: Okay some people have been asking to see all of the code. Here it is: http://pastebin.com/A7qM5nGW
When I said nothing in the switch modified input, it was to hide the fact I hadn't written anything in the switch yet. I've been trying to get the quit part to work right before adding the more complicated stuff. Also, here's a sample file for what I run it on: http://pastebin.com/4c2f4Z5N
Okay my friend found it. It has nothing to do with the while loop itself. I briefly forgot that args[0] is the name of the program. So it's actually running through the parent loop once with nothing, then actually quitting, and then running through the appropriate loop. It was fixed by making the parent loop like so...
foreach(filename; args[1..$]){
...
do{
...
while(input[0] != 'q');
}
as opposed to:
foreach(filename; args){
etc...
I am making Pacman in C++ with the Ncurses library. I am able to move Pacman with my code, but I want to move it so that pacman keeps moving even when I am not pressing any key and when I press another direction key, it changes direction. Right now, the pacman only takes one step when I press a key. Also I have to press a key 2 or 3 times before pacman moves in that direction.
if (ch==KEY_LEFT)
{
int b,row,column;
getyx(stdscr,row,column);
int h;
do // do-whileloop to move the pacman left until it hits the wall
{
column-=1;
mvprintw(row,column,">"); //print the ">" symbol
refresh();
waitf(0.1); //this pauses the game for 0.1sec
attron(COLOR_PAIR(1));
mvprintw(row,column,">");
attroff(COLOR_PAIR(1));
refresh();
waitf(0.1);
mvprintw(row,(b),"O"); //showing the open mouth of pacman
refresh();
waitf(0.1);
attron(COLOR_PAIR(1));a
mvprintw(row,column,"O");
attroff(COLOR_PAIR(1));
h = getch();
}
while(h == KEY_LEFT);
}
right = getch();
loop to move right in an if condition
up = getch();
loop to move up in an if condition
down = getch();
oop for moving down in an if condition.
The standard solution to this is the finite-state machine. The character has six or so possible states: standing, moving up, moving right, moving down, moving left, dead. Rather than a keypress directly moving the character, the keypress should change the character's state.
In such a small application, rather than implementing an incredibly flexible finite-state machine, you may use a very simple implementation as such:
enum PlayerState {
Standing,
MovingUp,
MovingRight,
MovingDown,
MovingLeft,
Dead
};
Then, inside your game loop you can add a very simple state check which then takes the appropriate action for the frame.
switch(state) {
case Standing:
break;
case MovingUp:
player.PositionY += 1;
break;
// ...
}
The last step is to hook input, which depends on your method of retrieving input. Using callbacks, an example is:
void KeyDown(Key k) {
switch(k) {
case UpArrow:
if(state != Dead)
state = MovingUp;
break;
case RightArrow:
if(state != Dead)
state = MovingRight;
// ...
}
}
You can see why in a larger project it would be important to implement a more flexible finite-state machine, but hopefully this example has given you an easy-to-understand idea.
You need an equivalent of kbhit, ie. a non-blocking getch. Which really gives the solution, set O_NONBLOCK on the input. See an example here. Once you have this, simply loop contiguously and just check for the key hit, w/o waiting on actual key press.
Function getch is blocked until some key is pressed. If you don't want to be blocked then call _kbhit before getch too make sure that there is something in input buffer.
EDIT: Take a look at ncurses functions nodelay and cbreak. They enable asynchronous input.
I suggest you take a look at the model-view-controller model, it will help you with this problems and all the other problems that you will have if you continue your program like this.
Edit: shortcut
To move your pacman continuously you will need a separate thread to control it and make it move. Take a look at pthreads for that.
If you keep only the user input in the main run loop of your program, the problem that you have to press the keys a few times will go away too (the problem here is that the processor has to be on the getch() line when you press the key, otherwise it will not be detected.
It is pretty easy
for each direction make 4 function
and inside the function,put in the other 3 direction function which get activated by kbhit.
and put a else statement in which it keeps moving forward if you do not hit a button i.e (!kbhit());
and then put all this in a loop.
If you do this for all the direction functions you should be able to get the desirable outcome.
I'm a rookie programmer, so please be polite.
Well i'm trying to write a simple Terminal Backgammon game, just for fun, but i have a problem.
The entire game runs in a while loop which keeps re running as long as nobody moved all their bricks to the end of the board.
A simple integer controls whatever it is black or white who plays.
I wrote a function to check for any possible moves, cause i want to program to skip the turn in case absolutely no moves can be made.
Well, i want this function to run and in case it returns false(No possible moves) then i want the rest of the code to skip and change the turn to the next player. For example if the dice combination gives no possible moves for black, then i want the program to skip black and go to white.
So i sort of want to break the rest of the while loop, but keep it running.
It's a little complicated for me to explain the issue, but i hope you guys understand.
Thanks alot
- Martin
It sounds like you want to use continue:
while (someCondition)
{
doSomething();
if (someOtherCondition)
continue;
doSomethingElse();
}
In this example, if someOtherCondition is true, the continue statement will cause the program to jump back to the top of the loop rather than continuing to execute the following statements. If someOtherCondition is false, doSomethingElse() will get run as normal.
I think this is roughly what you want to know.
Hope it helps.
while( keepRunning )
{
bool noPossibleMoves = checkForPossibleMoves();
setup for each loop iteration
Do things here that are always necessary.
if( noPossibleMoves )
{
continue; // This will go to the top of the while loop
}
wait for user input etc...
...
...
}