I'm writing a simple console game and I'm having problems with console flickering (i think system("cls") might be the issue?). I tried using double buffers but I messed it up I guess.I know Move() function doesnt work fully correct but it's enough to show movement on console. I'm also unsure about kbhit and getch, since usage of these is not recommended. What are some good alternatives?
void Snake::DrawBuffer()
{
for (int i = 0; i < HEIGHT; i++)
{
for (int j = 0; j < WIDTH; j++)
{
std::cout << buffer[WIDTH * i + j];
}
std::cout << '\n';
}
}
void Snake::WriteNextBuffer()
{
for (int i = 0; i < WIDTH * HEIGHT; i++)
nextbuffer[i] = ' ';
for (int i = 0; i < length; i++)
nextbuffer[body[i]] = 'o';
}
void Snake::WriteBuffer()
{
for (int i = 0; i < WIDTH * HEIGHT; i++)
{
buffer[i] = nextbuffer[i];
}
}
void Snake::Move()
{
char key;
if (_kbhit())
key = _getch();
else
key = lastkey;
switch (key)
{
case 'w':
if (lastkey != 's')
{
body.pop_back();
body.emplace(body.begin(), head - WIDTH);
}
break;
case 's':
if (lastkey != !'w')
{
body.pop_back();
body.emplace(body.begin(), head + WIDTH);
}
break;
case 'a':
if (lastkey != 'd')
{
body.pop_back();
body.emplace(body.begin(), head - 1);
}
break;
case 'd':
if (lastkey != 'a')
{
body.pop_back();
body.emplace(body.begin(), head + 1);
}
break;
}
head = body[0];
lastkey = key;
}
void Snake::Frame()
{
Move();
WriteNextBuffer();
WriteBuffer();
DrawBuffer();
}
void Snake::Game()
{
while (1)
{
Frame();
system("cls");
}
}