Hi, I have been writing a battleship game and I almost done. Just need one thing. I have followed all your advices and cut the code down a lot and understood how the game is supposed to be implemented I am struggling on the part where the computer randomly assigns ships to its map but does not show them to the user during the actual game. For example I click start and the computer should randomly assign ships (without displaying them on the board of course) with the user firing and the board does a show where the ship is or is not. Here is the snippet of code where I attempt to assign a value to each square that is supposed to hold a ship
public int[,] RandomShip(Grid grid)
{
enemyShipArray = new int[row, col];
for (int i = 0; i < 1; i++)
{
x = rand.Next(1, 97);
((Button)grid.Children[x]).Tag = 1;
x = x + 1;
((Button)grid.Children[x]).Tag = 1;
x = x + 1;
((Button)grid.Children[x]).Tag = 1;
x = x + 1;
((Button)grid.Children[x]).Tag = 1;
}
for (int a = 0; a < 2; a++)
{
x = rand.Next(1, 98);
((Button)grid.Children[x]).Tag = 1;
x = x + 1;
((Button)grid.Children[x]).Tag = 1;
x = x + 1;
((Button)grid.Children[x]).Tag = 1;
}
for (int a = 0; a < 3; a++)
{
x = rand.Next(1, 99);
((Button)grid.Children[x]).Tag = 1;
x = x + 1;
((Button)grid.Children[x]).Tag = 1;
}
for (int a = 0; a < 4; a++)
{
x = rand.Next(1, 100);
((Button)grid.Children[x]).Tag = 1;
}
return enemyShipArray;
}
Note that this is a method within a seperate class. In the code it can be seen that I want to assign the square a Red background but only when the user clicks on it and there is a ship there. To solve this I assigned a tag to each square that contains a ship so it is marked with a 1. Now onto the function where I press the Start button and the computer must randomly assign the ships without showing.
private void StartButton_Click(object sender, RoutedEventArgs e)
{
enemyShips.RandomShip(gridEnemy);
}
I am passing the enemy grid as the grid to execute the function RandomShip to randomize the ships. Now what I am struggling is how to pass the marked
((Button)grid.Children[x]).Tag = 1;
element into the function where the button click on the enemygrid occurs so it knows which square is marked and which is not.
private void ButtonEnemy_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if( (== 1)
{
((Button)sender).Background = Brushes.Red;
}
else
{
((Button)sender).Background = Brushes.Blue;
}
}
Ideally I would want to put something like
if( ((Button)grid.Children[x]).Tag == 1)
then color the square Red and else color it Blue. Though I do not know how to make the compiler pick up the meaning of the tag equaling the 1. Thanks!
What I have tried:
I have tried even passing a button as an argument into the randomship function even though I know thats wrong but I do not know how to just glue this together.