1
I’m writing a Sudoku game with C and ncurses, below follows the code of a function that receives a pointer to a variable (ch) which stores typed key with function getch(), if the number already exists horizontally, vertically or in the block returns false, if not true.
Doubt:
- In the code, if you replace
*ch-'0'for*ch, it stops working correctly, returnsfalseonly in numbers added by user, ignoring the standards, the behavior also changes according to the cursor position. Why? What is the difference?
Code:
bool
num(int *ch)
{
// g.y e g.x Armazenam a posição do cursor no array
// g.r_board Array de referência
if (g.r_board[g.y][g.x] > 0)
{
hide_banner(); // Esconde frase da tela
show_banner("Número fixo"); // Mostra uma frase na tela
show_cursor(); // Move o cursor pra posição original
return false;
}
// Verifica se tem número igual na horizontal
// g.board Array que armazena números do jogo
for (int i = 0; i < 9; i++)
if (g.board[g.y][i] == (*ch-'0'))
{
hide_banner();
show_banner("Número igual horizontal");
show_cursor();
return false;
}
// Verifica se tem número igual na vertical
for (int i = 0; i < 9; i++)
if (g.board[i][g.x] == (*ch-'0'))
{
hide_banner();
show_banner("Número igual vertical");
show_cursor();
return false;
}
// Verifica se tem número igual dentro do bloco
for (int i = (g.y/3)*3, j = i+3; i < j; i++)
for (int k = (g.x/3)*3, l = k+3; k < l; k++)
if (g.board[i][k] == (*ch-'0'))
{
hide_banner();
show_banner("Número igual bloco");
show_cursor();
return false;
}
return true;
}
I arrived at this code on trial-error basis, I wrote several. The curious thing is that if you write
*ch - 0,*chor anything other than*ch-'0'does not work, do not understand why, does not make sense, reading all the code does not make sense even,*chshouldn’t it work? I mean, the whole value within the variable is being compared to the integer values of the array.– Matheus
If you do
30 - 20and wants the result10, if you do only30will result in10?– Maniero
Got it, the function getch() stores the whole number of the ascii table and not the literal number, for example, digit 1 and the function stores 49 in the variable. The documents I read about this function didn’t say that, so I let it go unnoticed.
– Matheus