Advertisement
Guest User

Untitled

a guest
Apr 25th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 16.95 KB | None | 0 0
  1. //---------------------------------------------------------------------------
  2. //Program: Skeleton for Task 1c � group assignment
  3. //Author: Pascale Vacher
  4. //Last updated: 24 February 2017
  5. //---------------------------------------------------------------------------
  6.  
  7. //---------------------------------------------------------------------------
  8. //----- include libraries
  9. //---------------------------------------------------------------------------
  10.  
  11. //include standard libraries
  12. //BEAR IS SO COOL
  13. #include <iostream>
  14. #include <iomanip>
  15. #include <conio.h>
  16. #include <cassert>
  17. #include <string>
  18. #include <sstream>
  19. #include <vector>
  20. #include <fstream>
  21. using namespace std;
  22.  
  23. //include our own libraries
  24. #include "ConsoleUtils.h"   //for Clrscr, Gotoxy, etc.
  25.  
  26. //---------------------------------------------------------------------------
  27. //----- define constants
  28. //---------------------------------------------------------------------------
  29.  
  30. //defining the size of the grid
  31. const int  SIZEX(16);       //horizontal dimension
  32. const int  SIZEY(11);       //vertical dimension
  33. //defining symbols used for display of the grid and content
  34. const char BEAR('@');       //bear
  35. const char TUNNEL(' ');     //tunnel
  36. const char WALL('#');
  37. const char BOMB('0');       //Bomb
  38. const char TRIGGER('T');    //Trigger
  39. const char EXIT('X');       //Exit//border
  40. //defining the command letters to move the bear on the maze
  41. const int  UP(72);          //up arrow
  42. const int  DOWN(80);        //down arrow
  43. const int  RIGHT(77);       //right arrow
  44. const int  LEFT(75);        //left arrow
  45.  
  46. //defining the other command letters
  47. const char QUIT('Q');       //to end the game
  48. //score
  49.  
  50.  
  51. struct Item {
  52.     int x, y;
  53.     char symbol;
  54. };
  55.  
  56. //ifstream inUsername;
  57. //ofstream outUsername;
  58. //ifstream inPlayerScore;
  59. //ofstream outPlayerScore;
  60. //---------------------------------------------------------------------------
  61. //----- run game
  62. //---------------------------------------------------------------------------
  63.  
  64.  
  65. int main()
  66. {
  67.     int score(500);
  68.     //int PreviousScore(0);
  69.     string playerName;
  70.     int keyPresses(0);
  71.  
  72.     void mainMenu(string&);
  73.  
  74.     //calls the main menu
  75.     mainMenu(playerName);
  76.  
  77.     //function declarations (prototypes)
  78.     void initialiseGame(char g[][SIZEX], char m[][SIZEX], vector<Item>& bears);
  79.     void paintGame(const char g[][SIZEX], string mess, vector<Item>& theBears, const char BEAR, string& playerName, bool cheatMode, int& score, int& keyPresses);
  80.     bool wantsToQuit(const int key);
  81.     bool isArrowKey(const int k);
  82.     bool cheatMode = false;
  83.     int  getKeyPress();
  84.     void updateGameData(char g[][SIZEX], char m[][SIZEX], vector<Item>& theBears, int key, string& mess, bool cheatMode, int& z, int& score, int& keyPresses, string& playerName);
  85.     void updateGrid(char g[][SIZEX], const char m[][SIZEX], vector<Item>& bears);
  86.     void endProgram();
  87.     void txtFile(string playerName, int score, int keyPresses);
  88.     //local variable declarations
  89.     int z = 0;
  90.     char grid[SIZEY][SIZEX];
  91.     //grid for display
  92.  
  93.     char maze[SIZEY][SIZEX];
  94.     //structure of the maze
  95.  
  96.     Item bear = { 1, 0, BEAR };
  97.     Item bearTwo = { 1, 1, BEAR };
  98.     Item bearThree = { 1, 2, BEAR };
  99.     vector<Item> theBears = { bear, bearTwo, bearThree };//Bears vector
  100.  
  101.     string message("LET'S START...");   //current message to player
  102.  
  103.     //action...
  104.     initialiseGame(grid, maze, theBears);   //initialise grid (incl. walls & bear)
  105.     paintGame(grid, message, theBears, BEAR, playerName, cheatMode, score, keyPresses);         //display game info, modified grid & messages
  106.     int key(getKeyPress());             //read in  selected key: arrow or letter command
  107.     while (!wantsToQuit(key))           //while user does not want to quit
  108.     {
  109.         if (key == 'C')
  110.         {
  111.             cheatMode = !cheatMode;
  112.             message = "CHEAT MODE ON!";
  113.             cout << '\a';
  114.             score = 500;
  115.         }
  116.         else
  117.         {
  118.             if (isArrowKey(key))
  119.             {
  120.                 updateGameData(grid, maze, theBears, key, message, cheatMode, z, score, keyPresses, playerName);        //move bear in that direction
  121.                 updateGrid(grid, maze, theBears);                   //update grid information
  122.             }
  123.             else
  124.             {
  125.                 message = "INVALID KEY!";   //set 'Invalid key' message
  126.  
  127.             }
  128.         }
  129.         paintGame(grid, message, theBears, BEAR, playerName, cheatMode, score, keyPresses);     //display game info, modified grid & messages
  130.         key = getKeyPress();            //display menu & read in next option
  131.     }
  132.     endProgram();
  133.     txtFile(playerName, score, keyPresses); //write to text file
  134.                         //display final message
  135.    
  136.     return 0;
  137. }
  138.  
  139. void mainMenu(string& playerName)
  140. {
  141.     void fileInName(string& playerName);
  142.     void showMessage(WORD backColour, WORD textColour, int x, int y, const string message);
  143.     showMessage(clRed, clYellow, 40, 10, "3 Bears Project 2016-17");
  144.     showMessage(clRed, clYellow, 40, 11, "Team DAB 2.0");
  145.     showMessage(clBlue, clWhite, 40, 12, "Player Name: ");
  146.     cin >> playerName;      //allows the player to enter his name
  147.     SelectBackColour(clBlack);      //resets the background colour to black when the screen clears
  148.  
  149.     Clrscr();
  150.  
  151. }
  152.  
  153. //---------------------------------------------------------------------------
  154. //----- initialise game state
  155. //---------------------------------------------------------------------------
  156.  
  157. void initialiseGame(char grid[][SIZEX], char maze[][SIZEX], vector<Item>& theBears)
  158. { //initialise grid & place bear in middle
  159.     void setInitialMazeStructure(char maze[][SIZEX], vector<Item>& theBears);
  160.     void setInitialDataFromMaze(char maze[][SIZEX], vector<Item>& theBears);
  161.     void updateGrid(char g[][SIZEX], const char m[][SIZEX], vector<Item>& theBears);
  162.  
  163.     setInitialMazeStructure(maze, theBears);        //initialise maze
  164.     setInitialDataFromMaze(maze, theBears); //initialise bear's position
  165.     updateGrid(grid, maze, theBears);       //prepare grid
  166. }
  167.  
  168. void setInitialMazeStructure(char maze[][SIZEX], vector<Item>& theBears)
  169. { //set the position of the walls in the maze
  170.     //initialise maze configuration
  171.     int initialMaze[SIZEY][SIZEX]   //local array to store the maze structure
  172.         = { { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
  173.         { 1, 0, 3, 0, 3, 0, 0, 0, 0, 1, 0, 0, 0, 3, 0, 1 },
  174.         { 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1 },
  175.         { 1, 0, 1, 0, 1, 5, 0, 0, 0, 3, 0, 1, 0, 1, 0, 1 },
  176.         { 1, 2, 1, 0, 1, 3, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1 },
  177.         { 1, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1 },
  178.         { 1, 2, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1 },
  179.         { 1, 0, 1, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1 },
  180.         { 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1 },
  181.         { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
  182.         { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } };
  183.     // with 1 for wall, 0 for tunnel, etc.
  184.     //copy into maze structure
  185.     for (int row(0); row < SIZEY; ++row)
  186.     {
  187.         for (int col(0); col < SIZEX; ++col)
  188.         {
  189.             switch (initialMaze[row][col])
  190.             {
  191.             case 0: maze[row][col] = TUNNEL; break;
  192.             case 1: maze[row][col] = WALL; break;
  193.             case 2: maze[row][col] = BEAR; break;
  194.             case 3: maze[row][col] = BOMB; break;
  195.             case 4: maze[row][col] = TRIGGER; break;
  196.             case 5: maze[row][col] = EXIT; break;
  197.             }
  198.         }
  199.     }
  200. }
  201. void setInitialDataFromMaze(char maze[][SIZEX], vector<Item>& theBears)
  202. { //extract bear's coordinates from initial maze info
  203.     for (int row(0); row < SIZEY; ++row)
  204.         for (int col(0); col < SIZEX; ++col)
  205.             for (int i = 0; i < theBears.size(); i++)
  206.                 switch (maze[row][col])
  207.             {
  208.                 case BEAR:
  209.                 {
  210.                     theBears[i].x = col;
  211.                     theBears[i].y = row;
  212.                     maze[row][col] = TUNNEL;
  213.                 }
  214.                 break;
  215.                 //will work for other items too
  216.             }
  217. }
  218.  
  219. //---------------------------------------------------------------------------
  220. //----- update grid state
  221. //---------------------------------------------------------------------------
  222.  
  223. void updateGrid(char grid[][SIZEX], const char maze[][SIZEX], vector<Item>& theBears)
  224. { //update grid configuration after each move
  225.     void setMaze(char g[][SIZEX], const char b[][SIZEX]);
  226.     void placeBears(char g[][SIZEX], vector<Item>& theBears);
  227.  
  228.  
  229.     setMaze(grid, maze);    //reset the empty maze configuration into grid
  230.     placeBears(grid, theBears);
  231.  
  232.     //set bear in grid
  233. }
  234.  
  235. void setMaze(char grid[][SIZEX], const char maze[][SIZEX])
  236. { //reset the empty/fixed maze configuration into grid
  237.     for (int row(0); row < SIZEY; ++row)
  238.         for (int col(0); col < SIZEX; ++col)
  239.             grid[row][col] = maze[row][col];
  240. }
  241.  
  242. void placeBears(char g[][SIZEX], vector<Item>& theBears)
  243. { //place bear at its new position in grid
  244.     for (int i = 0; i < theBears.size(); i++) //for Loop for passing x and y into bears vector
  245.  
  246.         g[theBears[i].y][theBears[i].x] = theBears[i].symbol;
  247. }
  248.  
  249. void triggerBombs(char grid[][SIZEX], char maze[][SIZEX], vector<Item>& theBears)
  250. {
  251.     void updateGrid(char grid[][SIZEX], const char maze[][SIZEX], vector<Item>& theBears);
  252.  
  253.     for (int row(0); row < SIZEY; ++row)
  254.     {
  255.         for (int col(0); col < SIZEX; ++col)
  256.         {
  257.             if (maze[row][col] == BOMB)
  258.             {
  259.                 maze[row][col] = TUNNEL;
  260.             }
  261.         }
  262.     }
  263.     updateGrid(grid, maze, theBears);
  264. }
  265.  
  266. //---------------------------------------------------------------------------
  267. //----- move the bear
  268. //---------------------------------------------------------------------------
  269. void updateGameData(char g[][SIZEX], char maze[][SIZEX], vector<Item>& theBears, const int key, string& mess, bool cheatMode, int& z, int& score, int& keyPresses, string& playerName)
  270. { //move bear in required direction
  271.  
  272.     bool isArrowKey(const int k);
  273.     void setKeyDirection(int k, int& dx, int& dy, int& , int& keyPresses);
  274.     void triggerBombs(char maze[][SIZEX], char grid[][SIZEX], vector<Item>& theBears);
  275.     void showMessage(const WORD backColour, const WORD textColour, int x, int y, const string message);
  276.     void endProgram();
  277.     void txtFile(string playerName, int score, int keyPresses);
  278.     //reset message to blank
  279.     mess = "                                         ";     //reset message to blank
  280.  
  281.     //calculate direction of movement for given key
  282.     int dx(0), dy(0);
  283.     setKeyDirection(key, dx, dy, score, keyPresses);
  284.     for (int i = 0; i < theBears.size(); i++)
  285.         //check new target position in grid and update game data (incl. bear coordinates) if move is possible
  286.         switch (g[theBears[i].y + dy][theBears[i].x + dx])
  287.     {           //...depending on what's on the target position in grid...
  288.         case TUNNEL:            //can move
  289.             theBears[i].y += dy;        //go in that Y direction
  290.             theBears[i].x += dx;        //go in that X direction
  291.  
  292.             break;
  293.         case WALL:              //hit a wall and stay there
  294.             cout << '\a';       //beep the alarm
  295.             mess = "CANNOT GO THERE!";
  296.             break;
  297.  
  298.         case BEAR:
  299.             cout << '\a';       //beep the alarm
  300.             mess = "CANNOT GO THERES!";
  301.             break;
  302.  
  303.         case EXIT:
  304.        
  305.             cout << '\a';
  306.             theBears.erase(theBears.begin() + i);
  307.             mess = "BEAR SAVED!";
  308.             Sleep(50);
  309.             z++;
  310.             if (z >= 3)
  311.             {
  312.                 showMessage(clBlack, clGreen, 40, 9, "  All Bears rescued! You win!     ");
  313.                
  314.                
  315.         /*  system("pause");
  316.                
  317.                 exit(0);*/
  318.             }
  319.            
  320.             showMessage(clBlack, clGreen, 15 + z, 2, "@");
  321.            
  322.             break;
  323.        
  324.  
  325.         case TRIGGER:
  326.         {
  327.             if (cheatMode == false)
  328.             {
  329.        
  330.             theBears[i].y += dy;        //go in that Y direction
  331.             theBears[i].x += dx;        //go in that X direction
  332.             triggerBombs(g, maze, theBears);
  333.             mess = "Trigger activated!";
  334.            
  335.             }
  336.             else
  337.             {
  338.                 theBears[i].y += dy;        //go in that Y direction
  339.                 theBears[i].x += dx;        //go in that X direction
  340.             }
  341.  
  342.             break;
  343.         }
  344.  
  345.         case BOMB:
  346.         {
  347.             if (cheatMode == false)
  348.             {
  349.                 cout << '\a';                                       //Play an audio alert to let the player know
  350.                 maze[theBears[i].y + dy][theBears[i].x + dx] = ' '; //delete the bomb by modifying the maze
  351.                 theBears.erase(theBears.begin() + i);               //remove the bear from the vector
  352.                 mess = "BOMB HIT!";                                 //message the player that a bombs been hit
  353.                 system("pause");
  354.                     exit(0);
  355.             }
  356.             else
  357.             {
  358.                 theBears[i].y += dy;        //go in that Y direction
  359.                 theBears[i].x += dx;        //go in that X direction
  360.             }
  361.             txtFile(playerName, score, keyPresses); //write to text file
  362.    
  363.            
  364.             break;
  365.         }
  366.     }
  367. }
  368. //---------------------------------------------------------------------------
  369. //----- process key
  370. //---------------------------------------------------------------------------
  371. void setKeyDirection(const int key, int& dx, int& dy, int& score, int& keyPresses)
  372. { //calculate direction indicated by key
  373.     bool isArrowKey(const int k);
  374.  
  375.     assert(isArrowKey(key));
  376.     if (isArrowKey(key) == true){
  377.         score--;
  378.         keyPresses++;
  379.     }
  380.  
  381.     switch (key)    //...depending on the selected key...
  382.     {
  383.     case LEFT:      //when LEFT arrow pressed...
  384.         dx = -1;    //decrease the X coordinate
  385.         dy = 0;
  386.         break;
  387.     case RIGHT:     //when RIGHT arrow pressed...
  388.         dx = +1;    //increase the X coordinate
  389.         dy = 0;
  390.         break;
  391.     case UP:        //when UP arrow pressed...
  392.         dx = 0;
  393.         dy = -1;    //decrease the Y coordinate
  394.         break;
  395.     case DOWN:      //when DOWN arrow pressed...
  396.         dx = 0;
  397.         dy = +1;    //increase the Y coordinate
  398.         break;
  399.  
  400.     }
  401. }
  402.  
  403. int getKeyPress()
  404. { //get key or command (in uppercase) selected by user
  405.     //KEEP THIS FUNCTION AS GIVEN
  406.     int keyPressed;
  407.     keyPressed = _getch();          //read in the selected arrow key or command letter
  408.     while (keyPressed == 224)       //ignore symbol following cursor key
  409.         keyPressed = _getch();
  410.     return toupper(keyPressed);     //return it in uppercase
  411. }
  412.  
  413. bool isArrowKey(const int key)
  414. {   //check if the key pressed is an arrow key (also accept 'K', 'M', 'H' and 'P')
  415.     return (key == LEFT) || (key == RIGHT) || (key == UP) || (key == DOWN);
  416. }
  417. bool wantsToQuit(const int key)
  418. {   //check if the user wants to quit (when key is 'Q' or 'q')
  419.     return toupper(key) == QUIT;
  420. }
  421.  
  422. //---------------------------------------------------------------------------
  423. //----- display info on screen
  424. //---------------------------------------------------------------------------
  425.  
  426. string tostring(char x) {
  427.     std::ostringstream os;
  428.     os << x;
  429.     return os.str();
  430. }
  431. void showMessage(const WORD backColour, const WORD textColour, int x, int y, const string message)
  432. {
  433.     Gotoxy(x, y);
  434.     SelectBackColour(backColour);
  435.     SelectTextColour(textColour);
  436.     cout << message;
  437. }
  438. void paintGame(const char g[][SIZEX], string mess, vector<Item>& theBears, const char BEAR, string& playerName, bool cheatMode, int& score, int& keyPresses)
  439. { //display game title, messages, maze, bear and other items on screen
  440.     string tostring(char x);
  441.     void showMessage(const WORD backColour, const WORD textColour, int x, int y, const string message);
  442.     void paintGrid(const char g[][SIZEX]);
  443.     string previousScore(string name, int& score);
  444.  
  445.     //display Player Name
  446.     showMessage(clWhite, clRed, 40, 0, playerName);
  447.     while (playerName.length() > 20)
  448.     {
  449.         playerName.resize(20);
  450.     }
  451.     //display game title
  452.     showMessage(clBlack, clYellow, 0, 0, "___GAME___");
  453.     showMessage(clWhite, clRed, 40, 0, "FoP Task 1c: February 2017");
  454.     showMessage(clWhite, clRed, 40, 1, "Name:" + playerName);
  455.     //display menu options available
  456.     showMessage(clRed, clYellow, 40, 3, "TO MOVE USE KEYBOARD ARROWS ");
  457.     showMessage(clRed, clYellow, 40, 4, "TO QUIT ENTER 'Q'           ");
  458.     showMessage(clRed, clYellow, 40, 4, "TO ENTER CHEAT MODE ENTER 'C'          ");
  459.  
  460.     //print auxiliary messages if any
  461.     showMessage(clBlack, clWhite, 40, 8, mess); //display current message
  462.  
  463.     //display rescued bears
  464.  
  465.     showMessage(clBlack, clYellow, 0, 2, "Rescued Bears: ");
  466.     string cheatModeActive;
  467.     if (cheatMode == true)
  468.     {
  469.         cheatModeActive = "Yes";
  470.     }
  471.     else
  472.     {
  473.         cheatModeActive = "No";
  474.     }
  475.     showMessage(clBlack, clYellow, 0, 3, "Cheat mode: " + cheatModeActive);
  476.  
  477.    
  478.  
  479.  
  480.     string previousscore = previousScore(playerName, score);
  481.  
  482.  
  483.  
  484.     showMessage(clBlack, clYellow, 40, 7, "SCORE: ");
  485.     cout << score;
  486.  
  487.     showMessage(clBlack, clYellow, 40, 6, "PREVIOUS SCORE: ");
  488.     cout << previousscore;
  489.  
  490.     showMessage(clBlack, clYellow, 40, 5, "KEY PRESSES: ");
  491.     cout << keyPresses;
  492.  
  493.     //print auxiliary messages if any
  494.     showMessage(clBlack, clWhite, 40, 8, mess); //display current message
  495.  
  496.     // display grid contents
  497.     paintGrid(g);
  498. }
  499.  
  500.  
  501. void paintGrid(const char g[][SIZEX])
  502. { //display grid content on screen
  503.     SelectBackColour(clBlack);
  504.     SelectTextColour(clWhite);
  505.     Gotoxy(0, 6);
  506.     for (int row(0); row < SIZEY; ++row)
  507.     {
  508.         for (int col(0); col < SIZEX; ++col)
  509.             cout << g[row][col];    //output cell content
  510.         cout << endl;
  511.     }
  512. }
  513. void txtFile(string playerName, int score, int keyPresses)
  514. {
  515.  
  516.  
  517.  
  518.  
  519.         ofstream fout;//("playerName.txt", ios::out);
  520.         fout.open(playerName +".txt", ios::out);
  521.         if (fout.fail())
  522.         {
  523.             cout << "\nError opening file";
  524.         }
  525.        
  526.         else
  527.         {
  528.             fout <<setprecision(2);
  529.             fout << setw(4) << "Score:\t" << score << endl;
  530.             fout << setw(4) << "Name:\t" << playerName;
  531.             fout.close();
  532.         }
  533.    
  534. }
  535. string previousScore(string PlayerName, int& score)
  536. {
  537.     string previousscore;
  538.     ifstream fin(PlayerName +".txt", ios::in);
  539.  
  540.  
  541.     if (fin.is_open())
  542.     {
  543.         fin >> score;
  544.         previousscore = score;
  545.         fin.close();
  546.     }
  547.  
  548.     else
  549.     {
  550.         previousscore = "500";
  551.     }
  552.    
  553.  
  554.     return previousscore;
  555.    
  556. }
  557.  
  558. void endProgram()
  559. {
  560.     void showMessage(const WORD backColour, const WORD textColour, int x, int y, const string message);
  561.     showMessage(clRed, clYellow, 40, 8, "");    //hold output screen until a keyboard key is hit
  562.     system("pause");
  563.     exit(0);
  564. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement