OK. I could just let this go down, like threads do so very often here, because "the problems too hard" or whatever.
This problem is not that hard to solve!
I'll leave this for those who care.
This:
( GetAsyncKeyState('A") & 0x8000 )
from Windows.h will read the state of the 'A' key. It returns true if the key is down.
Let's try it out:
#include <iostream>
#include <Windows.h>
using std::cout;
1 2 3 4 5 6 7
|
int main()
{
while(true)// listen for key press
{
if( GetAsyncKeyState('A") & 0x8000 ) cout << 'A';
}
}
|
This either outputs nothing, or 'A's so fast it fills the console instantly.
This isn't the desired behavior. We want one 'A' printed.
The trick is to watch for a
change in the key state, which is what makes this "complicated".
The expression GetAsyncKeyState('A") & 0x8000 returns the current (right now) state of the key, I will call it (symbolically) keyDownNow.
So, keyDowNow represents the value = GetAsyncKeyState('A") & 0x8000, which I just repeated because please don't forget it.
Declaring bool KeyDownLast = false; to keep the value from the last loop iteration. We are looking for a change in value in keyDownNow across 2 iterations of the while loop.
If keyDownNow == keyDownLast we do nothing. Only whey keyDownNow != keyDownLast do we act because the key was just either pressed (keyDownNow changed false->true) or released ( keyDopwnNow true->false).
What we need is called XOR or exclusive or which is like our regular inclusive or ||, except it's false when both are true.
Since it's been too long since boolean algebra class for me to remember how to derive an expression, I looked online:
I quickly found 2 ways:
Assuming bool a,b;
if( a ? !b : b ) <--> if( a XOR b )
or one can write a function:
bool myXOR(a,b) { return ( a || b ) && !( a && b ); }
Going with the 1st, we can now write:
1 2 3 4 5 6 7 8 9
|
if( keyDownNow ? !keyDownLast : keyDownLast )// keyDownNow XOR keyDownLast
{
keyDownLast = !keyDownLast;// record the change in state! Only 2 values = value "toggles"
if( keyDownLast )
cout << "5 down";// action on key down
else
cout << "5 up ";// action on key up
}
|
And we find we've solved the 1st problem with using the GetAsyncKeyState function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
#include <iostream>
#include <Windows.h>
using std::cout;
int main()
{
bool keyDownLast = false;
while(true)// listen for key press
{
if( (GetAsyncKeyState('A') & 0x8000) ? !keyDownLast : keyDownLast )
{
keyDownLast = !keyDownLast;// record the change in state!!!!!
if( keyDownLast ) cout << "A down";
else cout << "A up ";
}
}
}
|
I'll show how to define and use a gotoxy() function and the arrow keys to move, if you ask nice and promise to pay attention.
I doubt I'll be around here much longer. I'm getting my fill of this shallow place extra quick this time around. Time for another year long break.