问题
I am trying to make a simple snake game on console. I am using an int matrix to store all the data (borders, snake, food to eat) at their exact location.
I use this main code for now to run the program :
int main()
{
int tab[28][120];
create(tab, 28, 120);
paint(tab, 28, 120);
char i = '1';
char direction = 'R';
while(i != 'q')
{
if (kbhit())
i =getch();
translate(tab, direction, 28, 120);
paint(tab, 28, 120);
Sleep(300);
}
}
The main problem being, every time I repaint the matrix, it stutters. I tried putting the if(kbhit())
statement in a for()
loop with another paint()
call while taking of the Sleep(300)
to speed up the paint process but it still stutters, just faster.
Would using threads help ? I am not good at understanding them.
here is the whole program that goes with the main for those who want to test it:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <Windows.h>
void paint(int tab[28][120], int ligneMax, int colonneMax)
{
system("cls");
for (int i = 0; i < ligneMax; i++)
{
for (int j = 0; j < colonneMax; j++)
{
printf("%c", tab[i][j]);
}
printf("\n");
}
}
void create(int tab[28][120], int Nbligne, int Nbcolonne)
{
int randligne = rand() % 26 + 1;
int randcols = rand() % 118 + 1;
for (int i = 0; i < Nbligne; i++)
{
for (int j = 0; j < Nbcolonne; j++)
{
tab[i][j] = ' ';
if (i == 0 || i == Nbligne - 1)
tab[i][j] = 205;
if (j == 0 || j == Nbcolonne - 1)
tab[i][j] = 186;
if (i == 0 && j == 0)
tab[i][j] = 201;
if (i == 0 && j == Nbcolonne - 1)
tab[i][j] = 187;
if (i == Nbligne - 1 && j == 0)
tab[i][j] = 200;
if (i == Nbligne - 1 && j == Nbcolonne - 1)
tab[i][j] = 188;
if (i == 14 && j == 60)
tab[i][j] = 254;
if (i == 14 && j == 59)
tab[i][j] = 184;
if (i == 14 && j == 58)
tab[i][j] = 184;
if (i == randligne && j == randcols)
tab[i][j] = 176;
}
}
}
void translate(int tab[28][120], char direction, int Nbligne, int Nbcolonne)
{
if (direction == 'R')
{
for (int i = 0; i < Nbligne; i++)
{
for (int j = 0; j < Nbcolonne; j++)
{
if (tab[i][j] == 254)
{
tab[i][j] = 184;
tab[i][j + 1] = 254;
goto stop;
}
}
}
stop: NULL;
}
}
I am aware the translate function is complete (it only moves the head right for now), but it does matter on the present issue.
来源:https://stackoverflow.com/questions/50119458/c-console-repainting-stuttering-not-fluid