Skip to main content

Correction

#include <stdio.h>
#define ROWS 10
#define COLS 10

void initGrille(char grille[ROWS][COLS], int robotX, int robotY) {
    for (int i = 0; i < ROWS; i++)
        for (int j = 0; j < COLS; j++)
            grille[i][j] = '.'; // Remplir la grilleimage.png

    // Ajouter quelques obstacles
    grille[1][1] = 'X'; grille[3][5] = 'X'; grille[6][7] = 'X';
    grille[robotX][robotY] = 'R'; // Placer le robot
}image.png

void afficherGrille(char grille[ROWS][COLS]) {
    for (int i = 0; i < ROWS; i++) {
        for (int j = 0; j < COLS; j++)
            printf("%c ", grille[i][j]);
        printf("\n");
    }
}

void deplacerRobot(char grille[ROWS][COLS], int *robotX, int *robotY, int direction) {
    grille[*robotX][*robotY] = '.'; // Retirer l'ancien emplacement
    int newX = *robotX, newY = *robotY;

    switch (direction) {
        case 'H': newX--; break; // Haut
        case 'B': newX++; break; // Bas
        case 'G': newY--; break; // Gauche
        case 'D': newY++; break; // Droite
    }

    // Vérifier le mouvement
    if (newX >= 0 && newX < ROWS && newY >= 0 && newY < COLS && grille[newX][newY] != 'X') {
        *robotX = newX; *robotY = newY; // Mettre à jour la position
    } else {
        printf("Mouvement impossible (obstacle ou hors de la grille).\n");
    }

    grille[*robotX][*robotY] = 'R'; // Remettre le robot
}

int main() {
    char grille[ROWS][COLS];
    int robotX = ROWS / 2, robotY = COLS / 2; // Position initiale

    initGrille(grille, robotX, robotY);
    afficherGrille(grille);

    char commande;
    while (1) {
        printf("\nEntrez une commande (H = haut, B = bas, G = gauche, D = droite, Q = quitter) : ");
        scanf(" %c", &commande);

        if (commande == 'H' || commande == 'B' || commande == 'G' || commande == 'D') {
            deplacerRobot(grille, &robotX, &robotY, commande);
        } else if (commande == 'Q') {
            break;
        } else {
            printf("Commande non reconnue.\n");
        }
        afficherGrille(grille);
    }
    return 0;
}