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
|
#include <iostream>
#include <ctime>
enum EMove { keUp = 'w',
keDown = 'z',
keLeft = 'a',
keRight = 's'};
// Function declarations
void InitializeBoard(char[4][4]);
void PrintBoard(char[4][4]);
void LocateSpace(int&, int&, char [4][4]);
void Randomize(char[4][4]);
void Move(char[4][4], const EMove);
int main() {
char caaBoard[4][4];
InitializeBoard(caaBoard);
Randomize(caaBoard);
using namespace std;
do {
PrintBoard(caaBoard);
cout << endl << "w = Up, z = Down, a = Left, s = Right" << endl;
cout << endl << "Make your move partner." << endl;
char cNextMove;
cin >> cNextMove;
EMove eNextMove = (EMove)cNextMove;
Move(caaBoard, eNextMove);
cout << endl;
} while (caaBoard != {
{'1', '2', '3', '4'},
{'5', '6', '7', '8'},
{'9', 'A', 'B', 'C'},
{'D', 'E', 'F', ' '}
});
cout << "Ride em high cowboy." << endl;
return 0;
}
void InitializeBoard(char caaBoard[4][4]) {
const char kcaaInitial[4][4] = {
{'1', '2', '3', '4'},
{'5', '6', '7', '8'},
{'9', 'A', 'B', 'C'},
{'D', 'E', 'F', ' '}
};
for (int iRow = 0; iRow < 4; ++iRow) {
for (int iCol = 0; iCol < 4; ++iCol) {
caaBoard[iRow][iCol] = kcaaInitial[iRow][iCol];
}
}
}
void PrintBoard(char caaBoard[4][4]) {
using namespace std;
for (int iRow = 0; iRow < 4; ++iRow) {
for (int iCol = 0; iCol < 4; ++iCol) {
cout << caaBoard[iRow][iCol];
}
cout << endl;
}
}
void LocateSpace(int& irRow, int& irCol, char caaBoard[4][4]) {
for (int iRow = 0; iRow < 4; ++iRow) {
for (int iCol = 0; iCol < 4; ++iCol) {
if (caaBoard[iRow][iCol] == ' ') {
irRow = iRow;
irCol = iCol;
}
}
}
}
void Randomize(char caaBoard[4][4]) {
using namespace std;
srand((unsigned int)time(0));
for (int iIndex = 0; iIndex < 1000000; ++iIndex) {
const int kiNextMove = (rand() % 4);
switch (kiNextMove) {
case 0:
{
Move(caaBoard, keUp);
break;
}
case 1:
{
Move(caaBoard, keDown);
break;
}
case 2:
{
Move(caaBoard, keLeft);
break;
}
case 3:
{
Move(caaBoard, keRight);
break;
}
}
}
}
void Move(char caaBoard[4][4], const EMove keMove) {
int iRowSpace;
int iColSpace;
LocateSpace(iRowSpace, iColSpace, caaBoard);
int iRowMove(iRowSpace);
int iColMove(iColSpace);
switch (keMove) {
case keUp:
{
iRowMove = iRowSpace + 1;
break;
}
case keDown:
{
iRowMove = iRowSpace - 1;
break;
}
case keLeft:
{
iColMove = iColSpace + 1;
break;
}
case keRight:
{
iColMove = iColSpace - 1;
break;
}
}
// Make sure that the square to be moved is in bounds
if (iRowMove >= 0 && iRowMove < 4 && iColMove >= 0 && iColMove < 4) {
caaBoard[iRowSpace][iColSpace] = caaBoard[iRowMove][iColMove];
caaBoard[iRowMove][iColMove] = ' ';
}
}
|