Restart confusion

Pages: 12
I am currently making a program that acts as a simple bowling score calculator, it allows for multiple players, each to be names and then shows the score frame by frame, all in command line,
But I have struck up an issue, I am unaware of a way to allow the user to restart the program halfway through the program. say mid-game?

Is there a way I can code in a command e.g. "RESTART" that can be input at any point causing the program to restart?

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

BowlingGame.h
#ifndef BOWLING_GAME_H
#define BOWLING_GAME_H

#include <string>
#include <vector>
#include "Player.h"

using namespace std;

class BowlingGame
{
public:
	BowlingGame();
	~BowlingGame();

	int initialize();
	int update();
	int shutdown();

	const vector<Player> getPlayers() const { return _players; }
	int getCurrentTurn() const { return _turn; }
	int getGameNumber() const { return _gameNumber; }
	int getLaneID() const { return _laneID; }

private:
	enum NAME_VALIDATION
	{
		NAME_LENGTH_INVALID,
		NAME_ALREADY_TAKEN,
		NAME_IS_VALID
	};
	int nameIsValid(const string &name);
	int _gameNumber;
	int _laneID;
	vector<Player> _players;
	int _turn;
	int _frame;
};

#endif



BowlingGame.cpp
#include "BowlingGame.h"
#include "InterfaceManager.h"

BowlingGame::BowlingGame()
{
	_gameNumber = 1;
	_laneID = 1;
	_turn = 0;
	_frame = 0;
}

BowlingGame::~BowlingGame()
{
}

int BowlingGame::initialize()
{
	SetConsoleTitle(TEXT("Bowling Score Sheet"));
	int playerCount = 0;
	do
	{
		Interface.drawSplashScreen(*this);
		playerCount = Interface.getIntegerValue(" How many players are on your team?(1-6): ");
	}
	while (playerCount < 1 || playerCount > 6);
	for (int i = 0; i < playerCount; i++)
		_players.push_back(Player());
	for (int i = 0; i < playerCount; i++)
	{
		Interface.drawSplashScreen(*this);
		char textBuffer[64];
		_snprintf_s(textBuffer, 64, " Please enter a name for player %d: ", i+1);
		string playerName = Interface.getStringValue(textBuffer);
		int valid = nameIsValid(playerName);
		while (valid != NAME_IS_VALID)
		{
			Interface.drawSplashScreen(*this);
			string msg;
			if (valid == NAME_LENGTH_INVALID)
				msg = " Name must be between 3 and 16 characters long.\n";
			else if (valid == NAME_ALREADY_TAKEN)
				msg = " The name provided already exists.\n";
			msg.append(textBuffer);
			playerName = Interface.getStringValue(msg);
			valid = nameIsValid(playerName);
		};
		_players[i].setName(playerName);
	}
	_turn = _players.size()-1;
	_frame = 0;
	return 1;
}

int BowlingGame::update()
{
	_turn = (_turn + 1) % _players.size();
	if (_turn == 0)
		_frame++;
	if (_frame > 10)	//end of game, all players have been through ten frames
	{
		Interface.drawGameOverScreen(*this);
		bool replay = Interface.getBooleanValue(" Would you like to play again? ");
		if (replay)
		{
			_gameNumber++;
			_players.clear();
			return initialize();
		}
		else
			return 0;	//quit the game
	}
	bool turnEnded = false;
	while (!turnEnded)
	{
		Interface.drawScoreTable(*this);
		turnEnded = _players[_turn].bowlBall(_frame);
	}
	return 1;
}

int BowlingGame::shutdown()
{
	_players.clear();
	return 1;
}

int BowlingGame::nameIsValid(const string &name)
{
	if (name.length() < 3 || name.length() > 16) return NAME_LENGTH_INVALID;
	for (int i = 0; i < (int)_players.size(); i++)
		if (name == _players[i].getName())
			return NAME_ALREADY_TAKEN;
	return NAME_IS_VALID;
}


InterfaceManager.cpp
#include "InterfaceManager.h"
#include "GameUtil.h"
#include "BowlingGame.h"
#include "Player.h"
#include <Windows.h>

InterfaceManager::InterfaceManager()
{
}

InterfaceManager::~InterfaceManager()
{
}

int InterfaceManager::getIntegerValue(const string &message)
{
	cout << message;
	string input;
	cin >> input;
	return GameUtil::stringToInteger(input.c_str(), true);	//strict input
}

string InterfaceManager::getStringValue(const string &message)
{
	cout << message;
	string input;
	cin >> input;
	return input;
}

bool InterfaceManager::getBooleanValue(const string &message)
{
	cout << message;
	string input;
	cin >> input;
	return GameUtil::stringToBoolean(input.c_str());
}

void InterfaceManager::drawSplashScreen(const BowlingGame &game)
{
	vector<Player> players = game.getPlayers();
	console.setSize(84, 28 + (players.size() * 3), true);
	console.clear();
	cout << "                        .! ! ! ! /\n";
	cout << "                      .  ! ! !  /\n";
	cout << "                    .    ! !   /\n";
	cout << "                  .      !    /\n";
	cout << "                .            /\n";
	cout << "              .      o      /\n";
	cout << "            .              /\n";
	cout << "          .     . '.      /\n";
	cout << "        .     '     '    /\n";
	cout << "      .     0 |         /\n";
	cout << "            |/\n";
	cout << "           /|\n";
	cout << "           / |\n\n";
	
	for (int i = 0; i < (int)players.size(); i++)
	{
		cout << " Player " << i+1 << ": " << players[i].getName() << "\n";
	}
	cout << "\n";
}

void InterfaceManager::drawScoreTable(const BowlingGame &game)
{
	vector<Player> players = game.getPlayers();
	int currentTurn = game.getCurrentTurn();
	console.clear();
	print(" _______________________________________________________________________________ \n");
	print("| Lane: %d, Game: %d |__1__|__2__|__3__|__4__|__5__|__6__|__7__|__8__|__9__|__10__|\n",
		game.getLaneID(), game.getGameNumber());
	int cursorPosY = console.getCurPosY();
	for (int i = 0; i < (int)players.size(); i++)
	{
		print("|                  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |   |\n");
		print("|                  |     |     |     |     |     |     |     |     |     |      |\n");
		if (i < (int)players.size()-1)
			print("|------------------|-----|-----|-----|-----|-----|-----|-----|-----|-----|------|\n");
		else
			print("`------------------'-----'-----'-----'-----'-----'-----'-----'-----'-----'------'\n");
	}
	for (int i = 0; i < (int)players.size(); i++)
	{
		if (currentTurn == i)
		{
			console.save();
			//console.setFgColour(_yellow);
		}
		console.setCurPosY(cursorPosY);
		Player player = players[i];
		vector<Score> scores = player.getScores();
		for (int j = 0; j < (int)scores.size(); j++)
		{
			console.setCurPosX(21 + (j*6));
			print(scores[j].getScore(Score::FIRST).c_str());
			console.setCurPosX(23 + (j*6));
			print(scores[j].getScore(Score::SECOND).c_str());
			if (j == 9)
			{
				console.setCurPosX(25 + (j*6));
				print(scores[j].getScore(Score::THIRD).c_str());
			}
		}
		console.setCurPosY(cursorPosY+1);
		int space = 18 - player.getName().length();
		console.setCurPosX(space);
		print(player.getName().c_str());
		int totalScore = 0;
		for (int j = 0; j < (int)scores.size(); j++)
		{
			if (!scores[j].isOpen() || j == 9)
			{
				totalScore += scores[j].total;
				char buffer[4];
				_snprintf_s(buffer, 4, "%d", totalScore);
				console.setCurPosX(21 + (j*6));
				print(buffer);
			}
		}
		cursorPosY += 3;
		if (currentTurn == i)
		{
			console.restore();
		}
	}
	console.setCurPosXY(0, 3 + players.size() * 3);
	print(" Current player's turn: %s\n\n", players[currentTurn].getName().c_str());
}

void InterfaceManager::drawGameOverScreen(const BowlingGame &game)
{
	drawScoreTable(game);
	vector<Player> players = game.getPlayers();
	int topScore = 0, totalScore = 0;
	vector<Player> topPlayers;
	for (int i = 0; i < (int)players.size(); i++)
	{
		int score = players[i].calculateScore();
		totalScore += score;
		if (score > topScore)
		{
			topPlayers.clear();
			topScore = score;
			topPlayers.push_back(players[i]);
		}
		else if (score == topScore)
		{
			topPlayers.push_back(players[i]);
		}
	}
	if (topPlayers.size() == 1)
		cout << " The winner for this game is " << topPlayers[0].getName();
	else
	{
		cout << " The game resulted in a tie between ";
		for (int i = 0; i < (int)topPlayers.size() - 1; i++)
		{
			cout << topPlayers[i].getName();
			if (i < (int)topPlayers.size() - 2)
				cout << ", ";
		}
		cout << " and " << topPlayers.back().getName();
	}
	cout << " with " << topScore << " points!\n";
	cout << " The team scored a total of " << totalScore << " points.\n\n";
}

Last edited on
Of course, there should be a way to go about that, but it greatly depends on the structure and style of your program.

Aceix.
There are a couple of ways to handle this.

1) Any place you accept input from the user, check for the keyword "RESTART" and exit out of any nested functions you're in with an indicator that the main() should go back to the start of the program.

2) Any place you accept input from the user, check for the keyword "RESTART", then throw an exception. Your main can then have a catch handler for that exception that takes it back to the beginning of the program.




How would I check for the keyword? using if( ==) and I don't quit understand what you mean by exception?
if(input == "RESTART") would work if input was a string and the user typed it all in capitals. I assume in your case that input would be an int (pins knocked down?) so you would need to use an integer for the keyword, something like -1 that would not be entered normally.

Exceptions are for error handling and not appropriate for something like this.
I did attempt to do that I wrote something similar to

if(input == "Restart")
{
BowlingGame.intialise;
}

But it seemed to get caught in a loop while working in which you it would send you back to the start but as soon as you tried to restart it again it wouldn't clear the screen, but would just print the next cout
Do I need to do it with a pointer to the main? or would that still not clear the memory and arrays?
You can clear the screen and reset any arrays or anything else you need to do before starting over.
1
2
3
4
5
6
7
if(input == "Restart")
{
    // Clear screen
    // Clear arrays
    // What ever else
    BowlingGame.intialise;
}

I do not understand what you mean by "a pointer to main"? This should all be happening inside the game loop in main.
My main is very small

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

#include <string>
#include "BowlingGame.h"

int main (int argc, char *argv[])
{   
	BowlingGame Game;

    Game.initialize ();  //Run initialise method from BowlingGame
    while (Game.update());   // continue until false is returned
    Game.shutdown ();	//Run shutdown method in BowlingGame to clear player names
    return 0;
}



As it is only used to intialize methods in other classes
I know a lot of people will says how bad is this but why not using goto?

1
2
3
4
5
6
7
8
9
10
11
12
int main (int argc, char *argv[])
{   
    BowlingGame Game;

restart:
    Game.initialize ();
    while (Game.update());
    Game.shutdown ();
    goto restart;

    return 0;
}
Last edited on
Last edited on
I expected some kind of loop like LB pointed out. Your code is hard to follow also with unneeded functions like:
1
2
3
4
5
6
7
int InterfaceManager::getIntegerValue(const string &message)
{
	cout << message;
	string input;
	cin >> input;
	return GameUtil::stringToInteger(input.c_str(), true);	//strict input
}

You could just as easily print the message, get the input and cast to an int(assuming that is what stringToInteger() does) and get rid of both functions.
I'm not trying to get the game to restart at the end, It already does that, I just ask if the user wants to reply at the end of the program and it restarts it, what I want to be able to do is allow the user to type in a keyword e.g. "RESTART" at any point and the program will go back to the start, I don't know how or where to code this./
That depends entirely on how you're processing input.
you mean something like this? :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int main(int argc, char *argv[])
{
	BowlingGame Game;

	Game.initialize();
	while (Game.update())
	{
		std::cout << "restart the game?";
		char answer;
		std::cin >> answer;

		if (answer == 'Y')
		{
			Game.shutdown();
			Game.initialize();
		}
	};
	Game.shutdown();

	return 0;
}
The problem is with the way your game is structured. One way to clean it up would be like I suggested earlier.
1
2
3
4
5
6
7
playerCount = Interface.getIntegerValue(" How many players are on your team?(1-6): ");

// could easily be written without any functions as:
cout << " How many players are on your team?(1-6): "
string input;
cin >> input;
playerCount = (int) input;

In the code that you posted, Interface.getIntegerValue() is called once and it calls another function. A function should only do one thing, but one thing should not be split into two or more functions and there is no reason to write a function to do a simple thing one time. Your code jumps around so much you might as well be using goto.

In a GUI program, main() might only initialization the main window and all the rest is handled in the main window class and other classes. A console program works differently and main() is the equivalent of the main window class.

If you do not understand what I am trying to say, try writing a flowchart for your game.
That's almost what I want, but that would omit the naming of the players, there are 4 points to the program

1 How Many players

2 The Names of the players

3 How many pins did (player) knock down [in the way you've coded it, it asks after every frame is complete]

4 would you like to replay

I just want to be able to type in a keyword at any of these four input prompts that will allow me to functionally restart the program
okay I understand that, it is very messy, unfortunatley GameUtil::stringToInteger() is where the parameters are passed stopping invalid input
In that case, if it was me, I would combine that and GameUtil::stringToBoolean() into one function called something like GameUtil::validateInput() and pass the string as an argument. If it passes, continue or if it fails do whatever you do to get correct input.

As for number 4, if the user wants to replay, it starts over anyway so you do not really need a keyword there. Of the other 3, 2 are integer inputs so making the keyword an integer that is out of bounds (input < 0 || input > 10) like -1 or 100 would probably work best then just use.
1
2
if(input == keyword)
    replay();
Yes, but the program HAS to be able to restart at any point, I can't just rely on it restarting at the end, its a requirement that I can restart it and because I'm a freaking idiot that decided to use console instead of GUI I can't work this out for shit.
Pages: 12