-1

I have a simple little console game which heavily relies on user input to move around a game board. Originally, we were implementing standard input and dealing with having to press enter for each move; However, we are now looking into platform specific user input methods so we can stick to moving on char press instead of waiting for an enter keypress.

To do this, we've set up our environment like so:

#if defined(_WIN32) || defined(_WIN64) || defined(_WINDOWS_)
    #define PLATFORM_NAME "windows" // Windows
    #include <conio.h>
#elif defined(__APPLE__) || defined(__linux__)
    #define PLATFORM_NAME "unix"
#endif

we plan to use _getch() when a windows platform is detected, otherwise use getchar() for unix based.

currently we have our input calls set up like so:

void handleKeybinds() {
    char ascii = 0;
    if (PLATFORM_NAME == "windows") {
        ascii = tolower(_getch());
    } else {
        system("/bin/stty raw");
        ascii = tolower(getchar());
        system("/bin/stty cooked");
    }
    //move player
}

this works completely fine when compiling on windows (seeing as how conio.h is compatible) however, results in an undefined _getch() since conio is not included as a header file on a linux server. How would we make the compiler completely ignore this line when on anything other than windows, similarly to how the header only includes conio.h when on a windows system.

Thank you!

Bryce Hahn
  • 63
  • 1
  • 11
  • 1
    Write a function that calls the OS-specific stuff and have preprocessor directives in the body so that the compiler only sees the definition that is right for the platform. Also see https://wiki.c2.com/?StringlyTyped. Note that you're comparing two string literals using `==`, which isn't guaranteed to work since it compares the memory address of the strings. Compilers may store identical strings in the same place but it isn't guaranteed to happen. – eesiraed May 30 '20 at 21:37
  • @BessieTheCow This is exactly what I was looking for thank you so much! I have updated my post with an answer on your solution. – Bryce Hahn Jun 01 '20 at 20:46

1 Answers1

0

Thanks to BessieTheCow for the help! I got my user input working on both platforms! As mentioned above in their comment, I have moved the platform define checking to where the input is being recorded, which allows for the compiler to ignore the undeclared methods on the alternate platforms!

char GameBoard::getInputs() {
    char ascii = 0;
    #if defined(_WIN32) || defined(_WIN64) || defined(_WINDOWS_)
        ascii = tolower(_getch());
    #else
        system("/bin/stty raw");
        ascii = tolower(getchar());
        system("/bin/stty cooked");
    #endif

    return ascii;
}

Thanks for the help!

Bryce Hahn
  • 63
  • 1
  • 11