Advertisement
Vita94

Ship sinking game

Apr 15th, 2013
17,471
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.43 KB | None | 0 0
  1. #include <iostream>
  2. #include <ctime>
  3. using namespace std;
  4.  
  5. const int rows = 10;
  6. const int elements = 10;
  7.  
  8. int maxships = 10;
  9.  
  10. int matrix[rows][elements];
  11.  
  12. void Clear()
  13. {
  14.     for(int i=0; i < rows; i++)
  15.     {
  16.         for(int j=0; j < elements; j++)
  17.         {
  18.             matrix[i][j] = 0;
  19.         }
  20.     }
  21. }
  22.  
  23. void Show()
  24. {
  25.     for(int i=0; i < rows; i++)
  26.     {
  27.         for(int j=0; j < elements; j++)
  28.         {
  29.             cout << matrix[i][j] << " ";
  30.         }
  31.         cout << endl;
  32.     }
  33. }
  34.  
  35. int NumberOfShips()
  36. {
  37.     int c = 0;
  38.  
  39.     for(int i=0; i < rows; i++)
  40.     {
  41.         for(int j=0; j < elements; j++)
  42.         {
  43.             if(matrix[i][j] == 1)
  44.                 c++;
  45.         }
  46.     }
  47.  
  48.     return c;
  49. }
  50.  
  51. void SetShips()
  52. {
  53.     int s = 0;
  54.     while(s < maxships)
  55.     {
  56.         int x = rand() % rows;
  57.         int y = rand() % elements;
  58.         if(matrix[x][y] != 1)
  59.         {
  60.             s++;
  61.             matrix[x][y] = 1;
  62.         }
  63.     }
  64. }
  65.  
  66. bool Attack(int x,int y)
  67. {
  68.     if(matrix[x][y] == 1)
  69.     {
  70.         matrix[x][y] = 2;
  71.         return true;
  72.     }
  73.     return false;
  74. }
  75.  
  76. int main()
  77. {
  78.     srand(time(NULL));
  79.     Clear();
  80.     SetShips();
  81.     int pos1,pos2;
  82.     char prompt;
  83.     while(1)
  84.     {
  85.         cout << "Please input location: "; cin >> pos1 >> pos2;
  86.         if(Attack(pos1,pos2))
  87.             cout << "You got me! :)" << endl;
  88.         else
  89.             cout << "Sorry no ship at that position!" << endl;
  90.         cout << "Number of ships left: " << NumberOfShips() << endl;
  91.         cout << "Do you want to surrender (y/n)? "; cin >> prompt;
  92.         if(prompt == 'y')
  93.             break;
  94.     }
  95.     cout << "Game over!" << endl;
  96.     Show();
  97.     system("pause");
  98.     return 0;
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement