0% found this document useful (0 votes)
3 views1 page

KeyboardInput - копия

The document contains a C++ implementation for detecting keyboard input. It includes a method to check if a specific key is pressed and another method to determine the direction based on key presses for 'w', 'a', 's', and 'd'. The code utilizes terminal settings to enable non-blocking input and modifies input flags accordingly.

Uploaded by

will.am.4277
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views1 page

KeyboardInput - копия

The document contains a C++ implementation for detecting keyboard input. It includes a method to check if a specific key is pressed and another method to determine the direction based on key presses for 'w', 'a', 's', and 'd'. The code utilizes terminal settings to enable non-blocking input and modifies input flags accordingly.

Uploaded by

will.am.4277
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

#include "KeyboardInput.

h"
#include <cstdio>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>

bool KeyboardInput::isKeyPressed(char key) {


struct termios oldt, newt;
int ch;
int oldf;

tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);

ch = getchar();

tcsetattr(STDIN_FILENO, TCSANOW, &oldt);


fcntl(STDIN_FILENO, F_SETFL, oldf);

if(ch != EOF && ch == key) {


return true;
}

return false;
}

KeyboardInput::Direction KeyboardInput::getDirection() {
bool up = isKeyPressed('w');
bool down = isKeyPressed('s');
bool left = isKeyPressed('a');
bool right = isKeyPressed('d');

if (up && right) return Direction::UP_RIGHT;


if (up && left) return Direction::UP_LEFT;
if (down && right) return Direction::DOWN_RIGHT;
if (down && left) return Direction::DOWN_LEFT;
if (up) return Direction::UP;
if (down) return Direction::DOWN;
if (left) return Direction::LEFT;
if (right) return Direction::RIGHT;

return Direction::NONE;
}

You might also like