using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Unity.Netcode; using UnityEngine; namespace GrassCutter { /// /// Commands behind the cheat console (~ / F1). Anything that touches the shared game runs on the host only; /// "help", "clear" and friends work for everyone. /// public static class Cheats { public class Command { public string name, args, desc; public bool hostOnly = true; public Func run; /// Tab completion for the first argument. public Func> complete; } public static readonly List All = new List(); static readonly Dictionary s_byName = new Dictionary(); static readonly string[] Spawnables = { "bundle", "hay", "brick" }; static Cheats() { Add("help", "[command]", "List commands, or explain one.", Help, hostOnly: false, complete: () => All.Select(c => c.name)); Add("money", " | set ", "Add cash (10k, 2.5m, 1b work), or set the wallet.", Money); Add("perk", " [level]", "Give a perk (max level by default). 'perk all' buys the whole web.", Perk, complete: () => PerkNames().Prepend("all")); Add("resetperks", "", "Take every perk back.", _ => { foreach (var d in GameDefs.Perks) Ts.ServerSetPerk(d.id, 0); Ts.Save(); return "All perks reset."; }); Add("tool", "", "Hand yourself a tool: " + string.Join(", ", ToolNames()) + ".", Tool, complete: () => ToolNames().Prepend("all")); Add("time", "", "Set the clock at the base: 12 is noon, 0 is midnight.", args => { Ts.ServerSetPhase(float.Parse(args[0]) / 24f - 0.5f + 1f); return $"It's {args[0]}:00 at the base."; }); Add("tank", "", "Fill the tool in your hands.", _ => { Me.Tools.CheatFill(); return "Container full."; }, hostOnly: false); Add("ship", "", "Add shipped kilos (pays nothing).", Ship); Add("freebuild", "", "Build on standing grass, on or off.", _ => { BuildRules.AnyGround = !BuildRules.AnyGround; return BuildRules.AnyGround ? "Building on standing grass." : "Cut ground only."; }); Add("mow", "", "Cut the whole sector you stand in.", _ => $"Cut {MowMap.CutSector(HexGrid.SectorAt(Planet.LocalUp)):0} m² here."); Add("tp", "", "Teleport to the base, across the planet, the nearest stake or survey point, or a spot.", Tp, complete: () => new[] { "base", "far", "equator", "stake", "point" }); Add("spawn", " [count]", "Spawn cargo where you look: " + string.Join(", ", Spawnables) + ".", Spawn, complete: () => Spawnables); Add("fly", "", "Toggle flying / noclip. Space up, Ctrl down, Shift faster.", _ => { var p = Me; p.SetFlying(!p.Flying); return p.Flying ? "Flying ON" : "Flying OFF"; }, hostOnly: false); Add("speed", "", "Walk / fly speed multiplier (1 = normal).", Speed, hostOnly: false); Add("timescale", "", "Game speed (0.1 – 5).", TimeScale); Add("weather", " [minutes]", "Change the weather now.", Weather, complete: () => WeatherNames()); Add("twister", "", "Start a twister 25 m ahead of you.", _ => { Ts.ServerTwister(Me.transform.position + Me.transform.forward * 25f); return "Twister!"; }); Add("beer", "", "Drink a Grass Beer, no machine and no grass needed.", _ => { TreatHand.I?.Play(TreatId.Beer); return "Cheers."; }); Add("cigar", "", "Light a Herb Cigar, no machine and no grass needed.", _ => { TreatHand.I?.Play(TreatId.Cigar); return "Puff."; }); Add("ufo", "", "Bring a saucer down 30 m ahead of you.", _ => { Ts.ServerUfo(Me.transform.position + Me.transform.forward * 30f); return "They're coming."; }); Add("save", "", "Save the game now.", _ => { Ts.Save(); return "Saved."; }); Add("clear", "", "Clear the console.", _ => null, hostOnly: false); } static void Add(string name, string args, string desc, Func run, bool hostOnly = true, Func> complete = null) { var c = new Command { name = name, args = args, desc = desc, run = run, hostOnly = hostOnly, complete = complete }; All.Add(c); s_byName[name] = c; } static IEnumerable WeatherNames() { for (int i = 0; i < (int)WeatherKind.Count; i++) yield return ((WeatherKind)i).ToString().ToLowerInvariant(); } static string Weather(string[] args) { for (int i = 0; i < (int)WeatherKind.Count; i++) if (string.Equals(((WeatherKind)i).ToString(), args[0], StringComparison.OrdinalIgnoreCase)) { float minutes = args.Length > 1 ? float.Parse(args[1], System.Globalization.CultureInfo.InvariantCulture) : 5f; Ts.ServerSetWeather((WeatherKind)i, minutes * 60f); return $"Weather: {(WeatherKind)i} for {minutes:0.#} min."; } return "Weather is one of: " + string.Join(", ", WeatherNames()) + "."; } static TeamState Ts => TeamState.Instance; static PlayerAgent Me => PlayerAgent.Local; static bool IsHost => NetworkManager.Singleton && NetworkManager.Singleton.IsServer; /// Runs one line. Returns the text to print (null = nothing; "clear" is handled by the console). public static string Run(string line) { var parts = (line ?? "").Trim().Split((char[])null, StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 0) return null; string name = parts[0].ToLowerInvariant(); if (!s_byName.TryGetValue(name, out var cmd)) return $"Unknown command '{name}'. Type help."; if (cmd.hostOnly && !IsHost) return "Only the host can use cheats."; if (cmd.hostOnly && (!Ts || !Me)) return "Start or join a game first."; try { return cmd.run(parts.Skip(1).ToArray()); } catch (Exception e) { Debug.LogWarning("[Cheats] " + e); return $"Usage: {cmd.name} {cmd.args}"; } } /// Tab completion: the input with its current word completed (or unchanged), plus the candidates. public static string Complete(string line, out List options) { options = new List(); var parts = (line ?? "").TrimStart().Split(' '); IEnumerable pool; if (parts.Length <= 1) pool = All.Select(c => c.name); else if (parts.Length == 2 && s_byName.TryGetValue(parts[0].ToLowerInvariant(), out var cmd) && cmd.complete != null) pool = cmd.complete(); else return line; string word = parts[parts.Length - 1].ToLowerInvariant(); options = pool.Where(o => o.StartsWith(word, StringComparison.OrdinalIgnoreCase)).Distinct().ToList(); if (options.Count == 0) return line; // longest common prefix of the matches string common = options[0]; foreach (var o in options) { int n = 0; while (n < common.Length && n < o.Length && char.ToLowerInvariant(common[n]) == char.ToLowerInvariant(o[n])) n++; common = common.Substring(0, n); } parts[parts.Length - 1] = options.Count == 1 ? options[0] + " " : common; return string.Join(" ", parts); } // ───────────────────────── commands ───────────────────────── static string Help(string[] a) { if (a.Length > 0 && s_byName.TryGetValue(a[0].ToLowerInvariant(), out var c)) return $"{c.name} {c.args}\n {c.desc}{(c.hostOnly ? " (host)" : "")}"; return "Commands (Tab completes, ↑↓ history):\n" + string.Join("\n", All.Select(x => $" {x.name} {x.args} — {x.desc}")); } /// "5000", "10k", "2.5m", "1b" → a number. public static long ParseAmount(string s) { s = s.Trim().ToLowerInvariant().Replace("$", "").Replace("_", "").Replace(",", "."); double mul = 1; if (s.EndsWith("k")) mul = 1e3; else if (s.EndsWith("m")) mul = 1e6; else if (s.EndsWith("b")) mul = 1e9; if (mul > 1) s = s.Substring(0, s.Length - 1); return (long)Math.Round(double.Parse(s, CultureInfo.InvariantCulture) * mul); } static string Money(string[] a) { if (a[0].ToLowerInvariant() == "set") Ts.ServerSetMoney(ParseAmount(a[1])); else Ts.ServerSetMoney(Ts.Money.Value + ParseAmount(a[0])); return "Wallet: " + UIK.Money(Ts.Money.Value); } static IEnumerable PerkNames() => GameDefs.Perks.Select(p => p.id.ToString().ToLowerInvariant()); static string Perk(string[] a) { string what = a[0].ToLowerInvariant(); int? level = a.Length > 1 ? int.Parse(a[1], CultureInfo.InvariantCulture) : (int?)null; if (what == "all") { foreach (var d in GameDefs.Perks) Ts.ServerSetPerk(d.id, level ?? d.maxLevel); Ts.Save(); return level.HasValue ? $"Every perk set to level {level}." : "Every perk, every level. Enjoy."; } // match the id or the display name, ignoring spaces var def = GameDefs.Perks.FirstOrDefault(p => p.id.ToString().ToLowerInvariant() == what || p.nameEn.Replace(" ", "").ToLowerInvariant() == what) ?? GameDefs.Perks.FirstOrDefault(p => p.id.ToString().ToLowerInvariant().StartsWith(what)); if (def == null) return $"No perk '{what}'. Tab shows the list."; Ts.ServerSetPerk(def.id, level ?? def.maxLevel); Ts.Save(); return $"{def.name}: level {Ts.Level(def.id)}/{def.maxLevel}"; } static IEnumerable ToolNames() => Enum.GetNames(typeof(ToolId)).Where(n => n != "None").Select(n => n.ToLowerInvariant()); static string Tool(string[] a) { string what = a[0].ToLowerInvariant(); foreach (ToolId t in Enum.GetValues(typeof(ToolId))) { if (t == ToolId.None || (what != "all" && t.ToString().ToLowerInvariant() != what)) continue; Ts.ServerGiveTool(Me, t); if (what != "all") return GameDefs.Tool(t).name + " is yours."; } return what == "all" ? "Every tool is yours." : $"No tool '{what}'."; } static string Ship(string[] a) { Ts.Shipped.Value += ParseAmount(a[0]); return $"Shipped {GameDefs.Kilos(Ts.Shipped.Value)}"; } static string Tp(string[] a) { Vector3 to; string where = a.Length > 0 ? a[0].ToLowerInvariant() : "base"; if (a.Length >= 3) to = new Vector3(float.Parse(a[0], CultureInfo.InvariantCulture), float.Parse(a[1], CultureInfo.InvariantCulture), float.Parse(a[2], CultureInfo.InvariantCulture)); else if (a.Length == 2) to = Planet.OnSurface(Planet.FromLatLon(float.Parse(a[0], CultureInfo.InvariantCulture), float.Parse(a[1], CultureInfo.InvariantCulture))); else if (where == "far") to = Planet.OnSurface(Planet.FromLatLon(-89f, 0f)); else if (where == "equator") to = Planet.OnSurface(Planet.FromLatLon(0f, 90f)); else if (where == "stake" || where == "point") { int id = Landmarks.Instance.Nearest(Me.transform.position, where == "point"); if (id < 0) return "None left."; to = Landmarks.Spot(id) + Me.transform.right * 2f; } else to = new Vector3(0f, 0.3f, -2f); if (a.Length != 3 && where != "base") to += Planet.Up(to) * 0.2f; Me.Teleport(to); return "Teleported to " + to.ToString("F1"); } /// A spot a couple of metres ahead of the camera, in front of any wall. static Vector3 AimSpot(float ahead = 2.5f) { var cam = CameraFx.Cam ? CameraFx.Cam.transform : Me.head; var dir = cam.forward; float d = ahead; if (Physics.Raycast(cam.position, dir, out var hit, ahead + 0.5f, (1 << Layers.Default) | (1 << Layers.Build) | Layers.CargoMask, QueryTriggerInteraction.Ignore)) d = Mathf.Max(0.6f, hit.distance - 0.6f); var p = cam.position + dir * d; float above = Vector3.Dot(p - Me.transform.position, Me.transform.up); return above < 0.6f ? p + Me.transform.up * (0.6f - above) : p; } static string Spawn(string[] a) { string what = a[0].ToLowerInvariant(); int n = a.Length > 1 ? Mathf.Clamp(int.Parse(a[1], CultureInfo.InvariantCulture), 1, 50) : 1; int k = Array.IndexOf(Spawnables, what); if (k < 0) return $"Can't spawn '{what}'. Try: {string.Join(", ", Spawnables)}"; for (int i = 0; i < n; i++) { var at = AimSpot() + new Vector3((i % 4 - 1.5f) * 0.8f, (i / 4) * 0.9f, 0f); Spawner.Instance.SpawnCargo((CargoKind)k, at, Quaternion.Euler(0f, UnityEngine.Random.Range(0f, 360f), 0f), Vector3.zero); } return $"Spawned {n} x {what}."; } static string Speed(string[] a) { Me.CheatSpeed = Mathf.Clamp(float.Parse(a[0], CultureInfo.InvariantCulture), 0.1f, 10f); return $"Speed x{Me.CheatSpeed:0.##}"; } static string TimeScale(string[] a) { Time.timeScale = Mathf.Clamp(float.Parse(a[0], CultureInfo.InvariantCulture), 0.1f, 5f); return $"Time scale {Time.timeScale:0.##}"; } } }