Thread: Battleship in C: Adding randomic boats

  1. #1
    Registered User
    Join Date
    Dec 2017
    Posts
    3

    Battleship in C: Adding randomic boats

    Good night!

    I'm in a process to improved my Battleship which I develop using C language and one the things I want to do is who the boats are put in the arena in a randomic way. But there some boats like a Hidro-plane who occupy three spaces forming and V even in horizontal and vertical way and there more than one to add. My question are who can I add? I try somethings, but I fail.

    Here is what I managed to do.

    SinglePlayer.zip

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,743
    It's hard to say what we should be commenting on when there are half a dozen source files, each with a main(), and each with the problem in various stages of evolution.

    How To Become A Hacker
    Writing code in something other than English significantly cuts down on the number of people who can help you.

    You're still using fflush(stdin) and gets()


    None of your functions neither accept parameters, nor return results.
    Perhaps introducao() would be a lot simpler if it had the help of a sub-function to do the loop for you, with a parameter being the string you want to output.

    Both creditos() and menu() call themselves and each other recursively. This problem can be solved by making the "input and decision" done somewhere else.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Dec 2017
    Posts
    3
    Thanks for reply me, well I call each function in his own because if other button is pressed the function Introducao run.

    Sorry for code is written in portuguese, I forget that, was trying to find help in my languague forum who I forget about that,

    Now about gets() and fflush(stdin) in don't knew about it. I understand the why don't uses gets() anymore, but still don't understand about fflush(stdin).

  4. #4
    Registered User
    Join Date
    Dec 2017
    Posts
    1,155
    Randomic placementation of battleshipian boatality can be effectuated thuswise:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    #define SIZE 10
    #define EMPTY '-'
    
    /*
    // If you want to try using color codes.
    void print_board(char board[][SIZE]) {
        //         A  B  C  D  E  F  G  H   I   J   K   L   M   N
        int c[] = {31,32,33,34,35,36,37,131,132,133,134,135,136,137};
        for (int row = 0; row < SIZE; row++) {
            for (int col = 0; col < SIZE; col++) {
                char ch = board[row][col];
                if (ch)
                    printf("\033[%d;%dm", c[ch-'A'] / 100, c[ch-'A'] % 100);
                printf(" %c ", ch ? ch : EMPTY);
                if (ch)
                    printf("\033[m");
            }
            printf("\n");
        }
    }
    */
    
    void print_board(char board[][SIZE]) {
        for (int row = 0; row < SIZE; row++) {
            for (int col = 0; col < SIZE; col++) {
                char ch = board[row][col];
                printf(" %c ", ch ? ch : EMPTY);
            }
            printf("\n");
        }
    }
    
    int line_fits(char board[][SIZE], int sz, int x, int y, int dx, int dy) {
        while (sz-- > 0) {
            if (x >= SIZE || y >= SIZE || board[y][x])
                return 0;
            x += dx;
            y += dy;
        }
        return 1;
    }
    
    void place_line(char board[][SIZE], char id, int sz) {
        int x, y, dx, dy;
    
        do {
            x = rand() % SIZE;
            y = rand() % SIZE;
            dx = dy = 0;
            if (rand() % 2 == 0)
                dx = 1;  // horizontal
            else
                dy = 1;  // vertical
        } while (!line_fits(board, sz, x, y, dx, dy));
    
        while (sz-- > 0) {
            board[y][x] = id;
            x += dx;
            y += dy;
        }
    }
    
    /*
    v's have 4 placement directions:
      0        1        2        3
                       *          *
    *   *      *         *      *
      *      *   *     *          *
    */
    
    void place_v(char board[][SIZE], int id) {
        // Relative offsets from middle point for each placement direction.
        struct {int dx, dy, ex, ey;} dir[4] = {
            {-1,-1, 1,-1}, {-1, 1, 1, 1}, {-1,-1,-1, 1}, { 1,-1, 1, 1} };
        int x, y, d, x1, y1, x2, y2;
    
        do {
            x = rand() % SIZE;
            y = rand() % SIZE;
            d = rand() % 4;
            y1 = y + dir[d].dy;
            x1 = x + dir[d].dx;
            y2 = y + dir[d].ey;
            x2 = x + dir[d].ex;
        } while (board[y][x] ||
                 y1 < 0 || y1 >= SIZE ||
                 x1 < 0 || x1 >= SIZE ||
                 y2 < 0 || y2 >= SIZE ||
                 x2 < 0 || x2 >= SIZE ||
                 board[y1][x1] ||
                 board[y2][x2]);
    
        board[y][x] = id;
        board[y1][x1] = id;
        board[y2][x2] = id;
    }
    
    int main() {
        char board[SIZE][SIZE] = {{0}};
        srand(time(NULL));
    
        place_v(board, 'A');
        place_v(board, 'B');
        place_v(board, 'C');
        place_line(board, 'D', 3);
        place_line(board, 'E', 5);
        place_line(board, 'F', 2);
        place_line(board, 'G', 4);
        place_line(board, 'H', 1);
        place_line(board, 'I', 3);
    
        print_board(board);
    
        return 0;
    }
    The errors of great men are venerable because they are more fruitful than the truths of little men. - Nietzsche

  5. #5
    Registered User
    Join Date
    Dec 2017
    Posts
    3
    Hello guys,

    Thanks for reply me, I was late to response because I was find on web references to work. I managed to put the boats randomicaly, but I still have some issues

    -Array are input every time until program ends.
    -Array show where boats are put, instead start with '~' symbol and according to player put where to shot the array will showing what shot.
    -Player can't shoot

    I'm comment the code with variables translated and explain some functions. Hope can help understand better.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <locale.h>
    #include <windows.h>
    #include <time.h>
    
    #define ARENA 14 //Array weight
    #define AGUA '~' //Water in array
    #define ERRO 'X' //When the player miss a shot
    #define DESTROYER 'D'//When player hit a Destroyer
    #define SUBMARINO 'S'//When player hit a Submarine
    #define HIDROAVIAO 'H'//When player hit a Seaplane
    #define PORTAAVIAO 'P'//When player hit a aircraft carrier
    
    void limpaTela () //Use to clear screen
    {
    #ifdef __WIN32__
        system("CLS");
    #else
    //printf("\e[H\e[2J");
        system("clear");
    #endif
    }
    
    void limpaBuffer () //Use to clear buffer
    {
    #ifdef __WIN32__
        fflush(stdin);
    #else
        __fpurge(stdin);
    #endif
    }
    
    struct almirante //Player profile and dates
    {
        char nome[100];
        int placar;
        int disparos;
    };
    
    
    struct almirante jogador; //Player struct
    
    struct Embarcacoes //Player craft
    {
        int submarino;
        int destroyer;
        int hidroaviao;
        int portaaviao;
    };
    
    typedef struct Embarcacoes embarcacoes;
    
    embarcacoes qt_embarcacoes = {3, 3, 2, 2}; //Quantitifes of each player's craft receive
    
    int contador_de_barcos = 9; //Total of boats
    
    char campo[ARENA][ARENA]; //Show array in screen
    
    
    /*These 8 functions are used to define and put every boat on array
    direcao = direction
    linha = line
    coluna = column
    l = line
    c = column
    */
    int verifica_submarino (int direcao, int linha, int coluna, char A[ARENA][ARENA])
    {
        int l, c;
    
        if(direcao)
        {
            for(c = coluna; c <= coluna + 1; c++)
            {
                if(c >= ARENA || A[linha][c] == SUBMARINO)
                {
                    return 0;
                }
    
            }
        } else
        {
            for(l = linha; l <= linha + 1; l++)
            {
                if(l >= ARENA || A[l][coluna] == SUBMARINO)
                    return 0;
            }
        }
        return 1;
    }
    
    void imprime_submarino (int direcao, int linha, int coluna, char A[ARENA][ARENA])
    {
        int l, c;
    
        if(direcao)
        {
            for(c = coluna; c < coluna + 1; c++)
            {
                A[linha][c] = SUBMARINO;
            }
        } else
        {
            for(l = linha; l < linha + 1; l++)
            {
                A[l][coluna] = SUBMARINO;
            }
        }
    
        if(A == campo)
        {
            qt_embarcacoes.submarino--;
        }
    }
    
    
    int verifica_destroyer (int direcao, int linha, int coluna, char A[ARENA][ARENA])
    {
        int l, c;
    
        if(direcao)
        {
            for(c = coluna; c <= coluna + 3; c++)
            {
                if(c >= ARENA || A[linha][c] == DESTROYER)
                {
                    return 0;
                }
    
            }
        } else
        {
            for(l = linha; l <= linha + 3; l++)
            {
                if(l >= ARENA || A[l][coluna] == DESTROYER)
                    return 0;
            }
        }
        return 1;
    }
    
    void imprime_destroyer (int direcao, int linha, int coluna, char A[ARENA][ARENA])
    {
        int l, c;
    
        if(direcao)
        {
            for(c = coluna; c < coluna + 3; c++)
            {
                A[linha][c] = DESTROYER;
            }
        } else
        {
            for(l = linha; l < linha + 3; l++)
            {
                A[l][coluna] = DESTROYER;
            }
        }
    
        if(A == campo)
        {
            qt_embarcacoes.destroyer--;
        }
    }
    
    
    int verifica_hidroaviao (int direcao, int linha, int coluna, char A[ARENA][ARENA])
    {
        int l, c;
    
        if(direcao)
        {
            for(c = coluna; c <= coluna + 2; c++)
            {
                if(c >= ARENA || A[linha][c] == HIDROAVIAO)
                {
                    return 0;
                }
    
            }
        } else
        {
            for(l = linha; l <= linha + 2; l++)
            {
                if(l >= ARENA || A[l][coluna] == HIDROAVIAO)
                    return 0;
            }
        }
        return 1;
    }
    
    void imprime_hidroaviao (int direcao, int linha, int coluna, char A[ARENA][ARENA])
    {
        int l, c;
    
        if(direcao)
        {
            for(c = coluna; c < coluna + 2; c++)
            {
                A[linha][c] = HIDROAVIAO;
            }
        } else
        {
            for(l = linha; l < linha + 2; l++)
            {
                A[l][coluna] = HIDROAVIAO;
            }
        }
    
        if(A == campo)
        {
            qt_embarcacoes.hidroaviao--;
        }
    }
    
    
    int verifica_portaaviao (int direcao, int linha, int coluna, char A[ARENA][ARENA])
    {
        int l, c;
    
        if(direcao)
        {
            for(c = coluna; c <= coluna + 4; c++)
            {
                if(c >= ARENA || A[linha][c] == PORTAAVIAO)
                {
                    return 0;
                }
    
            }
        } else
        {
            for(l = linha; l <= linha + 4; l++)
            {
                if(l >= ARENA || A[l][coluna] == PORTAAVIAO)
                    return 0;
            }
        }
        return 1;
    }
    
    void imprime_portaaviao (int direcao, int linha, int coluna, char A[ARENA][ARENA])
    {
        int l, c;
    
        if(direcao)
        {
            for(c = coluna; c < coluna + 4; c++)
            {
                A[linha][c] = PORTAAVIAO;
            }
        } else
        {
            for(l = linha; l < linha + 4; l++)
            {
                A[l][coluna] = PORTAAVIAO;
            }
        }
    
        if(A == campo)
        {
            qt_embarcacoes.portaaviao--;
        }
    }
    
    /* The function haBarcos (Are there boats) is used to check if are still boats to put in array
    embarcacoes = craft
    */
    int haBarcos(int embarcacoes, char A[ARENA][ARENA])
    {
        switch(embarcacoes)
        {
        case 1:
            if(A == campo)
            {
                if(qt_embarcacoes.submarino == 0)
                {
                    return 0;
                }
            }
            break;
    
        case 2:
            if(A == campo)
            {
                if(qt_embarcacoes.destroyer == 0)
                {
                    return 0;
                }
            }
            break;
    
        case 3:
            if(A == campo)
            {
                if(qt_embarcacoes.hidroaviao == 0)
                {
                    return 0;
                }
            }
            break;
    
        case 4:
            if(A == campo)
            {
                if(qt_embarcacoes.portaaviao == 0)
                {
                    return 0;
                }
            }
            break;
        }
        return 1;
    }
    
    /* Select boats randomly and put in Array
    embarcacoes = craft
    linha = line
    coluna = column
    direcao = direction
    */
    void colherEmbarcacoes (char A[ARENA][ARENA])
    {
        int embarcacoes, linha, coluna, direcao = 0;
    
        srand((unsigned)time(NULL));
    
        do
        {
            embarcacoes = 1 + (rand() % 4);
            while(!haBarcos(embarcacoes, A))
            {
                 embarcacoes = 1 + (rand() % 4);
            }
    
    
        linha = 1 + (rand() % 14);
        coluna = 1 + (rand() % 14);
        direcao = 1 + rand() % 2;
    
        if(verificaEmbarcacoes(embarcacoes, direcao, linha, coluna, A))
        {
            imprime_embarcacoes(embarcacoes, direcao, linha, coluna, A);
            imprimeTabuleiro(A);
            contador_de_barcos--;
        }
    
        } while(contador_de_barcos);
    
    }
    /*
    */
    int verificaEmbarcacoes (int embarcacoes, int direcao, int linha, int coluna, char A[ARENA][ARENA])
    {
        switch(embarcacoes)
        {
        case 1:
            return verifica_submarino(direcao, linha, coluna, A);
        case 2:
            return verifica_destroyer(direcao, linha, coluna, A);
        case 3:
            return verifica_hidroaviao(direcao, linha, coluna, A);
        case 4:
            return verifica_portaaviao(direcao, linha, coluna, A);
        }
        return 0;
    }
    
    void imprime_embarcacoes (int embarcacoes, int direcao, int linha, int coluna, char A[ARENA][ARENA])
    {
        switch(embarcacoes)
        {
        case 1:
            imprime_submarino(direcao, linha, coluna, A);
            break;
        case 2:
            imprime_destroyer(direcao, linha, coluna, A);
            break;
        case 3:
            imprime_hidroaviao(direcao, linha, coluna, A);
            break;
        case 4:
            imprime_portaaviao(direcao, linha, coluna, A);
            break;
        }
    }
    
    /*Prepare the array*/
    void preparaTabuleiro ()
    {
        int l, c;
    
    
        for(l = 1; l < ARENA; l = l + 1)
        {
            for(c = 1; c < ARENA; c = c + 1)
            {
                campo[l][c] = AGUA;
            }
            printf("\n");
        }
    
    
    }
    
    /*Print the array*/
    void imprimeTabuleiro (char A[ARENA][ARENA])
    {
        int l, c;
        if(A == campo)
        {
    
        for(l = 1; l < ARENA; l = l + 1)
        {
            for(c = 1; c < ARENA; c = c + 1)
            {
                printf(" \t%c", campo[l][c]);
            }
            printf("\n");
        }
    
        }
    }
    
    /* Input where to shot and conditions
    */
    void batalha_naval (int direcao, int linha, int coluna, char A[ARENA][ARENA])
    {
        int hidro_cont, porta_cont, des_cont;
        int vida_inimiga;
        int l, c;
    
        jogador.placar = 0;
        jogador.disparos = 46;
        vida_inimiga = 36;
        hidro_cont = 0;
        porta_cont = 0;
        des_cont = 0;
    
        imprimeTabuleiro(campo);
    
        //Condition to continue playing
        do
        {
    
            //Try
            printf("Almirante %s\n", jogador.nome); //Player Name
            printf("Disparo Restantes: %i/46\n", jogador.disparos); //Remaning shot
            printf("Vida Inimiga: %i/36\n\n", vida_inimiga); //Enemy health
            printf("Informe a linha: "); //Line where to shot
            scanf("%i", &l);
            printf("Informe a coluna: "); //Colunm where to shot
            scanf("%i", &c);
            printf("\n");
    
            //What happen to array when shot
            if(l >= 1 && l < ARENA && c >= 1 && c < ARENA  && campo[l][c] == AGUA)
            {
                switch(campo[l][c])
                {
                case 0:
                    campo[l][c] = ERRO;
                    imprimeTabuleiro(A);
                    jogador.disparos--;
                    printf("Errou\n");
                    break;
    
                case 1:
                    campo[l][c] = SUBMARINO;
                    imprimeTabuleiro(campo);
                    vida_inimiga--;
                    printf("Acertou!\n");
                    break;
    
                case 2:
                    campo[l][c] = HIDROAVIAO;
                    imprimeTabuleiro(campo);
                    vida_inimiga--;
                    hidro_cont = (hidro_cont == 3 ? 0 : hidro_cont+1);
                    printf("Acertou!\n");
                    break;
    
                case 3:
                    campo[l][c] = PORTAAVIAO;
                    imprimeTabuleiro(campo);
                    vida_inimiga--;
                    porta_cont = (porta_cont == 4 ? 0 : porta_cont+1);
                    printf("Acertou\n");
                    break;
    
                case 4:
                    campo[l][c] = DESTROYER;
                    imprimeTabuleiro(campo);
                    vida_inimiga--;
                    des_cont = (des_cont == 3 ? 0 : des_cont+1);
                    printf("Acertou!\n");
                    break;
    
                default:
                    printf("ErrROU!\n");
                }
            }
    
            //Victory condition
            if(vida_inimiga == 0)
            {
                system("cls");
                puts("FIM DO JOGO");
                puts("VOCÊ VENCEU!");
                puts("");
                jogador.placar = jogador.placar + 1;
                printf("Jogador: %s\nPlacar: %i", jogador.nome, jogador.placar);
                puts("");
                system("pause");
                exit(1);
            }
    
            //Loss condition
            if(jogador.disparos == 0)
            {
                system("cls");
                puts("FIM DO JOGO");
                puts("VOCÊ PERDEU");
                jogador.placar = jogador.placar + 0;
                printf("Jogador: %s\nPlacar: %i", jogador.nome, jogador.placar);
                puts("");
                system("pause");
                exit(1);
            }
    
        }
        while (vida_inimiga != 0 && jogador.disparos != 0);   //Fim do Do/While
    }
    
    
    int main ()
    {
        setlocale(LC_ALL,"portuguese");
        preparaTabuleiro();
        imprimeTabuleiro(campo);
        colherEmbarcacoes(campo);
        void batalha_naval(int direcao, int linha, int coluna, char A[ARENA][ARENA]);
        system("pause");
        return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Battleship help!
    By alias in forum C Programming
    Replies: 1
    Last Post: 12-01-2011, 08:46 PM
  2. Battleship help
    By mars_red in forum C++ Programming
    Replies: 3
    Last Post: 02-09-2008, 08:02 PM
  3. Battleship
    By BOBBY HILL in forum C Programming
    Replies: 2
    Last Post: 05-07-2002, 09:36 AM
  4. battleship
    By Leeman_s in forum Game Programming
    Replies: 10
    Last Post: 04-26-2002, 07:01 PM
  5. Battleship
    By Unregistered in forum Game Programming
    Replies: 11
    Last Post: 11-29-2001, 04:35 AM

Tags for this Thread