-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrabbittest.cpp
688 lines (588 loc) · 19.9 KB
/
rabbittest.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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
// rabbits.cpp
// Portions you are to complete are marked with a TODO: comment.
// We've provided some incorrect return statements (so indicated) just
// to allow this skeleton program to compile and run, albeit incorrectly.
// The first thing you probably want to do is implement the utterly trivial
// functions (marked TRIVIAL). Then get Arena::display going. That gives
// you more flexibility in the order you tackle the rest of the functionality.
// As you finish implementing each TODO: item, remove its TODO: comment.
#include <iostream>
#include <string>
#include <random>
#include <utility>
#include <cstdlib>
#include <cctype>
using namespace std;
///////////////////////////////////////////////////////////////////////////
// Manifest constants
///////////////////////////////////////////////////////////////////////////
const int MAXROWS = 20; // max number of rows in the arena
const int MAXCOLS = 25; // max number of columns in the arena
const int MAXRABBITS = 100; // max number of rabbits allowed
const int NORTH = 0;
const int EAST = 1;
const int SOUTH = 2;
const int WEST = 3;
const int NUMDIRS = 4;
const int EMPTY = 0;
const int HAS_POISON = 1;
///////////////////////////////////////////////////////////////////////////
// Type definitions
///////////////////////////////////////////////////////////////////////////
class Arena; // This is needed to let the compiler know that Arena is a
// type name, since it's mentioned in the Rabbit declaration.
class Rabbit
{
public:
// Constructor
Rabbit(Arena* ap, int r, int c);
// Accessors
int row() const;
int col() const;
bool isDead() const;
// Mutators
void move();
private:
Arena* m_arena;
int m_row;
int m_col;
// TODO: You'll probably find that a rabbit object needs additional
// data members to support your implementation of the behavior affected
// by poisoned carrots.
};
class Player
{
public:
// Constructor
Player(Arena* ap, int r, int c);
// Accessors
int row() const;
int col() const;
bool isDead() const;
// Mutators
string dropPoisonedCarrot();
string move(int dir);
void setDead();
private:
Arena* m_arena;
int m_row;
int m_col;
bool m_dead;
};
class Arena
{
public:
// Constructor/destructor
Arena(int nRows, int nCols);
~Arena();
// Accessors
int rows() const;
int cols() const;
Player* player() const;
int rabbitCount() const;
int getCellStatus(int r, int c) const;
int numberOfRabbitsAt(int r, int c) const;
void display(string msg) const;
// Mutators
void setCellStatus(int r, int c, int status);
bool addRabbit(int r, int c);
bool addPlayer(int r, int c);
void moveRabbits();
private:
int m_grid[MAXROWS][MAXCOLS];
int m_rows;
int m_cols;
Player* m_player;
Rabbit* m_rabbits[MAXRABBITS];
int m_nRabbits;
int m_turns;
// Helper functions
void checkPos(int r, int c, string functionName) const;
bool isPosInBounds(int r, int c) const;
};
class Game
{
public:
// Constructor/destructor
Game(int rows, int cols, int nRabbits);
~Game();
// Mutators
void play();
private:
Arena* m_arena;
// Helper functions
string takePlayerTurn();
};
///////////////////////////////////////////////////////////////////////////
// Auxiliary function declarations
///////////////////////////////////////////////////////////////////////////
int randInt(int lowest, int highest);
bool decodeDirection(char ch, int& dir);
bool attemptMove(const Arena& a, int dir, int& r, int& c);
bool recommendMove(const Arena& a, int r, int c, int& bestDir);
void clearScreen();
///////////////////////////////////////////////////////////////////////////
// Rabbit implementation
///////////////////////////////////////////////////////////////////////////
Rabbit::Rabbit(Arena* ap, int r, int c)
{
if (ap == nullptr)
{
cout << "***** A rabbit must be created in some Arena!" << endl;
exit(1);
}
if (r < 1 || r > ap->rows() || c < 1 || c > ap->cols())
{
cout << "***** Rabbit created with invalid coordinates (" << r << ","
<< c << ")!" << endl;
exit(1);
}
m_arena = ap;
m_row = r;
m_col = c;
}
int Rabbit::row() const
{
return m_row;
}
int Rabbit::col() const
{
// TODO: TRIVIAL: Return what column the Rabbit is at
// Delete the following line and replace it with the correct code.
return 1; // This implementation compiles, but is incorrect.
}
bool Rabbit::isDead() const
{
// TODO: Return whether the Rabbit is dead
// Delete the following line and replace it with the correct code.
return false; // This implementation compiles, but is incorrect.
}
void Rabbit::move()
{
// TODO:
// Return without moving if the rabbit has eaten one poisoned
// carrot (so is supposed to move only every other turn) and
// this is a turn it does not move.
// Otherwise, attempt to move in a random direction; if can't
// move, don't move. If it lands on a poisoned carrot, eat the
// carrot and remove it from the game (so it is no longer on that
// grid point).
}
///////////////////////////////////////////////////////////////////////////
// Player implementation
///////////////////////////////////////////////////////////////////////////
Player::Player(Arena* ap, int r, int c)
{
if (ap == nullptr)
{
cout << "***** The player must be created in some Arena!" << endl;
exit(1);
}
if (r < 1 || r > ap->rows() || c < 1 || c > ap->cols())
{
cout << "**** Player created with invalid coordinates (" << r
<< "," << c << ")!" << endl;
exit(1);
}
m_arena = ap;
m_row = r;
m_col = c;
m_dead = false;
}
int Player::row() const
{
// TODO: TRIVIAL: Return what row the Player is at
// Delete the following line and replace it with the correct code.
return 1; // This implementation compiles, but is incorrect.
}
int Player::col() const
{
// TODO: TRIVIAL: Return what column the Player is at
// Delete the following line and replace it with the correct code.
return 1; // This implementation compiles, but is incorrect.
}
string Player::dropPoisonedCarrot()
{
if (m_arena->getCellStatus(m_row, m_col) == HAS_POISON)
return "There's already a poisoned carrot at this spot.";
m_arena->setCellStatus(m_row, m_col, HAS_POISON);
return "A poisoned carrot has been dropped.";
}
string Player::move(int dir)
{
// TODO: Attempt to move the player one step in the indicated
// direction. If this fails,
// return "Player couldn't move; player stands."
// A player who moves onto a rabbit, and this
// returns "Player walked into a rabbit and died."
// Otherwise, return one of "Player moved north.",
// "Player moved east.", "Player moved south.", or
// "Player moved west."
return "Player couldn't move; player stands."; // This implementation compiles, but is incorrect.
}
bool Player::isDead() const
{
// TODO: Return whether the Player is dead
// Delete the following line and replace it with the correct code.
return false; // This implementation compiles, but is incorrect.
}
void Player::setDead()
{
m_dead = true;
}
///////////////////////////////////////////////////////////////////////////
// Arena implementation
///////////////////////////////////////////////////////////////////////////
Arena::Arena(int nRows, int nCols)
{
if (nRows <= 0 || nCols <= 0 || nRows > MAXROWS || nCols > MAXCOLS)
{
cout << "***** Arena created with invalid size " << nRows << " by "
<< nCols << "!" << endl;
exit(1);
}
m_rows = nRows;
m_cols = nCols;
m_player = nullptr;
m_nRabbits = 0;
m_turns = 0;
for (int r = 1; r <= m_rows; r++)
for (int c = 1; c <= m_cols; c++)
setCellStatus(r, c, EMPTY);
}
Arena::~Arena()
{
// TODO: Deallocate the player and all remaining dynamically allocated
// rabbits.
}
int Arena::rows() const
{
// TODO: TRIVIAL: Return the number of rows in the arena
// Delete the following line and replace it with the correct code.
return 1; // This implementation compiles, but is incorrect.
}
int Arena::cols() const
{
// TODO: TRIVIAL: Return the number of columns in the arena
// Delete the following line and replace it with the correct code.
return 1; // This implementation compiles, but is incorrect.
}
Player* Arena::player() const
{
return m_player;
}
int Arena::rabbitCount() const
{
// TODO: TRIVIAL: Return the number of rabbits in the arena
// Delete the following line and replace it with the correct code.
return 0; // This implementation compiles, but is incorrect.
}
int Arena::getCellStatus(int r, int c) const
{
checkPos(r, c, "Arena::getCellStatus");
return m_grid[r-1][c-1];
}
int Arena::numberOfRabbitsAt(int r, int c) const
{
// TODO: Return the number of rabbits at row r, column c
// Delete the following line and replace it with the correct code.
return 0; // This implementation compiles, but is incorrect.
}
void Arena::display(string msg) const
{
char displayGrid[MAXROWS][MAXCOLS];
int r, c;
// Fill displayGrid with dots (empty) and stars (poisoned carrots)
for (r = 1; r <= rows(); r++)
for (c = 1; c <= cols(); c++)
displayGrid[r-1][c-1] = (getCellStatus(r,c) == EMPTY ? '.' : '*');
// Indicate each rabbit's position
// TODO: If one rabbit is at some grid point, set the displayGrid char
// to 'R'. If it's 2 though 8, set it to '2' through '8'.
// For 9 or more, set it to '9'.
// Indicate the player's position
if (m_player != nullptr)
displayGrid[m_player->row()-1][m_player->col()-1] = (m_player->isDead() ? 'X' : '@');
// Draw the grid
clearScreen();
for (r = 1; r <= rows(); r++)
{
for (c = 1; c <= cols(); c++)
cout << displayGrid[r-1][c-1];
cout << endl;
}
cout << endl;
// Write message, rabbit, and player info
if (msg != "")
cout << msg << endl;
cout << "There are " << rabbitCount() << " rabbits remaining." << endl;
if (m_player == nullptr)
cout << "There is no player!" << endl;
else if (m_player->isDead())
cout << "The player is dead." << endl;
cout << m_turns << " turns have been taken." << endl;
}
void Arena::setCellStatus(int r, int c, int status)
{
checkPos(r, c, "Arena::setCellStatus");
m_grid[r-1][c-1] = status;
}
bool Arena::addRabbit(int r, int c)
{
if (! isPosInBounds(r, c))
return false;
// Don't add a rabbit on a spot with a poisoned carrot
if (getCellStatus(r, c) != EMPTY)
return false;
// Don't add a rabbit on a spot with a player
if (m_player != nullptr && m_player->row() == r && m_player->col() == c)
return false;
// If there are MAXRABBITS existing rabbits, return false. Otherwise,
// dynamically allocate a new rabbit at coordinates (r,c). Save the
// pointer to newly allocated rabbit and return true.
// TODO: Implement this.
return false; // This implementation compiles, but is incorrect.
}
bool Arena::addPlayer(int r, int c)
{
if (! isPosInBounds(r, c))
return false;
// Don't add a player if one already exists
if (m_player != nullptr)
return false;
// Don't add a player on a spot with a rabbit
if (numberOfRabbitsAt(r, c) > 0)
return false;
m_player = new Player(this, r, c);
return true;
}
void Arena::moveRabbits()
{
// Move all rabbits
// TODO: Move each rabbit. Mark the player as dead if necessary.
// Deallocate any dead dynamically allocated rabbit.
// Another turn has been taken
m_turns++;
}
bool Arena::isPosInBounds(int r, int c) const
{
return (r >= 1 && r <= m_rows && c >= 1 && c <= m_cols);
}
void Arena::checkPos(int r, int c, string functionName) const
{
if (!isPosInBounds(r, c))
{
cout << "***** " << "Invalid arena position (" << r << ","
<< c << ") in call to " << functionName << endl;
exit(1);
}
}
///////////////////////////////////////////////////////////////////////////
// Game implementation
///////////////////////////////////////////////////////////////////////////
Game::Game(int rows, int cols, int nRabbits)
{
if (nRabbits < 0)
{
cout << "***** Cannot create Game with negative number of rabbits!" << endl;
exit(1);
}
if (nRabbits > MAXRABBITS)
{
cout << "***** Trying to create Game with " << nRabbits
<< " rabbits; only " << MAXRABBITS << " are allowed!" << endl;
exit(1);
}
int nEmpty = rows * cols - nRabbits - 1; // 1 for Player
if (nEmpty < 0)
{
cout << "***** Game created with a " << rows << " by "
<< cols << " arena, which is too small too hold a player and "
<< nRabbits << " rabbits!" << endl;
exit(1);
}
// Create arena
m_arena = new Arena(rows, cols);
// Add player
int rPlayer;
int cPlayer;
do
{
rPlayer = randInt(1, rows);
cPlayer = randInt(1, cols);
} while (m_arena->getCellStatus(rPlayer, cPlayer) != EMPTY);
m_arena->addPlayer(rPlayer, cPlayer);
// Populate with rabbits
while (nRabbits > 0)
{
int r = randInt(1, rows);
int c = randInt(1, cols);
if (r == rPlayer && c == cPlayer)
continue;
m_arena->addRabbit(r, c);
nRabbits--;
}
}
Game::~Game()
{
delete m_arena;
}
string Game::takePlayerTurn()
{
for (;;)
{
cout << "Your move (n/e/s/w/c or nothing): ";
string playerMove;
getline(cin, playerMove);
Player* player = m_arena->player();
int dir;
if (playerMove.size() == 0)
{
if (recommendMove(*m_arena, player->row(), player->col(), dir))
return player->move(dir);
else
return player->dropPoisonedCarrot();
}
else if (playerMove.size() == 1)
{
if (tolower(playerMove[0]) == 'c')
return player->dropPoisonedCarrot();
else if (decodeDirection(playerMove[0], dir))
return player->move(dir);
}
cout << "Player move must be nothing, or 1 character n/e/s/w/c." << endl;
}
}
void Game::play()
{
m_arena->display("");
Player* player = m_arena->player();
if (player == nullptr)
return;
while ( ! player->isDead() && m_arena->rabbitCount() > 0)
{
string msg = takePlayerTurn();
m_arena->display(msg);
if (player->isDead())
break;
m_arena->moveRabbits();
m_arena->display(msg);
}
if (player->isDead())
cout << "You lose." << endl;
else
cout << "You win." << endl;
}
///////////////////////////////////////////////////////////////////////////
// Auxiliary function implementation
///////////////////////////////////////////////////////////////////////////
// Return a uniformly distributed random int from lowest to highest, inclusive
int randInt(int lowest, int highest)
{
if (highest < lowest)
swap(highest, lowest);
static random_device rd;
static default_random_engine generator(rd());
uniform_int_distribution<> distro(lowest, highest);
return distro(generator);
}
bool decodeDirection(char ch, int& dir)
{
switch (tolower(ch))
{
default: return false;
case 'n': dir = NORTH; break;
case 'e': dir = EAST; break;
case 's': dir = SOUTH; break;
case 'w': dir = WEST; break;
}
return true;
}
// Return false without changing anything if moving one step from (r,c)
// in the indicated direction would run off the edge of the arena.
// Otherwise, update r and c to the position resulting from the move and
// return true.
bool attemptMove(const Arena& a, int dir, int& r, int& c)
{
// TODO: Implement this function
// Delete the following line and replace it with the correct code.
return false; // This implementation compiles, but is incorrect.
}
// Recommend a move for a player at (r,c): A false return means the
// recommendation is that the player should drop a poisoned carrot and
// not move; otherwise, this function sets bestDir to the recommended
// direction to move and returns true.
bool recommendMove(const Arena& a, int r, int c, int& bestDir)
{
// TODO: Implement this function
// Delete the following line and replace it with your code.
return false; // This implementation compiles, but is incorrect.
// Your replacement implementation should do something intelligent.
// You don't have to be any smarter than the following, although
// you can if you want to be: If staying put runs the risk of a
// rabbit possibly moving onto the player's location when the rabbits
// move, yet moving in a particular direction puts the player in a
// position that is safe when the rabbits move, then the chosen
// action is to move to a safer location. Similarly, if staying put
// is safe, but moving in certain directions puts the player in
// danger of dying when the rabbits move, then the chosen action should
// not be to move in one of the dangerous directions; instead, the player
// should stay put or move to another safe position. In general, a
// position that may be moved to by many rabbits is more dangerous than
// one that may be moved to by few.
//
// Unless you want to, you do not have to take into account that a
// rabbit might be poisoned and thus sometimes less dangerous than one
// that is not. That requires a more sophisticated analysis that
// we're not asking you to do.
}
///////////////////////////////////////////////////////////////////////////
// main()
///////////////////////////////////////////////////////////////////////////
int main()
{
// Create a game
// Use this instead to create a mini-game: Game g(3, 5, 2);
Game g(10, 12, 40);
// Play the game
g.play();
}
///////////////////////////////////////////////////////////////////////////
// clearScreen implementation
///////////////////////////////////////////////////////////////////////////
// DO NOT MODIFY OR REMOVE ANYTHING BETWEEN HERE AND THE END OF THE FILE!!!
// THE CODE IS SUITABLE FOR VISUAL C++, XCODE, AND g++/g31 UNDER LINUX.
// Note to Xcode users: clearScreen() will just write a newline instead
// of clearing the window if you launch your program from within Xcode.
// That's acceptable. (The Xcode output window doesn't have the capability
// of being cleared.)
#ifdef _WIN32
#include <windows.h>
void clearScreen()
{
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hConsole, &csbi);
DWORD dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
COORD upperLeft = { 0, 0 };
DWORD dwCharsWritten;
FillConsoleOutputCharacter(hConsole, TCHAR(' '), dwConSize, upperLeft,
&dwCharsWritten);
SetConsoleCursorPosition(hConsole, upperLeft);
}
#else // not _WIN32
#include <iostream>
#include <cstring>
#include <cstdlib>
void clearScreen() // will just write a newline in an Xcode output window
{
static const char* term = getenv("TERM");
if (term == nullptr || strcmp(term, "dumb") == 0)
cout << endl;
else
{
static const char* ESC_SEQ = "\x1B["; // ANSI Terminal esc seq: ESC [
cout << ESC_SEQ << "2J" << ESC_SEQ << "H" << flush;
}
}
#endif