using System.Collections; using System.Collections.Generic; using Unity.VisualScripting; using UnityEngine; public class GamePole : MonoBehaviour { public GameManager gameManager; public GameObject eLiters, eNums, ePole; public GameObject[] ShipMass; private List placedShips = new List(); public bool IsReady { get; private set; } = false; GameObject[] Liters; GameObject[] Nums; public GameObject[,] Pole; public int LengPole = 10; public int[,] PoleShot; // 0 - не стрелял 1 - промах 2 - ранил 3 - уничтожен public int[,] FreePole; // поле для растоновки кораблей public Material hitMaterial; private GameObject ghostShip = null; private int ghostShipIndex = -1; private int currentShipIndex = 0; private int shipCaunt = 10; public GameObject[] missEffectPrefabs; // промах void Awake() { PoleShot = new int[LengPole, LengPole]; FreePole = new int[LengPole, LengPole]; if (gameManager == null) gameManager = GetComponentInParent(); } void Start() { CreatePole(); } public Cell GetCell(int x, int y) { // Проверяем, что поле уже создано if (Pole == null) return null; // Проверяем корректность координат if (x < 0 || x >= LengPole || y < 0 || y >= LengPole) return null; GameObject cellObject = Pole[x, y]; if (cellObject == null) return null; return cellObject.GetComponent(); } public List GetPlacedShips() { return placedShips; } void CreatePole() { Vector3 StartPoze = transform.position; float XX = 1; // теперь будем использовать локальные координаты float ZZ = -1; Liters = new GameObject[LengPole]; Nums = new GameObject[LengPole]; for (int Nadpis = 0; Nadpis < LengPole; Nadpis++) { // --- Буквы --- Liters[Nadpis] = Instantiate(eLiters, transform); // делаем дочерним Liters[Nadpis].transform.localPosition = new Vector3(XX, 0, 0); Liters[Nadpis].GetComponent().Index = Nadpis; XX++; // --- Цифры --- Nums[Nadpis] = Instantiate(eNums, transform); // делаем дочерним Nums[Nadpis].transform.localPosition = new Vector3(0, 0, ZZ); Nums[Nadpis].GetComponent().Index = Nadpis; ZZ--; } XX = 1; ZZ = -1; Pole = new GameObject[LengPole, LengPole]; for (int Z = 0; Z < LengPole; Z++) { for (int X = 0; X < LengPole; X++) { Pole[X, Z] = Instantiate(ePole, transform); // делаем дочерним Pole[X, Z].transform.localPosition = new Vector3(XX, 0, ZZ); XX++; } XX = 1; ZZ--; } } public List<(int x, int y)> GetAvailableShots() // получаем доступные для выстрела поля { var available = new List<(int, int)>(); for (int x = 0; x < LengPole; x++) { for (int y = 0; y < LengPole; y++) { if (PoleShot[x, y] == 0) available.Add((x, y)); } } return available; } public int[] SearchWreckedShip() // ищем корабли ваокруг { for (int x = 0; x < LengPole; x++) { for (int y = 0; y < LengPole; y++) { if (PoleShot[x, y] == 2) { // Проверяем клетки вокруг if (HasFreeAdjacent( x, y)) return new int[] { x, y }; } } } return null; } private bool HasFreeAdjacent( int x, int y) { int[,] dirs = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } }; foreach (var i in new int[] { 0, 1, 2, 3 }) { int dx = x + dirs[i, 0]; int dy = y + dirs[i, 1]; if (dx >= 0 && dx < LengPole && dy >= 0 && dy < LengPole) { if (PoleShot[dx, dy] == 0) return true; } } return false; } public bool Shot(int x, int y) { if (PoleShot[x, y] != 0) return true; // затычка bool hit = Pole[x, y].GetComponent().hit(); if (hit) { var cell = Pole[x, y].GetComponent(); if (cell != null && cell.deck != null) { PoleShot[x, y] = 2; gameManager.playerCamera.GetComponent().Shake(0.3f, 0.2f); var ship = cell.deck.GetComponentInParent(); if (ship != null && ship.IsDestroyed()) { HitAroundShip(ship); ship.Destroy(); bool isPlayer = this == gameManager.playerField; // gameManager.ShipDestroyed(isPlayer); } } } else { PoleShot[x, y] = 1; if (missEffectPrefabs != null && missEffectPrefabs.Length > 0) { Vector3 spawnPos = Pole[x, y].transform.position; // выбираем случайный элемент GameObject prefab = missEffectPrefabs[Random.Range(0, missEffectPrefabs.Length)]; if (prefab != null) { GameObject effect = Instantiate(prefab, spawnPos, Quaternion.identity); // Автоматически уничтожаем через 2 секунды Destroy(effect, 2f); } } if (EffectManager.Instance != null) { Vector3 basePos = Pole[x, y].transform.position; // Случайное смещение: по Y от 5 до 10, по X от -1 до 1 float randomY = Random.Range(7f, 14f); float randomX = Random.Range(-2f, 2f); Vector3 spawnPos = basePos + new Vector3(randomX, randomY, 0f); GameObject textFx = EffectManager.Instance.PlayMissText(spawnPos); if (textFx != null) { // Случайный масштаб для разнообразия float scale = Random.Range(3f, 4f); textFx.transform.localScale *= scale; } } } return hit; } // обвдим корабль void HitAroundShip(Ship ship) { foreach (var coord in ship.deckCoords) { for (int dx = -1; dx <= 1; dx++) { for (int dy = -1; dy <= 1; dy++) { int nx = coord.x + dx; int ny = coord.y + dy; if (nx >= 0 && nx < LengPole && ny >= 0 && ny < LengPole) { if (dx == 0 && dy == 0) { PoleShot[nx, ny] = 3; // корабль убит continue; } var cell = Pole[nx, ny].GetComponent(); if (cell != null) { PoleShot[nx, ny] = 1; cell.hit(); } } } } } } public void ClearPole() { ClearGhost(); foreach (var ship in placedShips) { if (ship != null) Destroy(ship); } placedShips.Clear(); currentShipIndex = 0; IsReady = false; for (int x = 0; x < LengPole; x++) { for (int y = 0; y < LengPole; y++) { if (Pole[x, y] != null) { var cell = Pole[x, y].GetComponent(); if (cell != null) { cell.deck = null; cell.HideAll(); } } FreePole[x, y] = 0; PoleShot[x, y] = 0; } } } // проверяемс свободны ли клетки bool CanPlaceShip(int[,] field, int start_x, int start_y, int length, Direction dir) { int dx = 0, dy = 0; switch (dir) { case Direction.Left: dx = -1; break; case Direction.Right: dx = 1; break; case Direction.Up: dy = -1; break; case Direction.Down: dy = 1; break; } for (int i = 0; i < length; i++) { int x = start_x + dx * i; int y = start_y + dy * i; if (x < 0 || x >= LengPole || y < 0 || y >= LengPole) return false; if (field[x, y] != 0) return false; } return true; } public bool PlaceShipManual(int x, int y, Direction direction) { if (currentShipIndex >= shipCaunt) return false; GameObject shipPrefab = ShipMass[currentShipIndex]; int size = shipPrefab.GetComponent().decks.Count; if (!CanPlaceShip(FreePole, x, y, size, direction)) return false; GameObject ship = Instantiate(shipPrefab, transform); ship.SetActive(true); // Поворот switch (direction) { case Direction.Left: ship.transform.localRotation = Quaternion.Euler(0, 0, 0); break; case Direction.Right: ship.transform.localRotation = Quaternion.Euler(0, 180, 0); break; case Direction.Up: ship.transform.localRotation = Quaternion.Euler(0, 90, 0); break; case Direction.Down: ship.transform.localRotation = Quaternion.Euler(0, 270, 0); break; } Vector3 basePos = Pole[x, y].transform.localPosition; ship.transform.localPosition = new Vector3(basePos.x, basePos.y - 0.1f, basePos.z); int end_x = x + (direction == Direction.Left ? -size + 1 : direction == Direction.Right ? size - 1 : 0); int end_y = y + (direction == Direction.Up ? -size + 1 : direction == Direction.Down ? size - 1 : 0); PlaceShip(FreePole, ship, x, y, end_x, end_y); placedShips.Add(ship); ClearGhost(); // убираем призрак currentShipIndex++; return true; } public void ShowShipGhost(int x, int y, Direction direction) { if(currentShipIndex >= shipCaunt) return; int size = ShipMass[currentShipIndex].GetComponent().decks.Count; if (!CanPlaceShip(FreePole, x, y, size, direction)) { if (ghostShip != null) ghostShip.SetActive(false); // просто скрываем return; } // Если уже создан призрак нужного типа — просто обновляем позицию if (ghostShip != null && ghostShipIndex == currentShipIndex) { ghostShip.SetActive(true); // вдруг был скрыт } else { if (ghostShip != null) Destroy(ghostShip); ghostShip = Instantiate(ShipMass[currentShipIndex], transform); ghostShipIndex = currentShipIndex; foreach (Collider col in ghostShip.GetComponentsInChildren()) col.enabled = false; foreach (Renderer renderer in ghostShip.GetComponentsInChildren()) renderer.material.color = new Color(1f, 1f, 1f, 0.3f); // полупрозрачный } // Поворот switch (direction) { case Direction.Left: ghostShip.transform.localRotation = Quaternion.Euler(0, 0, 0); break; case Direction.Right: ghostShip.transform.localRotation = Quaternion.Euler(0, 180, 0); break; case Direction.Up: ghostShip.transform.localRotation = Quaternion.Euler(0, 90, 0); break; case Direction.Down: ghostShip.transform.localRotation = Quaternion.Euler(0, 270, 0); break; } Vector3 basePos = Pole[x, y].transform.localPosition; ghostShip.transform.localPosition = new Vector3(basePos.x, basePos.y - 0.1f, basePos.z); } public void ClearGhost() { if (ghostShip != null) { Destroy(ghostShip); ghostShip = null; ghostShipIndex = -1; } } // раставляем корабли public void ArrangeShip(bool hideShips = false) { ClearPole(); foreach (GameObject shipPrefab in ShipMass) { GameObject ship = Instantiate(shipPrefab); ship.transform.SetParent(this.transform, false); ship.SetActive(true); placedShips.Add(ship); if (hideShips) { foreach (Renderer r in ship.GetComponentsInChildren()) r.enabled = false; } int quantity = ship.GetComponent().decks.Count; // Генерируем список всех возможных позиций List<(int x, int y, Direction dir)> possiblePlacements = new(); for (int x = 0; x < LengPole; x++) { for (int y = 0; y < LengPole; y++) { foreach (Direction direction in System.Enum.GetValues(typeof(Direction))) { if (CanPlaceShip(FreePole, x, y, quantity, direction)) possiblePlacements.Add((x, y, direction)); } } } // Если нет ни одного подходящего места if (possiblePlacements.Count == 0) { Debug.LogWarning("Не удалось разместить корабль, перезапускаем расстановку."); ArrangeShip(hideShips); continue; } // Перемешиваем возможные позиции Shuffle(possiblePlacements); // Берем первую подходящую var (start_x, start_y, dir) = possiblePlacements[0]; switch (dir) { case Direction.Left: ship.transform.localRotation = Quaternion.Euler(0, 0, 0); break; case Direction.Right: ship.transform.localRotation = Quaternion.Euler(0, 180, 0); break; case Direction.Up: ship.transform.localRotation = Quaternion.Euler(0, 90, 0); break; case Direction.Down: ship.transform.localRotation = Quaternion.Euler(0, 270, 0); break; } Vector3 basePos = Pole[start_x, start_y].transform.localPosition; ship.transform.localPosition = new Vector3(basePos.x, basePos.y - 0.1f, basePos.z); int end_x = start_x + (dir == Direction.Left ? -quantity + 1 : dir == Direction.Right ? quantity - 1 : 0); int end_y = start_y + (dir == Direction.Up ? -quantity + 1 : dir == Direction.Down ? quantity - 1 : 0); PlaceShip(FreePole, ship, start_x, start_y, end_x, end_y); } IsReady = true; } void Shuffle(List list) { for (int i = list.Count - 1; i > 0; i--) { int j = Random.Range(0, i + 1); (list[i], list[j]) = (list[j], list[i]); } } // тут раставляются корабли void PlaceShip(int[,] FreePole, GameObject ship, int start_x, int start_y, int end_x, int end_y) { var decks = ship.GetComponent().decks; int deckIndex = 0; if (start_x != end_x) { int step = start_x < end_x ? 1 : -1; for (; start_x != end_x + step; start_x += step) { SetDeckAndAround(FreePole, start_x, start_y, decks[deckIndex]); ship.GetComponent().AddDeckCoord(start_x, start_y); deckIndex++; } } else { int step = start_y < end_y ? 1 : -1; for (; start_y != end_y + step; start_y += step) { SetDeckAndAround(FreePole, start_x, start_y, decks[deckIndex]); ship.GetComponent().AddDeckCoord(start_x, start_y); deckIndex++; } } } // тут устанавливаем палубы и свободное поле делаем не свободным void SetDeckAndAround(int[,] FreePole, int x, int y, GameObject deck) { FreePole[x, y] = 1; // Привязка палубы к клетке Pole[x, y].GetComponent().deck = deck; // TODU надо придумать что-то поумнее deck.SetActive(true); for (int dx = -1; dx <= 1; dx++) { for (int dy = -1; dy <= 1; dy++) { int nx = x + dx; int ny = y + dy; if (nx >= 0 && nx < LengPole && ny >= 0 && ny < LengPole && FreePole[nx, ny] == 0) { FreePole[nx, ny] = 2; } } } } // тут копируем корабли public void CopyShipsFrom(GamePole sourceField, bool hideShips = true) { ClearPole(); foreach (var originalShip in sourceField.placedShips) { GameObject copy = Instantiate(originalShip); // Делаем копию дочерним объектом текущего поля copy.transform.SetParent(this.transform, false); // Копируем ЛОКАЛЬНЫЕ координаты, чтобы корабли встали на сетку поля copy.transform.localPosition = originalShip.transform.localPosition; copy.transform.localRotation = originalShip.transform.localRotation; if (hideShips) { foreach (Renderer r in copy.GetComponentsInChildren()) r.enabled = false; } placedShips.Add(copy); var ship = copy.GetComponent(); var sourceShip = originalShip.GetComponent(); for (int i = 0; i < sourceShip.deckCoords.Count; i++) { var coord = sourceShip.deckCoords[i]; Pole[coord.x, coord.y].GetComponent().deck = ship.decks[i]; ship.AddDeckCoord(coord.x, coord.y); } } IsReady = true; } }