NadekoBot/NadekoBot.Core/Modules/Gambling/Common/CurrencyRaffleGame.cs

86 lines
2.3 KiB
C#
Raw Normal View History

2017-10-20 03:55:14 +00:00
using Discord;
using NadekoBot.Common;
2017-10-20 15:20:26 +00:00
using NLog;
2017-10-19 12:10:22 +00:00
using System.Collections.Generic;
2017-10-20 03:55:14 +00:00
using System.Linq;
2017-10-19 12:10:22 +00:00
namespace NadekoBot.Core.Modules.Gambling.Common
{
public class CurrencyRaffleGame
{
2017-10-20 15:20:26 +00:00
public enum Type {
Mixed,
Normal
}
2017-10-19 12:10:22 +00:00
2017-10-20 15:20:26 +00:00
public class User
2017-10-19 12:10:22 +00:00
{
2017-10-20 15:20:26 +00:00
public IUser DiscordUser { get; set; }
public int Amount { get; set; }
public override int GetHashCode()
{
return DiscordUser.GetHashCode();
}
public override bool Equals(object obj)
{
return obj is User u
? u.DiscordUser == DiscordUser
: false;
}
}
private readonly HashSet<User> _users = new HashSet<User>();
public IEnumerable<User> Users => _users;
public Type GameType { get; }
private readonly Logger _log;
2017-10-19 12:10:22 +00:00
2017-10-20 15:20:26 +00:00
public CurrencyRaffleGame(Type type)
{
GameType = type;
_log = LogManager.GetCurrentClassLogger();
2017-10-19 12:10:22 +00:00
}
2017-10-20 15:20:26 +00:00
public bool AddUser(IUser usr, int amount)
2017-10-19 12:10:22 +00:00
{
2017-10-20 15:20:26 +00:00
// if game type is normal, and someone already joined the game
// (that's the user who created it)
if (GameType == Type.Normal && _users.Count > 0 &&
_users.First().Amount != amount)
2017-10-20 03:55:14 +00:00
return false;
2017-10-20 15:20:26 +00:00
if (!_users.Add(new User
{
DiscordUser = usr,
Amount = amount,
}))
{
return false;
}
2017-10-19 12:10:22 +00:00
2017-10-20 03:55:14 +00:00
return true;
2017-10-19 12:10:22 +00:00
}
2017-10-20 15:20:26 +00:00
public User GetWinner()
{
var rng = new NadekoRandom();
if (GameType == Type.Mixed)
{
var num = rng.Next(0, Users.Sum(x => x.Amount));
var sum = 0;
foreach (var u in Users)
{
sum += u.Amount;
if (sum > num)
return u;
}
_log.Error("Woah. Report this.\nRoll: {0}\nAmounts: {1}", num, string.Join(",", Users.Select(x => x.Amount)));
}
var usrs = _users.ToArray();
return usrs[rng.Next(0, usrs.Length)];
}
2017-10-19 12:10:22 +00:00
}
}