0

I’m trying to write a program that makes the you have to press the 'A' key when the X moves to the middle. I've managed to get the X to move, but I don't know how to make it check if you pressed 'A' at the write time, and also recognize if you press it at the wrong time or you don't press it at all. How would I do that? (The program below is just a test program)

TL;DR how would I make it so you have to press the 'A' key when 'X' is in the center of the vector?

Sorry if this is a dumb question.

#include <iostream>
#include <vector>
#include <thread>
#include <chrono>

int main() {
    std::vector <char> hi = {'X','O','O','O','O','O','O','O'};
    for (int i = 0; i < hi.size() - 1; i++) {
        for (int i = 0; i < hi.size() - 1; i++) {
            std::cout << hi[i];
        }
        
        char temp = hi[i + 1];
        hi[i + 1] = hi[i];
        hi[i] = temp;
        
        std::this_thread::sleep_for (std::chrono::seconds(1));
        std::cout << std::endl << "\E[2J\E[2H";
    }
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • 4
    First you need to find a way how to detect a keypress with your specific OS environment. – πάντα ῥεῖ Sep 30 '22 at 14:00
  • 2
    ncurses might help you with the reading, then depending on your requirements you can just have a separate thread for reading the input or poll for a key being pressed in the main thread – Alan Birtles Sep 30 '22 at 14:09
  • 2
    Standard C++ library does not have the capabilities you need, out of the box. You'll need a support library, like ncurses, or your use your operating system's API to be able to implement the behavior you are looking for. – Eljay Sep 30 '22 at 14:10
  • Use a timer if you can, and find a way detect keypress as @πάνταῥεῖ said. For example QT has a module that counts x seconds and then executes a command that you give while not interrupting the flow. So basically the structure can be: start counting to 3 and move on, look for a keypress, and when the timer is done counting stop what you're doing and move the X. I do not know how can you do that nor if its possible to do that but it can help. –  Sep 30 '22 at 14:11
  • If you're looking for a simple way of doing this without using additional libraries like ncurses, you may be able to get away with using system("stty raw") to set the terminal to "raw" mode. This means it will send the input without the user having to press enter and you can read up on it [from cwhiii's post here.](https://stackoverflow.com/questions/421860/capture-characters-from-standard-input-without-waiting-for-enter-to-be-pressed) Please note that it is bad practice to use system() since it introduces security vulnerabilities, (and slow) however, for a personal app this should be fine. – Shades Sep 30 '22 at 15:21

0 Answers0