Skip to content

Commit 0e35a74

Browse files
committed
Refactor
1 parent af21c2d commit 0e35a74

File tree

5 files changed

+128
-124
lines changed

5 files changed

+128
-124
lines changed

CoinThrow.cs

Lines changed: 51 additions & 105 deletions
Original file line numberDiff line numberDiff line change
@@ -2,133 +2,79 @@
22
using CounterStrikeSharp.API.Core;
33
using CounterStrikeSharp.API.Core.Attributes.Registration;
44
using CounterStrikeSharp.API.Modules.Commands;
5-
using CounterStrikeSharp.API.Modules.Commands.Targeting;
65
using CounterStrikeSharp.API.Modules.Utils;
7-
using Nexd.MySQL;
86

97
namespace CoinThrow
108
{
11-
public partial class CoinThrow : BasePlugin, IPluginConfig<ConfigCT>
9+
public class CoinThrow : BasePlugin, IPluginConfig<Config>
1210
{
13-
private Dictionary<string, DateTime> lastCoinThrowTimes = new Dictionary<string, DateTime>();
14-
private MySqlDb? mySql;
11+
private readonly Dictionary<string, DateTime> _lastCoinThrowTimes = new();
12+
private static readonly Random Random = new();
13+
private const int CooldownSeconds = 10;
14+
15+
private Database? _database;
16+
1517
public override string ModuleAuthor => "TICHOJEBEC";
1618
public override string ModuleName => "CoinThrow";
17-
public override string ModuleVersion => "v1.0";
18-
public ConfigCT Config { get; set; } = new ConfigCT();
19+
public override string ModuleVersion => "v1.1";
20+
21+
public Config Config { get; set; } = new();
22+
public void OnConfigParsed(Config config) => Config = config;
1923

20-
public void OnConfigParsed(ConfigCT config)
21-
{
22-
Config = config;
23-
}
24-
private static void GetPlayers(out List<CCSPlayerController> players)
25-
{
26-
players = Utilities.GetPlayers().Where(s => s.IsValid && s.PlayerPawn.Value != null).ToList();
27-
}
2824
public override void Load(bool hotReload)
2925
{
30-
InitializeDatabase();
31-
Console.WriteLine("CoinThrow plugin was successfully loaded!");
32-
}
33-
private void InitializeDatabase()
34-
{
35-
try
36-
{
37-
mySql = new MySqlDb(Config.DBHost, Config.DBUser, Config.DBPassword, Config.DBDatabase);
38-
mySql.ExecuteNonQueryAsync(@"
39-
CREATE TABLE IF NOT EXISTS `cointhrow` (
40-
`id` INT AUTO_INCREMENT PRIMARY KEY,
41-
`player_steamid` VARCHAR(32) NOT NULL UNIQUE,
42-
`player_name` VARCHAR(32) NOT NULL,
43-
`counts` INT(11) NOT NULL DEFAULT 0
44-
);
45-
");
46-
Console.WriteLine($"Connection to the database {Config.DBHost} successful.");
47-
}
48-
catch (Exception ex)
49-
{
50-
Console.WriteLine($"Connection to the database was unsuccessful: {ex.Message}.");
51-
}
52-
}
53-
private int GetPlayerThrows(string playerSteamID)
54-
{
55-
if (mySql == null)
56-
throw new InvalidOperationException("Database not initialized.");
57-
var result = mySql.Table("cointhrow")
58-
.Where(MySqlQueryCondition.New("player_steamid", "=", playerSteamID))
59-
.Select();
60-
if (result.Rows > 0)
61-
{
62-
return result.Get<int>(0, "counts");
63-
}
64-
return 0;
26+
_database = new Database(Config.DbHost, Config.DbPort, Config.DbDatabase, Config.DbUser, Config.DbPassword);
27+
_database.Initialize();
28+
29+
Console.WriteLine("[CoinThrow] Plugin loaded successfully.");
6530
}
66-
private bool CanPlayerThrowCoin(string steamID)
31+
32+
private bool IsOnCooldown(string steamId, out double remainingSeconds)
6733
{
68-
if (!lastCoinThrowTimes.ContainsKey(steamID))
34+
if (_lastCoinThrowTimes.TryGetValue(steamId, out var lastThrow))
6935
{
70-
return true;
36+
var elapsed = DateTime.Now - lastThrow;
37+
if (elapsed.TotalSeconds < CooldownSeconds)
38+
{
39+
remainingSeconds = CooldownSeconds - elapsed.TotalSeconds;
40+
return true;
41+
}
7142
}
72-
DateTime lastThrowTime = lastCoinThrowTimes[steamID];
73-
TimeSpan timeSinceLastThrow = DateTime.Now - lastThrowTime;
74-
return timeSinceLastThrow.TotalSeconds >= 10;
75-
}
76-
private void UpdateLastCoinThrowTime(string steamID)
77-
{
78-
lastCoinThrowTimes[steamID] = DateTime.Now;
43+
44+
remainingSeconds = 0;
45+
return false;
7946
}
80-
private void AddOrUpdateCoinThrowInDatabase(string playerSteamID, string playerName)
81-
{
82-
if (mySql == null)
83-
throw new InvalidOperationException("Database not initialized.");
8447

85-
var result = mySql.Table("cointhrow")
86-
.Where(MySqlQueryCondition.New("player_steamid", "=", playerSteamID))
87-
.Select();
48+
private void UpdateLastCoinThrowTime(string steamId) =>
49+
_lastCoinThrowTimes[steamId] = DateTime.Now;
8850

89-
if (result.Rows > 0)
90-
{
91-
int currentCount = Convert.ToInt32(result[0]["counts"]);
92-
currentCount++;
93-
mySql.Table("cointhrow")
94-
.Where(MySqlQueryCondition.New("player_steamid", "=", playerSteamID))
95-
.Update(new MySqlQueryValue
96-
{
97-
["player_name"] = playerName,
98-
["counts"] = currentCount.ToString()
99-
});
100-
}
101-
else
102-
{
103-
mySql.Table("cointhrow").Insert(new MySqlQueryValue
104-
{
105-
["player_steamid"] = playerSteamID,
106-
["player_name"] = playerName,
107-
["counts"] = "1"
108-
});
109-
}
110-
}
11151
[ConsoleCommand("css_cointhrow", "Throw a coin with the result being heads or tails")]
11252
public void OnCoinThrowCommand(CCSPlayerController? player, CommandInfo command)
11353
{
114-
if (player != null && player.PlayerPawn.Value != null)
54+
if (player == null || player.PlayerPawn.Value == null || !player.IsValid)
55+
return;
56+
57+
string steamId = player.SteamID.ToString();
58+
59+
if (IsOnCooldown(steamId, out var remaining))
11560
{
116-
if (!CanPlayerThrowCoin(player.SteamID.ToString()))
117-
{
118-
player.PrintToChat($"You can throw the coin only once every {ChatColors.DarkRed}10 {ChatColors.Default}seconds!");
119-
return;
120-
}
121-
122-
Random random = new Random();
123-
bool coinResult = random.Next(2) == 0;
124-
125-
string resultString = coinResult ? "Heads" : "Tails";
126-
Server.PrintToChatAll($"Player {ChatColors.Green}{player.PlayerName}{ChatColors.Default} threw the coin and the result is {ChatColors.Green}{resultString}{ChatColors.Default}.");
127-
AddOrUpdateCoinThrowInDatabase(player.SteamID.ToString(), player.PlayerName);
128-
int totalThrows = GetPlayerThrows(player.SteamID.ToString());
129-
Server.PrintToChatAll($"His total number of throws is {ChatColors.Green}{totalThrows}x{ChatColors.Default}.");
130-
UpdateLastCoinThrowTime(player.SteamID.ToString());
61+
player.PrintToChat($"You can throw the coin only once every {ChatColors.DarkRed}{CooldownSeconds}{ChatColors.Default} seconds! ({remaining:F0}s left)");
62+
return;
13163
}
64+
65+
string resultString = Random.Next(2) == 0 ? "Heads" : "Tails";
66+
67+
Server.PrintToChatAll(
68+
$"Player {ChatColors.Green}{player.PlayerName}{ChatColors.Default} threw the coin and the result is {ChatColors.Green}{resultString}{ChatColors.Default}."
69+
);
70+
71+
int totalThrows = _database?.IncrementPlayerThrows(steamId, player.PlayerName) ?? 0;
72+
73+
Server.PrintToChatAll(
74+
$"His total number of throws is {ChatColors.Green}{totalThrows}x{ChatColors.Default}."
75+
);
76+
77+
UpdateLastCoinThrowTime(steamId);
13278
}
13379
}
13480
}

CoinThrow.csproj

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,19 @@
55
<ImplicitUsings>enable</ImplicitUsings>
66
<Nullable>enable</Nullable>
77
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
8+
9+
<LangVersion>latest</LangVersion>
10+
<Optimize>true</Optimize>
11+
<Deterministic>true</Deterministic>
12+
<AssemblyName>CoinThrow</AssemblyName>
13+
<RootNamespace>CoinThrow</RootNamespace>
814
</PropertyGroup>
915

1016
<ItemGroup>
11-
<PackageReference Include="CounterStrikeSharp.API" Version="1.0.255" />
12-
<PackageReference Include="Nexd.MySQL" Version="1.0.2" />
17+
<PackageReference Include="CounterStrikeSharp.API" Version="*" />
18+
<PackageReference Include="System.Text.Json" Version="*" />
19+
<PackageReference Include="MySqlConnector" Version="2.3.7" />
20+
<PackageReference Include="Dapper" Version="2.1.24" />
1321
</ItemGroup>
1422

15-
</Project>
23+
</Project>

Config.cs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
using CounterStrikeSharp.API.Core;
2+
using System.Text.Json.Serialization;
3+
4+
namespace CoinThrow
5+
{
6+
public class Config : BasePluginConfig
7+
{
8+
[JsonPropertyName("DBDatabase")] public string DbDatabase { get; set; } = "database";
9+
[JsonPropertyName("DBUser")] public string DbUser { get; set; } = "user";
10+
[JsonPropertyName("DBPassword")] public string DbPassword { get; set; } = "password";
11+
[JsonPropertyName("DBHost")] public string DbHost { get; set; } = "localhost";
12+
[JsonPropertyName("DBPort")] public int DbPort { get; set; } = 3306;
13+
}
14+
}

Configs.cs

Lines changed: 0 additions & 16 deletions
This file was deleted.

Database.cs

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
using Dapper;
2+
using MySqlConnector;
3+
using System.Data;
4+
5+
namespace CoinThrow
6+
{
7+
public class Database(string host, int port, string database, string user, string password)
8+
{
9+
private readonly string _connectionString = $"Server={host};Port={port};Database={database};User={user};Password={password};";
10+
private IDbConnection? _db;
11+
12+
public void Initialize()
13+
{
14+
try
15+
{
16+
_db = new MySqlConnection(_connectionString);
17+
_db.Execute(@"
18+
CREATE TABLE IF NOT EXISTS `cointhrow` (
19+
`id` INT AUTO_INCREMENT PRIMARY KEY,
20+
`player_steamid` VARCHAR(32) NOT NULL UNIQUE,
21+
`player_name` VARCHAR(32) NOT NULL,
22+
`counts` INT NOT NULL DEFAULT 0
23+
);
24+
");
25+
26+
Console.WriteLine("[CoinThrow] Connected to database successfully.");
27+
}
28+
catch (Exception ex)
29+
{
30+
Console.WriteLine($"[CoinThrow] Database connection failed: {ex.Message}");
31+
}
32+
}
33+
34+
public int IncrementPlayerThrows(string steamId, string playerName)
35+
{
36+
if (_db == null) throw new InvalidOperationException("Database not initialized.");
37+
38+
_db.Execute(@"
39+
INSERT INTO cointhrow (player_steamid, player_name, counts)
40+
VALUES (@SteamID, @Name, 1)
41+
ON DUPLICATE KEY UPDATE
42+
player_name = VALUES(player_name),
43+
counts = counts + 1;
44+
", new { SteamID = steamId, Name = playerName });
45+
46+
return _db.QuerySingle<int>(
47+
"SELECT counts FROM cointhrow WHERE player_steamid = @SteamID",
48+
new { SteamID = steamId }
49+
);
50+
}
51+
}
52+
}

0 commit comments

Comments
 (0)