-3

I am making a chess game in C. It needs to be strickly c. But my chess pieces are not responding to movement as they should. The movement of the pieces is defined by coordinates.

I think the problem should be in this function:

// função mover peça com problema encontrar
int moverPeca(int linOri, int linDes, int colOri, int colDes) {
    int mover = 0;
    char peca;
    //deslocamento vertical e deslocamento horizontal (nº linhas que avança)
    int dV = abs(linDes - linOri);
    int dH = abs(colDes - colOri);

    if ((linOri >= 0 && linOri < 8 && colOri >= 0 && colOri < 8) &&
        (linDes >= 0 && linDes < 8 && colDes >= 0 && colDes < 8)) {
        peca = xadrez[linOri][colOri];

        // definição do movimento apropriado da peça Torre - mexe na vertical e na horizontal quantas casas quiseres
        if ((peca == 'T' || peca == 't') && (dV == 0 || dH == 0)) {

            mover = 1;
        }

        // definição do movimento apropriado da peça Bispo - só mexe na diagonal quantas casas quiseres
        if ((peca == 'B' || peca == 'b') && (dV == dH)) {

            mover = 1;
        }

        // definição do movimento apropriado da peça Cavalo mexe em L 2/3 ou 3/2
        if ( (peca == 'C' || peca == 'c') && 
            ( (dV == 1 && dH == 2) || (dV == 2 && dH == 1) ) ) {

            mover = 1;
        }

        // definição do movimento apropriado da peça Q Rainha anda de todas as formas H e V
        if ( (peca == 'Q' || peca == 'q') && 
            ( (dV == dH) || (dV == 0) || (dH == 0) ) ) {

            mover = 1;
        }

        // definição do movimento apropriado da peça K REi só anda 1 casa na V ou H ou Diagonal
        if ( (peca == 'K' || peca == 'k') && 
            ( (dV >= 0 && dV <= 1) && (dH >= 0 && dH <= 1 ) ) ) {

            mover = 1;
        }

        // definição do movimento apropriado da peça p peão pode andar 2 casas a 1 vez e depois anda sempre só uma e come na diagonal
        if ((peca == 'p') && ( (linOri - linDes) == 1) && (dH == 0) ) {

            mover = 1;
        }

        // definição do movimento apropriado da peça p peão pode andar 2 casas a 1 vez e depois anda sempre só uma e come na diagonal

        if ((peca == 'P') && ( (linDes - linOri) == 1) && (dH == 0) ) {

            mover = 1;
        }


        if (mover) {
            xadrez[linDes][colDes] = xadrez[linOri][colOri];
            xadrez[linOri][colOri] = ' ';
        }
        return 1;
    }
    else {
        return 0;
    }
}

This is the code I have so far:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

// Matriz de 8 por 8 para fazer os quadrados do jogo
char xadrez[8][8] = {
    { 'T', 'C', 'B', 'Q', 'K', 'B', 'C', 'T'}, //Pretas em maiúsculas
    { 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'},
    { ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
    { ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
    { ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
    { ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
    { 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'},//Brancas em minúsculas
    { 't', 'c', 'b', 'q', 'k', 'b', 'c', 't'}

};

// Função para pintar a tela e o texto dentro dos quadrados
void pintarTelaTexto() {
    system("CLS");// serve para limpar a tela
    //linha - coluna e r para controle da casa central onde vamos por a letra
    int lin, col, r;

    for (lin=0; lin < 8; lin++) {

        for (r=0; r < 3; r++) {
            for (col=0; col < 8; col++) {
                //char letra com problema nao aparece na casa central apa

                char peca = xadrez[lin][col];
                char letra = ((lin + col) % 2 == 0) ? '\xB2' : ' ';
                letra = (r == 1 && peca != ' ') ? peca : letra; // operador ternário
                    if ((lin + col ) % 2 == 0) {
                        printf("\xB2\xB2%c\xB2\xB2", letra);
                    }
                    else {
                        // %c para inserção da letra
                        printf("  %c  ", letra);
                    }
            }
            printf("\n");
        }
    }
}

// função mover peça com problema encontrar
int moverPeca(int linOri, int linDes, int colOri, int colDes) {
    int mover = 0;
    char peca;
    //deslocamento vertical e deslocamento horizontal (nº linhas que avança)
    int dV = abs(linDes - linOri);
    int dH = abs(colDes - colOri);

    if ((linOri >= 0 && linOri < 8 && colOri >= 0 && colOri < 8) &&
        (linDes >= 0 && linDes < 8 && colDes >= 0 && colDes < 8)) {
        peca = xadrez[linOri][colOri];

        // definição do movimento apropriado da peça Torre - mexe na vertical e na horizontal quantas casas quiseres
        if ((peca == 'T' || peca == 't') && (dV == 0 || dH == 0)) {

            mover = 1;
        }

        // definição do movimento apropriado da peça Bispo - só mexe na diagonal quantas casas quiseres
        if ((peca == 'B' || peca == 'b') && (dV == dH)) {

            mover = 1;
        }

        // definição do movimento apropriado da peça Cavalo mexe em L 2/3 ou 3/2
        if ( (peca == 'C' || peca == 'c') && 
            ( (dV == 1 && dH == 2) || (dV == 2 && dH == 1) ) ) {

            mover = 1;
        }

        // definição do movimento apropriado da peça Q Rainha anda de todas as formas H e V
        if ( (peca == 'Q' || peca == 'q') && 
            ( (dV == dH) || (dV == 0) || (dH == 0) ) ) {

            mover = 1;
        }

        // definição do movimento apropriado da peça K REi só anda 1 casa na V ou H ou Diagonal
        if ( (peca == 'K' || peca == 'k') && 
            ( (dV >= 0 && dV <= 1) && (dH >= 0 && dH <= 1 ) ) ) {

            mover = 1;
        }

        // definição do movimento apropriado da peça p peão pode andar 2 casas a 1 vez e depois anda sempre só uma e come na diagonal
        if ((peca == 'p') && ( (linOri - linDes) == 1) && (dH == 0) ) {

            mover = 1;
        }

        // definição do movimento apropriado da peça p peão pode andar 2 casas a 1 vez e depois anda sempre só uma e come na diagonal

        if ((peca == 'P') && ( (linDes - linOri) == 1) && (dH == 0) ) {

            mover = 1;
        }


        if (mover) {
            xadrez[linDes][colDes] = xadrez[linOri][colOri];
            xadrez[linOri][colOri] = ' ';
        }
        return 1;
    }
    else {
        return 0;
    }
}

// MAIN
int main() {
    int linOri, linDes, colOri, colDes;
    while (1) {
        pintarTelaTexto();
        printf("Informe a linha e coluna de origem: ");
        scanf("%d %d", &linOri, &colOri );
        printf("\nInforme a linha e coluna de destino: ");
        scanf("%d %d", &linDes, &colDes );
        int resultado = moverPeca(linOri, colOri, linDes, colDes);
        if (resultado != 1) {
            switch (resultado) {
            case 9: printf("A peça não pode ser usada assim"); getch(); break;
            case 0: printf("\nERRO : Coordenadas Inválidas"); getch(); break;
            case 1: break;
            }
        }

    }
    getch();
    return 0;

}
Diana Moura
  • 31
  • 11
  • The posted code contains several non-portable statements. IE. `system("CLS");`, `getch()` The result is the code will not run (or even compile) on OSs other than windows – user3629249 Jan 01 '19 at 18:35
  • OT: regarding statements like: `scanf("%d %d", &linOri, &colOri );` Always check the returned value (not the parameter values) to assure the operation was successful – user3629249 Jan 01 '19 at 18:37
  • regarding: `case 1: break;` the possibility of the value (at this point in the code) is 0 because of the proceeding: `if (resultado != 1)` Also, should always have a `default:` case, to handle unexpected values – user3629249 Jan 01 '19 at 18:39
  • OT: for ease of readability and understanding: follow the axiom: *only one statement per line and (at most) one variable declaration per statement.* – user3629249 Jan 01 '19 at 18:42

1 Answers1

2

Your moverPeca function expects parameters in the following order:

int moverPeca(int linOri, int linDes, int colOri, int colDes)

That is line-origin, line-destination, column-origin, and column-destination, in that order.

But you are invoking it with:

int resultado = moverPeca(linOri, colOri, linDes, colDes);

The result is that the colOri and linDes are getting swapped in the function invocation. So instead of attempting to move the pawn from [6,4] to [5,4], the code attempts to move the pawn from [6,4] to [4,4].

Simple fix is to declare moverPeca like this:

int moverPeca(int linOri, int colOri, int linDes, int colDes)
selbie
  • 100,020
  • 15
  • 103
  • 173
  • you are the officially nominated code-hero of the day! It worked thank you so much! I didn't know the order of the parameters could be so important – Diana Moura Jan 01 '19 at 19:46
  • 1
    @DianaMoura - I am happy to help. But I need to be honest - coming to stackoverflow to enlist others to debug your program is not going to enable you to grow your skills and get more proficient. Parameter ordering is a fundamental concept of almost all programming languages. And mismatched parameter ordering is a common mistake that even experienced engineers make. But you should have been able to diagnose this bug yourself. Simply by adding additional "printf" statements into your code to display the values of variables and program flow would have solved this problem for you. – selbie Jan 02 '19 at 03:13
  • Thanks for the tips @selbie I will keep them in mind. Also it's my first time learning a programming language (1st subject, 1st year) so I am not used to debugging yet. Will definitely learn it. Did send it to my teacher as well though. – Diana Moura Jan 03 '19 at 20:28