TL;DR
I am trying to capture keyboard events (more specifically, the Ctrl+c command) in my own C++ program. I am attempting this through generic keyboard presses in SDL2.
END TL;DR
I have found links on SO and the internet that cover the subject of handling keyboard events with SDL2. I have a few of them listed here.
https://stackoverflow.com/questions/28105533/sdl2-joystick-dont-capture-pressed-event
https://lazyfoo.net/tutorials/SDL/04_key_presses/index.php
http://www.cplusplus.com/forum/windows/182214/
http://gigi.nullneuron.net/gigilabs/handling-keyboard-and-mouse-events-in-sdl2/
The major issue I think is causing the problem is that I am also using an Xbox-style joystick at the same time. I have had no issues whatsoever with capturing joystick events. I have been doing that for a long time now. I am having issues trying to get anything with the keyboard to throw an event. I have tried if(event.type == SDL_KEYDOWN) and then checking which key it was, but that appears to return nothing. I feel like there is some macro that I need to define to allow this since I keep finding the same solutions on the internet.
I have included the entire script that I am running at the moment.
#include <boost/thread.hpp>
// Time library
#include <chrono>
// vector data structure
#include <vector>
// Thread-safe base variables
#include <atomic>
// std::cout
#include <iostream>
// Joystick library
#include <SDL2/SDL.h>
// Counters for printing
std::atomic_int printcounter{ 0 };
// This is every 3 * 1000 milliseconds
const int printer = 300;
// If an event is found, allow for printing.
std::atomic_bool eventupdate{ false };
// This function converts the raw joystick axis from the SDL library to proper double precision floating-point values.
double intToDouble(int input)
{
return (double) input / 32767.0 ;
}
// Prevent joystick values from going outside the physical limit
double clamp(double input)
{
return (input < -1.0) ? -1.0 : ( (input > 1.0) ? 1.0 : input);
}
// SDL library joystick deadband
const int JOYSTICK_DEAD_ZONE = 5000;
// These are the raw read in values from the joystick in XInput (XBox) mode.
//Normalized direction
int leftX = 0;
int leftY = 0;
int rightX = 0;
int rightY = 0;
int leftTrigger = -32768;
int rightTrigger = -32768;
// Button array
uint buttons[11] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
// Tbe pov hat is only 4 bits - 1, 2, 4, 8
int povhat = 0;
// These are the rectified joystick values
double leftstickx = 0;
double leftsticky = 0;
double rightstickx = 0;
double rightsticky = 0;
double lefttrigger = 0;
double righttrigger = 0;
// These are the rectified boolean buttons
bool leftstickbut = false;
bool rightstickbut = false;
bool xbutton = false;
bool ybutton = false;
bool abutton = false;
bool bbutton = false;
bool rightbut = false;
bool leftbut = false;
bool startbut = false;
bool backbut = false;
bool centbut = false;
// This is the boolean that controls running the robot.
std::atomic_bool quitrobot{false};
// Joystick values
static double joyvalues[6] = { 0, 0, 0, 0, 0, 0};
static bool joybuttons[11] = { false };
// Sleep function
void wait(int milliseconds)
{
boost::this_thread::sleep_for(boost::chrono::milliseconds{milliseconds});
}
// Now the main code
int main(int argc, char** argv)
{
// Now the robot goes through the looping code until a quit flag is set to true
while ( ! quitrobot)
{
// Now we look for an Xbox-style joystick
std::cout << "Looking for gamepad..." << std::endl;
while(true)
{
// Now the program waits until an Xbox-style joystick is plugged in.
// resetting SDL makes things more stable
SDL_Quit();
// restart SDL with the expectation that a jostick is required.
SDL_Init(SDL_INIT_JOYSTICK);
// SDL_HINT_GRAB_KEYBOARD
// check for a joystick
int res = SDL_NumJoysticks();
if (res > 0) { break; } // Here a joystick has been detected.
if (res < 0)
{
std::cout << "Joystick detection error: " << std::to_string(res) << std::endl;
}
// we don't want the program running super fast when detecting hardware.
wait(20);
}
// Now we check to make sure that the joystick is valid.
// Open the joystick for reading and store its handle in the joy variable
SDL_Joystick *joy = SDL_JoystickOpen(0);
if (joy == NULL) {
/* back to top of while loop */
continue;
}
// Get information about the joystick
const char *name = SDL_JoystickName(joy);
const int num_axes = SDL_JoystickNumAxes(joy);
const int num_buttons = SDL_JoystickNumButtons(joy);
const int num_hats = SDL_JoystickNumHats(joy);
printf("Now reading from joystick '%s' with:\n"
"%d axes\n"
"%d buttons\n"
"%d hats\n\n",
name,
num_axes,
num_buttons,
num_hats);
/* I'm using a logitech F350 wireless in X mode.
If num axis is 4, then gamepad is in D mode, so neutral drive and wait for X mode.
[SAFETY] This means 'D' becomes our robot-disable button.
This can be removed if that's not the goal. */
if (num_axes < 5) {
/* back to top of while loop */
continue;
}
// This is the read joystick and drive robot loop.
while(true)
{
// poll for disconnects or bad things
SDL_Event e;
if (SDL_PollEvent(&e)) {
// SDL generated quit command
if (e.type == SDL_QUIT) { break; }
// Checking for Ctrl+c on the keyboard
// SDL_Keymod modstates = SDL_GetModState();
// if (modstates & KMOD_CTRL)
// {
// One of the Ctrl keys are being held down
// std::cout << "Pressed Ctrl key." << std::endl;
// }
if(e.key.keysym.scancode == SDLK_RCTRL || e.key.keysym.scancode == SDLK_LCTRL || SDL_SCANCODE_RCTRL == e.key.keysym.scancode || e.key.keysym.scancode == SDL_SCANCODE_LCTRL)
{
std::cout << "Pressed QQQQ." << std::endl;
}
if (e.type == SDL_KEYDOWN)
{
switch(e.key.keysym.sym){
case SDLK_UP:
std::cout << "Pressed up." << std::endl;
break;
case SDLK_RCTRL:
std::cout << "Pressed up." << std::endl;
break;
case SDLK_LCTRL:
std::cout << "Pressed up." << std::endl;
break;
}
// Select surfaces based on key press
switch( e.key.keysym.sym )
{
case SDLK_UP:
std::cout << "Pressed Up." << std::endl;
break;
case SDLK_DOWN:
std::cout << "Pressed Up." << std::endl;
break;
case SDLK_LEFT:
std::cout << "Pressed Up." << std::endl;
break;
case SDLK_RIGHT:
std::cout << "Pressed Up." << std::endl;
break;
}
std::cout << "Pressed blah di blah blah please print me." << std::endl;
}
// Checking which joystick event occured
if (e.jdevice.type == SDL_JOYDEVICEREMOVED) { break; }
// Since joystick is not erroring out, we can
else if( e.type == SDL_JOYAXISMOTION )
{
//Motion on controller 0
if( e.jaxis.which == 0 )
{
// event happened
eventupdate = true;
// Left X axis
if( e.jaxis.axis == 0 )
{
// dead zone check
if( e.jaxis.value > -JOYSTICK_DEAD_ZONE && e.jaxis.value < JOYSTICK_DEAD_ZONE)
{
leftX = 0;
}
else
{
leftX = e.jaxis.value;
}
}
// Right Y axis
else if( e.jaxis.axis == 1 )
{
// dead zone check
if( e.jaxis.value > -JOYSTICK_DEAD_ZONE && e.jaxis.value < JOYSTICK_DEAD_ZONE)
{
leftY = 0;
}
else
{
leftY = e.jaxis.value;
}
}
// Left trigger
else if ( e.jaxis.axis == 2 )
{
// dead zone check
if( e.jaxis.value > -JOYSTICK_DEAD_ZONE && e.jaxis.value < JOYSTICK_DEAD_ZONE)
{
leftTrigger = 0;
}
else
{
leftTrigger = e.jaxis.value;
}
}
// Right X axis
else if( e.jaxis.axis == 3 )
{
// dead zone check
if( e.jaxis.value > -JOYSTICK_DEAD_ZONE && e.jaxis.value < JOYSTICK_DEAD_ZONE)
{
rightX = 0;
}
else
{
rightX = e.jaxis.value;
}
}
// Right Y axis
else if( e.jaxis.axis == 4 )
{
// dead zone check
if( e.jaxis.value > -JOYSTICK_DEAD_ZONE && e.jaxis.value < JOYSTICK_DEAD_ZONE)
{
rightY = 0;
}
else
{
rightY = e.jaxis.value;
}
}
// Right trigger
else if( e.jaxis.axis == 5 )
{
// dead zone check
if( e.jaxis.value > -JOYSTICK_DEAD_ZONE && e.jaxis.value < JOYSTICK_DEAD_ZONE)
{
rightTrigger = 0;
}
else
{
rightTrigger = e.jaxis.value;
}
}
}
}
else if ( e.type == SDL_JOYBUTTONUP || e.type == SDL_JOYBUTTONDOWN )
{
// now we are looking for button events.
if (e.jbutton.which == 0)
{
// event happened
eventupdate = true;
// buttons[e.jbutton.button] = e.jbutton.state;
if (e.jbutton.button == 0)
{
buttons[0] = e.jbutton.state;
}
if (e.jbutton.button == 1)
{
buttons[1] = e.jbutton.state;
}
if (e.jbutton.button == 2)
{
buttons[2] = e.jbutton.state;
}
if (e.jbutton.button == 3)
{
buttons[3] = e.jbutton.state;
}
if (e.jbutton.button == 4)
{
buttons[4] = e.jbutton.state;
}
if (e.jbutton.button == 5)
{
buttons[5] = e.jbutton.state;
}
if (e.jbutton.button == 6)
{
buttons[6] = e.jbutton.state;
}
if (e.jbutton.button == 7)
{
buttons[7] = e.jbutton.state;
}
if (e.jbutton.button == 8)
{
buttons[8] = e.jbutton.state;
}
if (e.jbutton.button == 9)
{
buttons[9] = e.jbutton.state;
}
if (e.jbutton.button == 10)
{
buttons[10] = e.jbutton.state;
}
if (e.jbutton.button == 11)
{
buttons[11] = e.jbutton.state;
}
}
}
else if ( e.type == SDL_JOYHATMOTION)
{
if (e.jhat.which == 0)
{
// event happened
eventupdate = true;
povhat = e.jhat.value;
}
}
}
// Now that we have read in the values directly from the joystick we need top convert the values properly.
leftstickx = clamp(intToDouble(leftX));
leftsticky = clamp(intToDouble(leftY));
rightstickx = clamp(intToDouble(rightX));
rightsticky = clamp(intToDouble(rightY));
lefttrigger = clamp(intToDouble(leftTrigger));
righttrigger = clamp(intToDouble(rightTrigger));
// rectify the buttons to become boolean values instead of integers.
abutton = buttons[0] > 0;
bbutton = buttons[1] > 0;
xbutton = buttons[2] > 0;
ybutton = buttons[3] > 0;
//
rightbut = buttons[4] > 0;
leftbut = buttons[5] > 0;
//
centbut = buttons[8] > 0;
startbut = buttons[7] > 0;
backbut = buttons[6] > 0;
//
leftstickbut = buttons[9] > 0;
rightstickbut = buttons[10] > 0;
// Transfer axis to the array.
joyvalues[0] = leftstickx;
joyvalues[1] = leftsticky;
joyvalues[2] = rightstickx;
joyvalues[3] = rightsticky;
joyvalues[4] = lefttrigger;
joyvalues[5] = righttrigger;
// We are using the "B" button to quit the program
if (bbutton)
{
quitrobot = true;
std::cout << "Shutting down program." << std::endl;
break;
}
if (eventupdate)
{
// This section of code is meant for running code that happens when SDL has detected an event.
// This code section can be used for something else as well.
if (e.key.keysym.sym == SDL_SCANCODE_RCTRL || e.key.keysym.sym == SDL_SCANCODE_LCTRL || e.key.keysym.sym == SDLK_LCTRL || e.key.keysym.sym == SDLK_RCTRL)
{
std::cout << "SDL Event: Ctrl pressed.\n" << std::endl;
}
// Simply print the event
eventupdate = false;
} else {}
if ( ! (printcounter = ((printcounter + 1) % printer)))
{
// const Uint8 *state = SDL_GetKeyboardState(NULL);
// if (state[SDL_SCANCODE_RETURN]) {
// printf("<RETURN> is pressed.\n");
// }
}
// Sleep the program for a short bit
wait(5);
}
// Reset SDL since the robot is no longer being actuated.
SDL_JoystickClose(joy);
// We get here only if the joystick has been disconnected.
std::cout << "Gamepad disconnected.\n" << std::endl;
}
// The program then completes.
return 0;
}
The most important part of that huge block of code is lines 129 to 179. I was doing more fooling around trying to get key capture to work but I could not get a response. Everywhere else is logic for the joystick reading (which has worked for me flawlessly). I have been referring to this link for all of the macros available to the programmer. I have not been able to capture the left control button or the right control button. I have also been trying the arrow keys for kicks as well and those are not working either. I know there are remnants of other code snippets thrown in there as I was testing. Given all of my testing, I am just not sure how to capture any keyboard keys, let alone Ctrl+c. None of my desired print statements print.
I am able to run the code on Ubuntu 1804 LTS with the stock GUI manager and window manager. I have a feeling the problem might also have something to do with the operating system not letting SDL2 capture the keyboard, but I don't know what to do to allow only the keyboard or certain keys to be consumed by SDL2.
I am trying to not use platform-specific code since I already have successfully used platform-specific signal interrupts. My goal is to simply make a certain combination of depressed keys result in a program terminating. I figured that, since SDL2 can access all keys on a keyboard, that I should be able to simply
Unless you want to read keyboard input from stdin you need to open a window and focus it to get key events in SDL. Here's an example (note the call to SDL_Init uses SDL_INIT_VIDEO and there's some code in there for rendering a background and handling resize events).
#include <iostream>
#include <SDL2/SDL.h>
int main(int argc, char** argv)
{
if (SDL_Init(SDL_INIT_VIDEO) < 0) { // also initialises the events subsystem
std::cout << "Failed to init SDL.\n";
return -1;
}
SDL_Window *window = SDL_CreateWindow(
"Window", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
680, 480, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);
if(!window) {
std::cout << "Failed to create window.\n";
return -1;
}
// Create renderer and select the color for drawing.
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, 0);
SDL_SetRenderDrawColor(renderer, 200, 200, 200, 255);
while(true)
{
// Clear the entire screen and present.
SDL_RenderClear(renderer);
SDL_RenderPresent(renderer);
SDL_Event event;
while (SDL_PollEvent(&event))
{
if (event.type == SDL_QUIT) {
SDL_Quit();
return 0;
}
if(event.type == SDL_WINDOWEVENT) {
if (event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) {
int width = event.window.data1;
int height = event.window.data2;
std::cout << "resize event: " << width << "," << height << std::endl;
}
}
if (event.type == SDL_KEYDOWN) {
int key = event.key.keysym.sym;
if (key == SDLK_ESCAPE) {
SDL_Quit();
return 0;
}
std::cout << "key event: " << key << std::endl;
}
}
}
return 0;
}
Key events are sent to the currently focused window and SDL uses the underlying OS to handle this. E.g. In Linux this means SDL calls X11 functions.
edit:
As detailed in this question it appears you can also get a snapshot of the state of the keys. In either case I think a window needs to be opened to receive events even though I've edited this multiple times to come to that conclusion (apologies if that caused any confusion). Your OS may provide functions for polling the state of the keyboard without using events or windows, such as GetAsyncKeyState in Windows.
Related
I've been implementing a dirty hack for a "panic" keyboard shortcut in a RHEL 8.4 environment to kill our application in the event that it hangs because we use a Mutter environment which prevents the user from being able to interact with the OS and only shows our application.
At first I looked into Gnome keyboard shortcuts, but it appears those get overridden or blocked entirely by Mutter, because that didn't work. So I repurposed some old driver code I wrote to write a standalone process that runs in the background and monitors the /dev/input/event file for keyboard events and responds to the Ctrl+Alt+Delete key sequence. When pressed, I use Qt to spawn a QMessageBox that when "Yes" is selected, it calls the script that kills and relaunches our application, and "No" just closes the dialog.
However, there's an issue where regardless of what you click, the dialog reappears. Through some testing, it appears this happens if you press Ctrl+Alt+Delete again while the dialog is visible, but I don't understand how that can happen, because the QMessageBox is modal and calling exec() on it should block the main thread, since the code immediately after reads the dialog result. So I also tried zeroing out the event data at the start of each loop to make sure a previous event isn't being read repeatedly while no events are taking place, but that had no effect either.
Can anyone tell what's going on here?
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <linux/input.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <QApplication>
#include <QMessageBox>
using namespace std;
#define BITS_PER_LONG (sizeof(long) * 8)
#define NBITS(x) (((x - 1) / BITS_PER_LONG) + 1)
#define OFF(x) (x % BITS_PER_LONG)
#define LONG(x) (x / BITS_PER_LONG)
#define test_bit(bit, array) ((array[LONG(bit)] >> OFF(bit)) & 1)
string detect();
void poll(string handler);
int main(int argc, char ** argv) {
QApplication app(argc, argv);
bool found = false;
string handler = detect();
poll(handler);
return app.exec();
}
string detect() {
int eventX = 0;
string handler = "";
bool found = false;
while(!found) {
ostringstream oss;
oss << "/dev/input/event" << eventX;
handler = oss.str();
int fd = open(handler.c_str(), O_RDONLY);
if(fd < 0) {
if((errno == EACCES) && (getuid() != 0)) {
cout << "You must run as root to detect the keyboard." << endl;
exit(1);
} else {
// No more event handler files.
break;
}
}
// Read event code bits from event handler file descriptor.
unsigned long bit[EV_MAX][NBITS(KEY_MAX)];
memset(bit, 0, sizeof(bit));
ioctl(fd, EVIOCGBIT(0, EV_MAX), bit[0]);
// Read key events from file descriptor.
ioctl(fd, EVIOCGBIT(EV_KEY, KEY_MAX), bit[EV_KEY]);
// Test to make sure the event file defines the Ctrl, Alt, and Delete key events.
if(
( test_bit( KEY_LEFTCTRL, bit[EV_KEY] ) || test_bit( KEY_RIGHTCTRL, bit[EV_KEY] ) ) &&
( test_bit( KEY_LEFTALT, bit[EV_KEY] ) || test_bit( KEY_RIGHTALT, bit[EV_KEY] ) ) &&
test_bit(KEY_DELETE, bit[EV_KEY])
) {
cout << "Keyboard Found # " << handler << endl;
found = true;
}
close(fd);
eventX++;
}
if(!found) {
cout << "No keyboard event file found." << endl;
exit(2);
}
return handler;
}
void poll(string handler) {
ifstream keyboard(handler.c_str(), ios::in | ios::binary);
struct input_event event;
char data[sizeof(event)];
int states[2] = { 0, 0 };
bool dialogBlocked = false;
bool done = false;
while(!done) {
if(keyboard.is_open() && keyboard.good()) {
memset(data, 0, sizeof(event));
keyboard.read(data, sizeof(event));
memcpy(&event, data, sizeof(event));
if((event.code == KEY_LEFTCTRL) || (event.code == KEY_RIGHTCTRL)) {
if(event.value > 0) {
states[0] = 1;
} else {
states[0] = 0;
}
}
if((event.code == KEY_LEFTALT) || (event.code == KEY_RIGHTALT)) {
if(event.value > 0) {
states[1] = 1;
} else {
states[1] = 0;
}
}
if((event.code == KEY_DELETE) && (event.value > 0)) {
if((states[0] > 0) && (states[1] > 0) && !dialogBlocked) {
// Ctrl+Alt+Delete detected. Call killX.
dialogBlocked = true;
QMessageBox msgBox;
msgBox.setModal(true);
msgBox.setText("Do you want to reset?");
msgBox.setWindowTitle("Reset");
msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::No);
msgBox.setStyleSheet(
"QMessageBox {"
" background: rgb(220, 220, 220);"
" color: rgb(0, 0, 0);"
"}"
"QPushButton {"
" border: 1px solid rgb(20, 20, 20);"
" border-radius: 5px;"
" padding: 2px;"
"}"
"QPushButton:enabled {"
" background: rgb(240, 240, 240);"
" color: rgb(20, 20, 20);"
"}"
"QPushButton:!enabled {"
" background: rgb(200, 200, 200);"
" color: rgb(250, 250, 250);"
"}"
);
int ret = msgBox.exec();
if(ret == QMessageBox::Yes) {
system("sudo /opt/eds/bin/killX");
}
}
}
if(dialogBlocked) {
// Wait until Ctrl+Alt keys are released to let operator open dialog again.
if((states[0] == 0) && (states[1] == 0)) {
dialogBlocked = false;
}
}
} else {
cout << "Lost connection to keyboard. Attempting to re-establish..." << endl;
bool detected = false;
if(keyboard.is_open()) keyboard.close();
while(!detected) {
string redetectedHandler = detect();
if(!redetectedHandler.empty()) {
keyboard.open(redetectedHandler.c_str(), ios::in | ios::binary);
if(keyboard.is_open()) {
cout << "Connection to keyboard re-established." << endl;
detected = true;
}
}
}
}
}
if(keyboard.is_open()) keyboard.close();
}
You are never setting done to true, and by this you have a infinite loop which reopens the dialog regardless if you clicked on the yes option.
Also your I am not sure what system("sudo /opt/eds/bin/killX"); is intended to do. If you intend to kill the current process then it does not do the job. For simplicity sake you can call std::terminate then indeed, you would not have to set done to true, since you are exiting the loop abnormally.
So you have 2 options:
if(ret == QMessageBox::Yes) {
system("sudo /opt/eds/bin/killX");
done = true;
}
or
#include <exception>
....
if(ret == QMessageBox::Yes) {
std::terminate();
}
I am trying to implement parts of a Linux based network Tic-Tac-Toe program into a Winsock server program. I am having some issues as the Linux version opens a socket as in integer variable:
int client_sock = 0; however, in the Winsock application a Csocket object is created: m_pClientSocket = new CSocket();
Now obviously when I try to compile the function that sends the players move to the server:
if (!SendStatus(client_sock, MOVE)) {
ServerDisconnected();
}
I get an invalid variable type error as the function is expecting an int and it's receiving a Csock object.
My question is how do I get the functions to work? I have tried getting the socket handle and using that but I'm not sure if that's the right direction and using this SendStatus(this->m_pClientSocket->GetSocketHandle(), WIN); is giving me issues as it's a static function.
Send Status Function:
bool SendStatus(int socket, StatusCode status)
{
char* data = (char*)&status;
size_t left = sizeof(status);
ptrdiff_t rc;
while (left)
{
rc = send(socket, data + sizeof(status) - left, left, 0);
if (rc <= 0) return false;
left -= rc;
}
return true;
}
TakeTurn Function:
bool TakeTurn(TTTBoard& board)
{
bool game_over = false;
bool input_good = false;
int row = 0, col = 0;
// Display the board
board.DrawBoard();
while (!input_good)
{
printf("Enter move (row col): ");
// Make sure two integers were inputted
if (scanf_s("%d %d", &row, &col) == 2)
{
if (row < 0 || row > 2)
printf("Invalid row input. Try again.\n");
else if (col < 0 || col > 2)
printf("Invalid column input. Try again.\n");
else if (!board.IsBlank(row, col))
printf("That cell isn't blank. Try again.\n");
else
input_good = true;
}
else
printf("Invalid move input. Try again.\n");
// flush any data from the internal buffers
int c;
while ((c = getchar()) != '\n' && c != EOF);
}
board.PlayerMakeMove(row, col);
cout << "Sending move to server" << endl;
// Send the move to the server
if (!SendStatus(client_sock, MOVE))
ServerDisconnected();
if (!SendInt(client_sock, row))
ServerDisconnected();
if (!SendInt(client_sock, col))
ServerDisconnected();
// Check for win/draw
if (board.IsWon())
{
cout << "YOU WIN!!!!" << endl;
game_over = true;
SendStatus(client_sock, WIN);
}
else if (board.IsDraw())
{
cout << "You tied ._." << endl;
game_over = true;
SendStatus(client_sock, DRAW);
}
return game_over;
}
Hopefully I have shared enough info, I didn't want to bloat the question, thanks!
So I have most of my game finish up however, I want to save the score and name of the player to a text file and display it. So far the user input works and does save to a text file named score.txt however the input is invisible and you can't see what you are typing. Does anyone know why this is happening?
Main
int main()
{
DWORD mode; /* Preserved console mode */
INPUT_RECORD event; /* Input event */
BOOL EXITGAME = FALSE; /* Program termination flag */
unsigned int counter = 0; /* The number of times 'Esc' is pressed */
/* Get the console input handle */
HANDLE hstdin = GetStdHandle( STD_INPUT_HANDLE );
/* Preserve the original console mode */
GetConsoleMode( hstdin, &mode );
/* Set to no line-buffering, no echo, no special-key-processing */
SetConsoleMode( hstdin, 0 );
srand ( time(NULL) ); //initialize the random seed
// Variables
int health = 2;
// Declare variable positions
player.x=1;
player.y=1;
treasure.x = 20;
treasure.y = 5;
treasure.z= 0;
traps.x = 1;
traps.y = 7;
traps.z = 0;
lives.x = 1;
lives.y = 9;
ofstream file;
int score = 0;
string name;
string line;
/*
while(treasure.z < 2)
{
treasure.x = (rand() % 24);
treasure.y = (rand() % 16);
if(treasure.x == 0 && treasure.y == 0)
{
treasure.z++;
}
}
while(traps.z < 3)
{
traps.x = (rand() % 24);
traps.y = (rand() % 16);
if(traps.x == 0 && traps.y == 0)
{
traps.z++;
}
}
while(lives.z < 2)
{
lives.x = (rand() % 24);
lives.y = (rand() % 16);
}
*/
clrscr();
setcolor(15);
while (!EXITGAME)
{
if (WaitForSingleObject( hstdin, 0 ) == WAIT_OBJECT_0) /* if kbhit */
{
DWORD count; /* ignored */
/* Get the input event */
ReadConsoleInput( hstdin, &event, 1, &count );
/* Only respond to key release events */
if ((event.EventType == KEY_EVENT)
&& !event.Event.KeyEvent.bKeyDown)
clrscr();
putmenu();
gotoxy(6,20);
cout<<"Lives: " << health;
gotoxy(6,22);
cout<<"Score: " << score;
Sleep(50);
switch (event.Event.KeyEvent.wVirtualKeyCode)
{
case VK_ESCAPE:
clrscr();
putend();
EXITGAME = TRUE;
break;
case VK_LEFT:
// left key move player left
moveleft();
break;
case VK_RIGHT:
// right key move player right
moveright();
break;
case VK_UP:
// up key move player up
moveup();
break;
case VK_DOWN:
// down key move player down
movedown();
break;
case VK_A:
// left key move player left
moveleft();
break;
case VK_D:
// right key move player right
moveright();
break;
case VK_W:
// up key move player up
moveup();
break;
case VK_S:
// down key move player down
movedown();
break;
}//switch
puttreasure();
puttraps();
putlives();
putplayer();
if((player.x == lives.x) && (player.y == lives.y))
{
health++;
lives.x = 0;
lives.y = 0;
}
if((player.x == traps.x) && (player.y == traps.y))
{
health--;
traps.x = 0;
traps.y = 0;
}
if((player.x == treasure.x)&& (player.y == treasure.y))
{
score += 100;
EXITGAME = true;
}
else if(health == 0)
{
EXITGAME = true;
}
if(EXITGAME == true)
{
score = score + (health * 100);
}
}
}
if(EXITGAME == true)
{
// clear screen
clrscr();
}
setcolor(10);
cout << "Enter your name ";
cin >> name;
ofstream out("score.txt");
out << name;
out << "\n";
out << score;
out.close();
/* if(file.is_open())
{
while( getline (file, line))
cout << line << '\n';
}*/
gotoxy(1,23);cout<<" ";
SetConsoleMode( hstdin, mode );
return 0;
}
/* Set to no line-buffering, no echo, no special-key-processing */
You turned off echo - means that the user wont see what they type
I am trying to make a custom app library with SDL as apart of an academic project, and I ran into an issue..
Basically, everything works fine, it compiles, does what I expect it to do, but... its extremely slow, the first element is reacting quite quickly, other elements within the set are completely unresponsive (i need to click them 20 times for the to react, they work just slow)
Below the function that draws the elements from a vector type container, the return 1 means that the handle function ran into an unexpected error or the user X'ed out the window.
Any advice on how to make this react faster?
void StoreDraw::setCamera(size_t input)
{
rectangle.x = containerArray[input].elementLocX;
rectangle.y = containerArray[input].elementLocY;
rectangle.h = containerArray[input].elementPicture->h;
rectangle.w = containerArray[input].elementPicture->w;
}
bool StoreDraw::vectorDraw()
{
/* Draw FloatingElements */
for(size_t i = 0; i < containerArray.size(); i++)
{
if(SDL_PollEvent(&event))//containerArray[i].event
{
if(event.type == SDL_MOUSEBUTTONDOWN)
{
if(event.button.button == SDL_BUTTON_LEFT)
{
locationX = event.button.x;
locationY = event.button.y;
printf("X:%d\tY:%d\n", locationX, locationY);
if(!containerArray[i].handleEvent(locationX, locationY)){drawEnvironment();}
}
}
if(event.type == SDL_QUIT)
{
return 1;
}
}
}
SDL_Flip(screen);
return 0;
}
bool StoreDraw::drawEnvironment()
{
SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 0,0,0));
SDL_BlitSurface(background, NULL, screen, NULL);
for(size_t i = 0; i < containerArray.size(); i++)
{
setCamera(i);
SDL_BlitSurface(containerArray[i].elementPicture, NULL, screen, &rectangle);
}
SDL_Flip(screen);
}
bool FloatingElement::handleEvent(int x, int y)
{
printf("Object responding.\n");
if((x > elementLocX) && (x < (elementLocX + (elementPicture->w))) && (y > elementLocY) && (y < (elementLocY + (elementPicture->h))))
{
x = (x - (elementPicture->w)/2);
y = (y - (elementPicture->h)/2);
setLocation(x,y);
printf("Object responding.\n");
return 0;
}
return 1;
}
As far as I can see, the problem is how frequently you are checking for events. When you call vectorDraw() it polls the events and acts as intended, but the events eventually end and the function returns. I think there should be a main loop in the code that always checks for events and calls functions when necessary, while vectorDraw() only checks the location of a click and calls the handleEvent() of the container array.
Edit:
I think I found the problem. This is how you're doing now:
bool StoreDraw::vectorDraw()
{
/* Draw FloatingElements */
for(size_t i = 0; i < containerArray.size(); i++)
{
if(SDL_PollEvent(&event))//containerArray[i].event
{
if(event.type == SDL_MOUSEBUTTONDOWN)
{
if(event.button.button == SDL_BUTTON_LEFT)
{
// Check Events
}
}
if(event.type == SDL_QUIT)
{
return 1;
}
}
}
SDL_Flip(screen);
return 0;
}
int main() {
while( ::quit == false ) {
while(SDL_PollEvent(&event) == 1) {
if( event.type != SDL_QUIT ) {
if( event.type == SDL_MOUSEBUTTONDOWN) {
storeDraw::vectorDraw();
}
} else {
quit = true;
break;
}
}
}
}
}
So, what is happening:
After the main loop polls the event, it calls vectorDraw() and vectorDraw() polls events again. By doing so, vectorDraw() doesn't get the information of the click it called, as it was already polled in the main loop. Without the information, it doesn't act upon it.
So, in order to solve the problem, you can change the functions to be somewhat like this:
bool StoreDraw::vectorDraw(SDL_Event event)
{
/* Draw FloatingElements */
for(size_t i = 0; i < containerArray.size(); i++)
{
// Check Events
}
SDL_Flip(screen);
return 0;
}
int main() {
while( ::quit == false ) {
while(SDL_PollEvent(&event) == 1) {
if( event.type != SDL_QUIT ) {
if( event.type == SDL_MOUSEBUTTONDOWN) {
if(event.button.button == SDL_BUTTON_LEFT)
{
storeDraw::vectorDraw(event);
}
}
} else {
quit = true;
break;
}
}
}
}
}
Now, only the main loop polls events and acts on them if possible. And vectorDraw() doesn't poll them anymore, only acts upon them if they meet it's criteria (left mouse button down, in this case). Now the event checking should act as intended.
I created a TrayPopupWidget that should pops up nearby the tray.
Then I realized that if the user changes the orientation, or height of the taskbar it will pops up at the wrong place. So I created the TaskbarDetector class.
I tried to get the a window geometry of the tray|taskbar, but I only get wrong window property...
I tried on KDE,LXDE -> same bad behaviour...
The code:
http://bzfriendsplasm.svn.sourceforge.net/viewvc/bzfriendsplasm/BZFriends/taskbardetector.cpp?revision=156&view=markup
//Getting screen resolutoin
int num_sizes;
Rotation original_rotation;
Display *display = XOpenDisplay(NULL);
Window root = RootWindow(display, 0);
XRRScreenSize *xrrs = XRRSizes(display, 0, &num_sizes);
XRRScreenConfiguration *conf = XRRGetScreenInfo(display, root);
XRRConfigCurrentRate(conf);
SizeID original_size_id = XRRConfigCurrentConfiguration(conf, &original_rotation);
p_screenWidth = xrrs[original_size_id].width;
p_screenHeight = xrrs[original_size_id].height;
//Getting tray position
unsigned long sysTraySelection = 0;
Screen *screen = XDefaultScreenOfDisplay(display);
//FIXME !!!
QString *net_sys_tray = new QString("_NET_SYSTEM_TRAY_S%i");
(*net_sys_tray) = net_sys_tray->replace ("%i",QString::number (XScreenNumberOfScreen(screen)));
sysTraySelection = XInternAtom(display, net_sys_tray->toLocal8Bit (), False);
if ( sysTraySelection == None)
return Unknown;
trayWindow = XGetSelectionOwner(display, sysTraySelection);
XWindowAttributes w_attr;
unsigned long status = XGetWindowAttributes (display,trayWindow,&w_attr);
if ( status == 0)
return Unknown;
p_taskBarLeft = w_attr.y;
p_taskBarTop = w_attr.x;
p_taskBarBottom = w_attr.x + w_attr.height;
p_taskBarRight = w_attr.y + w_attr.width;
qDebug () << QString("Window id: " ) + QString::number (trayWindow);
qDebug() << QString("SysTraySelection: ") + QString::number (sysTraySelection );
qDebug() << QString("Top ") + QString::number (p_taskBarTop);
qDebug() << QString("Left ") + QString::number (p_taskBarLeft);
qDebug() << QString("Bottom ") + QString::number (p_taskBarBottom);
qDebug() << QString("Right " ) + QString::number (p_taskBarRight);
XCloseDisplay(display);
delete net_sys_tray;
return decideOrientation ();
Finally, I found a way to detect it!
I'm searching for a window, that has a dock property and visible, and then I call XGetWindowAttributes(...) on it.
If I set a filter method to the QApplication::setEventFilter() I can get every XEvent, _NET_WORKAREA event too(this event happens when you resize or move the taskbar), then I re-call taskbar/tray detection method.
However, this worked on KDE4 and GNOME and LXDE, I'm planning to allow the user to set the popup position by himself.
bool TaskBarDetector::lookUpDockWindow ( unsigned long &rootWindow, bool check)
{
Display *display = QX11Info::display ();
Window parent;
Window *children;
unsigned int noOfChildren;
int status;
if ( check && checkDockProperty(rootWindow) )
{
trayWindow = rootWindow;
return true;
}
status = XQueryTree (display, rootWindow, &rootWindow, &parent, &children, &noOfChildren);
if (status == 0)
{
qDebug() << "ERROR - Could not query the window tree. Aborting.";
trayWindow = 0;
return false;
}
if (noOfChildren == 0)
{
trayWindow = 0;
return false;
}
for (unsigned int ind = 0 ; ind < noOfChildren; ++ind )
{
if ( lookUpDockWindow ( children[ind] ,true) )
return true;
}
XFree ((char*) children);
trayWindow = 0;
return false;
}
bool TaskBarDetector::checkDockProperty(unsigned long window)
{
Display *x11display = QX11Info::display ();
Atom *atoms;
int numberAtoms = 0;
char *atomName;
XTextProperty prop;
XWindowAttributes windowattr;
atoms = XListProperties (x11display, window, &numberAtoms);
for (int ind = 0; ind < numberAtoms; ++ind )
{
atomName = XGetAtomName(x11display, atoms[ind]);
if (QString(atomName).compare ("_NET_WM_WINDOW_TYPE" ) != 0 )
continue;
unsigned long status = XGetTextProperty (x11display,window,&prop,atoms[ind]);
if ( status == 0 )
continue;
int value = (int) (*prop.value);
if (value != 151 )
continue;
if (XGetWindowAttributes(x11display,window,&windowattr) == 0)
continue;
return windowattr.map_state == 2;
}
return false;
}
void TaskBarDetector::saveWindowAttr(unsigned long root)
{
XWindowAttributes windowattr;
Display *x11display =QX11Info::display ();
if (XGetWindowAttributes(x11display,trayWindow,&windowattr) == 0)
{
trayWindow = 0;
return;
}
int x = 0;
int y = 0;
Window *w = &trayWindow;
if( XTranslateCoordinates(x11display,trayWindow,root,windowattr.x,windowattr.y,&x,&y,w) == True)
{
p_taskBarTop = y;
p_taskBarLeft = x;
p_taskBarRight = p_taskBarLeft + windowattr.width;
p_taskBarBottom = p_taskBarTop + windowattr.height;
p_taskBarHeight = windowattr.height;
p_taskBarWidth = windowattr.width;
} else
{
p_orientation = Unknown;
p_taskBarTop = 0;
p_taskBarLeft = 0;
p_taskBarRight = 0;
p_taskBarBottom = 0;
p_taskBarHeight = 0;
p_taskBarWidth = 0;
}
bool TaskBarDetector::appEventFilter(void *msg, long *result)
{
Q_UNUSED(result);
if ( !TaskBarDetector::hasInstance() )
return false;
TaskBarDetector *detector = TaskBarDetector::getInstance();
#ifdef Q_WS_WIN
MSG *seged = static_cast<MSG*>(msg);
if ( seged->message == WM_SETTINGCHANGE && seged->wParam == SPI_SETWORKAREA )
{
detector->processDetectEvent();
return false;
}
return false;
#endif
#ifdef Q_WS_X11
XEvent *xevent = static_cast<XEvent*> (msg);
if ( xevent->type == PropertyNotify )
{
XPropertyEvent xpe = xevent->xproperty;
char * ch_atom_name = XGetAtomName(QX11Info::display(),xpe.atom);
QString atom_name = QString(ch_atom_name).trimmed ();
if ( atom_name == "_NET_WORKAREA" )
{
detector->processDetectEvent ();
return false;
}
}
return false;
#endif
}
}
The system tray is not necessarily a window per se. In KDE, this is just an area in the taskbar (and it is unrelated to the _NET_SYSTEM_TRAY_S%i selection owner).
You may want to try embedding a tray icon and getting its geometry, then display your widget "near" said icon (for some reasonable value of "near"). You can delete the icon once you know its geometry (but then if the user moves the tray, you won't know its new coordinates).
This is not 100% reliable, as the tray is in no way obliged to show all icons you can throw at it. Also, not visually pleasing because of the icon flicker. But it's better than nothing.