CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jun 2018
    Posts
    1

    Question Beginner: 2 player Battleships Game

    Hello,

    I'm trying to gradually get into C++ and learn it via a 2-Player Battleships game that will just run through 'Command Prompt' in Windows 10.

    I've attached my work so far of what I've done, but I'm getting stuck on the 'While' loop at the end and not entirely sure where it fits in, in the code or how to fit it in.

    The game will have both players selecting their 5 x Battleship positions on a 10x10 grid, each ship taking up 1 space.

    Then after positions have been selected the game begins at guessing each others coordinates.

    The code for selecting Battleships compiles and works correctly it's just the actually guessing game part which I'm faltering on.

    Any help on the matter would be greatly appreciated
    Attached Files Attached Files

  2. #2
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,396

    Re: Beginner: 2 player Battleships Game

    Quote Originally Posted by Jamos View Post
    ...
    The code for selecting Battleships compiles and works correctly it's just the actually guessing game part which I'm faltering on.

    Any help on the matter would be greatly appreciated
    Did you try to debug your code?
    Victor Nijegorodov

  3. #3
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,824

    Re: Beginner: 2 player Battleships Game

    Rather than an attachment, just post the code using code tags so that it is easy to read.

    Code:
    /*Battleships 
    2018
    */
    
    #include <iostream>
    #include <cstdlib>
    #include <string>
    #include <fstream>
    
    const int GRID_SIZE = 10;
    
    const char EMPTY_CELL = '~';
    
    const int NUMBER_OF_PIECES = 6;
    
    struct player_t
    {
        std::string name;
        char pieceBoard[GRID_SIZE][GRID_SIZE];
        char otherBoard[GRID_SIZE][GRID_SIZE];
        int numberOfPieces;
    	int numberOfPiecesAlive;
    };
    
    void initBoard(char board[][GRID_SIZE]);
    
    void displayBoard(char board[][GRID_SIZE]);
    
    void placePieces(std::string name, char board[][GRID_SIZE]);
    
    void saveGame(player_t p1, player_t p2);
    
    void loadGame(player_t *p1, player_t *p2);
    
    player_t initPlayer(player_t p);
    
    int main()
    {
        player_t player1;
        player_t player2;
        player1 = initPlayer(player1);
        player2 = initPlayer(player2);
        saveGame(player1, player2);
        loadGame(&player1, &player2);
        displayBoard(player1.pieceBoard);
        displayBoard(player2.pieceBoard);
        return 0;
    }
    
    player_t initPlayer(player_t p)
    {
        std::string name;
        std::cout << "enter your name: ";
        std::cin >> name;
        p.name = name;
        p.numberOfPieces = NUMBER_OF_PIECES;
    	p.numberOfPiecesAlive = NUMBER_OF_PIECES;
        initBoard(p.pieceBoard);
        initBoard(p.otherBoard);
        std::cout << p.name << " your boards look like this:\n";
        displayBoard(p.pieceBoard);
        displayBoard(p.otherBoard);
        placePieces(p.name, p.pieceBoard);
        return p;
    }
    
    void initBoard(char board[][GRID_SIZE])
    {
        for(int i = 0; i < GRID_SIZE; i++)
        {
            for(int j = 0; j < GRID_SIZE; j++)
            {
                 board[i][j] = EMPTY_CELL;
            }
        }
    }
    
    void displayBoard(char board[][GRID_SIZE])
    {
        std::cout << "? 0 1 2 3 4 5 6 7 8 9\n";
        for(int i = 0; i < GRID_SIZE; i++)
        {
            std::cout << i << " ";
            for(int j = 0; j < GRID_SIZE; j++)
            {
                std::cout << board[i][j] << " ";
            }
            std::cout << "\n";
        }
        std::cout << "\n\n";
    }
    
    void placePieces(std::string name, char board[][GRID_SIZE])
    {
        int x = -1;
        int y = -1;
        std::cout << name << " it is time to place your pieces\n";
        for(int i = 0; i < NUMBER_OF_PIECES; i++)
        {
            std::cout << "Enter the x coordinate for your piece number " << (i + 1) << ": ";
            std::cin >> x;
            std::cout << "Enter the y coordinate for your piece number " << (i + 1) << ": ";
            std::cin >> y;
            board[x][y] = 'P';
            std::cout << "\t\tCurrent Status\n";
            displayBoard(board);
        }
    }
    
    void saveGame(player_t p1, player_t p2)
    {
        std::ofstream gameFile("game.saved");
        if(!gameFile)
        {
            std::cout << "Game could not be saved! returning back to play the game\n";
            return;
        }
        gameFile << p1.name << std::endl;
        for(int i = 0; i < GRID_SIZE; i++)
        {
            for(int j = 0; j < GRID_SIZE; j++)
            {
                gameFile << p1.pieceBoard[i][j];
            }
            gameFile << std::endl;
        }
        for(int i = 0; i < GRID_SIZE; i++)
        {
             for(int j = 0; j < GRID_SIZE; j++)
            {
                gameFile << p1.otherBoard[i][j];
            }
            gameFile << std::endl;
        }
        gameFile << p1.numberOfPieces << std::endl;
        gameFile << p2.name << std::endl;
        for(int i = 0; i < GRID_SIZE; i++)
        {
            for(int j = 0; j < GRID_SIZE; j++)
            {
                gameFile << p2.pieceBoard[i][j];
             }
             gameFile << std::endl;
        }
        for(int i = 0; i < GRID_SIZE; i++)
        {
             for(int j = 0; j < GRID_SIZE; j++);
        }
        gameFile << std::endl;
        gameFile << p2.numberOfPieces << std::endl;
        gameFile.close();
        std::cout << "Saving game and quitting\n";
        std::exit(0);
    }
    
    void loadGame(player_t *p1, player_t *p2)
    {
        std::ifstream gameFile("game.saved");
        if(!gameFile)
        {
            std::cout << "saved game could not be loaded\n program will now shutdown\n";
            std::exit(2);
        }
        gameFile >> p1->name;
        for(int i = 0; i < GRID_SIZE; i++)
        {
            for(int j = 0; j < GRID_SIZE; j++)
            {
                gameFile >> p1->pieceBoard[i][j];
            }
        }
        for(int i = 0; i < GRID_SIZE; i++)
        {
            for(int j = 0; j < GRID_SIZE; j++)
            {
                gameFile >> p1->otherBoard[i][j];
            }
        }
        gameFile >> p1->numberOfPieces;
        gameFile >> p2->name;
        for(int i = 0; i < GRID_SIZE; i++)
        {
            for(int j = 0; j < GRID_SIZE; j++)
            {
                gameFile >> p2->pieceBoard[i][j];
            }
        }
        for(int i = 0; i < GRID_SIZE; i++)
        {
            for(int j = 0; j < GRID_SIZE; j++)
            {
                gameFile >> p2->otherBoard[i][j];
             }
        }
        gameFile >> p2->numberOfPieces;
    }
    
    while(p1.numberOfPiecesAlive =>0 && p2.numberOfPiecesAlive =>0)
    {
         //player one just chose x and y
    if (player2.pieceBoard[chosenY][chosenX] == 'P')
    	{
    		cout << "\nHit a boat!":
    		player1.otherBoard[chosenY][chosenX} = 'X';
    		player2.pieceBoard[chosenY][chosenX] == 'X'
    		player2.numberOfPiecesAlive -= 1;
    	}
    else
    	{
    		cout << "\nYou missed all the boats.."
    		player1.otherBoard[chosenY][chosenX} = 'M'; //M for miss, or anything you like
    	}
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  4. #4
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,824

    Re: Beginner: 2 player Battleships Game

    As I understand this, you are actually holding 4 boards - home & away for each player? Why? Don't you just want one board for each of the two players? As each player takes it in turns, what about an array of 2 elements of type player_t (with only 1 board each) and modulo 2 incrementing? That way taking turns and accessing the other player's board is easy. Then you only need to write code for one player.

    I know it's considered good to use std::string to hold strings, but in player_t if you make name say char[80], then it makes saving/loading much easier! Consider (not tried) and assuming name is a char[].

    Code:
    void saveGame(player_t p1, player_t p2)
    {
        std::ofstream gameFile("game.saved");
        if(!gameFile)
        {
            std::cout << "Game could not be saved! returning back to play the game\n";
            return;
        }
    
        gameFile.write((char*)&p1, sizeof(p1));
        gameFile.write((char*)&p2, sizeof(p2));
    
        gameFile.close();
        std::cout << "Saving game and quitting\n";
        std::exit(0);
    }
    and similarly for loadGame() using .read(). See http://www.cplusplus.com/reference/i.../istream/read/

    Also note this is passing p1, p2 by value so that a copy of p1 and p2 is done which is time consuming. It would be better to pass by reference.

    Also note that in your code for save/load, you using stream insertion to save the player's name. If the name contains a space, this is fine when using stream insertion. But when using stream extraction to retrieve the name then the extraction only obtains the name upto the first white-space char (space, tab, newline etc). So if a name contains a space then it would be written but not read correctly.

    Code:
    while(p1.numberOfPiecesAlive =>0 && p2.numberOfPiecesAlive =>0)
    This would be written as

    Code:
    while(p1.numberOfPiecesAlive >= 0 && p2.numberOfPiecesAlive >= 0)
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured