ChucK/keyboard
From CSWiki
As shown in kb.ck; ChucK can use your computer's keyboard as a interface using KBHit.
// the event
KBHit kb;
// time-loop
while( true )
{
// wait on kbhit event
kb => now;
// potentially more than 1 key at a time
while( kb.more() )
{
// print key value
<<< "ascii: ", kb.getchar() >>>;
}
}
However, this can get a little tricky. First of all; .getchar() not only returns the top acii code from the stack, it also removes it from there and so when you call .getchar() you should immediately do something with the value it returns; you can't simply set a series of tests loose on it like this;
//example of a naive attempt to read the keyboard that won't work very well.
while( kb.more() )
{
if (kb.getchar()== 1) { do(something) );
if (kb.getchar()== 2) { do(something_else) );
}
Because the second line will actually refer to a different value then the first. It may seem paradoxical but this;
if( kb.getchar() == kb.getchar() ) <<<"true?">>>;
will only be true in some cases and not at all in every case.
This means that if you'd like to run several tests on the value returned by getchar() you must first chuck that value to a variable, then run your tests on that variable instead.
while( kb.more() )
{
//store number to avoid it getting lost after one check
kb.getchar() => int K;
//now you can safely run tests on it.
if (K == 1) { do(something) };
if (K == 2) { do(something_else) };
}
Another thing that gets a little tricky when reading the keyboard is that some keys return not one but two values, one after the other. You can see this for yourself by running kb.ck (copied above and it can be found in examples/event as well). If you hit one of the cursor keys or for example the function keys you'll see two numbers added to your schreen instead of just one. This means that if we want to know wether one of the cursor keys was hit we first need to test the first of those two numbers and if it's the right one we alse check the second number like in this slightly more elborate example;
// the keyboard input
KBHit kb;
//some setting that's of great importance somewhere
int bla;
// time-loop
while( true )
{
// wait on kbhit event
kb => now;
// potentially more than 1 key at a time
while( kb.more() )
{
//store number to avoid it getting lost after one check
kb.getchar() => int K;
//arrow keys are encoded in two numbers with the first being 224
if (K == 224 )
{
//wait for the second number
kb => now;
//the same "anti number disapear" trick
kb.getchar() => int L;
//do intuitively sensible stuff to "up"...
if(L == 72) 1 +=> bla;
//........and "down"......
if(L == 80) 1 -=> bla;
//...and make the result go somewhere.
<<<"bla is", bla>>>;
}
else
{
//do something else to normal keys
<<<K>>>;
}
}
}
