246 lines
12 KiB
C#
246 lines
12 KiB
C#
using System.Collections.Generic;
|
||||
|
|
using UnityEngine;
|
|||
|
|
|
|||
|
|
/// <summary>
|
|||
|
|
/// Покупка и торг с продавцом [B]: найденные игроком дефекты (кузов, колеса, подкапотное пространство,
|
|||
|
|
/// ошибки OBD, скрытый перекрас) становятся аргументами и снижают цену на 10–25%.
|
|||
|
|
/// Можно сразу заказать эвакуатор до гаража, если машина не на ходу.
|
|||
|
|
/// </summary>
|
|||
|
|
public class SellerBargainUI : MonoBehaviour
|
|||
|
|
{
|
|||
|
|
[SerializeField] private KeyCode openKey = KeyCode.B;
|
|||
|
|
[SerializeField] private float interactDistance = 7f;
|
|||
|
|
[SerializeField] private float maxDiscountPercent = 25f;
|
|||
|
|
[SerializeField] private float towTruckPrice = 60f;
|
|||
|
|
|
|||
|
|
private CarOwnership target;
|
|||
|
|
private List<CarInspection.Defect> defects = new List<CarInspection.Defect>();
|
|||
|
|
private readonly HashSet<string> usedArguments = new HashSet<string>();
|
|||
|
|
private float discountPercent;
|
|||
|
|
private string sellerReply;
|
|||
|
|
private bool isOpen;
|
|||
|
|
private Vector2 scroll;
|
|||
|
|
private Transform player;
|
|||
|
|
|
|||
|
|
private static readonly string[] AgreeReplies =
|
|||
|
|
{
|
|||
|
|
"Ну да, есть такое... Ладно, скину немного.",
|
|||
|
|
"Эх, глазастый попался. Давай уступлю.",
|
|||
|
|
"Это мелочи, но так и быть — минус.",
|
|||
|
|
"Хорошо, хорошо, торг уместен.",
|
|||
|
|
"Ты прав, придется вложиться. Сбавлю."
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
private void Update()
|
|||
|
|
{
|
|||
|
|
if (isOpen)
|
|||
|
|
{
|
|||
|
|
if (Input.GetKeyDown(KeyCode.Escape) || target == null) Close();
|
|||
|
|
return;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if (GameInputLock.IsLocked || VehicleInteraction.Current != null) return;
|
|||
|
|
MainMenuAndBootManager menu = MainMenuAndBootManager.Instance;
|
|||
|
|
if (menu != null && !menu.IsPlaying) return;
|
|||
|
|
|
|||
|
|
if (player == null)
|
|||
|
|
{
|
|||
|
|
PlayerMovement pm = FindAnyObjectByType<PlayerMovement>();
|
|||
|
|
if (pm != null) player = pm.transform;
|
|||
|
|
}
|
|||
|
|
if (player == null || !player.gameObject.activeInHierarchy) return;
|
|||
|
|
|
|||
|
|
CarOwnership near = CarOwnership.FindNearestNotOwned(player.position, interactDistance);
|
|||
|
|
if (near == null) return;
|
|||
|
|
|
|||
|
|
GameHUD.SetContextHint($"{near.carTitle} — продавец {near.sellerName} ждет: [B] Оформить сделку / Торговаться");
|
|||
|
|
if (Input.GetKeyDown(openKey)) Open(near);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private void Open(CarOwnership car)
|
|||
|
|
{
|
|||
|
|
target = car;
|
|||
|
|
defects = CarInspection.CollectDefects(car);
|
|||
|
|
usedArguments.Clear();
|
|||
|
|
discountPercent = 0f;
|
|||
|
|
sellerReply = $"Здравствуйте! Машина {car.carTitle}, {car.year} г. Прошу {GameUI.Money(car.askingPrice)}. Смотрите, проверяйте.";
|
|||
|
|
isOpen = true;
|
|||
|
|
GameInputLock.Lock(this);
|
|||
|
|
ProceduralAudioManager.Instance?.Play(SfxId.Notification);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private void Close()
|
|||
|
|
{
|
|||
|
|
isOpen = false;
|
|||
|
|
target = null;
|
|||
|
|
GameInputLock.Unlock(this);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private float CurrentPrice => target == null ? 0f : Mathf.Round(target.askingPrice * (1f - discountPercent / 100f) / 10f) * 10f;
|
|||
|
|
|
|||
|
|
private bool CarIsDrivable()
|
|||
|
|
{
|
|||
|
|
if (target == null) return false;
|
|||
|
|
EngineBayManager bay = target.GetComponent<EngineBayManager>();
|
|||
|
|
EnginePart bat = bay != null ? bay.GetPart(EnginePartType.Battery) : null;
|
|||
|
|
bool engineOk = bay == null || (bat != null && bat.charge >= 20f && bay.GetPart(EnginePartType.SparkPlugs) != null);
|
|||
|
|
int wheels = 0;
|
|||
|
|
foreach (WheelCollider wc in target.GetComponentsInChildren<WheelCollider>()) if (wc.enabled) wheels++;
|
|||
|
|
return engineOk && wheels >= 4;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private void UseArgument(CarInspection.Defect d)
|
|||
|
|
{
|
|||
|
|
if (usedArguments.Contains(d.text)) return;
|
|||
|
|
usedArguments.Add(d.text);
|
|||
|
|
|
|||
|
|
if (discountPercent >= maxDiscountPercent - 0.01f)
|
|||
|
|
{
|
|||
|
|
sellerReply = "Всё, ниже не опущу! Это и так последняя цена.";
|
|||
|
|
ProceduralAudioManager.Instance?.Play(SfxId.Error);
|
|||
|
|
return;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
float add = d.discountPercent * Random.Range(0.85f, 1.25f);
|
|||
|
|
discountPercent = Mathf.Min(maxDiscountPercent, discountPercent + add);
|
|||
|
|
sellerReply = AgreeReplies[Random.Range(0, AgreeReplies.Length)] + $" Скидка уже {discountPercent:F0}%.";
|
|||
|
|
ProceduralAudioManager.Instance?.Play(SfxId.Ui, null, 1f, 1.2f);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private void Buy(bool withTowTruck)
|
|||
|
|
{
|
|||
|
|
GameEconomyManager eco = GameEconomyManager.Instance;
|
|||
|
|
float price = CurrentPrice;
|
|||
|
|
float total = price + (withTowTruck ? towTruckPrice : 0f);
|
|||
|
|
|
|||
|
|
if (eco != null && !eco.CanAfford(total))
|
|||
|
|
{
|
|||
|
|
sellerReply = "Денег не хватает? Приходите, когда соберете нужную сумму.";
|
|||
|
|
ProceduralAudioManager.Instance?.Play(SfxId.Error);
|
|||
|
|
return;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
CarOwnership car = target;
|
|||
|
|
car.isOwned = true;
|
|||
|
|
car.purchasePrice = price;
|
|||
|
|
car.expenses = 0f;
|
|||
|
|
if (eco != null)
|
|||
|
|
{
|
|||
|
|
eco.TrySpend(price, $"Покупка {car.carTitle}", null, false);
|
|||
|
|
if (withTowTruck) eco.TrySpend(towTruckPrice, "Эвакуатор до гаража", car);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
CarMarketManager market = FindAnyObjectByType<CarMarketManager>();
|
|||
|
|
if (market != null && car.Listing != null) market.MarkListingSold(car.Listing);
|
|||
|
|
|
|||
|
|
if (withTowTruck) TowToGarage(car);
|
|||
|
|
|
|||
|
|
GameHUD.Notify($"Куплено: {car.carTitle} за {GameUI.Money(price)}" + (discountPercent > 0.5f ? $" (скидка {discountPercent:F0}%)" : ""), GameUI.Green);
|
|||
|
|
Close();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public static void TowToGarage(CarOwnership car)
|
|||
|
|
{
|
|||
|
|
GameEconomyManager eco = GameEconomyManager.Instance;
|
|||
|
|
if (eco == null || eco.garageCarSpot == null || car == null) return;
|
|||
|
|
|
|||
|
|
Vector3 pos = eco.garageCarSpot.position;
|
|||
|
|
// Если место в боксе занято — ставим во дворе рядом
|
|||
|
|
foreach (CarOwnership other in CarOwnership.All)
|
|||
|
|
{
|
|||
|
|
if (other == null || other == car) continue;
|
|||
|
|
if (Vector3.Distance(other.transform.position, pos) < 3.5f)
|
|||
|
|
{
|
|||
|
|
pos = eco.garageCarSpot.position + eco.garageCarSpot.forward * 11f + eco.garageCarSpot.right * 4.5f;
|
|||
|
|
break;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// Старые кирпичи (и их физический якорь) убираем — в гараже поставим новые под пустую ступицу
|
|||
|
|
foreach (WheelBrickSupport b in FindObjectsByType<WheelBrickSupport>(FindObjectsSortMode.None))
|
|||
|
|
if (Vector3.Distance(b.transform.position, car.transform.position) < 4f) b.RemoveBricks();
|
|||
|
|
|
|||
|
|
Rigidbody rb = car.GetComponent<Rigidbody>();
|
|||
|
|
Vector3 target = pos + Vector3.up * 0.35f;
|
|||
|
|
car.transform.SetPositionAndRotation(target, eco.garageCarSpot.rotation);
|
|||
|
|
if (rb != null)
|
|||
|
|
{
|
|||
|
|
rb.position = target;
|
|||
|
|
rb.rotation = eco.garageCarSpot.rotation;
|
|||
|
|
rb.linearVelocity = Vector3.zero;
|
|||
|
|
rb.angularVelocity = Vector3.zero;
|
|||
|
|
}
|
|||
|
|
Physics.SyncTransforms();
|
|||
|
|
|
|||
|
|
foreach (CarPart wheel in car.GetComponentsInChildren<CarPart>(true))
|
|||
|
|
{
|
|||
|
|
if (wheel.LinkedWheelCollider == null || wheel.gameObject.activeSelf || wheel.State == PartState.Installed) continue;
|
|||
|
|
WheelBrickSupport.CreateUnderWheel(wheel);
|
|||
|
|
}
|
|||
|
|
GameHUD.Notify($"Эвакуатор доставил {car.carTitle} в гараж", GameUI.Blue);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
private void OnGUI()
|
|||
|
|
{
|
|||
|
|
if (!isOpen || target == null) return;
|
|||
|
|
GameUI.Begin(-10);
|
|||
|
|
float w = GameUI.VirtualWidth;
|
|||
|
|
float h = GameUI.VirtualHeight;
|
|||
|
|
GameUI.DrawRect(new Rect(0, 0, w, h), GameUI.Bg.WithAlpha(0.55f));
|
|||
|
|
|
|||
|
|
Rect r = new Rect(w * 0.5f - 560, h * 0.5f - 420, 1120, 840);
|
|||
|
|
GUI.Box(r, GUIContent.none, GameUI.PanelSolid);
|
|||
|
|
|
|||
|
|
GUI.Label(new Rect(r.x + 30, r.y + 18, r.width - 60, 44), $"СДЕЛКА: {target.carTitle}", GameUI.Header);
|
|||
|
|
GUI.Label(new Rect(r.x + 30, r.y + 62, r.width - 60, 30),
|
|||
|
|
$"{target.year} г. • пробег {target.mileageKm:N0} км • продавец: {target.sellerName} • цена в объявлении: {GameUI.Money(target.askingPrice)}", GameUI.Small);
|
|||
|
|
|
|||
|
|
Rect reply = new Rect(r.x + 30, r.y + 104, r.width - 60, 64);
|
|||
|
|
GUI.Box(reply, GUIContent.none, GameUI.Panel);
|
|||
|
|
GUI.Label(new Rect(reply.x + 16, reply.y + 8, reply.width - 32, reply.height - 16), $"<color=#9AA0A6>Продавец:</color> «{sellerReply}»", GameUI.Label);
|
|||
|
|
|
|||
|
|
GUI.Label(new Rect(r.x + 30, r.y + 186, r.width - 60, 30), "<b>Найденные дефекты — аргументы для снижения цены:</b>", GameUI.Label);
|
|||
|
|
|
|||
|
|
Rect listView = new Rect(r.x + 30, r.y + 222, r.width - 60, 400);
|
|||
|
|
int hidden = 0;
|
|||
|
|
float rowH = 54f;
|
|||
|
|
List<CarInspection.Defect> shown = new List<CarInspection.Defect>();
|
|||
|
|
foreach (var d in defects) { if (d.revealed) shown.Add(d); else hidden++; }
|
|||
|
|
|
|||
|
|
scroll = GUI.BeginScrollView(listView, scroll, new Rect(0, 0, listView.width - 24, Mathf.Max(listView.height, shown.Count * rowH + 10)));
|
|||
|
|
float y = 0;
|
|||
|
|
if (shown.Count == 0)
|
|||
|
|
GUI.Label(new Rect(0, 0, listView.width - 30, 60), "Явных дефектов не видно. Осмотрите машину внимательнее: капот, OBD-сканер, толщиномер ЛКП.", GameUI.Small);
|
|||
|
|
foreach (var d in shown)
|
|||
|
|
{
|
|||
|
|
bool used = usedArguments.Contains(d.text);
|
|||
|
|
GUI.Label(new Rect(4, y + 12, listView.width - 290, 34), $"• {d.text}", GameUI.Label);
|
|||
|
|
if (used)
|
|||
|
|
GUI.Label(new Rect(listView.width - 270, y + 12, 240, 34), "<color=#4CD07D>учтено</color>", GameUI.LabelCenter);
|
|||
|
|
else if (GameUI.Btn(new Rect(listView.width - 270, y + 6, 240, 44), "Указать продавцу"))
|
|||
|
|
UseArgument(d);
|
|||
|
|
y += rowH;
|
|||
|
|
}
|
|||
|
|
GUI.EndScrollView();
|
|||
|
|
|
|||
|
|
if (hidden > 0)
|
|||
|
|
GUI.Label(new Rect(r.x + 30, r.y + 628, r.width - 60, 30),
|
|||
|
|
$"<color=#F2A93B>Возможны скрытые дефекты ({hidden}).</color> Проверьте: открыть капот и щуп, OBD-сканер [Tab], толщиномер ЛКП [Tab].", GameUI.Small);
|
|||
|
|
|
|||
|
|
GUI.Label(new Rect(r.x + 30, r.y + 666, 760, 50),
|
|||
|
|
$"Итоговая цена: <b><color=#4CD07D>{GameUI.Money(CurrentPrice)}</color></b> (скидка {discountPercent:F0}%)", new GUIStyle(GameUI.Label) { fontSize = 24 });
|
|||
|
|
|
|||
|
|
GameEconomyManager eco = GameEconomyManager.Instance;
|
|||
|
|
string balance = eco == null ? "" : (eco.Unlimited ? "Свободный режим: деньги не ограничены" : $"На счету: {eco.FormatMoney(eco.Money)}");
|
|||
|
|
GUI.Label(new Rect(r.x + 30, r.y + 708, r.width - 60, 30), balance, GameUI.Small);
|
|||
|
|
|
|||
|
|
bool drivable = CarIsDrivable();
|
|||
|
|
float by = r.yMax - 92;
|
|||
|
|
if (GameUI.Btn(new Rect(r.x + 30, by, 330, 62), "КУПИТЬ\n<size=15>своим ходом</size>", GameUI.ButtonAccent))
|
|||
|
|
Buy(false);
|
|||
|
|
if (GameUI.Btn(new Rect(r.x + 380, by, 400, 62), $"КУПИТЬ + ЭВАКУАТОР В ГАРАЖ\n<size=15>+{GameUI.Money(towTruckPrice)}{(drivable ? "" : " — машина не на ходу!")}</size>"))
|
|||
|
|
Buy(true);
|
|||
|
|
if (GameUI.Btn(new Rect(r.xMax - 300, by, 270, 62), "ОТКАЗАТЬСЯ", GameUI.ButtonDanger))
|
|||
|
|
Close();
|
|||
|
|
}
|
|||
|
|
}
|