Systems/GameStats.cs

Utility for recording player-local statistics with optional per-car and per-map variants. It creates slugged stat names from resource paths, determines current map path, and calls the sandbox Stats service to increment or set values when the local player's car is valid.

Networking
using Machines.GameModes;
using Machines.Player;

namespace Machines.Systems;

[Flags]
public enum StatScope
{
	Global = 1,
	Car = 2,
	Map = 4,

	All = Global | Car | Map,
}

/// <summary>
/// Stat helpers with optional per-car and per-map variants. Local player only.
/// </summary>
public static class GameStats
{
	/// <summary>
	/// Stat-safe slug from a resource path: lowercase filename, spaces as hyphens.
	/// </summary>
	public static string Slug( string resourcePath )
	{
		if ( string.IsNullOrWhiteSpace( resourcePath ) )
			return "unknown";

		var fileName = System.IO.Path.GetFileNameWithoutExtension( resourcePath );
		return fileName.ToLowerInvariant().Replace( ' ', '-' );
	}

	/// <summary>
	/// The current map's resource path, falling back to the scene name.
	/// </summary>
	public static string CurrentMapPath()
	{
		var mode = BaseGameMode.Current;
		return mode?.Map?.ResourcePath ?? mode?.Scene?.Name ?? "";
	}

	/// <summary>
	/// Increment a stat across the requested scope variants.
	/// </summary>
	public static void Increment( string name, double amount = 1, StatScope scope = StatScope.All, Car car = null )
	{
		Record( name, amount, scope, car, increment: true );
	}

	/// <summary>
	/// Set a stat value across the requested scope variants.
	/// </summary>
	public static void SetValue( string name, double value, StatScope scope = StatScope.All, Car car = null )
	{
		Record( name, value, scope, car, increment: false );
	}

	private static void Record( string name, double value, StatScope scope, Car car, bool increment )
	{
		car ??= Car.Local;

		if ( !car.IsValid() || !car.IsLocalPlayer )
			return;

		if ( scope.HasFlag( StatScope.Global ) )
			Submit( name, value, increment );

		if ( scope.HasFlag( StatScope.Car ) && car.Resource.IsValid() )
			Submit( $"{name}-car-{Slug( car.Resource.ResourcePath )}", value, increment );

		if ( scope.HasFlag( StatScope.Map ) )
		{
			var mapPath = CurrentMapPath();
			if ( !string.IsNullOrWhiteSpace( mapPath ) )
				Submit( $"{name}-map-{Slug( mapPath )}", value, increment );
		}
	}

	private static void Submit( string statName, double value, bool increment )
	{
		if ( increment )
			Sandbox.Services.Stats.Increment( statName, value );
		else
			Sandbox.Services.Stats.SetValue( statName, value );
	}
}