1
0
mirror of https://github.com/pevans/erc-c.git synced 2024-06-25 12:29:34 +00:00

Allow access to the last key pressed and key_pressed status

This commit is contained in:
Peter Evans 2018-01-16 23:42:10 -06:00
parent 05e95d7798
commit b1177784a0
2 changed files with 67 additions and 0 deletions

View File

@ -29,9 +29,17 @@ typedef struct {
*/
int xcoords;
int ycoords;
/*
* This is true when a key is pressed, and false if not. We
* determine this from an SDL_PollEvent() call.
*/
bool key_pressed;
} vm_screen;
extern bool vm_screen_active(vm_screen *);
extern bool vm_screen_key_pressed(vm_screen *);
extern char vm_screen_last_key(vm_screen *);
extern int vm_screen_add_window(vm_screen *, int, int);
extern int vm_screen_init();
extern int vm_screen_xcoords(vm_screen *);

View File

@ -6,6 +6,7 @@
* program, which only knows to call the functions here.
*/
#include <ctype.h>
#include <stdbool.h>
#include <stdlib.h>
@ -163,8 +164,45 @@ vm_screen_free(vm_screen *screen)
bool
vm_screen_active(vm_screen *screen)
{
SDL_Event event;
char ch;
static int counter = 100;
// There may be _many_ events in the queue; for example, you may be
// facerolling on Zork because it feels good. And good for you if
// so--but still we have to handle all those keyboard events!
while (SDL_PollEvent(&event)) {
ch = '\0';
// It seems we may have pressed a key...
if (event.key) {
// The sym field is of type SDL_Keycode; this type, however,
// maps roughly to Unicode, which of course maps roughly to
// ASCII in the low range.
ch = (char)event.key->keysym.sym;
// If we had shift pressed, we need to uppercase the
// character.
if (event.key->keysym.mod & KMOD_LSHIFT ||
event.key->keysym.mod & KMOD_RSHIFT
) {
ch = toupper(ch);
}
}
switch (event.type) {
case SDL_KEYDOWN:
screen->key_pressed = true;
screen->last_key = ch;
break;
case SDL_KEYUP:
// Note we do not erase the last_key value.
screen->key_pressed = false;
break;
}
}
if (counter--) {
return true;
}
@ -210,3 +248,24 @@ vm_screen_draw_rect(vm_screen *screen, vm_area *area)
SDL_RenderFillRect(screen->render, &rect);
}
/*
* Just a simple wrapper around the key pressed state (mostly in case we
* ever switch from SDL to something else, and a field stops making
* sense).
*/
bool
vm_screen_key_pressed(vm_screen *scr)
{
return scr->key_pressed;
}
/*
* Similar logic as for key_pressed; this is just a dumb getter for the
* last_key field.
*/
char
vm_screen_last_key(vm_screen *scr)
{
return scr->last_key;
}