Ir ao conteúdo

C++ Código de Batalha Naval em C++


Ir à solução Resolvido por arfneto,

Posts recomendados

Postado

<CODE>

 

Estou fazendo um trabalho de Batalha Naval, mas estou com algumas dificuldades, pois fiz o código abaixo, mas o professor está pedindo para fazer um jogo Humano vs. Computador e que a inserção e bombardeio do computador sejam aleatórios. Como poderei fazer isso aproveitando este código?

Agradeço!

#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <conio.h>
#include <time.h>

using namespace std;

const int SIZE = 10;
const int FRIGATE = 2;
const int SUB = 3;
const int DESTROYER = 3;
const int BATTLESHIP = 4;
const int CARRIER = 5;
const int TOTAL_POS = 17;
const int HEADS = 1;
const int TAILS = 0;

// Class Player
class Player
{

public:

    // Public attributes
    string name;
    char boardPlayer[SIZE][SIZE];
    char BoardOpponent[SIZE][SIZE];
    int ships;
    // Constructor
    Player()
    {
        ships = TOTAL_POS;
        for (int cont1 = 0; cont1 < SIZE; cont1++)
        {
            for (int cont2 = 0; cont2 < SIZE; cont2++)
            {
                boardPlayer[cont1][cont2] = '~';
                BoardOpponent[cont1][cont2] = '~';
            }
        }
    }

    // Show board
    void BOARD()
    {
        cout << name << "'s Board..." << "\n\n";
        for (int cont1 = 0; cont1 < SIZE; cont1++)
        {
            for (int cont2 = 0; cont2 < SIZE; cont2++)
            {
                cout << boardPlayer[cont1][cont2] << " ";
            }
            cout << "\n";
        }
        cout << "\n";
        cout << "Caption:\n";
        cout << "~ [Water]\n";
        cout << "0 [Ship]\n";
        cout << "\n";
    }

    // Board Player 2
    void board2()
    {
        cout << name << "'s round\n";
        cout << "Opponent's board:\n\n";
        for (int cont1 = 0; cont1 < SIZE; cont1++)
        {
            for (int cont2 = 0; cont2 < SIZE; cont2++)
            {
                cout << BoardOpponent[cont1][cont2] << " ";
            }
            cout << "\n";
        }
        cout << "\n";
        cout << "Caption:\n";
        cout << "~ [Water]\n";
        cout << "# [Missed]\n";
        cout << "X [Target]\n";
        cout << "\n";
    }

    // Configure position of Frigate
    void configureFrigate()
    {
        // Local variables
        int row;
        int column;
        char pos;
        bool flag = false;
        // Positioning ship
        do
        {
            system("cls");
            BOARD();
            cout << "------------------------\n";
            cout << "POSITIONING FRIGATE\n";
            cout << "------------------------\n";
            cout << "Position Y (0-9):";
            cin >> row;
            if (row < SIZE && row >= 0)
            {
                cout << "Position X (0-9):";
                cin >> column;
                if (column < SIZE && column >= 0)
                {
                    cout << "Do you want to position the boat vertically (1) or horizontally (2)?";
                    cin >> pos;
                    if (pos == '1')
                    {
                        // Check if is possible to insert the ship
                        if (SIZE - row != 1)
                        {
                            // Check that there are no other boats there
                            int times = 0;
                            for (int cont = row; cont < row + FRIGATE; cont++)
                            {
                                if (boardPlayer[cont][column] == '~')
                                {
                                    times++;
                                }
                            }
                            // If the number of spaces with water is equal to the size of the boat,
                            // then it is possible to position the boat
                            if (times == FRIGATE)
                            {

                                for (int cont = row; cont < row + FRIGATE; cont++)
                                {
                                    boardPlayer[cont][column] = 'F';
                                }
                                flag = true;
                            }
                        }
                    }
                    else
                    {
                        if (pos == '2')
                        {
                            // Check if is possible to insert the ship
                            if (SIZE - column != 1)
                            {
                                // Check that there are no other ship there
                                int times = 0;
                                for (int cont = column; cont < column + FRIGATE; cont++)
                                {
                                    if (boardPlayer[row][cont] == '~')
                                    {
                                        times++;
                                    }
                                }
                                // If the number of spaces with water is equal to the size of the boat,
                                // then it is possible to position the ship
                                if (times == FRIGATE)
                                {

                                    for (int cont = column; cont < column + FRIGATE; cont++)
                                    {
                                        boardPlayer[row][cont] = 'F';
                                    }
                                    flag = true;
                                }
                            }
                        }
                    }
                }
            }

            if (flag == false)
            {
                cout << "SHIP CANNOT BE POSITIONED, TRY AGAIN!\n";
                cout << "Press enter to continue...";
                _getch();
            }
            else
            {
                cout << "SUCCESSFUL POSITIONED SHIP\n";
                cout << "Press enter to continue...";
                _getch();
            }

        } while (flag == false);
    }

    // Configure position of Sub
    void configureSubmarine()
    {
        // Local variables
        int row;
        int column;
        char pos;
        bool flag = false;
        // Positioning ship
        do
        {
            system("cls");
            BOARD();
            cout << "------------------------\n";
            cout << "POSITIONING SUBMARINE\n";
            cout << "------------------------\n";
            cout << "Position Y (0-9):";
            cin >> row;
            if (row < SIZE && row >= 0)
            {
                cout << "Position X (0-9):";
                cin >> column;
                if (column < SIZE && column >= 0)
                {
                    cout << "Do you want to position the boat vertically (1) or horizontally (2)?";
                    cin >> pos;
                    if (pos == '1')
                    {
                        // Check if is possible to insert the ship
                        if (SIZE - row != 1)
                        {
                            // Check that there are no other boats there
                            int times = 0;
                            for (int cont = row; cont < row + SUB; cont++)
                            {
                                if (boardPlayer[cont][column] == '~')
                                {
                                    times++;
                                }
                            }
                            // If the number of spaces with water is equal to the size of the boat,
                            // then it is possible to position the boat
                            if (times == SUB)
                            {
                                for (int cont = row; cont < row + SUB; cont++)
                                {
                                    boardPlayer[cont][column] = 'S';
                                }
                                flag = true;
                            }
                        }
                    }
                    else
                    {
                        if (pos == '2')
                        {
                            // Check if is possible to insert the ship
                            if (SIZE - column != 1)
                            {
                                // // Check that there are no other ship there
                                int times = 0;
                                for (int cont = column; cont < column + SUB; cont++)
                                {
                                    if (boardPlayer[row][cont] == '~')
                                    {
                                        times++;
                                    }
                                }
                                // If the number of spaces with water is equal to the size of the boat,
                                // then it is possible to position the ship
                                if (times == SUB)
                                {
                                    for (int cont = column; cont < column + SUB; cont++)
                                    {
                                        boardPlayer[row][cont] = 'S';
                                    }
                                    flag = true;
                                }
                            }
                        }
                    }
                }
            }
            if (flag == false)
            {
                cout << "SHIP CANNOT BE POSITIONED, TRY AGAIN!\n";
                cout << "Press enter to continue...";
                _getch();
            }
            else
            {
                cout << "SUCCESSFUL POSITIONED SHIP\n";
                cout << "Press enter to continue...";
                _getch();
            }
        } while (flag == false);
    }

    // Configure position of Destroyer
    void configureDestroyer()
    {
        // Local variables
        int row;
        int column;
        char pos;
        bool flag = false;
        // Positioning ship
        do
        {
            system("cls");
            BOARD();
            cout << "------------------------\n";
            cout << "POSITIONING DESTROYER\n";
            cout << "------------------------\n";
            cout << "Position Y (0-9):";
            cin >> row;
            if (row < SIZE && row >= 0)
            {
                cout << "Position X (0-9):";
                cin >> column;
                if (column < SIZE && column >= 0)
                {
                    cout << "Do you want to position the boat vertically (1) or horizontally (2)?";
                    cin >> pos;
                    if (pos == '1')
                    {
                        // Check if is possible to insert the ship
                        if (SIZE - row != 1)
                        {
                            // Check that there are no other boats there
                            int times = 0;
                            for (int cont = row; cont < row + DESTROYER; cont++)
                            {
                                if (boardPlayer[cont][column] == '~')
                                {
                                    times++;
                                }
                            }
                            // If the number of spaces with water is equal to the size of the boat,
                            // then it is possible to position the boat
                            if (times == DESTROYER)
                            {
                                for (int cont = row; cont < row + DESTROYER; cont++)
                                {
                                    boardPlayer[cont][column] = 'D';
                                }
                                flag = true;
                            }
                        }
                    }
                    else
                    {
                        if (pos == '2')
                        {
                            // Check if is possible to insert the ship
                            if (SIZE - column != 1)
                            {
                                // // Check that there are no other ship there
                                int times = 0;
                                for (int cont = column; cont < column + DESTROYER; cont++)
                                {
                                    if (boardPlayer[row][cont] == '~')
                                    {
                                        times++;
                                    }
                                }
                                // If the number of spaces with water is equal to the size of the boat,
                                // then it is possible to position the ship
                                if (times == DESTROYER)
                                {
                                    for (int cont = column; cont < column + DESTROYER; cont++)
                                    {
                                        boardPlayer[row][cont] = 'D';
                                    }
                                    flag = true;
                                }
                            }
                        }
                    }
                }
            }
            if (flag == false)
            {
                cout << "SHIP CANNOT BE POSITIONED, TRY AGAIN!\n";
                cout << "Press enter to continue...";
                _getch();
            }
            else
            {
                cout << "SUCCESSFUL POSITIONED SHIP\n";
                cout << "Press enter to continue...";
                _getch();
            }
        } while (flag == false);
    }

    // Configure position of Battleship
    void configureBattleship()
    {
        // Local variables
        int row;
        int column;
        char pos;
        bool flag = false;
        // Positioning ship
        do
        {
            system("cls");
            BOARD();
            cout << "------------------------\n";
            cout << "POSITIONING BATTLESHIP\n";
            cout << "------------------------\n";
            cout << "Position Y (0-9):";
            cin >> row;
            if (row < SIZE && row >= 0)
            {
                cout << "Position column (0-9):";
                cin >> column;
                if (column < SIZE && column >= 0)
                {
                    cout << "Do you want to position the boat vertically (1) or horizontally (2)??";
                    cin >> pos;
                    if (pos == '1')
                    {
                        // Check if is possible to insert the ship
                        if (SIZE - row > 2)
                        {
                            // Check that there are no other ship there
                            int times = 0;
                            for (int cont = row; cont < row + BATTLESHIP; cont++)
                            {
                                if (boardPlayer[cont][column] == '~')
                                {
                                    times++;
                                }
                            }
                            // If the number of spaces with water is equal to the size of the boat,
                            // then it is possible to position the ship
                            if (times == BATTLESHIP)
                            {
                                for (int cont = row; cont < row + BATTLESHIP; cont++)
                                {
                                    boardPlayer[cont][column] = 'B';
                                }
                                flag = true;
                            }
                        }
                    }
                    else
                    {
                        if (pos == '2')
                        {
                            // Check if is possible to insert the ship
                            if (SIZE - column > 2)
                            {
                                // Check that there are no other ship there
                                int times = 0;
                                for (int cont = column; cont < column + BATTLESHIP; cont++)
                                {
                                    if (boardPlayer[row][cont] == '~')
                                    {
                                        times++;
                                    }
                                }
                                // If the number of spaces with water is equal to the size of the boat,
                                // then it is possible to position the ship
                                if (times == BATTLESHIP)
                                {
                                    // Posição legal
                                    for (int cont = column; cont < column + BATTLESHIP; cont++)
                                    {
                                        boardPlayer[row][cont] = 'B';
                                    }
                                    flag = true;
                                }
                            }
                        }
                    }
                }
            }
            if (flag == false)
            {
                cout << "SHIP CANNOT BE POSITIONED, TRY AGAIN!\n";
                cout << "Press enter to continue...";;
                _getch();
            }
            else
            {
                cout << "SUCCESSFUL POSITIONED SHIP\n";
                cout << "Press enter to continue...";
                _getch();
            }

        } while (flag == false);
    }
    // Configure position of Aircraft Carrier
    void configureCarrier()
    {
        // Local variables
        int row;
        int column;
        char pos;
        bool flag = false;
        // Positioning ship
        do
        {
            system("cls");
            BOARD();
            cout << "------------------------\n";
            cout << "POSITIONING AIRCRAFT CARRIER\n";
            cout << "------------------------\n";
            cout << "Position Y (0-9):";
            cin >> row;
            if (row < SIZE && row >= 0)
            {
                cout << "Position column (0-9):";
                cin >> column;
                if (column < SIZE && column >= 0)
                {
                    cout << "Do you want to position the boat vertically (1) or horizontally (2)??";
                    cin >> pos;
                    if (pos == '1')
                    {
                        // Check if is possible to insert the ship
                        if (SIZE - row > 2)
                        {
                            // Check that there are no other ship there
                            int times = 0;
                            for (int cont = row; cont < row + CARRIER; cont++)
                            {
                                if (boardPlayer[cont][column] == '~')
                                {
                                    times++;
                                }
                            }
                            // If the number of spaces with water is equal to the size of the boat,
                            // then it is possible to position the ship
                            if (times == CARRIER)
                            {
                                for (int cont = row; cont < row + CARRIER; cont++)
                                {
                                    boardPlayer[cont][column] = 'A';
                                }
                                flag = true;
                            }
                        }
                    }
                    else
                    {
                        if (pos == '2')
                        {
                            // Check if is possible to insert the ship
                            if (SIZE - column > 2)
                            {
                                // Check that there are no other ship there
                                int times = 0;
                                for (int cont = column; cont < column + CARRIER; cont++)
                                {
                                    if (boardPlayer[row][cont] == '~')
                                    {
                                        times++;
                                    }
                                }
                                // If the number of spaces with water is equal to the size of the boat,
                                // then it is possible to position the ship
                                if (times == CARRIER)
                                {
                                    for (int cont = column; cont < column + CARRIER; cont++)
                                    {
                                        boardPlayer[row][cont] = 'A';
                                    }
                                    flag = true;
                                }
                            }
                        }
                    }
                }
            }
            if (flag == false)
            {
                cout << "SHIP CANNOT BE POSITIONED, TRY AGAIN!\n";
                cout << "Press enter to continue...";;
                _getch();
            }
            else
            {
                cout << "SUCCESSFUL POSITIONED SHIP\n";
                cout << "Press enter to continue...";
                _getch();
            }

        } while (flag == false);
    }
    // Check positions (how many positions have already been destroyed)
    bool checkPosition()
    {
        if (ships == 0)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    // Game
    bool play(Player* attacked)
    {
        // Local variables
        int row;
        int column;
        bool flag = false;
        do
        {
            system("cls");
            board2();
            cout << "\n";
            cout << "---------------\n";
            cout << "ATTACK!\n";
            cout << "---------------\n";
            cout << "Position Y (0-9):";
            cin >> row;
            if (row < SIZE && row >= 0)
            {
                cout << "Position X (0-9):";
                cin >> column;
                if (column < SIZE && column >= 0)
                {
                    // Check for a ship in position
                    if (attacked->boardPlayer[row][column] == 'O' && BoardOpponent[row][column] == '~')
                    {
                        BoardOpponent[row][column] = 'X';
                        attacked->ships--;
                        cout << "TARGET!\n";
                        cout << "Press enter to continue...";
                        _getch();
                        return true;
                    }
                    else
                    {
                        if (attacked->boardPlayer[row][column] == '~' && BoardOpponent[row][column] == '~')
                        {
                            BoardOpponent[row][column] = '#';
                            cout << "MISSED\n";
                            cout << "Press enter to continue...";
                            _getch();
                            return false;
                        }
                    }
                }
            }
            cout << "ATTACK CANNOT BE CARRIED OUT, TRY AGAIN\n";
            cout << "Press enter to continue\n";
            _getch();
        } while (flag == false);
        return false;
    }
};

int main()
{

    // Generate random numbers
    srand(time(NULL));
    // Variables
    string name_1;
    string name_2;
    int move;
    int cont;
    int player_op;
    bool flag = false;
    bool end = false;
    string op;

    // Players
    cout << "Name of Player 1:";
    cin >> name_1;

    cout << "Name of Player 2:";
    cin >> name_2;

    Player* j1 = new Player();
    j1->name = name_1;

    Player* j2 = new Player();
    j2->name = name_2;

    // Player 1 Move
    cout << "Player 1, configure your ships\n";
    cout << "Press enter to start...";
    _getch();
    for (cont = 0; cont < 1; cont++)
    {
        j1->configureFrigate();
        j1->configureSubmarine();
        j1->configureDestroyer();
        j1->configureBattleship();
        j1->configureCarrier();
    }    

    // Player 2 Move
    cout << "Player 2, configure your ships\n";
    cout << "Press enter to start......";
    _getch();
    for (cont = 0; cont < 1; cont++)
    {
        j2->configureFrigate();
        j2->configureSubmarine();
        j2->configureDestroyer();
        j2->configureBattleship();
        j2->configureCarrier();
    }

    system("cls");

    // Decide who starts
    do
    {
        cout << "Let's decide who starts...\n";
        cout << "Player 1 heads or tails (heads / tails)?";
        cin >> op;
        if (op == "heads")
        {
            player_op = HEADS;
            flag = true;
        }
        else
        {
            if (op == "tails")
            {
                player_op = TAILS;
                flag = true;
            }
        }

    } while (flag == false);
    if (rand() % 2 == player_op)
    {
        move = 1;
        cout << "The Player 1 (" << j1->name << ") starts...";
    }
    else
    {
        move = 2;
        cout << "The Player 2(" << j2->name << ") starts...";
    }
    cout << "Input enter to start the game...\n";
    _getch();

    // Objects
    Player* attacker = new Player();
    Player* attacked = new Player();
    Player* winner = new Player();
    Player* loser = new Player();

    // Game to finish, end=true
    do
    {
        if (move == 1)
        {
            attacker = j1;
            attacked = j2;
        }
        else
        {
            attacker = j2;
            attacked = j1;
        }
        while (attacker->play(attacked))
        {
            if (!attacked->checkPosition())
            {
                winner = attacker;
                loser = attacked;
                end = true;
                break;
            }
        }
        if (move == 1)
        {
            move++;
        }
        else
        {
            move--;
        }
    } while (end == false);

    // Show the final result
    system("cls");
    cout << "-----------\n";
    cout << "END GAME\n";
    cout << "-----------\n\n";
    cout << "The winner is " << winner->name << " and " << loser->name << " is the loser.";
    return 0;
}

 

  • Amei 1
  • Solução
Postado
Em 15/03/2020 às 19:54, IgorCoelho disse:

Como poderei fazer isso aproveitando este código?

 

Cada jogador vai ter uma instância da classe Player. Se no caso do jogador você usa um menu para o cara ir montando a frota no caso do computador vai usar um "sorteio". A dinâmica do jogo não muda por ser humano x humano ou vs computador ou mesmo computador vs computador. 

 

Esse código não parece muito bom. Tem muita repetição. e a ideia de usar um menu e prompts e reads para ler os dados é um pouco desanimadora. Provavelmente o jogador morreria de tédio antes mesmo de terminar de montar a frota.

 

Seria melhor criar uma interface grafica, ou algo com X e ponto mesmo, na tela. Ou usar a entrada a partir de um arquivo texto e imprimir um tabuleiro como a gente fazia nos '80 em FORTRAN. Meu palpite ao menos.

  • Curtir 1
Postado
Em 16/03/2020 às 19:54, arfneto disse:

É porque eu sou iniciante na programação e estou apanhando muito para fazer esse exercício. Eu já tentei de várias formas, mas nenhuma deu certo. A melhor foi essa, mas ainda não é o que o professor deseja!

 

Postado

 

Entendo. Ainda está um pouco longe de funcionar.

 

Você precisa colocar esses métodos dentro de uma classe. Não é assim omo escreveu, Board1() Board2(). Entendeu o que eu escrevi sobre as instâncias?

 

É difícil pensar no jogo em um computador só, a menos que o adversário seja o computador, certo?

Crie uma conta ou entre para comentar

Você precisa ser um usuário para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar agora

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...