Skip to content

Commit

Permalink
improvement: add configurable dices
Browse files Browse the repository at this point in the history
  • Loading branch information
derkalle4 committed Jan 22, 2025
1 parent e92c47e commit a1f1551
Show file tree
Hide file tree
Showing 14 changed files with 260 additions and 51 deletions.
100 changes: 88 additions & 12 deletions src/RollTheDice+Config.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
using System.IO.Enumeration;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Config;
using System.IO.Enumeration;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Config;

namespace RollTheDice
{
public class MapConfig
{
// disabled
[JsonPropertyName("enabled")] public bool Enabled { get; set; } = true;
// disabled features
[JsonPropertyName("dices")] public Dictionary<string, bool> Features { get; set; } = new();
// dices configuration
[JsonPropertyName("dices")] public Dictionary<string, Dictionary<string, object>> Dices { get; set; } = new();
}

public class PluginConfig : BasePluginConfig
Expand All @@ -20,8 +21,8 @@ public class PluginConfig : BasePluginConfig
[JsonPropertyName("enabled")] public bool Enabled { get; set; } = true;
// debug prints
[JsonPropertyName("debug")] public bool Debug { get; set; } = false;
// disabled features
[JsonPropertyName("dices")] public Dictionary<string, bool> Features { get; set; } = new();
// dices configuration
[JsonPropertyName("dices")] public Dictionary<string, Dictionary<string, object>> Dices { get; set; } = new();
// map configurations
[JsonPropertyName("maps")] public Dictionary<string, MapConfig> MapConfigs { get; set; } = new Dictionary<string, MapConfig>();
}
Expand Down Expand Up @@ -79,17 +80,55 @@ private void UpdateConfig()
// iterate through all dices and add them to the configuration file
foreach (var dice in _dices)
{
if (!Config.Features.ContainsKey(dice.Method.Name))
// create entry for dice if it does not exist
if (!Config.Dices.ContainsKey(dice.Method.Name))
{
Config.Dices[dice.Method.Name] = new Dictionary<string, object>();
}
// load current entries for dice
var diceConfig = Config.Dices[dice.Method.Name];
// Ensure "enabled" key exists
if (!diceConfig.ContainsKey("enabled"))
{
Config.Features.Add(dice.Method.Name, true);
diceConfig["enabled"] = true;
}
// Check for further configuration of a dice and add it accordingly
var methodName = $"{dice.Method.Name}Config";
var method = GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance);
if (method != null)
{
var additionalConfig = method.Invoke(this, null) as Dictionary<string, object> ?? new();
// check if configuration does exist
foreach (var kvp in additionalConfig)
{
if (!diceConfig.ContainsKey(kvp.Key))
{
diceConfig[kvp.Key] = ConvertJsonElement(kvp.Value);
}
}
// Remove keys that should not exist anymore, ignoring the "enabled" key
var keysToRemove = diceConfig.Keys.Except(additionalConfig.Keys).Where(key => key != "enabled").ToList();
foreach (var key in keysToRemove)
{
diceConfig.Remove(key);
}
// sort keys by alphabet
var sortedKeys = diceConfig.Keys.OrderBy(key => key).ToList();
var sortedDiceConfig = new Dictionary<string, object>();
foreach (var key in sortedKeys)
{
sortedDiceConfig[key] = diceConfig[key];
}
Config.Dices[dice.Method.Name] = sortedDiceConfig;

}
}
// delete all keys that do not exist anymore
foreach (var key in Config.Features.Keys)
// delete all dices that do not exist anymore
foreach (var key in Config.Dices.Keys)
{
if (!_dices.Any(dice => dice.Method.Name == key))
{
Config.Features.Remove(key);
Config.Dices.Remove(key);
}
}
}
Expand All @@ -99,5 +138,42 @@ private void SaveConfig()
var jsonString = JsonSerializer.Serialize(Config, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(_configPath, jsonString);
}

private Dictionary<string, object> GetDiceConfig(string diceName)
{
// first try the map-specific configuration
foreach (var mapConfig in _currentMapConfigs)
{
if (mapConfig.Dices.TryGetValue(diceName, out var config))
{
return config.ToDictionary(kvp => kvp.Key, kvp => ConvertJsonElement(kvp.Value));
}
}
// if not available, try the global configuration
if (Config.Dices.TryGetValue(diceName, out var globalConfig))
{
return globalConfig.ToDictionary(kvp => kvp.Key, kvp => ConvertJsonElement(kvp.Value));
}
return new Dictionary<string, object>();
}

private object ConvertJsonElement(object element)
{
if (element is JsonElement jsonElement)
{
return jsonElement.ValueKind switch
{
JsonValueKind.String => (object?)jsonElement.GetString() ?? string.Empty,
JsonValueKind.Number => jsonElement.TryGetSingle(out var number) ? (object)number : 0.0f,
JsonValueKind.True => (object)jsonElement.GetBoolean(),
JsonValueKind.False => (object)jsonElement.GetBoolean(),
JsonValueKind.Object => jsonElement.EnumerateObject().ToDictionary(property => property.Name, property => ConvertJsonElement(property.Value)),
JsonValueKind.Array => jsonElement.EnumerateArray().Select(element => ConvertJsonElement((object)element)).ToList(),
JsonValueKind.Undefined => (object)string.Empty,
_ => (object)string.Empty
};
}
return element;
}
}
}
14 changes: 13 additions & 1 deletion src/RollTheDice+DiceBigTaserBattery.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,16 @@ public partial class RollTheDice : BasePlugin

private Dictionary<string, string> DiceBigTaserBattery(CCSPlayerController player, CCSPlayerPawn playerPawn)
{
Dictionary<string, object> config = GetDiceConfig("DiceBigTaserBattery");
// create listener if not exists
if (_playersWithBigTaserBattery.Count() == 0)
{
RegisterEventHandler<EventWeaponFire>(EventDiceBigTaserBatteryOnWeaponFire);
}
int battery = _random.Next(2, 10);
int battery = _random.Next(
Convert.ToInt32(config["min_batteries"]),
Convert.ToInt32(config["max_batteries"]) + 1
);
_playersWithBigTaserBattery.Add(player, battery);
player.GiveNamedItem("weapon_taser");
return new Dictionary<string, string>
Expand Down Expand Up @@ -47,5 +51,13 @@ private HookResult EventDiceBigTaserBatteryOnWeaponFire(EventWeaponFire @event,
_playersWithBigTaserBattery[player]--;
return HookResult.Continue;
}

private Dictionary<string, object> DiceBigTaserBatteryConfig()
{
var config = new Dictionary<string, object>();
config["min_batteries"] = (int)2;
config["max_batteries"] = (int)10;
return config;
}
}
}
48 changes: 29 additions & 19 deletions src/RollTheDice+DiceChangeName.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,37 +10,26 @@ public partial class RollTheDice : BasePlugin

private Dictionary<string, string> DiceChangeName(CCSPlayerController player, CCSPlayerPawn playerPawn)
{
Dictionary<string, object> config = GetDiceConfig("DiceChangeName");
// random names from users
List<string> PlayerNames = Utilities.GetPlayers()
.Where(p => !p.IsBot)
.Select(p => p.PlayerName)
.ToList();
// random names from list
var RandomNames = new List<string>
{
"Hans Wurst", "Fritz Frosch", "Klaus Kleber", "Otto Normalverbraucher", "Peter Lustig",
"Karl-Heinz Klammer", "Gustav Gans", "Heinz Erhardt", "Wolfgang Witzig", "Ludwig Lustig",
"Rudi Rüssel", "Siggi Sorglos", "Berti Bratwurst", "Dieter Dosenbier", "Erwin Einhorn",
"Franz Fuchs", "Günther Gans", "Horst Hering", "Ingo Igel", "Jürgen Jux",
"Kurt Ketchup", "Lars Lachs", "Manfred Möhre", "Norbert Nudel", "Olaf Oktopus",
"Paul Pinguin", "Quirin Qualle", "Ralf Rabe", "Stefan Seestern", "Thomas Tintenfisch",
"Uwe Uhu", "Volker Vogel", "Willi Wurm", "Xaver Xylophon", "Yannik Yak",
"Zacharias Zebra", "Albert Apfel", "Bernd Banane", "Claus Clown", "Detlef Dachs",
"Egon Eule", "Ferdinand Frosch", "Gerd Giraffe", "Helmut Hase", "Igor Igel",
"Jochen Jaguar", "Knut Känguru", "Lothar Löwe", "Martin Marder", "Norbert Nashorn",
"Egon Kowalski", "Fritz Fink", "Heinz Hering"
};
// set random player name
string randomName = "";
// copy player names list
List<string> PlayerNamesCopy = new List<string>(PlayerNames);
List<string> PlayerNamesCopy = [.. PlayerNames];
// remove own name from list
PlayerNamesCopy.Remove(player.PlayerName);
// check if we have more then 4 players on the server
if (PlayerNames.Count > 3)
// check if we have at least X players on the server before we use player names instead of the predefined list
if (PlayerNamesCopy.Count >= Convert.ToInt32(config["min_players_for_using_player_names"]))
randomName = PlayerNamesCopy[_random.Next(PlayerNamesCopy.Count)];
else
randomName = RandomNames[_random.Next(RandomNames.Count)];
{
var namesList = ((List<object>)config["names"]).Cast<string>().ToList();
randomName = namesList[_random.Next(namesList.Count)];
}
_playersWithChangedNames.Add(player);
_playersWithChangedNamesOldNames[player] = player.PlayerName;
player.PlayerName = randomName;
Expand Down Expand Up @@ -69,5 +58,26 @@ private void DiceChangeNameReset()
_playersWithChangedNames.Clear();
_playersWithChangedNamesOldNames.Clear();
}

private Dictionary<string, object> DiceChangeNameConfig()
{
var config = new Dictionary<string, object>();
config["names"] = new List<string>
{
"Hans Wurst", "Fritz Frosch", "Klaus Kleber", "Otto Normalverbraucher", "Peter Lustig",
"Karl-Heinz Klammer", "Gustav Gans", "Heinz Erhardt", "Wolfgang Witzig", "Ludwig Lustig",
"Rudi Rüssel", "Siggi Sorglos", "Berti Bratwurst", "Dieter Dosenbier", "Erwin Einhorn",
"Franz Fuchs", "Günther Gans", "Horst Hering", "Ingo Igel", "Jürgen Jux",
"Kurt Ketchup", "Lars Lachs", "Manfred Möhre", "Norbert Nudel", "Olaf Oktopus",
"Paul Pinguin", "Quirin Qualle", "Ralf Rabe", "Stefan Seestern", "Thomas Tintenfisch",
"Uwe Uhu", "Volker Vogel", "Willi Wurm", "Xaver Xylophon", "Yannik Yak",
"Zacharias Zebra", "Albert Apfel", "Bernd Banane", "Claus Clown", "Detlef Dachs",
"Egon Eule", "Ferdinand Frosch", "Gerd Giraffe", "Helmut Hase", "Igor Igel",
"Jochen Jaguar", "Knut Känguru", "Lothar Löwe", "Martin Marder", "Norbert Nashorn",
"Egon Kowalski", "Fritz Fink", "Heinz Hering"
};
config["min_players_for_using_player_names"] = (int)4;
return config;
}
}
}
11 changes: 10 additions & 1 deletion src/RollTheDice+DiceChangePlayerSize.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ public partial class RollTheDice : BasePlugin

private Dictionary<string, string> DiceChangePlayerSize(CCSPlayerController player, CCSPlayerPawn playerPawn)
{
Dictionary<string, object> config = GetDiceConfig("DiceChangePlayerSize");
_playersWithChangedModelSize.Add(playerPawn);
float playerSize = float.Round((float)(_random.NextDouble() * (1.5 - 0.5) + 0.5), 2);
float playerSize = float.Round((float)(_random.NextDouble() * ((float)config["max_size"] - (float)config["min_size"]) + (float)config["min_size"]), 2);
var playerSceneNode = playerPawn.CBodyComponent?.SceneNode;
if (playerSceneNode == null)
return new Dictionary<string, string>
Expand Down Expand Up @@ -54,5 +55,13 @@ private void DiceChangePlayerSizeReset()
}
_playersWithChangedModelSize.Clear();
}

private Dictionary<string, object> DiceChangePlayerSizeConfig()
{
var config = new Dictionary<string, object>();
config["min_size"] = (float)0.5f;
config["max_size"] = (float)1.5f;
return config;
}
}
}
15 changes: 11 additions & 4 deletions src/RollTheDice+DiceChickenLeader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,16 @@ public partial class RollTheDice : BasePlugin
{
private Dictionary<string, string> DiceChickenLeader(CCSPlayerController player, CCSPlayerPawn playerPawn)
{
var amountChickens = 16;
Dictionary<string, object> config = GetDiceConfig("DiceChickenLeader");
// spawn chickens
for (int i = 0; i < amountChickens; i++)
for (int i = 0; i < Convert.ToInt32(config["amount_chicken"]); i++)
{
CChicken? chicken = Utilities.CreateEntityByName<CChicken>("chicken");
if (chicken != null)
{
Vector offset = new Vector(
(float)(100 * Math.Cos(2 * Math.PI * i / amountChickens)),
(float)(100 * Math.Sin(2 * Math.PI * i / amountChickens)),
(float)(100 * Math.Cos(2 * Math.PI * i / Convert.ToInt32(config["amount_chicken"]))),
(float)(100 * Math.Sin(2 * Math.PI * i / Convert.ToInt32(config["amount_chicken"]))),
0
);
chicken.Teleport(player.Pawn.Value!.AbsOrigin! + offset, player.Pawn.Value.AbsRotation!, player.Pawn.Value.AbsVelocity);
Expand Down Expand Up @@ -48,5 +48,12 @@ private Dictionary<string, string> DiceChickenLeader(CCSPlayerController player,
{ "playerName", player.PlayerName }
};
}

private Dictionary<string, object> DiceChickenLeaderConfig()
{
var config = new Dictionary<string, object>();
config["amount_chicken"] = (int)16;
return config;
}
}
}
14 changes: 13 additions & 1 deletion src/RollTheDice+DiceDecreaseHealth.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@ public partial class RollTheDice : BasePlugin
{
private Dictionary<string, string> DiceDecreaseHealth(CCSPlayerController player, CCSPlayerPawn playerPawn)
{
var healthDecrease = _random.Next(10, 30);
Dictionary<string, object> config = GetDiceConfig("DiceDecreaseHealth");
var healthDecrease = _random.Next(
Convert.ToInt32(config["min_health"]),
Convert.ToInt32(config["max_health"]) + 1
);
playerPawn.Health -= healthDecrease;
Utilities.SetStateChanged(playerPawn, "CBaseEntity", "m_iHealth");
return new Dictionary<string, string>
Expand All @@ -16,5 +20,13 @@ private Dictionary<string, string> DiceDecreaseHealth(CCSPlayerController player
{ "healthDecrease", healthDecrease.ToString() }
};
}

private Dictionary<string, object> DiceDecreaseHealthConfig()
{
var config = new Dictionary<string, object>();
config["min_health"] = (int)10;
config["max_health"] = (int)30;
return config;
}
}
}
14 changes: 13 additions & 1 deletion src/RollTheDice+DiceGiveHealthShot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@ public partial class RollTheDice : BasePlugin
{
private Dictionary<string, string> DiceGiveHealthShot(CCSPlayerController player, CCSPlayerPawn playerPawn)
{
int amount = _random.Next(1, 5);
Dictionary<string, object> config = GetDiceConfig("DiceGiveHealthShot");
int amount = _random.Next(
Convert.ToInt32(config["min_healthshots"]),
Convert.ToInt32(config["max_healthshots"]) + 1
);
for (int i = 0; i < amount; i++)
{
player.GiveNamedItem("weapon_healthshot");
Expand All @@ -17,5 +21,13 @@ private Dictionary<string, string> DiceGiveHealthShot(CCSPlayerController player
{ "amount", amount.ToString() }
};
}

private Dictionary<string, object> DiceGiveHealthShotConfig()
{
var config = new Dictionary<string, object>();
config["min_healthshots"] = (int)1;
config["max_healthshots"] = (int)5;
return config;
}
}
}
14 changes: 13 additions & 1 deletion src/RollTheDice+DiceIncreaseHealth.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@ public partial class RollTheDice : BasePlugin
{
private Dictionary<string, string> DiceIncreaseHealth(CCSPlayerController player, CCSPlayerPawn playerPawn)
{
var healthIncrease = _random.Next(10, 30);
Dictionary<string, object> config = GetDiceConfig("DiceIncreaseHealth");
var healthIncrease = _random.Next(
Convert.ToInt32(config["min_health"]),
Convert.ToInt32(config["max_health"]) + 1
);
if (playerPawn.Health + healthIncrease > playerPawn.MaxHealth)
{
playerPawn.MaxHealth = playerPawn.Health + healthIncrease;
Expand All @@ -21,5 +25,13 @@ private Dictionary<string, string> DiceIncreaseHealth(CCSPlayerController player
{ "healthIncrease", healthIncrease.ToString() }
};
}

private Dictionary<string, object> DiceIncreaseHealthConfig()
{
var config = new Dictionary<string, object>();
config["min_health"] = (int)10;
config["max_health"] = (int)30;
return config;
}
}
}
Loading

0 comments on commit a1f1551

Please sign in to comment.