Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace Battleships
- {
- class Program
- {
- static int[,] GenerateGrid(int[,] grid, int numShips, int GRID_SIZE)
- {
- Random rnd = new Random();
- for (int i = 0; i < numShips; i++)
- {
- int x = rnd.Next(0, GRID_SIZE - 1);
- int y = rnd.Next(0, GRID_SIZE - 1);
- grid[x, y] = grid[x, y] != 1 ? 1 : 2;
- }
- return (grid);
- }
- static void PrintGrid(int[,] grid)
- {
- int xLen = grid.GetLength(0);
- int yLen = grid.GetLength(1);
- for (int i = 0; i < xLen; i++, Console.Write(Environment.NewLine ))
- {
- for (int j = 0; j < yLen; Console.Write(string.Format("{0}", grid[i, j])), j++) { }
- }
- }
- static int[,] CheckIfInGrid(int x, int y, int[,] grid, int[,] playerGrid)
- {
- if (x < grid.GetLength(0) && y < grid.GetLength(1)) { playerGrid[x, y] = grid[x, y] == 1 ? 1 : 2; }
- else { Console.WriteLine("Invalid Location"); }
- return (playerGrid);
- }
- static bool CompareGrids(int[,] grid, int[,] playerGrid, int numShips)
- {
- int shipsFound = 0;
- int xLen = grid.GetLength(0);
- int yLen = grid.GetLength(1);
- for (int i = 0; i < xLen; i++)
- {
- for (int j = 0; j < yLen; j++)
- {
- if (grid[i,j] == 1 && playerGrid[i,j] == 1) { shipsFound++; }
- }
- }
- return (shipsFound == numShips ? true : false);
- }
- static void Main(string[] args)
- {
- const int NUM_SHIPS = 3;
- const int GRID_SIZE = 3;
- int[,] grid = GenerateGrid(new int[GRID_SIZE,GRID_SIZE], NUM_SHIPS, GRID_SIZE);
- int[,] playerGrid = new int[GRID_SIZE,GRID_SIZE];
- bool running = true;
- while (running)
- {
- int x, y;
- PrintGrid(playerGrid);
- Console.Write("Enter Coordinates to test (coordinates start at zero)\nX : ");
- string inputX = Console.ReadLine();
- bool resultX = Int32.TryParse(inputX, out x);
- Console.Write("\nY: ");
- string inputY = Console.ReadLine();
- bool resultY = Int32.TryParse(inputY, out y);
- if ((resultX) && (resultY)) { CheckIfInGrid(x, y, grid, playerGrid); }
- else { Console.WriteLine("Error: Invalid Coordinate entered"); }
- Console.WriteLine();
- if (CompareGrids(grid, playerGrid, NUM_SHIPS))
- {
- Console.WriteLine("You won, congratulations!!");
- running = false;
- }
- }
- Console.ReadLine();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement