Skip to content

Instantly share code, notes, and snippets.

@theraot
Created May 6, 2018 14:44
Show Gist options
  • Save theraot/33e351b4e4e3164afaed838e322b2b48 to your computer and use it in GitHub Desktop.
Save theraot/33e351b4e4e3164afaed838e322b2b48 to your computer and use it in GitHub Desktop.
// Note: Code For LinqPad
void Main()
{
bool TryGetCoordinates(string cell, out int indexRow, out int indexCol)
{
indexRow = -1;
indexCol = -1;
if (cell == null)
{
return false;
}
if (cell.Length != 2)
{
return false;
}
indexRow = (int)cell[0] - (int)'A';
indexCol = (int)cell[1] - (int)'1';
return indexRow < 5 && indexRow >= 0 && indexCol < 5 && indexCol >= 0;
}
//Just creating the objects
var board = new Box[5, 5];
for(var indexRow = 0; indexRow < 5; indexRow++)
{
for(var indexCol = 0; indexCol < 5; indexCol++)
{
var box = new Box();
// // Honestly, we do not need this
// box.vhID = (((char)(((int)'a') + indexRow))).ToString() + ((char)(((int)'1') + indexCol)).ToString();
board[indexRow, indexCol] = box;
}
}
// Placing ships
var random = new Random();
var totalShips = 4;
for (var ships = 0; ships < totalShips; ships++)
{
board[random.Next(0, 4), random.Next(0, 4)].hasShip = true;
}
// Game loop
var play = true;
while(play)
{
// Getting the target input
Box target = null;
while(true)
{
Console.WriteLine("Enter target:");
var input = Console.ReadLine().ToUpperInvariant().Trim();
if (TryGetCoordinates(input, out int irow, out int icol))
{
Console.WriteLine("Firing...");
target = board[irow, icol];
break;
}
Console.WriteLine("Invalid coordinate.");
}
if (target.hasShip)
{
target.hasShip = false;
totalShips--; // For victory condition
Console.WriteLine("Ship Destroyed!");
}
else
{
Console.WriteLine("Nothing.");
}
// Victory condition
if (totalShips == 0)
{
Console.WriteLine("You Win!");
break; // break the game loop
}
// Asking if continue playing
while(true)
{
Console.WriteLine("¿Do you want to continue playing (Y/N)?");
var input = Console.ReadLine().ToUpperInvariant().Trim();
if (input == "Y")
{
break;
}
else if (input == "N")
{
play = false; // break the game loop
Console.WriteLine("Game Over.");
break;
}
Console.WriteLine("Invalid input.");
}
}
Console.WriteLine("Thanks for playing!");
}
class Box
{
// public string vhID{get;set;} // Honestly, we do not need this
public bool hasShip{get;set;}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment