I have created a snake game that works but I believe since I used the system("cls"); function it has to reload the game every second causing an extreme glitch. Every time the screen reloads, it flickers. How do I fix this? The part of the code I think is causing this issue is below.
void Draw()
{
system("cls"); //system("clear");
for (int i = 0; i < width +2; i++)
cout << "-";
cout << endl;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
if (j == 0)
cout << "|";
if (i == y && j == x)
cout << "O";
else if (i == fruitY && j == fruitX)
cout << "o";
else
{
bool print = false;
for (int k = 0; k < nTail; k++)
{
if (tailX[k] == j && tailY[k] == i)
{
cout << "o";
print = true;
}
}
if (!print)
cout << " ";
}
if (j == width - 1)
cout << "|";
}
cout << endl;
}
for (int i = 0; i < width + 2; i++)
cout << "-";
cout << endl;
cout << "Score:" << score << endl;
cout << endl;
cout << "use arrow keys to control the snake";
}
You should use code tags to post code so that it's readable.
Aren't you writing spaces to all the blank parts of the screen anyway? Do you even need the system("cls")?
If you still get flickering, you can probably redraw the screen far more efficiently by only erasing what needs to be erased (e.g, the end of the tail) and writing only what needs to be drawn (e.g., the new head).
BTW, if you ignore people's responses, they will stop helping you.
or the (also nonstandard) gotoxy or similar function that let you update only the text that changed, and leave the rest in place, which is more efficient (less writing) and will clear up the flicker.
I think the gotoxy function would work well with this code, but I can't figure out how to fit it into my code. Would I add it in front of parts of the code that change when the screen updates (like the tail and food placement?)
I got rid of the glitching by deleting the system("cls") and adding a cin.get() but now the screen looks great, but the snake wont move at all. Any ideas? Thank you!
Your gotoxy function is empty. And you don't explicitly initialize your global x and y variables, which means they will automatically be initialized to 0 (but maybe that's what you want).