Advertisement
Guest User

Untitled

a guest
Feb 9th, 2016
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.98 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace Battleships
  7. {
  8. class Program
  9. {
  10. static int[,] GenerateGrid(int[,] grid, int numShips, int GRID_SIZE)
  11. {
  12. Random rnd = new Random();
  13. for (int i = 0; i < numShips; i++)
  14. {
  15. int x = rnd.Next(0, GRID_SIZE - 1);
  16. int y = rnd.Next(0, GRID_SIZE - 1);
  17. grid[x, y] = grid[x, y] != 1 ? 1 : 2;
  18. }
  19. return (grid);
  20. }
  21.  
  22. static void PrintGrid(int[,] grid)
  23. {
  24. int xLen = grid.GetLength(0);
  25. int yLen = grid.GetLength(1);
  26. for (int i = 0; i < xLen; i++, Console.Write(Environment.NewLine ))
  27. {
  28. for (int j = 0; j < yLen; Console.Write(string.Format("{0}", grid[i, j])), j++) { }
  29. }
  30. }
  31.  
  32. static int[,] CheckIfInGrid(int x, int y, int[,] grid, int[,] playerGrid)
  33. {
  34. if (x < grid.GetLength(0) && y < grid.GetLength(1)) { playerGrid[x, y] = grid[x, y] == 1 ? 1 : 2; }
  35. else { Console.WriteLine("Invalid Location"); }
  36. return (playerGrid);
  37. }
  38.  
  39.  
  40. static bool CompareGrids(int[,] grid, int[,] playerGrid, int numShips)
  41. {
  42. int shipsFound = 0;
  43. int xLen = grid.GetLength(0);
  44. int yLen = grid.GetLength(1);
  45. for (int i = 0; i < xLen; i++)
  46. {
  47. for (int j = 0; j < yLen; j++)
  48. {
  49. if (grid[i,j] == 1 && playerGrid[i,j] == 1) { shipsFound++; }
  50. }
  51. }
  52. return (shipsFound == numShips ? true : false);
  53. }
  54.  
  55. static void Main(string[] args)
  56. {
  57. const int NUM_SHIPS = 3;
  58. const int GRID_SIZE = 3;
  59. int[,] grid = GenerateGrid(new int[GRID_SIZE,GRID_SIZE], NUM_SHIPS, GRID_SIZE);
  60. int[,] playerGrid = new int[GRID_SIZE,GRID_SIZE];
  61. bool running = true;
  62. while (running)
  63. {
  64. int x, y;
  65. PrintGrid(playerGrid);
  66. Console.Write("Enter Coordinates to test (coordinates start at zero)\nX : ");
  67. string inputX = Console.ReadLine();
  68. bool resultX = Int32.TryParse(inputX, out x);
  69. Console.Write("\nY: ");
  70. string inputY = Console.ReadLine();
  71. bool resultY = Int32.TryParse(inputY, out y);
  72. if ((resultX) && (resultY)) { CheckIfInGrid(x, y, grid, playerGrid); }
  73. else { Console.WriteLine("Error: Invalid Coordinate entered"); }
  74. Console.WriteLine();
  75.  
  76. if (CompareGrids(grid, playerGrid, NUM_SHIPS))
  77. {
  78. Console.WriteLine("You won, congratulations!!");
  79. running = false;
  80. }
  81. }
  82. Console.ReadLine();
  83. }
  84. }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement