Code Improvement

I've crafted myself a single - player Battleship game, but I need ways to improve it. So it's both more readable, manageable, and efficient. This codes display to the player, in which he get's to see. It also tells you if you hit a ship, and what type of ships, while putting a marker over the place you hit on the bored. So in what ways can I improve the code?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
  #include <cstdlib>
#include <iostream>
using namespace std;

class Arrays {
public:
	int Display[10][10] = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
						   {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
						   {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
						   {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
						   {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
						   {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
						   {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
						   {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
						   {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
						   {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}};

	int Actulal[10][10] = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
						   {0, 0, 0, 4, 4, 4, 4, 0, 0, 0},
						   {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
						   {2, 0, 0, 0, 0, 0, 5, 0, 0, 0},
						   {2, 0, 0, 0, 0, 0, 5, 0, 0, 0},
						   {2, 0, 1, 1, 0, 0, 5, 0, 0, 0},
						   {0, 0, 0, 0, 0, 0, 5, 0, 0, 0},
						   {0, 0, 0, 0, 0, 0, 5, 0, 0, 0},
						   {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
						   {3, 3, 3, 0, 0, 0, 0, 0, 0, 0}};
} P;

class Status {
public:
	int x;
	int y;
	int hits;
	int Hits = 0;

} A;

int main() {
	cout << "Game begins: \n";
	cout << "4 means miss, 8 means hit \n";

	do {
		for (int x = 0; x < 10; x++) {
			for (int y = 0; y < 10; y++) {
				cout << P.Display[y][x] << " , ";
			}
			cout << endl;
		}
		cout << "Enter the collum number" << endl;
		cin >> A.x;
		cout << "Enter the row number" << endl;
		cin >> A.y;

		switch (P.Actulal[A.y][A.x]) {
		case 1:
			cout << "You hit a Destroyer!" << endl;
			P.Display[A.x][A.y] = 8;
			P.Actulal[A.x][A.y] = 6;
			A.Hits = A.Hits + 1;
			break;

		case 2:
			cout << "You hit a Submarine!" << endl;
			P.Display[A.x][A.y] = 8;
			P.Actulal[A.x][A.y] = 6;
			A.Hits = A.Hits + 1;
			break;

		case 3:
			cout << "You hit a Cruiser!" << endl;
			P.Display[A.x][A.y] = 8;
			P.Actulal[A.x][A.y] = 6;
			A.Hits = A.Hits + 1;
			break;

		case 4:
			cout << "You hit a Battleship!" << endl;
			P.Display[A.x][A.y] = 8;
			P.Actulal[A.x][A.y] = 6;
			A.Hits = A.Hits + 1;
			break;

		case 5:
			cout << "You hit a Carrier!" << endl;
			P.Display[A.x][A.y] = 8;
			P.Actulal[A.x][A.y] = 6;
			A.Hits = A.Hits + 1;
			break;

		case 6:
			cout << "You already hit there \n";
			break;
		default:
			cout << "You missed \n";
			P.Display[A.x][A.y] = 4;
			P.Actulal[A.x][A.y] = 6;
		};
	} while (A.Hits != 17);
	cout << "Game Over!";
}
Last edited on
For initializing your 2D Display array:
1
2
3
4
5
6
7
8
9

int Display[10][10];
for(int index = 0; index < 10; index++)
{
  for (int index2 = 0; index2 < 10; index2++)
  {
  Display[index][index2] = 0;
  }
}
closed account (SECMoG1T)
using classes: 3 files {game.h, game.cpp, main.cpp}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
///game.h
#ifndef _GAME_H
#define _GAME_H


#include <list>
#include <ctime>
#include <random>
#include <iostream>


class Vessel ///Vessel object
{
public:
    Vessel(int row = 0, int col = 0, char typ = ' ', bool status = false);
    void setHit();
    void setRowNCol(int row,int col);
    void setType(char type);
    bool isHit() const;
    char getType() const;
    friend bool operator ==(const Vessel& lhs,const Vessel& rhs);
    friend bool operator !=(const Vessel& lhs,const Vessel& rhs);
private:
    int   _Row;    ///x coordinate
    int   _Col;    ///y coordinate
    char  _Type;   /// B = Battleship, C = Cruiser; D = Destroyer; S = Submarine; E = Carrier; * = empty
    bool  _Status; /// hit = true, else false
};

class GameBoard
{
public:
    static Vessel NullVessel;///
public:
    GameBoard(const int maxsize = 10);
    void boardDraw();
    Vessel& VesselInMap(const Vessel&);///return a reference to a Vessel object if present

private:
    int  randomNumbers(int lowest,int highest);      ///for generating random numbers
    void boardInit();          ///initialize my board i.e my ships and their locations

protected:
    const int        _MaxSize; ///max board size
    std::list<Vessel> _Map;     ///store Vessel  only
};

class Game : public GameBoard
{
public:
    Game(const int& maxboardsize = 10);
    void run();

private:
    int getInput(const int& lower = 0, const int& upper = (9), const char* mssg = "enter you value: ");
    bool won();
    char proceed();
    void printHit(char type);
};

#endif // _GAME_H

///main.cpp
#include "game.h"

int main()
{
    Game myGame;

    myGame.run();
}

///game.cpp
#include "game.h"

/********************************class Vessel definition///***********************/
Vessel::Vessel(int row, int col, char typ, bool status )
    :_Row(row), _Col(col), _Type(typ), _Status(status) {}

void Vessel::setHit()
{
    _Status = true;
}

void Vessel::setRowNCol(int row,int col)
{
    _Row = row;
    _Col = col;
}

void Vessel::setType(char type)
{
    _Type = type;
}

bool Vessel::isHit() const
{
    return _Status;
}

char Vessel::getType() const
{
    return _Type;
}

bool operator ==(const Vessel& lhs,const Vessel& rhs)
{
    return (lhs._Row == rhs._Row && lhs._Col == rhs._Col);
}

bool operator !=(const Vessel& lhs,const Vessel& rhs)
{
    return !(lhs == rhs);
}

/*********************class GameBoard ************************************/
Vessel GameBoard::NullVessel = Vessel(-1,-1);

GameBoard::GameBoard(const int maxsize )
    :_MaxSize(maxsize), _Map( {})
{
    boardInit();
}

void GameBoard::boardDraw()
{
    std::cout<<"\n\n";
    std::cout<<"     1    2    3    4    5    6    7    8    9    10";
    std::cout<<"\n   -------------------------------------------------\n";
    for(int row = 0; row < _MaxSize; row++)
    {
        std::cout<<row+1;
        if((row+1) == 10)
            std::cout<< "|";
        else
            std::cout<<" |";

        for(int col = 0; col < _MaxSize; col++)
        {
            Vessel _temp(row,col);

            const auto _pos = VesselInMap(_temp);

            if(_pos != NullVessel && _pos.isHit())
                std::cout<<"  "<<_pos.getType()<<" ";

            else
                std::cout<<"  * ";

            if(col != _MaxSize -1)
                std::cout<<" ";
        }
        std::cout<<"|\n";
    }
    std::cout<<"   -------------------------------------------------\n\n";
}

Vessel& GameBoard::VesselInMap(const Vessel& _pos)
{
    for(Vessel& _posref : _Map)
    {
        if(_posref == _pos)
            return _posref;
    }

    return NullVessel;
}

int  GameBoard::randomNumbers(int lowest, int highest)
{
    static std::mt19937  _Mt(std::time(nullptr)); ///you can also use srand and rand in cstdlib
    static std::uniform_int_distribution<int> _intDist(lowest,highest);

    return _intDist(_Mt);
}

void GameBoard::boardInit()
{
    ///i create 20 random ships, 4 for every type
    char shipType [5] {'B','C','D','E','S'};

    for(auto _type : shipType)
    {
        for(int i = 0; i < 4; i++)
        {
            int row = randomNumbers(0,_MaxSize-1);
            int col = randomNumbers(0,_MaxSize-1);
            Vessel     _shipPos(row,col);

            while(VesselInMap(_shipPos)!= NullVessel)///position not occupied
            {
                _shipPos.setRowNCol(randomNumbers(0,_MaxSize-1),randomNumbers(0,_MaxSize-1));
            }

            _shipPos.setType(_type);
            _Map.push_back(_shipPos);
        }
    }
}

/******************************Game class *****************************************/
Game::Game(const int& maxboardsize)
    :GameBoard(maxboardsize) {}

int Game::getInput(const int& lower, const int& upper, const char* mssg)
{
    int value{};
    std::cout<<"\n"<<mssg<<": ";
    std::cin>>value;

    while((value < lower || value > upper) ||(!std::cin))
    {
        if(!std::cin)
        {
           std::cin.clear();
           std::cin.ignore(1000,'\n');
        }
        std::cout<<"\n"<<mssg<<" (retry): ";
        std::cin >>value;
    }

    return value;
}

bool Game::won()
{
    for(auto _ship : GameBoard::_Map)
    {
        if(!_ship.isHit())
            return false;
    }

    return true;
}

char Game::proceed()
{
    char c;
    std::cout<<"\nEnter q to quit, any other key to continue... ";
    std::cin >> c;
    std::cout<<"\n\n";

    return c;
}

void Game::printHit(char type)
{
    switch(type)
    {
    case 'B':
        std::cout<<"your hit a Battleship\n";
        break;
    case 'C':
        std::cout<<"you destroyed a Cruiser\n";
        break;
    case 'E':
        std::cout<<"you blew up a Carrier\n";
        break;
    case 'D':
        std::cout<<"you sunk a destroyer\n";
        break;
    case 'S':
        std::cout<<"you destroyed a submarine\n";
        break;
    default :
        std::cout<<"you missed\n";
        break;
    }

}

void Game::run()
{
    std::cout << "Game begins: \n";
    std::cout<<"\n-------------------------------------------------\n";
    std::cout<<"B = Battleship    C = Cruiser   E = Carrier\n";
    std::cout<<"D = Destroyer     S = Submarine\n";
    std::cout<<"\n-------------------------------------------------\n\n";

    boardDraw();

    int rounds = 25;///can change this
    bool _won   = false;

    while(rounds--)
    {
        int row = getInput(1,_MaxSize,"Enter row");
        int col = getInput(1,_MaxSize,"Enter col");
        std::cout<<"\n******************************************\n";

        Vessel pos(row-1,col-1);
        Vessel& ship = VesselInMap(pos);

        if(ship != NullVessel)
            ship.setHit();

        printHit(ship.getType());
        boardDraw();

        if(won())
        {
            _won = true;
            break;
        }

        char cont = proceed();
        if(cont == 'q' || cont == 'Q')
            break;
    }

    if(_won)
    {
        std::cout<<"\n!!!!!!!!!You WON!!!!!!!!!!!!!!!!!!\n";
        std::cout<<"\n!!!!!!!!!medal recieved!!!!!!!!!!!\n";
    }

    else
    {
        std::cout<<"\n!!!Arrrrrrrgh you lost the game!!!!!!!\n";
        std::cout<<"\n!!!retry later for your luck!!!!!!!!!!\n";
    }
}
Last edited on
Topic archived. No new replies allowed.