Advertisement
fuccpuff

Untitled

Nov 18th, 2024
12
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.51 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.Linq;
  5. using System.Windows.Forms;
  6.  
  7. namespace SeaWedFri
  8. {
  9. public partial class Form1 : Form
  10. {
  11. private const int cellSize = 30;
  12. private int[,] playerField = new int[10, 10];
  13. private int[,] botField = new int[10, 10];
  14. private Button[,] playerButtons = new Button[10, 10];
  15. private Button[,] botButtons = new Button[10, 10];
  16. private Random random = new Random();
  17. private bool isHorizontal = true;
  18.  
  19. public Form1()
  20. {
  21. InitializeComponent();
  22. InitializeGame();
  23. }
  24.  
  25. private void InitializeGame()
  26. {
  27. CreateField(playerPanel, true);
  28. CreateField(botPanel, false);
  29. }
  30.  
  31. private void CreateField(Panel panel, bool isPlayer)
  32. {
  33. panel.Controls.Clear();
  34.  
  35. for (int x = 0; x < 10; x++)
  36. {
  37. for (int y = 0; y < 10; y++)
  38. {
  39. Button cell = new Button
  40. {
  41. Size = new Size(cellSize, cellSize),
  42. Location = new Point(x * cellSize, y * cellSize),
  43. Tag = new Point(x, y),
  44. BackColor = Color.LightBlue,
  45. Enabled = isPlayer // Отключаем возможность клика по клеткам бота до начала игры
  46. };
  47.  
  48. if (!isPlayer)
  49. {
  50. cell.Click += PlayerCell_Click;
  51. }
  52.  
  53. panel.Controls.Add(cell);
  54.  
  55. if (isPlayer)
  56. {
  57. playerButtons[x, y] = cell;
  58. }
  59. else
  60. {
  61. botButtons[x, y] = cell;
  62. }
  63. }
  64. }
  65. }
  66.  
  67. private void ship_MouseDown(object sender, MouseEventArgs e)
  68. {
  69. Button ship = sender as Button;
  70. ship.DoDragDrop(ship, DragDropEffects.Move);
  71. }
  72.  
  73. private void playerPanel_DragEnter(object sender, DragEventArgs e)
  74. {
  75. if (e.Data.GetDataPresent(typeof(Button)))
  76. e.Effect = DragDropEffects.Move;
  77. }
  78.  
  79. private void playerPanel_DragDrop(object sender, DragEventArgs e)
  80. {
  81. Button ship = (Button)e.Data.GetData(typeof(Button));
  82. Point dropLocation = playerPanel.PointToClient(new Point(e.X, e.Y));
  83.  
  84. int x = dropLocation.X / cellSize;
  85. int y = dropLocation.Y / cellSize;
  86.  
  87. int length = int.Parse(ship.Text);
  88. bool horizontal = isHorizontal;
  89.  
  90. if (CanPlaceShip(playerField, x, y, length, horizontal))
  91. {
  92. PlaceShip(playerField, x, y, length, horizontal, true);
  93.  
  94. // Скрываем или отключаем кнопку корабля после размещения
  95. ship.Enabled = false;
  96. ship.Visible = false;
  97.  
  98. logListBox.Items.Add($"Вы разместили корабль длиной {length} по координатам ({x}, {y}) {(horizontal ? "горизонтально" : "вертикально")}.");
  99. }
  100. else
  101. {
  102. MessageBox.Show("Невозможно разместить корабль здесь! Требуется отступ в одну клетку.");
  103. }
  104. }
  105.  
  106. private bool CanPlaceShip(int[,] field, int x, int y, int length, bool horizontal)
  107. {
  108. if (horizontal)
  109. {
  110. if (x + length > 10) return false;
  111. }
  112. else
  113. {
  114. if (y + length > 10) return false;
  115. }
  116.  
  117. for (int i = -1; i <= length; i++)
  118. {
  119. for (int j = -1; j <= 1; j++)
  120. {
  121. int xi = x + (horizontal ? i : j);
  122. int yj = y + (horizontal ? j : i);
  123. if (xi >= 0 && xi < 10 && yj >= 0 && yj < 10)
  124. {
  125. if (field[xi, yj] != 0) return false;
  126. }
  127. }
  128. }
  129. return true;
  130. }
  131.  
  132. private void PlaceShip(int[,] field, int x, int y, int length, bool horizontal, bool isPlayer)
  133. {
  134. if (horizontal)
  135. {
  136. for (int i = 0; i < length; i++)
  137. {
  138. field[x + i, y] = 1;
  139. if (isPlayer)
  140. {
  141. playerButtons[x + i, y].BackColor = Color.Green;
  142. }
  143. }
  144. }
  145. else
  146. {
  147. for (int i = 0; i < length; i++)
  148. {
  149. field[x, y + i] = 1;
  150. if (isPlayer)
  151. {
  152. playerButtons[x, y + i].BackColor = Color.Green;
  153. }
  154. }
  155. }
  156. }
  157.  
  158. private void PlaceBotShips()
  159. {
  160. int[] shipLengths = { 4, 3, 3, 2, 2, 2, 1, 1, 1, 1 };
  161.  
  162. foreach (int length in shipLengths)
  163. {
  164. bool placed = false;
  165. while (!placed)
  166. {
  167. int x = random.Next(10);
  168. int y = random.Next(10);
  169. bool horizontal = random.Next(2) == 0;
  170. if (CanPlaceShip(botField, x, y, length, horizontal))
  171. {
  172. PlaceShip(botField, x, y, length, horizontal, false); // isPlayer = false
  173. placed = true;
  174. }
  175. }
  176. }
  177. }
  178.  
  179. private void startGameButton_Click(object sender, EventArgs e)
  180. {
  181. // Проверяем, что все корабли размещены
  182. if (AreAllShipsPlaced())
  183. {
  184. PlaceBotShips();
  185. MessageBox.Show("Игра началась! Ход игрока.", "Морской бой");
  186. // Разрешаем клики по клеткам бота
  187. foreach (var button in botButtons)
  188. {
  189. button.Enabled = true;
  190. }
  191. }
  192. else
  193. {
  194. MessageBox.Show("Пожалуйста, разместите все свои корабли перед началом игры.");
  195. }
  196. }
  197.  
  198. private bool AreAllShipsPlaced()
  199. {
  200. foreach (var control in Controls.OfType<Button>())
  201. {
  202. if (control.Name.StartsWith("ship") && control.Enabled)
  203. {
  204. return false;
  205. }
  206. }
  207. return true;
  208. }
  209.  
  210. private void PlayerCell_Click(object sender, EventArgs e)
  211. {
  212. Button cell = sender as Button;
  213. Point coordinates = (Point)cell.Tag;
  214. int x = coordinates.X;
  215. int y = coordinates.Y;
  216.  
  217. if (botField[x, y] == 2 || botField[x, y] == 3)
  218. {
  219. MessageBox.Show("Вы уже стреляли сюда!");
  220. return;
  221. }
  222.  
  223. if (Shoot(x, y, botField))
  224. {
  225. cell.BackColor = Color.Red;
  226. logListBox.Items.Add($"Вы попали по координатам ({x}, {y})!");
  227.  
  228. if (IsShipDestroyed(botField, x, y))
  229. {
  230. MarkDestroyedShip(botField, botButtons, x, y);
  231. logListBox.Items.Add("Вы уничтожили корабль!");
  232. }
  233.  
  234. if (CheckWin(botField))
  235. {
  236. MessageBox.Show("Игрок выиграл!");
  237. logListBox.Items.Add("Игрок выиграл!");
  238. ResetGame();
  239. }
  240. }
  241. else
  242. {
  243. cell.BackColor = Color.Blue;
  244. logListBox.Items.Add($"Вы промахнулись по координатам ({x}, {y}).");
  245. BotTurn();
  246. }
  247. }
  248.  
  249. private bool Shoot(int x, int y, int[,] field)
  250. {
  251. if (field[x, y] == 1)
  252. {
  253. field[x, y] = 2;
  254. return true;
  255. }
  256. else if (field[x, y] == 0)
  257. {
  258. field[x, y] = 3;
  259. return false;
  260. }
  261. return false;
  262. }
  263.  
  264. private void BotTurn()
  265. {
  266. int x, y;
  267. do
  268. {
  269. x = random.Next(10);
  270. y = random.Next(10);
  271. }
  272. while (playerField[x, y] == 2 || playerField[x, y] == 3);
  273.  
  274. if (Shoot(x, y, playerField))
  275. {
  276. Button btn = GetButtonAt(true, x, y);
  277. if (btn != null)
  278. {
  279. btn.BackColor = Color.Red;
  280. }
  281.  
  282. logListBox.Items.Add($"Бот попал по вашим координатам ({x}, {y})!");
  283. if (IsShipDestroyed(playerField, x, y))
  284. {
  285. MarkDestroyedShip(playerField, playerButtons, x, y);
  286. logListBox.Items.Add("Ваш корабль уничтожен!");
  287. }
  288. if (CheckWin(playerField))
  289. {
  290. MessageBox.Show("Бот выиграл!");
  291. logListBox.Items.Add("Бот выиграл!");
  292. ResetGame();
  293. }
  294. else
  295. {
  296. BotTurn();
  297. }
  298. }
  299. else
  300. {
  301. Button btn = GetButtonAt(true, x, y);
  302. if (btn != null)
  303. {
  304. btn.BackColor = Color.Blue;
  305. }
  306. logListBox.Items.Add($"Бот промахнулся по координатам ({x}, {y}).");
  307. }
  308. }
  309.  
  310. private Button GetButtonAt(bool isPlayer, int x, int y)
  311. {
  312. if (isPlayer)
  313. {
  314. return playerButtons[x, y];
  315. }
  316. else
  317. {
  318. return botButtons[x, y];
  319. }
  320. }
  321.  
  322. private bool CheckWin(int[,] field)
  323. {
  324. for (int x = 0; x < 10; x++)
  325. {
  326. for (int y = 0; y < 10; y++)
  327. {
  328. if (field[x, y] == 1)
  329. {
  330. return false;
  331. }
  332. }
  333. }
  334. return true;
  335. }
  336.  
  337. private void ResetGame()
  338. {
  339. playerPanel.Controls.Clear();
  340. botPanel.Controls.Clear();
  341.  
  342. logListBox.Items.Clear();
  343.  
  344. playerField = new int[10, 10];
  345. botField = new int[10, 10];
  346.  
  347. playerButtons = new Button[10, 10];
  348. botButtons = new Button[10, 10];
  349.  
  350. InitializeGame();
  351.  
  352. // Сбрасываем корабли
  353. foreach (var control in Controls.OfType<Button>())
  354. {
  355. if (control.Name.StartsWith("ship"))
  356. {
  357. control.Enabled = true;
  358. control.Visible = true;
  359. control.BackColor = SystemColors.Control;
  360. }
  361. }
  362. }
  363.  
  364. private bool IsShipDestroyed(int[,] field, int x, int y)
  365. {
  366. Queue<Point> queue = new Queue<Point>();
  367. List<Point> shipCells = new List<Point>();
  368. queue.Enqueue(new Point(x, y));
  369.  
  370. while (queue.Count > 0)
  371. {
  372. Point p = queue.Dequeue();
  373. if (!shipCells.Contains(p))
  374. {
  375. shipCells.Add(p);
  376.  
  377. int[] dx = { -1, 1, 0, 0 };
  378. int[] dy = { 0, 0, -1, 1 };
  379.  
  380. for (int dir = 0; dir < 4; dir++)
  381. {
  382. int nx = p.X + dx[dir];
  383. int ny = p.Y + dy[dir];
  384. if (nx >= 0 && nx < 10 && ny >= 0 && ny < 10)
  385. {
  386. if (field[nx, ny] == 2)
  387. {
  388. queue.Enqueue(new Point(nx, ny));
  389. }
  390. else if (field[nx, ny] == 1)
  391. {
  392. return false;
  393. }
  394. }
  395. }
  396. }
  397. }
  398.  
  399. return true;
  400. }
  401.  
  402. private void MarkDestroyedShip(int[,] field, Button[,] buttons, int x, int y)
  403. {
  404. Color destroyedColor = Color.DarkRed;
  405. Queue<Point> queue = new Queue<Point>();
  406. List<Point> shipCells = new List<Point>();
  407. queue.Enqueue(new Point(x, y));
  408.  
  409. while (queue.Count > 0)
  410. {
  411. Point p = queue.Dequeue();
  412. if (!shipCells.Contains(p))
  413. {
  414. shipCells.Add(p);
  415. Button btn = buttons[p.X, p.Y];
  416. if (btn != null)
  417. {
  418. btn.BackColor = destroyedColor;
  419. }
  420.  
  421. int[] dx = { -1, 1, 0, 0 };
  422. int[] dy = { 0, 0, -1, 1 };
  423.  
  424. for (int dir = 0; dir < 4; dir++)
  425. {
  426. int nx = p.X + dx[dir];
  427. int ny = p.Y + dy[dir];
  428. if (nx >= 0 && nx < 10 && ny >= 0 && ny < 10 && field[nx, ny] == 2)
  429. {
  430. field[nx, ny] = -1; // Помечаем как обработанный
  431. queue.Enqueue(new Point(nx, ny));
  432. }
  433. }
  434. }
  435. }
  436. }
  437.  
  438. private void rotateButton_Click(object sender, EventArgs e)
  439. {
  440. isHorizontal = !isHorizontal;
  441. rotateButton.Text = isHorizontal ? "Горизонтально" : "Вертикально";
  442. }
  443. }
  444. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement