readkey(3alleg4)

πŸ’– readkey β€” bestie, the keyboard is talking to you πŸ’–

okay so this is readkey(3alleg4), straight out of the Allegro manual, aka the game programming library that basically raised a whole generation of us. it grabs the next character out of the keyboard buffer. that's it. that's the whole job. and yet. πŸŽ€


✨ SYNOPSIS ✨

#include <allegro.h>

int readkey();

🌸 DESCRIPTION 🌸

so readkey() returns the next character from the keyboard buffer, in ASCII format. if the buffer is empty it literally just sits there waiting until a key gets pressed β€” no cap, it will wait forever, it has nowhere else to be. πŸ¦‹

and if you wanna peek whether there are keypresses already queued up before committing to the wait? that's what keypressed() is for, bestie. use it. it's the vibe check before the commitment. πŸ’…

now here's the part that's giving main character energy: the return value is doing two jobs at once.

  • the low byte of the return value is the ASCII code of the key 🌈
  • the high byte is the scancode ⭐

and the scancode stays exactly the same no matter what state shift, ctrl and alt are in β€” iconic, unbothered, consistent. meanwhile the ASCII code does get affected by shift and ctrl in the normal way: shift changes the case, and ctrl+letter gives you the position of that letter in the alphabet, like ctrl+A = 1, ctrl+B = 2, etc. πŸ“

pressing alt+key? that returns only the scancode, with a zero ASCII code sitting in the low byte. so alt is out here ghosting the ASCII entirely. πŸ’€

for example:

int val;
...
val = readkey();
if ((val & 0xff) == 'd')     /* by ASCII code */
   allegro_message("You pressed 'd'\n");

if ((val >> 8) == KEY_SPACE) /* by scancode */
   allegro_message("You pressed Space\n");

if ((val & 0xff) == 3)       /* ctrl+letter */
   allegro_message("You pressed Control+C\n");

if (val == (KEY_X << 8))     /* alt+letter */
   allegro_message("You pressed Alt+X\n");

okay and now the important little caveat, and I need you to actually listen to this one: this function cannot return character values greater than 255. that's just the math, babe, there are only so many bits in a byte. so if you need to read Unicode input, you gotta use ureadkey() instead. don't fight it. πŸ‘‘

lowkey crucial: readkey() is an ASCII girlie. Unicode needs ureadkey(). periodt. 🫢

🌈 SEE ALSO 🌈


and that's the whole page, bestie!! πŸ’–βœ¨πŸŽ€ this was the readkey(3alleg4) page from the Allegro manual, version 4.4.3 β€” go press some keys, you got this, mwah πŸ’œπŸ¦‹πŸŒΈ