Reputation: 11
I'm a student currently developing a version of Othello for a university project.
It is mostly finalized so I'm looking for things I can improve on. One of these is making the board (which is printed to stdout) just replace the previous one with each play, ensuring the terminal doesn't move.
Below is the most recent attempt at doing so:
char c = ' ';
fflush(stdout);
contaPecas(e, pecas);
printf("\n\r* X-%d |SCORE| O-%d * \n\r\n\r 1 2 3 4 5 6 7 8 "" | N <peça>para novo jogo "
"em que o primeiro a jogar é o jogador com peça.\n\r", pecas->x, pecas->y);
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (j == 0)
printf("%d ", i+1);
if (opcao == 1 && verificaValida(i,j,turno) == 1)
c = '.';
else if (opcao == 2 && (*turno)->N != 0 && i == sugestao->y && j == sugestao->x)
c = '?';
else
switch (e.grelha[i][j]) {
case VALOR_O:
c = 'O';
break;
case VALOR_X:
c = 'X';
break;
case VAZIA:
c = '-';
break;
}
printf("%c ", c);
}
switch (i) {
case 0:
printf(" | A para novo jogo contra bot. O jogador comeca com peça X.\n\r");
break;
case 1:
printf(" | L<ficheiro>para ler um jogo de ficheiro.\n\r");
break;
case 2:
printf(" | E <ficheiro> escrever em ficheiro estado do jogo.\n\r");
break;
case 3:
printf(" | J<L,C>jogar peça atual na posição (l,c).\n\r");
break;
case 4:
printf(" | S para imprimir um ponto ‘.’nas posições com jogada válida.\n\r");
break;
case 5:
printf(" | H para sugestão de jogada. Deve ser colocado um ‘?’no sitio sugerido.\n\r");
break;
case 6:
printf(" | U para desfazer a última jogada(Undo).\n\r");
break;
case 7:
printf(" | Q para sair do jogo.\n\r");
break;
}
}
if (e.peca == 0) printf("\n\r");
else if (e.peca == VALOR_X) printf("Turn: X\n\r\n\r");
else printf("Turn: O\n\r\n\r");
if (opcao == 2 && (*turno)->N != 0)
printf("A melhor jogada é %d %d.\n\r", sugestao->y+1, sugestao->x+1);
}
I expected with fflush(stdout) it would erase the previous prints, and with '\r' that it would just write in the same place as it had previously, but it keeps writing under what was already written and making the terminal move. Any ideas on what I could do to fix this?
Upvotes: 0
Views: 94
Reputation: 41017
Even using \r
, the standard functions (scanf
, fgets
...) reads from stdin
until a Return is pressed, in these cases the cursor always goes down (consumes \n
) to the next line of the console.
You need to use some specialized library, you can check ncurses
on unixes or the console API in windows.
Another option (if you are under a vt100 compatible terminal) is using console codes:
#define gotoxy(x,y) printf("\033[%d;%dH", (x), (y))
(man console_codes
to get more info)
Upvotes: 2