Question: Use C# to perform the following tasks on the code provided @ the bottom of the page: Use the provided project and add the following
Use C# to perform the following tasks on the code provided @ the bottom of the page:
Use the provided project and add the following features to the app:
1. Use MessageBox.Show to display a message when the ship has been sunk
2. Add a score to the message that includes how many moves were made by the player
3. Fix some bugs: a player can re-click on an old hit and it could count as a new hit; a player could re-click on an old miss and it could count as a new miss.
4. The grand finale: create a reset method that is called after the player dismisses the messagebox.
5. Optional for after the semester is over: add a second grid below the first that allows the player to add their own ship and then write code for the computer to shoot at this ship.
All code for the forementioned program is listed below here, with the title of the file listed first:
Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms;
namespace WindowsFormsApplication1 { static class Program { ///
Form1.cs
using System; using System.Drawing; using System.Windows.Forms;
namespace WindowsFormsApplication1 { public partial class Form1 : Form { int[,] array = new int[10, 10]; // col, row TableLayoutPanel grid = new TableLayoutPanel();
public Form1() { InitializeComponent(); placeShips();
this.Size = new Size(320, 340); grid.Size = new Size(300, 300); grid.ColumnCount = 10; grid.RowCount = 10; Controls.Add(grid);
for (int row = 0; row < grid.RowCount; row++) { for (int col = 0; col < grid.ColumnCount; col++) { Button btn1 = new Button(); btn1.Size = new Size(30, 30); btn1.BackColor = Color.SkyBlue; btn1.Margin = new Padding(0); btn1.FlatStyle = new FlatStyle(); btn1.Click += new EventHandler(btnEventHandler); grid.Controls.Add(btn1, col, row); } } }
private void btnEventHandler(object sender, EventArgs e) { Button b = ((Button)sender);
for (int row = 0; row < grid.RowCount; row++) { for (int col = 0; col < grid.ColumnCount; col++) { if (grid.GetControlFromPosition(col, row).Equals(b)) { if (array[col, row] == 1) // ship { b.BackColor = Color.Red; } else if (array[col, row] == 0) // no ship { b.BackColor = Color.DodgerBlue; } return; } } } }
private void placeShips() { Random ran = new Random(); int row = ran.Next(0, 10); int col = ran.Next(0, 6); for (int i = 0; i < 4; i++) array[col + i, row] = 1; }
} }
Form1.Designer.cs
namespace WindowsFormsApplication1 { partial class Form1 { ///
///
#region Windows Form Designer generated code
///
#endregion } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
