I’m writing a little snake in C++ for this tutorial. Faced a problem like this that I need to use kbhit ()
and getch ()
to read user input. These capabilities are available in the conio.h
library, which is not available on Linux. Also, I tried this , but it didn’t help, the program just stopped when nothing happened.
I would like to know how to implement this on Linux, or are there any alternatives to this library?
Code:
# include & lt; iostream & gt;
#include & lt; conio.h & gt;
using namespace std;
bool GameOver;
const int height = 20;
const int width = 20;
int x, y, fruit_x, fruit_y, score;
enum eDirection {STOP, RIGHT, LEFT, UP, DOWN};
eDirection dir;
void setup () {
GameOver = false;
dir = STOP;
x = width / 2 - 1;
y = height / 2 - 1;
fruit_x = rand ()% width;
fruit_y = rand ()% height;
score = 0;
}
void draw () {
system ("clear");
for (int i = 0; i & lt; width; i ++)
{
cout & lt; & lt; "#";
}
cout & lt; & lt; endl;
for (int i = 0; i & lt; height; i ++)
{
for (int j = 0; j & lt; width; j ++)
{
if (j == 0 || j == width - 1)
{
cout & lt; & lt; "#";
}
if (i == y & amp; & amp; j == x)
{
cout & lt; & lt; "0";
}
else if (i == fruit_y & amp; & amp; j == fruit_x)
{
cout & lt; & lt; "F";
}
else
{
cout & lt; & lt; "";
}
}
cout & lt; & lt; endl;
}
for (int i = 0; i & lt; width; i ++)
{
cout & lt; & lt; "#";
}
cout & lt; & lt; endl;
}
void input () {
if (_kbhit)
{
switch (getch ())
{
case 'a':
dir = LEFT;
break;
case 'd':
dir = RIGHT;
break;
case 'w':
dir = UP;
break;
case 's':
dir = DOWN;
break;
case 'x':
GameOver = true;
break;
}
}
}
void logic () {
switch (dir)
{
case LEFT:
x--;
break;
case RIGHT:
x ++;
break;
case UP:
y--;
break;
case DOWN:
y ++;
break;
}
}
int main () {
setup ();
while (! GameOver)
{
draw ();
input ();
logic ();
}
}
Answer 1
Got a response on English StackOverflow from javad m
Step 1: Open a terminal and do the following:
sudo apt-get update & amp; & amp; upgrade sudo apt-get install git git clone https://github.com/zoelabbb/conio.h.git cd conio.h
Step 2:
sudo cp conio.h / usr / include /
or (step 2)
In the GUI using the
open-as-administrator
package:Copy file conio.h - & gt; !! copy the file, not the folder !! Go to / usr / include / Right click on / usr / include / Select "Open as administrator" Paste the file conio.h
Finally , after steps 1 and 2 , you can use
#include & lt; conio.h & gt;
in your code.