Move to islehorse

This commit is contained in:
Bluzume 2021-10-24 00:50:31 -04:00
parent f74d6a7834
commit d18338151f
1069 changed files with 53 additions and 10714 deletions

View file

@ -0,0 +1,78 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30114.105
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HorseIsleServer", "HorseIsleServer\HorseIsleServer.csproj", "{C48CBD82-AB30-494A-8FFA-4DE7069B5827}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|ARM = Debug|ARM
Debug|ARM64 = Debug|ARM64
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Linux|Any CPU = Linux|Any CPU
Linux|ARM = Linux|ARM
Linux|ARM64 = Linux|ARM64
Linux|x64 = Linux|x64
Linux|x86 = Linux|x86
MacOS|Any CPU = MacOS|Any CPU
MacOS|ARM = MacOS|ARM
MacOS|ARM64 = MacOS|ARM64
MacOS|x64 = MacOS|x64
MacOS|x86 = MacOS|x86
Windows|Any CPU = Windows|Any CPU
Windows|ARM = Windows|ARM
Windows|ARM64 = Windows|ARM64
Windows|x64 = Windows|x64
Windows|x86 = Windows|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.Debug|ARM.ActiveCfg = Debug|ARM
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.Debug|ARM.Build.0 = Debug|ARM
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.Debug|ARM64.ActiveCfg = Debug|ARM64
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.Debug|ARM64.Build.0 = Debug|ARM64
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.Debug|x64.ActiveCfg = Debug|x64
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.Debug|x64.Build.0 = Debug|x64
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.Debug|x86.ActiveCfg = Debug|x86
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.Debug|x86.Build.0 = Debug|x86
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.Linux|Any CPU.ActiveCfg = Linux|Any CPU
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.Linux|Any CPU.Build.0 = Linux|Any CPU
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.Linux|ARM.ActiveCfg = Linux|ARM
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.Linux|ARM.Build.0 = Linux|ARM
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.Linux|ARM64.ActiveCfg = Linux|ARM64
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.Linux|ARM64.Build.0 = Linux|ARM64
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.Linux|x64.ActiveCfg = Linux|x64
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.Linux|x64.Build.0 = Linux|x64
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.Linux|x86.ActiveCfg = Linux|x86
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.Linux|x86.Build.0 = Linux|x86
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.MacOS|Any CPU.ActiveCfg = MacOS|Any CPU
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.MacOS|Any CPU.Build.0 = MacOS|Any CPU
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.MacOS|ARM.ActiveCfg = MacOS|ARM
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.MacOS|ARM.Build.0 = MacOS|ARM
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.MacOS|ARM64.ActiveCfg = MacOS|ARM64
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.MacOS|ARM64.Build.0 = MacOS|ARM64
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.MacOS|x64.ActiveCfg = MacOS|x64
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.MacOS|x64.Build.0 = MacOS|x64
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.MacOS|x86.ActiveCfg = MacOS|x86
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.MacOS|x86.Build.0 = MacOS|x86
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.Windows|Any CPU.ActiveCfg = Windows|Any CPU
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.Windows|Any CPU.Build.0 = Windows|Any CPU
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.Windows|ARM.ActiveCfg = Windows|ARM
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.Windows|ARM.Build.0 = Windows|ARM
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.Windows|ARM64.ActiveCfg = Windows|ARM64
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.Windows|ARM64.Build.0 = Windows|ARM64
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.Windows|x64.ActiveCfg = Windows|x64
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.Windows|x64.Build.0 = Windows|x64
{C48CBD82-AB30-494A-8FFA-4DE7069B5827}.Windows|x86.ActiveCfg = Windows|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {52075F5B-6A74-493C-BA53-3AD720D643C2}
EndGlobalSection
EndGlobal

View file

@ -0,0 +1,47 @@
using System.Collections.Generic;
namespace HISP.Game
{
public class AbuseReport
{
public struct ReportReason
{
public string Id;
public string Name;
public string Meta;
}
private static List<ReportReason> reportReasons = new List<ReportReason>();
public static ReportReason[] ReportReasons
{
get
{
return reportReasons.ToArray();
}
}
public static bool DoesReasonExist(string id)
{
try
{
GetReasonById(id);
return true;
}
catch(KeyNotFoundException)
{
return false;
}
}
public static ReportReason GetReasonById(string id)
{
foreach(ReportReason reason in ReportReasons)
{
if (reason.Id == id)
return reason;
}
throw new KeyNotFoundException("No reason of: " + id + " Found.");
}
public static void AddReason(ReportReason reason)
{
reportReasons.Add(reason);
}
}
}

View file

@ -0,0 +1,394 @@
using HISP.Game.Horse;
using HISP.Player;
using HISP.Security;
using HISP.Server;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace HISP.Game
{
public class Arena
{
public class ArenaEntry
{
public User EnteredUser;
public HorseInstance EnteredHorse;
public int SubmitScore = 0;
public bool Done = false;
}
public static List<Arena> Arenas = new List<Arena>();
public Arena(int id, string type, int entryCost, int raceEvery, int slots, int timeOut)
{
RandomId = RandomID.NextRandomId();
Mode = "TAKINGENTRIES";
Id = id;
Type = type;
EntryCost = entryCost;
RaceEvery = raceEvery;
Slots = slots;
Timeout = timeOut;
Arenas.Add(this);
Entries = new List<ArenaEntry>();
}
public int Id;
public string Type;
public int EntryCost;
public int RandomId;
public int RaceEvery;
public int Slots;
public string Mode;
public int Timeout;
public List<ArenaEntry> Entries;
private Timer arenaTimeout;
public bool HaveAllPlayersCompleted()
{
int playersCompleted = 0;
foreach(ArenaEntry entry in Entries.ToArray())
{
if (entry.Done)
playersCompleted++;
}
if (playersCompleted >= Entries.Count)
return true;
else
return false;
}
public void SubmitScore(User user, int score)
{
foreach(ArenaEntry entry in Entries)
{
if(entry.EnteredUser.Id == user.Id)
{
entry.SubmitScore = score;
entry.Done = true;
break;
}
}
if (HaveAllPlayersCompleted())
End();
}
private string getSwf(ArenaEntry entry)
{
HorseInfo.StatCalculator speedCalculator = new HorseInfo.StatCalculator(entry.EnteredHorse, HorseInfo.StatType.SPEED, entry.EnteredUser);
HorseInfo.StatCalculator strengthCalculator = new HorseInfo.StatCalculator(entry.EnteredHorse, HorseInfo.StatType.STRENGTH, entry.EnteredUser);
HorseInfo.StatCalculator enduranceCalculator = new HorseInfo.StatCalculator(entry.EnteredHorse, HorseInfo.StatType.ENDURANCE, entry.EnteredUser);
HorseInfo.StatCalculator conformationCalculator = new HorseInfo.StatCalculator(entry.EnteredHorse, HorseInfo.StatType.CONFORMATION, entry.EnteredUser);
switch (Type)
{
case "BEGINNERJUMPING":
int bigJumps = Convert.ToInt32(Math.Round((double)strengthCalculator.Total / 100.0))+1;
return "jumpingarena1.swf?BIGJUMPS="+bigJumps+"&SPEEEDMAX="+speedCalculator.Total+"&JUNK=";
case "JUMPING":
int bonus = entry.EnteredHorse.BasicStats.Health + entry.EnteredHorse.BasicStats.Hunger + entry.EnteredHorse.BasicStats.Thirst + entry.EnteredHorse.BasicStats.Shoes;
return "jumpingarena2.swf?BONUS=" + bonus + "&STRENGTH=" + strengthCalculator.Total + "&SPEED=" + speedCalculator.Total + "&ENDURANCE=" + enduranceCalculator.Total + "&JUNK=";
case "CONFORMATION":
int baseScore = conformationCalculator.Total + ((entry.EnteredHorse.BasicStats.Groom > 750) ? 1000 : 500);
string swf = "dressagearena.swf?BASESCORE=" + baseScore;
int i = 1;
foreach (ArenaEntry ent in Entries.ToArray())
{
swf += "&HN" + i.ToString() + "=" + ent.EnteredUser.Username;
if (ent.EnteredUser.Id == entry.EnteredUser.Id)
swf += "&POS=" + i.ToString();
i++;
}
swf += "&JUNK=";
return swf;
case "DRAFT":
int draftAbility = Convert.ToInt32(Math.Round((((double)entry.EnteredHorse.BasicStats.Health * 2.0 + (double)entry.EnteredHorse.BasicStats.Shoes * 2.0) + (double)entry.EnteredHorse.BasicStats.Hunger + (double)entry.EnteredHorse.BasicStats.Thirst) / 6.0 + (double)strengthCalculator.Total + ((double)enduranceCalculator.Total / 2.0)));
swf = "draftarena.swf?DRAFTABILITY=" + draftAbility;
i = 1;
foreach (ArenaEntry ent in Entries.ToArray())
{
swf += "&HN" + i.ToString() + "=" + ent.EnteredUser.Username;
if (ent.EnteredUser.Id == entry.EnteredUser.Id)
swf += "&POS=" + i.ToString();
i++;
}
swf += "&J=";
return swf;
case "RACING":
int baseSpeed = Convert.ToInt32(Math.Round((((double)entry.EnteredHorse.BasicStats.Health * 2.0 + (double)entry.EnteredHorse.BasicStats.Shoes * 2.0) + (double)entry.EnteredHorse.BasicStats.Hunger + (double)entry.EnteredHorse.BasicStats.Thirst) / 6.0 + (double)speedCalculator.Total));
swf = "racingarena.swf?BASESPEED=" + baseSpeed + "&ENDURANCE=" + enduranceCalculator.Total;
i = 1;
foreach (ArenaEntry ent in Entries.ToArray())
{
swf += "&HN" + i.ToString() + "=" + ent.EnteredUser.Username;
if (ent.EnteredUser.Id == entry.EnteredUser.Id)
swf += "&POS=" + i.ToString();
i++;
}
swf += "&JUNK=";
return swf;
default:
return "test.swf";
}
}
public void Start()
{
Mode = "COMPETING";
if (Entries.Count <= 0)
{
reset();
return;
}
foreach(ArenaEntry entry in Entries.ToArray())
{
string swf = getSwf(entry);
string message = "";
switch (Type)
{
case "RACING":
entry.EnteredHorse.BasicStats.Hunger -= 200;
entry.EnteredHorse.BasicStats.Thirst -= 200;
entry.EnteredHorse.BasicStats.Tiredness -= 200;
entry.EnteredHorse.BasicStats.Shoes -= 100;
message = Messages.ArenaRacingStartup;
break;
case "DRAFT":
entry.EnteredHorse.BasicStats.Hunger -= 200;
entry.EnteredHorse.BasicStats.Thirst -= 200;
entry.EnteredHorse.BasicStats.Tiredness -= 200;
entry.EnteredHorse.BasicStats.Shoes -= 100;
message = Messages.ArenaDraftStartup;
break;
case "BEGINNERJUMPING":
entry.EnteredHorse.BasicStats.Hunger -= 200;
entry.EnteredHorse.BasicStats.Thirst -= 200;
entry.EnteredHorse.BasicStats.Tiredness -= 200;
entry.EnteredHorse.BasicStats.Shoes -= 100;
message = Messages.ArenaJumpingStartup;
break;
case "JUMPING":
entry.EnteredHorse.BasicStats.Hunger -= 300;
entry.EnteredHorse.BasicStats.Thirst -= 300;
entry.EnteredHorse.BasicStats.Tiredness -= 300;
entry.EnteredHorse.BasicStats.Shoes -= 100;
message = Messages.ArenaJumpingStartup;
break;
case "DRESSAGE":
entry.EnteredHorse.BasicStats.Mood -= 300;
entry.EnteredHorse.BasicStats.Tiredness -= 200;
message = Messages.ArenaConformationStartup;
break;
}
byte[] startingUpEventPacket = PacketBuilder.CreateChat(message, PacketBuilder.CHAT_BOTTOM_RIGHT);
byte[] swfModulePacket = PacketBuilder.CreateSwfModulePacket(swf, PacketBuilder.PACKET_SWF_CUTSCENE);
Logger.DebugPrint(entry.EnteredUser.Username + " Loading swf: " + swf);
entry.EnteredUser.LoggedinClient.SendPacket(swfModulePacket);
entry.EnteredUser.LoggedinClient.SendPacket(startingUpEventPacket);
}
arenaTimeout = new Timer(new TimerCallback(arenaTimedOut), null, Timeout * 60 * 1000, Timeout * 60 * 1000);
updateWaitingPlayers();
}
private void updateWaitingPlayers()
{
foreach (World.SpecialTile tile in World.SpecialTiles)
{
if (tile.Code == null)
continue;
if (tile.Code.StartsWith("ARENA-"))
{
string arenaId = tile.Code.Split('-')[1];
int id = int.Parse(arenaId);
if (id == this.Id)
GameServer.UpdateAreaForAll(tile.X, tile.Y, true);
}
}
}
private void arenaTimedOut(object state)
{
End();
}
private void reset()
{
// Delete all entries
Entries.Clear();
RandomId = RandomID.NextRandomId();
Mode = "TAKINGENTRIES";
if (arenaTimeout != null)
arenaTimeout.Dispose();
arenaTimeout = null;
}
public void End()
{
if(Mode == "COMPETING")
{
string chatMessage = Messages.ArenaResultsMessage;
string[] avaliblePlacings = new string[6] { Messages.ArenaFirstPlace, Messages.ArenaSecondPlace, Messages.ArenaThirdPlace, Messages.ArenaFourthPlace, Messages.ArenaFifthPlace, Messages.ArenaSixthPlace };
int[] expRewards = new int[Entries.Count];
expRewards[0] = 1;
int expAwardMul = 1;
for(int i = 1; i < Entries.Count; i++)
{
expRewards[i] = 2 * expAwardMul;
if (expAwardMul == 1)
expAwardMul = 2;
else
expAwardMul += 2;
}
expRewards = expRewards.ToArray().Reverse().ToArray();
int place = 0;
ArenaEntry[] winners = Entries.OrderByDescending(o => o.SubmitScore).ToArray();
foreach (ArenaEntry entry in winners)
{
string placing = avaliblePlacings[place % avaliblePlacings.Length];
chatMessage += Messages.FormatArenaPlacing(placing, entry.EnteredUser.Username, entry.SubmitScore);
place++;
}
place = 0;
foreach(ArenaEntry entry in winners)
{
try
{
byte[] arenaResults = PacketBuilder.CreateChat(chatMessage, PacketBuilder.CHAT_BOTTOM_RIGHT);
entry.EnteredUser.LoggedinClient.SendPacket(arenaResults);
int expReward = expRewards[place];
entry.EnteredHorse.BasicStats.Experience += expReward;
entry.EnteredUser.Experience += expReward;
if (place == 0) // WINNER!
{
int prize = EntryCost * Entries.Count;
entry.EnteredUser.AddMoney(prize);
byte[] youWinMessage = PacketBuilder.CreateChat(Messages.FormatArenaYouWinMessage(prize, expReward), PacketBuilder.CHAT_BOTTOM_RIGHT);
entry.EnteredUser.LoggedinClient.SendPacket(youWinMessage);
// Awards:
if (Entries.Count >= 2 && Type == "JUMPING")
entry.EnteredUser.Awards.AddAward(Award.GetAwardById(5)); // Good Jumper
if (Entries.Count >= 4 && Type == "JUMPING")
entry.EnteredUser.Awards.AddAward(Award.GetAwardById(6)); // Great Jumper
if (Entries.Count >= 2 && Type == "RACING")
entry.EnteredUser.Awards.AddAward(Award.GetAwardById(7)); // Good Racer
if (Entries.Count >= 4 && Type == "RACING")
entry.EnteredUser.Awards.AddAward(Award.GetAwardById(8)); // Great Racer
if (Entries.Count >= 2 && Type == "DRESSAGE")
entry.EnteredUser.Awards.AddAward(Award.GetAwardById(9)); // Good Dressage
if (Entries.Count >= 4 && Type == "DRESSAGE")
entry.EnteredUser.Awards.AddAward(Award.GetAwardById(10)); // Great Dressage
if (Entries.Count >= 2 && Type == "DRAFT")
entry.EnteredUser.Awards.AddAward(Award.GetAwardById(38)); // Strong Horse Award
if (Entries.Count >= 4 && Type == "DRAFT")
entry.EnteredUser.Awards.AddAward(Award.GetAwardById(39)); // Strongest Horse Award
}
else
{
entry.EnteredUser.TrackedItems.GetTrackedItem(Tracking.TrackableItem.ArenaLoss).Count++;
if(entry.EnteredUser.TrackedItems.GetTrackedItem(Tracking.TrackableItem.ArenaLoss).Count >= 100)
entry.EnteredUser.Awards.AddAward(Award.GetAwardById(32)); // Perseverance
byte[] youDONTWinMessage = PacketBuilder.CreateChat(Messages.FormatArenaOnlyWinnerWinsMessage(expReward), PacketBuilder.CHAT_BOTTOM_RIGHT);
entry.EnteredUser.LoggedinClient.SendPacket(youDONTWinMessage);
}
place++;
}
catch(Exception)
{
continue;
}
}
}
reset();
updateWaitingPlayers();
}
public void DeleteEntry(User user)
{
if (Mode == "COMPETING")
return;
foreach(ArenaEntry entry in Entries)
if(entry.EnteredUser.Id == user.Id)
{
Entries.Remove(entry);
break;
}
}
public void AddEntry(User user, HorseInstance horse)
{
if(!UserHasHorseEntered(user))
{
ArenaEntry arenaEntry = new ArenaEntry();
arenaEntry.EnteredUser = user;
arenaEntry.EnteredHorse = horse;
Entries.Add(arenaEntry);
}
}
public static Arena GetArenaUserEnteredIn(User user)
{
foreach (Arena arena in Arenas)
if (arena.UserHasHorseEntered(user))
return arena;
throw new KeyNotFoundException("user was not entered in any arena.");
}
public bool UserHasHorseEntered(User user)
{
foreach (ArenaEntry entry in Entries.ToArray())
if (entry.EnteredUser.Id == user.Id)
return true;
return false;
}
public static void StartArenas(int minutes)
{
foreach(Arena arena in Arenas)
{
if (minutes % arena.RaceEvery == 0)
if(arena.Mode == "TAKINGENTRIES")
arena.Start();
}
}
public static bool UserHasEnteredHorseInAnyArena(User user)
{
foreach (Arena arena in Arenas)
if (arena.UserHasHorseEntered(user))
return true;
return false;
}
public static Arena GetAreaById(int id)
{
foreach (Arena arena in Arenas)
if (arena.Id == id)
return arena;
throw new KeyNotFoundException("Arena with id " + id + " NOT FOUND!");
}
}
}

View file

@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HISP.Game.Services
{
public class Book
{
private static List<Book> libaryBooks = new List<Book>();
public static Book[] LibaryBooks
{
get
{
return libaryBooks.ToArray();
}
}
public int Id;
public string Title;
public string Author;
public string Text;
public Book(int id, string title, string author, string text)
{
Id = id;
Title = title;
Author = author;
Text = text;
libaryBooks.Add(this);
}
public static bool BookExists(int id)
{
try
{
GetBookById(id);
return true;
}
catch(KeyNotFoundException)
{
return false;
}
}
public static Book GetBookById(int id)
{
foreach(Book libaryBook in LibaryBooks)
{
if (libaryBook.Id == id)
return libaryBook;
}
throw new KeyNotFoundException("no book with id: " + id.ToString() + " found.");
}
}
}

View file

@ -0,0 +1,573 @@
using System;
using System.Collections.Generic;
using System.Linq;
using HISP.Player;
using HISP.Server;
namespace HISP.Game.Chat
{
public class Chat
{
public struct Correction
{
public string FilteredWord;
public string ReplacedWord;
}
public struct Reason
{
public string Name;
public string Message;
}
public struct Filter
{
public string FilteredWord;
public Reason Reason;
public bool MatchAll;
}
public enum ChatChannel
{
All = 0x14,
Ads = 0x1D,
Near = 0x15,
Buddies = 0x17,
Here = 0x18,
Isle = 0x1A,
Dm = 0x16,
Mod = 0x1c,
Admin = 0x1b
}
public static string PrivateMessageSound;
public static List<Filter> FilteredWords = new List<Filter>();
public static List<Correction> CorrectedWords = new List<Correction>();
public static List<Reason> Reasons = new List<Reason>();
public static bool ProcessCommand(User user, string message)
{
if (message.Length < 1)
return false;
string[] args = message.Split(' ').Skip(1).ToArray();
if (user.Administrator || user.Moderator)
{
if (message[0] == '%')
{
if (message.ToUpper().StartsWith("%GIVE"))
return Command.Give(message, args, user);
if (message.ToUpper().StartsWith("%GOTO"))
return Command.Goto(message, args, user);
if (message.ToUpper().StartsWith("%JUMP"))
return Command.Jump(message, args, user);
if (message.ToUpper().StartsWith("%KICK"))
return Command.Kick(message, args, user);
if (message.ToUpper().StartsWith("%RULES"))
return Command.Rules(message, args, user);
if (message.ToUpper().StartsWith("%NOCLIP"))
return Command.NoClip(message, args, user);
if (message.ToUpper().StartsWith("%STEALTH"))
return Command.Stealth(message, args, user);
if (message.ToUpper().StartsWith("%BAN"))
return Command.Ban(message, args, user);
if (message.ToUpper().StartsWith("%UNBAN"))
return Command.UnBan(message, args, user);
if (message.ToUpper().StartsWith("%ESCAPE"))
return Command.Escape(message, args, user);
if (message.ToUpper().StartsWith("%CALL HORSE"))
return Command.CallHorse(message, args, user);
return false;
}
}
if (message[0] == '!')
{
// Alias for !MUTE
if (message.ToUpper().StartsWith("!MUTEALL"))
return Command.Mute(message, new string[] { "ALL" }, user);
else if (message.ToUpper().StartsWith("!MUTEADS"))
return Command.Mute(message, new string[] { "ADS" }, user);
else if (message.ToUpper().StartsWith("!MUTEGLOBAL"))
return Command.Mute(message, new string[] { "GLOBAL" }, user);
else if (message.ToUpper().StartsWith("!MUTEISLAND"))
return Command.Mute(message, new string[] { "ISLAND" }, user);
else if (message.ToUpper().StartsWith("!MUTENEAR"))
return Command.Mute(message, new string[] { "NEAR" }, user);
else if (message.ToUpper().StartsWith("!MUTEHERE"))
return Command.Mute(message, new string[] { "HERE" }, user);
else if (message.ToUpper().StartsWith("!MUTEBUDDY"))
return Command.Mute(message, new string[] { "BUDDY" }, user);
else if (message.ToUpper().StartsWith("!MUTEPM"))
return Command.Mute(message, new string[] { "PM" }, user);
else if (message.ToUpper().StartsWith("!MUTEBR"))
return Command.Mute(message, new string[] { "BR" }, user);
else if (message.ToUpper().StartsWith("!MUTESOCIALS"))
return Command.Mute(message, new string[] { "SOCIALS" }, user);
else if (message.ToUpper().StartsWith("!MUTELOGINS"))
return Command.Mute(message, new string[] { "LOGINS" }, user);
else if (message.ToUpper().StartsWith("!MUTE"))
return Command.Mute(message, args, user);
// Alias for !UNMUTE
else if (message.ToUpper().StartsWith("!UNMUTEALL"))
return Command.UnMute(message, new string[] { "ALL" }, user);
else if (message.ToUpper().StartsWith("!UNMUTEADS"))
return Command.UnMute(message, new string[] { "ADS" }, user);
else if (message.ToUpper().StartsWith("!UNMUTEGLOBAL"))
return Command.UnMute(message, new string[] { "GLOBAL" }, user);
else if (message.ToUpper().StartsWith("!UNMUTEISLAND"))
return Command.UnMute(message, new string[] { "ISLAND" }, user);
else if (message.ToUpper().StartsWith("!UNMUTENEAR"))
return Command.UnMute(message, new string[] { "NEAR" }, user);
else if (message.ToUpper().StartsWith("!UNMUTEHERE"))
return Command.UnMute(message, new string[] { "HERE" }, user);
else if (message.ToUpper().StartsWith("!UNMUTEBUDDY"))
return Command.UnMute(message, new string[] { "BUDDY" }, user);
else if (message.ToUpper().StartsWith("!UNMUTEPM"))
return Command.UnMute(message, new string[] { "PM" }, user);
else if (message.ToUpper().StartsWith("!UNMUTEBR"))
return Command.UnMute(message, new string[] { "BR" }, user);
else if (message.ToUpper().StartsWith("!UNMUTESOCIALS"))
return Command.UnMute(message, new string[] { "SOCIALS" }, user);
else if (message.ToUpper().StartsWith("!UNMUTELOGINS"))
return Command.UnMute(message, new string[] { "LOGINS" }, user);
else if (message.ToUpper().StartsWith("!UNMUTE"))
return Command.UnMute(message, args, user);
// Alias for !HEAR
else if (message.ToUpper().StartsWith("!HEARALL"))
return Command.UnMute(message, new string[] { "ALL" }, user);
else if (message.ToUpper().StartsWith("!HEARADS"))
return Command.UnMute(message, new string[] { "ADS" }, user);
else if (message.ToUpper().StartsWith("!HEARGLOBAL"))
return Command.UnMute(message, new string[] { "GLOBAL" }, user);
else if (message.ToUpper().StartsWith("!HEARISLAND"))
return Command.UnMute(message, new string[] { "ISLAND" }, user);
else if (message.ToUpper().StartsWith("!HEARNEAR"))
return Command.UnMute(message, new string[] { "NEAR" }, user);
else if (message.ToUpper().StartsWith("!HEARHERE"))
return Command.UnMute(message, new string[] { "HERE" }, user);
else if (message.ToUpper().StartsWith("!HEARBUDDY"))
return Command.UnMute(message, new string[] { "BUDDY" }, user);
else if (message.ToUpper().StartsWith("!HEARPM"))
return Command.UnMute(message, new string[] { "PM" }, user);
else if (message.ToUpper().StartsWith("!HEARBR"))
return Command.UnMute(message, new string[] { "BR" }, user);
else if (message.ToUpper().StartsWith("!HEARSOCIALS"))
return Command.UnMute(message, new string[] { "SOCIALS" }, user);
else if (message.ToUpper().StartsWith("!HEARLOGINS"))
return Command.UnMute(message, new string[] { "LOGINS" }, user);
else if (message.ToUpper().StartsWith("!HEAR"))
return Command.UnMute(message, args, user);
else if (message.ToUpper().StartsWith("!AUTOREPLY"))
return Command.AutoReply(message, args, user);
else if (message.ToUpper().StartsWith("!QUIZ"))
return Command.Quiz(message, args, user);
else if (message.ToUpper().StartsWith("!WARP"))
return Command.Warp(message, args, user);
else if (message.ToUpper().StartsWith("!DANCE"))
return Command.Dance(message, args, user);
}
return false;
}
public static Object FilterMessage(string message) // Handles chat filtering and violation stuffs
{
if (!ConfigReader.BadWords) // Freedom of Speech Mode
return null;
string[] wordsSaid;
if (message.Contains(' '))
wordsSaid = message.Split(' ');
else
wordsSaid = new string[] { message };
foreach(Filter filter in FilteredWords)
{
if (!filter.MatchAll)
{
foreach (string word in wordsSaid)
{
if (word.ToLower() == filter.FilteredWord.ToLower())
return filter.Reason;
}
}
else
{
if (message.ToLower().Contains(filter.FilteredWord))
return filter.Reason;
}
}
return null;
}
public static byte GetSide(ChatChannel channel)
{
switch (channel)
{
case ChatChannel.All:
case ChatChannel.Ads:
case ChatChannel.Isle:
return PacketBuilder.CHAT_BOTTOM_LEFT;
case ChatChannel.Buddies:
case ChatChannel.Here:
case ChatChannel.Admin:
case ChatChannel.Mod:
return PacketBuilder.CHAT_BOTTOM_RIGHT;
case ChatChannel.Dm:
return PacketBuilder.CHAT_DM_RIGHT;
default:
Logger.ErrorPrint("unknown channel: " + (byte)channel);
return PacketBuilder.CHAT_BOTTOM_LEFT;
}
}
public static string GetDmRecipiant(string message)
{
if(message.Contains('|'))
{
string recipiantName = message.Split('|')[0];
return recipiantName;
}
else
{
return null;
}
}
public static string GetDmMessage(string message)
{
if (message.Contains('|'))
{
string messageStr = message.Split('|')[1];
return messageStr;
}
else
{
return message;
}
}
public static GameClient[] GetRecipiants(User user, ChatChannel channel, string to=null)
{
if (channel == ChatChannel.All)
{
List<GameClient> recipiants = new List<GameClient>();
foreach (GameClient client in GameServer.ConnectedClients)
{
if (client.LoggedIn)
if (!client.LoggedinUser.MuteGlobal && !client.LoggedinUser.MuteAll)
if (client.LoggedinUser.Id != user.Id)
if(!client.LoggedinUser.MutePlayer.IsUserMuted(user))
recipiants.Add(client);
}
return recipiants.ToArray();
}
if(channel == ChatChannel.Ads)
{
List<GameClient> recipiants = new List<GameClient>();
foreach (GameClient client in GameServer.ConnectedClients)
{
if (client.LoggedIn)
if (!client.LoggedinUser.MuteAds && !client.LoggedinUser.MuteAll)
if (client.LoggedinUser.Id != user.Id)
if (!client.LoggedinUser.MutePlayer.IsUserMuted(user))
recipiants.Add(client);
}
return recipiants.ToArray();
}
if(channel == ChatChannel.Buddies)
{
List<GameClient> recipiants = new List<GameClient>();
foreach (GameClient client in GameServer.ConnectedClients)
{
if (client.LoggedIn)
if (!client.LoggedinUser.MuteBuddy && !client.LoggedinUser.MuteAll)
if (client.LoggedinUser.Id != user.Id)
if (client.LoggedinUser.Friends.List.Contains(user.Id))
if (!client.LoggedinUser.MutePlayer.IsUserMuted(user))
recipiants.Add(client);
}
return recipiants.ToArray();
}
if (channel == ChatChannel.Isle)
{
List<GameClient> recipiants = new List<GameClient>();
if(World.InIsle(user.X,user.Y))
{
User[] usersInSile = GameServer.GetUsersInIsle(World.GetIsle(user.X, user.Y), true, false);
foreach (User userInIsle in usersInSile)
{
if (user.Id != userInIsle.Id)
if(!userInIsle.MuteAll && !userInIsle.MuteIsland)
if(!userInIsle.MutePlayer.IsUserMuted(user))
recipiants.Add(userInIsle.LoggedinClient);
}
return recipiants.ToArray();
}
else
{
return new GameClient[0];
}
}
if (channel == ChatChannel.Here)
{
List<GameClient> recipiants = new List<GameClient>();
User[] usersHere = GameServer.GetUsersAt(user.X, user.Y, true, false);
foreach (User userHere in usersHere)
{
if (user.Id != userHere.Id)
if (!userHere.MuteAll && !userHere.MuteHere)
if (!userHere.MutePlayer.IsUserMuted(user))
recipiants.Add(userHere.LoggedinClient);
}
return recipiants.ToArray();
}
if (channel == ChatChannel.Near)
{
List<GameClient> recipiants = new List<GameClient>();
User[] nearbyUsers = GameServer.GetNearbyUsers(user.X, user.Y, true, false);
foreach (User nearbyUser in nearbyUsers)
{
if (user.Id != nearbyUser.Id)
if (!nearbyUser.MuteAll && !nearbyUser.MuteNear)
if (!nearbyUser.MutePlayer.IsUserMuted(user))
recipiants.Add(nearbyUser.LoggedinClient);
}
return recipiants.ToArray();
}
if (channel == ChatChannel.Mod)
{
if (!user.Moderator || !user.Administrator) // No mod chat for non-mods!
{
Logger.WarnPrint(user.Username + " attempted to send in MOD chat, without being a MOD.");
return new GameClient[0];
}
List<GameClient> recipiants = new List<GameClient>();
foreach (GameClient client in GameServer.ConnectedClients)
{
if (client.LoggedIn)
if (client.LoggedinUser.Moderator)
if (client.LoggedinUser.Id != user.Id)
recipiants.Add(client);
}
return recipiants.ToArray();
}
if(channel == ChatChannel.Admin)
{
if (!user.Administrator) // No admin chat for non-admins!
{
Logger.WarnPrint(user.Username + " attempted to send in ADMIN chat, without being an ADMIN.");
return new GameClient[0];
}
List<GameClient> recipiants = new List<GameClient>();
foreach (GameClient client in GameServer.ConnectedClients)
{
if (client.LoggedIn)
if (client.LoggedinUser.Administrator)
if (client.LoggedinUser.Id != user.Id)
recipiants.Add(client);
}
return recipiants.ToArray();
}
if(channel == ChatChannel.Dm)
{
if (to != null)
{
List<GameClient> recipiants = new List<GameClient>();
foreach (GameClient client in GameServer.ConnectedClients)
{
if (client.LoggedIn)
if (!client.LoggedinUser.MutePrivateMessage && !client.LoggedinUser.MuteAll)
if (client.LoggedinUser.Username.ToLower() == to.ToLower())
recipiants.Add(client);
}
return recipiants.ToArray();
}
else
{
Logger.ErrorPrint("Channel is " + channel + " (DM) BUT no 'to' Paramater was specfied");
return new GameClient[0];
}
}
Logger.ErrorPrint(user.Username + " Sent message in unknown channel: " + (byte)channel);
return new GameClient[0]; // No recipiants
}
public static string DoCorrections(string message)
{
if (!ConfigReader.DoCorrections)
return message;
foreach(Correction correct in CorrectedWords)
message = message.Replace(correct.FilteredWord, correct.ReplacedWord);
return message.Trim();
}
public static string EscapeMessage(string message)
{
return message.Replace("<", "&lt;");
}
public static string FormatChatForOthers(User user, ChatChannel channel, string message, bool autoReply=false)
{
switch (channel)
{
case ChatChannel.All:
if (user.Moderator || user.Administrator)
return Messages.FormatGlobalChatMessageForMod(user.Username, message);
else
return Messages.FormatGlobalChatMessage(user.Username, message);
case ChatChannel.Ads:
return Messages.FormatAdsChatMessage(user.Username, message);
case ChatChannel.Buddies:
return Messages.FormatBuddyChatMessage(user.Username, message);
case ChatChannel.Dm:
string badge = "";
if (user.Moderator || user.Administrator)
badge += Messages.DmModBadge;
if (autoReply)
badge += Messages.DmAutoResponse;
return Messages.FormatDirectMessage(user.Username, message, badge);
case ChatChannel.Near:
return Messages.FormatNearbyChatMessage(user.Username, message);
case ChatChannel.Isle:
return Messages.FormatIsleChatMessage(user.Username, message);
case ChatChannel.Here:
return Messages.FormatHereChatMessage(user.Username, message);
case ChatChannel.Mod:
if (user.Moderator || user.Administrator)
return Messages.FormatModChatMessage(user.Username, message);
else
{
Logger.HackerPrint(user.Username + " Tried to send in mod chat without being a moderator. (Hack/Code Attempt)");
return "";
}
case ChatChannel.Admin:
if (user.Administrator)
return Messages.FormatAdminChatMessage(user.Username, message);
else
{
Logger.HackerPrint(user.Username + " Tried to send in mod chat without being a moderator. (Hack/Code Attempt)");
return "";
}
default:
Logger.ErrorPrint(user.Username + " is trying to end a message in unknown channel " + channel.ToString("X"));
return "not implemented yet :(";
}
}
public static string FormatChatForSender(User user, ChatChannel channel, string message, string dmRecipiant=null, bool autoReply=false)
{
switch (channel)
{
case ChatChannel.All:
if (user.Moderator || user.Administrator)
return Messages.FormatGlobalChatMessageForMod(user.Username, message);
else
return Messages.FormatGlobalChatMessage(user.Username, message);
case ChatChannel.Ads:
int numbListening = GameServer.GetNumberOfPlayersListeningToAdsChat(); // vry specific function ik
return Messages.FormatAdsChatForSender(numbListening-1, user.Username, message);
case ChatChannel.Buddies:
return Messages.FormatBuddyChatMessageForSender(GameServer.GetNumberOfBuddiesOnline(user), user.Username, message);
case ChatChannel.Isle:
int inIsle = 0;
if (World.InIsle(user.X, user.Y))
inIsle = GameServer.GetUsersInIsle(World.GetIsle(user.X, user.Y), false, false).Length -1;
return Messages.FormatIsleChatMessageForSender(inIsle, user.Username, message);
case ChatChannel.Here:
int usersHere = GameServer.GetUsersAt(user.X, user.Y, false, false).Length -1;
return Messages.FormatHereChatMessageForSender(usersHere, user.Username, message);
case ChatChannel.Near:
int nearbyUsers = GameServer.GetNearbyUsers(user.X, user.Y, false, false).Length -1;
return Messages.FormatNearChatMessageForSender(nearbyUsers, user.Username, message);
case ChatChannel.Mod:
int modsOnline = GameServer.GetNumberOfModsOnline() - 1;
return Messages.FormatModChatForSender(modsOnline, user.Username, message);
case ChatChannel.Admin:
int adminsOnline = GameServer.GetNumberOfAdminsOnline() - 1;
return Messages.FormatAdminChatForSender(adminsOnline, user.Username, message);
case ChatChannel.Dm:
string badge = "";
if (user.Moderator || user.Administrator)
badge += Messages.DmModBadge;
if (autoReply)
badge += Messages.DmAutoResponse;
return Messages.FormatDirectChatMessageForSender(user.Username, dmRecipiant, message, badge);
default:
Logger.ErrorPrint(user.Username + " is trying to end a message in unknown channel " + channel.ToString("X"));
return "not implemented yet :(";
}
}
public static string NonViolationChecks(User user, string message)
{
if(ConfigReader.DoNonViolations)
return null;
// Check if contains password.
if (message.ToLower().Contains(user.Password.ToLower()))
return Messages.PasswordNotice;
// Check if ALL CAPS
string[] wordsSaid;
if (message.Contains(' '))
wordsSaid = message.Split(' ');
else
wordsSaid = new string[] { message };
foreach (string word in wordsSaid)
{
string lettersOnly = "";
foreach(char c in word)
{
if((byte)c >= (byte)'A' && (byte)c <= (byte)'z') // is letter
{
lettersOnly += c;
}
}
if (lettersOnly.ToUpper() == lettersOnly && lettersOnly.Length >= 5)
return Messages.CapsNotice;
}
return null;
}
public static Reason GetReason(string name)
{
foreach (Reason reason in Reasons)
if (reason.Name == name)
return reason;
throw new KeyNotFoundException("Reason " + name + " not found.");
}
}
}

View file

@ -0,0 +1,733 @@
using HISP.Player;
using HISP.Server;
using HISP.Game.Items;
using System;
using System.Collections.Generic;
using HISP.Game.Events;
using HISP.Game.Horse;
namespace HISP.Game.Chat
{
public class Command
{
private static User findNamePartial(string name)
{
foreach (GameClient client in GameServer.ConnectedClients)
{
if (client == null)
continue;
if (client.LoggedIn)
{
if (client.LoggedinUser.Username.ToLower().Contains(name.ToLower()))
{
return client.LoggedinUser;
}
}
}
throw new KeyNotFoundException("name not found");
}
public static bool Give(string message, string[] args, User user)
{
if (args.Length <= 0)
return false;
if (!user.Administrator)
return false;
if(args[0].ToUpper() == "OBJECT")
{
int itemId = 0;
try
{
itemId = int.Parse(args[1]);
Item.GetItemById(itemId);
ItemInstance newItemInstance = new ItemInstance(itemId);
if(args.Length >= 3)
{
findNamePartial(args[2]).Inventory.AddIgnoringFull(newItemInstance);
}
else
{
user.Inventory.AddIgnoringFull(newItemInstance);
}
}
catch(Exception)
{
return false;
}
}
else if (args[0].ToUpper() == "HORSE")
{
int horseId = 0;
try
{
horseId = int.Parse(args[1]);
HorseInstance horse = new HorseInstance(HorseInfo.GetBreedById(horseId));
if (args.Length >= 3)
{
findNamePartial(args[2]).HorseInventory.AddHorse(horse);
}
else
{
user.HorseInventory.AddHorse(horse);
}
}
catch (Exception)
{
return false;
}
}
else if (args[0].ToUpper() == "MONEY")
{
int money = 0;
try
{
money = int.Parse(args[1]);
if (args.Length >= 3)
{
findNamePartial(args[2]).AddMoney(money);
}
else
{
user.AddMoney(money);
}
}
catch (Exception)
{
return false;
}
}
else if (args[0].ToUpper() == "QUEST")
{
int questId = 0;
try
{
questId = int.Parse(args[1]);
if(args.Length >= 3)
{
if (args[2].ToUpper() == "FORCE")
{
Quest.CompleteQuest(user, Quest.GetQuestById(questId));
goto msg;
}
}
Quest.ActivateQuest(user, Quest.GetQuestById(questId));
}
catch (Exception)
{
return false;
}
}
else
{
return false;
}
msg:;
byte[] chatPacket = PacketBuilder.CreateChat(Messages.FormatAdminCommandCompleteMessage(message.Substring(1)), PacketBuilder.CHAT_BOTTOM_LEFT);
user.LoggedinClient.SendPacket(chatPacket);
return true;
}
public static bool UnBan(string message, string[] args, User user)
{
if(args.Length <= 0)
return false;
if(!(user.Administrator || user.Moderator))
return false;
try{
string userName = args[0];
int id = Database.GetUserid(userName);
Database.UnBanUser(id);
}
catch(Exception e)
{
Logger.ErrorPrint(e.Message);
return false;
}
byte[] chatPacket = PacketBuilder.CreateChat(Messages.FormatAdminCommandCompleteMessage(message.Substring(1)), PacketBuilder.CHAT_BOTTOM_LEFT);
user.LoggedinClient.SendPacket(chatPacket);
return true;
}
public static bool Ban(string message, string[] args, User user)
{
if (args.Length <= 0)
return false;
if (!(user.Administrator || user.Moderator))
return false;
try{
string userName = args[0];
int id = Database.GetUserid(userName);
string ip = Database.GetIpAddress(id);
string reason = "NONE SPECIFIED";
if (args.Length >= 2)
{
reason = string.Join(" ", args, 1, args.Length - 1);
}
Database.BanUser(id, ip, reason);
}
catch(Exception)
{
return false;
}
try{
User bannedUser = GameServer.GetUserByName(args[0]);
bannedUser.LoggedinClient.Kick(Messages.KickReasonBanned);
}
catch(KeyNotFoundException){};
byte[] chatPacket = PacketBuilder.CreateChat(Messages.FormatAdminCommandCompleteMessage(message.Substring(1)), PacketBuilder.CHAT_BOTTOM_LEFT);
user.LoggedinClient.SendPacket(chatPacket);
return true;
}
public static bool Escape(string message, string[] args, User user)
{
if (!(user.Administrator || user.Moderator))
return false;
user.Teleport(Map.ModIsleX, Map.ModIsleY);
byte[] chatPacket = PacketBuilder.CreateChat(Messages.FormatAdminCommandCompleteMessage(message.Substring(1)) + Messages.ModIsleMessage, PacketBuilder.CHAT_BOTTOM_LEFT);
user.LoggedinClient.SendPacket(chatPacket);
return true;
}
public static bool Stealth(string message, string[] args, User user)
{
if (!(user.Administrator || user.Moderator))
return false;
user.Stealth = !user.Stealth;
byte[] chatPacket = PacketBuilder.CreateChat(Messages.FormatAdminCommandCompleteMessage(message.Substring(1)), PacketBuilder.CHAT_BOTTOM_LEFT);
user.LoggedinClient.SendPacket(chatPacket);
return true;
}
public static bool NoClip(string message, string[] args, User user)
{
if (!user.Administrator)
return false;
user.NoClip = !user.NoClip;
byte[] chatPacket = PacketBuilder.CreateChat(Messages.FormatAdminCommandCompleteMessage(message.Substring(1)), PacketBuilder.CHAT_BOTTOM_LEFT);
user.LoggedinClient.SendPacket(chatPacket);
return true;
}
public static bool Rules(string message, string[] args, User user)
{
if (!(user.Administrator || user.Moderator))
return false;
if (args.Length <= 0)
return false;
try
{
User toSend = GameServer.GetUserByName(args[0]);
toSend.Teleport(Map.RulesIsleX, Map.RulesIsleY);
byte[] studyTheRulesMsg = PacketBuilder.CreateChat(Messages.RulesIsleSentMessage, PacketBuilder.CHAT_BOTTOM_RIGHT);
toSend.LoggedinClient.SendPacket(studyTheRulesMsg);
}
catch (KeyNotFoundException)
{
return false;
}
byte[] chatPacket = PacketBuilder.CreateChat(Messages.FormatAdminCommandCompleteMessage(message.Substring(1))+Messages.FormatRulesCommandMessage(args[0]), PacketBuilder.CHAT_BOTTOM_LEFT);
user.LoggedinClient.SendPacket(chatPacket);
return true;
}
public static bool Kick(string message, string[] args, User user)
{
if (!(user.Administrator || user.Moderator))
return false;
if (args.Length <= 0)
return false;
try
{
User toKick = GameServer.GetUserByName(args[0]);
if (args.Length >= 2)
{
string reason = string.Join(" ", args, 1, args.Length - 1);
toKick.LoggedinClient.Kick(reason);
}
else
toKick.LoggedinClient.Kick(Messages.KickReasonKicked);
}
catch (KeyNotFoundException)
{
return false;
}
byte[] chatPacket = PacketBuilder.CreateChat(Messages.FormatAdminCommandCompleteMessage(message.Substring(1)), PacketBuilder.CHAT_BOTTOM_LEFT);
user.LoggedinClient.SendPacket(chatPacket);
return true;
}
public static bool Jump(string message, string[] args, User user)
{
if (args.Length <= 0)
return false;
if (!user.Administrator)
return false;
if(args.Length < 2)
{
return false;
}
try
{
User tp = findNamePartial(args[0]);
if (args[1].ToUpper() == "HERE")
tp.Teleport(user.X, user.Y);
}
catch (KeyNotFoundException)
{
return false;
}
byte[] chatPacket = PacketBuilder.CreateChat(Messages.FormatAdminCommandCompleteMessage(message.Substring(1)), PacketBuilder.CHAT_BOTTOM_LEFT);
user.LoggedinClient.SendPacket(chatPacket);
return true;
}
public static bool Goto(string message, string[] args, User user)
{
if (args.Length <= 0)
return false;
if (!user.Administrator)
return false;
if(args[0].ToUpper() == "PLAYER")
{
if(args.Length < 2)
return false;
try
{
User tpTo = findNamePartial(args[1]);
user.Teleport(tpTo.X, tpTo.Y);
}
catch (KeyNotFoundException)
{
return false;
}
}
else if(args[0].ToUpper() == "AREA")
{
if (args.Length < 2)
return false;
try
{
string area = string.Join(" ", args, 1, args.Length - 1);
bool teleported = false;
foreach(World.Waypoint waypnt in World.Waypoints)
{
if(waypnt.Name.ToLower().StartsWith(area.ToLower()))
{
user.Teleport(waypnt.PosX, waypnt.PosY);
teleported = true;
break;
}
}
if(!teleported)
return false;
}
catch(Exception)
{
return false;
}
}
else if(args[0].ToUpper() == "NPC")
{
if (args.Length < 2)
return false;
try
{
string npcName = string.Join(" ", args, 1, args.Length - 1);
bool teleported = false;
foreach (Npc.NpcEntry npc in Npc.NpcList)
{
if (npc.Name.ToLower().StartsWith(npcName.ToLower()))
{
user.Teleport(npc.X, npc.Y);
teleported = true;
break;
}
}
if (!teleported)
return false;
}
catch (Exception)
{
return false;
}
}
else if(args[0].Contains(","))
{
try
{
string[] xy = args[0].Split(',');
int x = int.Parse(xy[0]);
int y = int.Parse(xy[1]);
user.Teleport(x, y);
}
catch(FormatException)
{
return false;
}
}
else
{
return false;
}
byte[] chatPacket = PacketBuilder.CreateChat(Messages.FormatAdminCommandCompleteMessage(message.Substring(1)), PacketBuilder.CHAT_BOTTOM_LEFT);
user.LoggedinClient.SendPacket(chatPacket);
return true;
}
public static bool Warp(string message, string[] args, User user)
{
string formattedmessage = Messages.FormatPlayerCommandCompleteMessage(message.Substring(1));
if (user.CurrentlyRidingHorse == null)
goto onlyRiddenUnicorn;
if (user.CurrentlyRidingHorse.Breed.Type == "unicorn")
goto doCommand;
goto onlyRiddenUnicorn;
onlyRiddenUnicorn:;
formattedmessage = Messages.OnlyUnicornCanWarp;
goto sendText;
cantUnderstandCommand:;
formattedmessage += Messages.FailedToUnderstandLocation;
goto sendText;
doCommand:;
if (args.Length <= 0)
{
goto cantUnderstandCommand;
}
else
{
string areaName = string.Join(" ", args).ToLower();
try
{
User tp = findNamePartial(areaName);
user.Teleport(tp.X, tp.Y);
formattedmessage += Messages.SuccessfullyWarpedToPlayer;
goto playSwf;
}
catch (KeyNotFoundException)
{
foreach (World.Waypoint waypoint in World.Waypoints)
{
if (waypoint.Name.ToLower().Contains(areaName))
{
user.Teleport(waypoint.PosX, waypoint.PosY);
formattedmessage += Messages.SuccessfullyWarpedToLocation;
goto playSwf;
}
}
goto cantUnderstandCommand;
}
}
playSwf:;
byte[] swfPacket = PacketBuilder.CreateSwfModulePacket("warpcutscene", PacketBuilder.PACKET_SWF_CUTSCENE);
user.LoggedinClient.SendPacket(swfPacket);
sendText:;
byte[] chatPacket = PacketBuilder.CreateChat(formattedmessage, PacketBuilder.CHAT_BOTTOM_LEFT);
user.LoggedinClient.SendPacket(chatPacket);
return true;
}
public static bool CallHorse(string message, string[] args, User user)
{
if (!user.Administrator)
return false;
string formattedmessage = Messages.FormatPlayerCommandCompleteMessage(message.Substring(1));
WildHorse horse = WildHorse.WildHorses[GameServer.RandomNumberGenerator.Next(0, WildHorse.WildHorses.Length)];
horse.X = user.X;
horse.Y = user.Y;
GameServer.UpdateAreaForAll(user.X, user.Y);
byte[] chatPacket = PacketBuilder.CreateChat(formattedmessage, PacketBuilder.CHAT_BOTTOM_LEFT);
user.LoggedinClient.SendPacket(chatPacket);
return true;
}
public static bool AutoReply(string message, string[] args, User user)
{
string replyMessage = string.Join(" ", args);
string formattedmessage = Messages.FormatPlayerCommandCompleteMessage(message.Substring(1));
replyMessage = replyMessage.Trim();
if (replyMessage.Length > 1024)
{
byte[] tooLong = PacketBuilder.CreateChat(Messages.AutoReplyTooLong, PacketBuilder.CHAT_BOTTOM_RIGHT);
user.LoggedinClient.SendPacket(tooLong);
return false;
}
Object violationReason = Chat.FilterMessage(replyMessage);
if (violationReason != null)
{
byte[] hasVios = PacketBuilder.CreateChat(Messages.AutoReplyHasViolations, PacketBuilder.CHAT_BOTTOM_RIGHT);
user.LoggedinClient.SendPacket(hasVios);
return false;
}
user.AutoReplyText = replyMessage;
byte[] chatPacket = PacketBuilder.CreateChat(formattedmessage, PacketBuilder.CHAT_BOTTOM_LEFT);
user.LoggedinClient.SendPacket(chatPacket);
return true;
}
public static bool Dance(string message, string[] args, User user)
{
string moves = string.Join(" ", args).ToLower();
string formattedmessage = Messages.FormatPlayerCommandCompleteMessage(message.Substring(1));
if (user.ActiveDance != null)
user.ActiveDance.Dispose();
user.ActiveDance = new Dance(user, moves);
byte[] chatPacket = PacketBuilder.CreateChat(formattedmessage, PacketBuilder.CHAT_BOTTOM_LEFT);
user.LoggedinClient.SendPacket(chatPacket);
return true;
}
public static bool Quiz(string message, string[] args, User user)
{
bool quizActive = (GameServer.QuizEvent != null);
if(user.InRealTimeQuiz)
{
byte[] cantEnterRealTimeQuiz = PacketBuilder.CreateChat(Messages.EventAlreadyEnteredRealTimeQuiz, PacketBuilder.CHAT_BOTTOM_RIGHT);
user.LoggedinClient.SendPacket(cantEnterRealTimeQuiz);
return false;
}
if (quizActive)
{
string formattedmessage = Messages.FormatPlayerCommandCompleteMessage(message.Substring(1));
RealTimeQuiz.Participent participent = GameServer.QuizEvent.JoinEvent(user);
if(participent.Quit)
{
byte[] quizQuit = PacketBuilder.CreateChat(Messages.EventQuitRealTimeQuiz, PacketBuilder.CHAT_BOTTOM_RIGHT);
user.LoggedinClient.SendPacket(quizQuit);
return false;
}
participent.UpdateParticipent();
byte[] enteredRealTimeQuiz = PacketBuilder.CreateChat(Messages.EventEnteredRealTimeQuiz, PacketBuilder.CHAT_BOTTOM_RIGHT);
user.LoggedinClient.SendPacket(enteredRealTimeQuiz);
byte[] chatPacket = PacketBuilder.CreateChat(formattedmessage, PacketBuilder.CHAT_BOTTOM_LEFT);
user.LoggedinClient.SendPacket(chatPacket);
return true;
}
else
{
byte[] quizUnavailable = PacketBuilder.CreateChat(Messages.EventUnavailableRealTimeQuiz, PacketBuilder.CHAT_BOTTOM_RIGHT);
user.LoggedinClient.SendPacket(quizUnavailable);
return false;
}
}
public static bool Mute(string message, string[] args, User user)
{
string formattedmessage = Messages.FormatPlayerCommandCompleteMessage(message.Substring(1));
if (args.Length <= 0)
{
formattedmessage += Messages.MuteHelp;
goto leave;
}
string muteType = args[0];
if (muteType.ToUpper() == "GLOBAL")
{
user.MuteGlobal = true;
} else if (muteType.ToUpper() == "ISLAND")
{
user.MuteIsland = true;
} else if (muteType.ToUpper() == "NEAR")
{
user.MuteNear = true;
} else if (muteType.ToUpper() == "HERE")
{
user.MuteHere = true;
} else if (muteType.ToUpper() == "BUDDY")
{
user.MuteBuddy = true;
} else if (muteType.ToUpper() == "SOCIALS")
{
user.MuteSocials = true;
}
else if (muteType.ToUpper() == "PM")
{
user.MutePrivateMessage = true;
}
else if (muteType.ToUpper() == "BR")
{
user.MuteBuddyRequests = true;
}
else if (muteType.ToUpper() == "LOGINS")
{
user.MuteLogins = true;
}
else if (muteType.ToUpper() == "ALL")
{
user.MuteAll = true;
user.MuteGlobal = true;
user.MuteIsland = true;
user.MuteNear = true;
user.MuteHere = true;
user.MuteBuddy = true;
user.MuteSocials = true;
user.MutePrivateMessage = true;
user.MuteBuddyRequests = true;
user.MuteLogins = true;
}
else
{
formattedmessage += Messages.MuteHelp;
goto leave;
}
leave:;
byte[] chatPacket = PacketBuilder.CreateChat(formattedmessage, PacketBuilder.CHAT_BOTTOM_LEFT);
user.LoggedinClient.SendPacket(chatPacket);
return true;
}
public static bool UnMute(string message, string[] args, User user)
{
string formattedmessage = Messages.FormatPlayerCommandCompleteMessage(message.Substring(1));
if (args.Length <= 0)
{
formattedmessage += Messages.UnMuteHelp;
goto leave;
}
string muteType = args[0];
if (muteType.ToUpper() == "GLOBAL")
{
user.MuteGlobal = false;
}
else if (muteType.ToUpper() == "ISLAND")
{
user.MuteIsland = false;
}
else if (muteType.ToUpper() == "NEAR")
{
user.MuteNear = false;
}
else if (muteType.ToUpper() == "HERE")
{
user.MuteHere = false;
}
else if (muteType.ToUpper() == "BUDDY")
{
user.MuteBuddy = false;
}
else if (muteType.ToUpper() == "SOCIALS")
{
user.MuteSocials = false;
}
else if (muteType.ToUpper() == "PM")
{
user.MutePrivateMessage = false;
}
else if (muteType.ToUpper() == "BR")
{
user.MuteBuddyRequests = false;
}
else if (muteType.ToUpper() == "LOGINS")
{
user.MuteLogins = false;
}
else if (muteType.ToUpper() == "ALL")
{
user.MuteAll = false;
user.MuteGlobal = false;
user.MuteIsland = false;
user.MuteNear = false;
user.MuteHere = false;
user.MuteBuddy = false;
user.MuteSocials = false;
user.MutePrivateMessage = false;
user.MuteBuddyRequests = false;
user.MuteLogins = false;
}
else
{
formattedmessage += Messages.UnMuteHelp;
goto leave;
}
leave:;
byte[] chatPacket = PacketBuilder.CreateChat(formattedmessage, PacketBuilder.CHAT_BOTTOM_LEFT);
user.LoggedinClient.SendPacket(chatPacket);
return true;
}
}
}

View file

@ -0,0 +1,60 @@
using System.Collections.Generic;
namespace HISP.Game.Chat
{
public class SocialType
{
public SocialType(string type)
{
Socials = new List<Social>();
Type = type;
SocialTypes.Add(this);
}
public static List<SocialType> SocialTypes = new List<SocialType>();
public string Type;
public List<Social> Socials;
public class Social
{
public SocialType BaseSocialType;
public int Id;
public string ButtonName;
public string ForSender;
public string ForTarget;
public string ForEveryone;
public string SoundEffect;
}
public static Social GetSocial(int socialId)
{
foreach (SocialType sType in SocialTypes)
foreach (Social social in sType.Socials)
if (social.Id == socialId)
return social;
throw new KeyNotFoundException("Social " + socialId.ToString() + " not found!");
}
public static SocialType GetSocialType(string type)
{
foreach (SocialType stype in SocialTypes)
if (stype.Type == type)
return stype;
throw new KeyNotFoundException("SocialType " + type + " NOT FOUND!");
}
public static void AddNewSocial(string type, Social social)
{
foreach(SocialType stype in SocialTypes)
{
if(stype.Type == type)
{
social.BaseSocialType = stype;
stype.Socials.Add(social);
return;
}
}
SocialType sType = new SocialType(type);
social.BaseSocialType = sType;
sType.Socials.Add(social);
return;
}
}
}

View file

@ -0,0 +1,123 @@
using HISP.Game.Items;
using HISP.Server;
using System.Threading;
namespace HISP.Game.Events
{
public class IsleCardTradingGame
{
public bool Active;
private Timer tradingTimeout;
private const int TRADING_TIMEOUT = 5;
public void StartEvent()
{
Active = true;
tradingTimeout = new Timer(new TimerCallback(tradeTimedOut), null, TRADING_TIMEOUT * 60 * 1000, TRADING_TIMEOUT * 60 * 1000);
byte[] msg = PacketBuilder.CreateChat(Messages.EventStartIsleTradingGame, PacketBuilder.CHAT_BOTTOM_RIGHT);
foreach (GameClient client in GameServer.ConnectedClients)
if (client.LoggedIn)
client.SendPacket(msg);
// Give Trading Cards
int[] allUsers = Database.GetUsers();
foreach (int userid in allUsers)
{
int tradingCardId = Item.TradingCards[GameServer.RandomNumberGenerator.Next(0, Item.TradingCards.Length)];
for (int i = 0; i < 4; i++)
{
ItemInstance itm = new ItemInstance(tradingCardId);
if (GameServer.IsUserOnline(userid))
GameServer.GetUserById(userid).Inventory.AddWithoutDatabase(itm);
Database.AddItemToInventory(userid, itm);
}
}
}
public void EndEvent()
{
Active = false;
foreach(GameClient client in GameServer.ConnectedClients)
{
if(client.LoggedIn)
{
int totalCards = 0;
int totalTypes = 0;
foreach (int itemId in Item.TradingCards)
if (client.LoggedinUser.Inventory.HasItemId(itemId))
totalCards += client.LoggedinUser.Inventory.GetItemByItemId(itemId).ItemInstances.Count;
if (client.LoggedinUser.Inventory.HasItemId(Item.ColtTradingCard))
totalTypes++;
if (client.LoggedinUser.Inventory.HasItemId(Item.FillyTradingCard))
totalTypes++;
if (client.LoggedinUser.Inventory.HasItemId(Item.MareTradingCard))
totalTypes++;
if (client.LoggedinUser.Inventory.HasItemId(Item.StallionTradingCard))
totalTypes++;
if(totalCards > 4)
{
byte[] disqualifiedTooManyCards = PacketBuilder.CreateChat(Messages.EventDisqualifiedIsleTradingGame, PacketBuilder.CHAT_BOTTOM_RIGHT);
client.SendPacket(disqualifiedTooManyCards);
}
else if(totalTypes == 0)
{
byte[] noCardsMessage = PacketBuilder.CreateChat(Messages.EventNoneIsleTradingGame, PacketBuilder.CHAT_BOTTOM_RIGHT);
client.SendPacket(noCardsMessage);
}
else if(totalTypes == 1)
{
byte[] onlyOneTypeOfCardMesage = PacketBuilder.CreateChat(Messages.EventOnlyOneTypeIsleTradingGame, PacketBuilder.CHAT_BOTTOM_RIGHT);
client.SendPacket(onlyOneTypeOfCardMesage);
}
else if (totalTypes == 2)
{
byte[] onlyTwoTypeOfCardMesage = PacketBuilder.CreateChat(Messages.EventOnlyTwoTypeIsleTradingGame, PacketBuilder.CHAT_BOTTOM_RIGHT);
client.SendPacket(onlyTwoTypeOfCardMesage);
}
else if (totalTypes == 3)
{
byte[] onlyThreeTypeOfCardMesage = PacketBuilder.CreateChat(Messages.EventOnlyThreeTypeIsleTradingGame, PacketBuilder.CHAT_BOTTOM_RIGHT);
client.SendPacket(onlyThreeTypeOfCardMesage);
}
else if (totalTypes == 4)
{
client.LoggedinUser.TrackedItems.GetTrackedItem(Tracking.TrackableItem.IsleCardsGameWin).Count++;
byte[] wonIsleCardGame = PacketBuilder.CreateChat(Messages.EventWonIsleTradingGame, PacketBuilder.CHAT_BOTTOM_RIGHT);
client.SendPacket(wonIsleCardGame);
client.LoggedinUser.AddMoney(25000);
}
}
}
// Remove all trading cards from the game
foreach (int itemId in Item.TradingCards)
GameServer.RemoveAllItemsOfIdInTheGame(itemId);
tradingTimeout.Dispose();
tradingTimeout = null;
}
private void tradeTimedOut(object state)
{
EndEvent();
}
}
}

View file

@ -0,0 +1,148 @@
using HISP.Game.Items;
using HISP.Player;
using HISP.Server;
using System.Collections.Generic;
using System.Threading;
namespace HISP.Game.Events
{
public class ModsRevenge
{
public class ThrowTracker
{
public ThrowTracker(User thrower)
{
Thrower = thrower;
ThrownAt = new List<User>();
}
public User Thrower;
public List<User> ThrownAt;
}
public bool Active = false;
public const int REVENGE_TIMEOUT = 10;
private List<ThrowTracker> trackedThrows;
private Timer revengeTimeout;
public ThrowTracker[] TrackedThrows
{
get
{
return trackedThrows.ToArray();
}
}
public ModsRevenge()
{
trackedThrows = new List<ThrowTracker>();
Active = false;
}
public void StartEvent()
{
revengeTimeout = new Timer(new TimerCallback(revengeTimedOut), null, REVENGE_TIMEOUT * 60 * 1000, REVENGE_TIMEOUT * 60 * 1000);
int TOTAL_SPLATTERBALLS = 8; // I dont know the actural amount t-t
// Give Splatterballs
int[] allUsers = Database.GetUsers();
foreach (int userid in allUsers)
{
for (int i = 0; i < TOTAL_SPLATTERBALLS; i++)
{
ItemInstance itm = new ItemInstance(Item.ModSplatterball);
if (GameServer.IsUserOnline(userid))
GameServer.GetUserById(userid).Inventory.AddWithoutDatabase(itm);
Database.AddItemToInventory(userid, itm);
}
}
byte[] annoucePacket = PacketBuilder.CreateChat(Messages.EventStartModsRevenge, PacketBuilder.CHAT_BOTTOM_RIGHT);
foreach (GameClient client in GameServer.ConnectedClients)
if (client.LoggedIn)
client.SendPacket(annoucePacket);
}
public void EndEvent()
{
GameServer.RemoveAllItemsOfIdInTheGame(Item.ModSplatterball);
byte[] annoucePacket = PacketBuilder.CreateChat(Messages.EventEndModsRevenge, PacketBuilder.CHAT_BOTTOM_RIGHT);
foreach (GameClient client in GameServer.ConnectedClients)
if (client.LoggedIn)
client.SendPacket(annoucePacket);
}
private void revengeTimedOut(object state)
{
resetEvent();
EndEvent();
}
private void resetEvent()
{
revengeTimeout.Dispose();
trackedThrows.Clear();
Active = false;
}
private ThrowTracker getUserThrowTracker(User thrower)
{
foreach (ThrowTracker throwTracker in TrackedThrows)
{
if (throwTracker.Thrower.Id == thrower.Id)
return throwTracker;
}
ThrowTracker tracker = new ThrowTracker(thrower);
trackedThrows.Add(tracker);
return tracker;
}
private bool checkUserThrownAtAlready(ThrowTracker tracker, User thrownAt)
{
foreach (User user in tracker.ThrownAt)
{
if (user.Id == thrownAt.Id)
return true;
}
return false;
}
public void LeaveEvent(User userToLeave)
{
foreach (ThrowTracker thrownMemory in TrackedThrows)
{
if (thrownMemory.Thrower.Id == userToLeave.Id)
trackedThrows.Remove(thrownMemory);
}
}
public void Payout(User thrower, User throwAt)
{
ThrowTracker throwCounter = getUserThrowTracker(thrower);
if(!checkUserThrownAtAlready(throwCounter, throwAt))
{
byte[] otherEarned = PacketBuilder.CreateChat(Messages.FormatModSplatterBallAwardedOther(thrower.Username), PacketBuilder.CHAT_BOTTOM_RIGHT);
byte[] youEarned = PacketBuilder.CreateChat(Messages.FormatModSplatterBallAwardedYou(throwAt.Username), PacketBuilder.CHAT_BOTTOM_RIGHT);
thrower.AddMoney(50);
throwAt.AddMoney(500);
thrower.LoggedinClient.SendPacket(youEarned);
throwAt.LoggedinClient.SendPacket(otherEarned);
throwCounter.ThrownAt.Add(throwAt);
}
}
}
}

View file

@ -0,0 +1,89 @@
using HISP.Game.Horse;
using HISP.Game.Items;
using HISP.Player;
using HISP.Server;
using System.Collections.Generic;
namespace HISP.Game.Events
{
public class RandomEvent
{
public static List<RandomEvent> RandomEvents = new List<RandomEvent>();
public static RandomEvent GetRandomEvent()
{
int randomEvent = GameServer.RandomNumberGenerator.Next(0, RandomEvents.Count);
return RandomEvents[randomEvent];
}
public static void ExecuteRandomEvent(User user)
{
while (true)
{
RandomEvent rngEvent = RandomEvent.GetRandomEvent();
if (rngEvent.HorseHealthDown != 0 && user.HorseInventory.HorseList.Length <= 0)
continue;
if (rngEvent.Text.Contains("%HORSENAME%") && user.HorseInventory.HorseList.Length <= 0)
continue;
int moneyEarned = 0;
if (rngEvent.MinMoney != 0 || rngEvent.MaxMoney != 0)
moneyEarned = GameServer.RandomNumberGenerator.Next(rngEvent.MinMoney, rngEvent.MaxMoney);
if (moneyEarned < 0)
if (user.Money + moneyEarned < 0)
continue;
if (rngEvent.GiveObject != 0)
user.Inventory.AddIgnoringFull(new ItemInstance(rngEvent.GiveObject));
if(moneyEarned != 0)
user.AddMoney(moneyEarned);
HorseInstance effectedHorse = null;
if(user.HorseInventory.HorseList.Length > 0)
{
int randomHorseIndex = GameServer.RandomNumberGenerator.Next(0, user.HorseInventory.HorseList.Length);
effectedHorse = user.HorseInventory.HorseList[randomHorseIndex];
}
if (rngEvent.HorseHealthDown != 0)
effectedHorse.BasicStats.Health -= rngEvent.HorseHealthDown;
string horseName = "[This Message Should Not Appear, if it does its a bug.]";
if (effectedHorse != null)
horseName = effectedHorse.Name;
string msg = Messages.FormatRandomEvent(rngEvent.Text, moneyEarned, horseName);
byte[] chatPacket = PacketBuilder.CreateChat(Messages.RandomEventPrefix + msg, PacketBuilder.CHAT_BOTTOM_RIGHT);
user.LoggedinClient.SendPacket(chatPacket);
return;
}
}
public RandomEvent(int id, string text, int minMoney, int maxMoney, int horseHealth, int giveObject)
{
Id = id;
Text = text;
MinMoney = minMoney;
MaxMoney = maxMoney;
HorseHealthDown = horseHealth;
GiveObject = giveObject;
RandomEvents.Add(this);
}
public int Id;
public string Text;
public int MinMoney;
public int MaxMoney;
public int HorseHealthDown;
public int GiveObject;
}
}

View file

@ -0,0 +1,262 @@
using HISP.Player;
using HISP.Server;
using System.Collections.Generic;
using System.Threading;
namespace HISP.Game.Events
{
public class RealTimeQuiz
{
public class QuizQuestion
{
public QuizQuestion(QuizCategory category)
{
BaseCategory = category;
}
public QuizCategory BaseCategory;
public string Question;
public string[] Answers;
}
public class QuizCategory
{
public string Name;
public QuizQuestion[] Questions;
}
public class Participent
{
public Participent(User user, RealTimeQuiz Quiz)
{
UserInstance = user;
Won = false;
Quit = false;
CorrectAnswers = 0;
MistakenAnswers = 0;
baseQuiz = Quiz;
NextQuestion();
}
public void NextQuestion()
{
OnQuestion = baseQuiz.Questions[CorrectAnswers++];
}
public void UpdateParticipent()
{
if (this.Quit)
return;
byte[] realTimeQuizQuestion = PacketBuilder.CreateMetaPacket(Meta.BuildRealTimeQuiz(this));
this.UserInstance.LoggedinClient.SendPacket(realTimeQuizQuestion);
}
public void CheckAnswer(string answer)
{
foreach (string correctAnswer in OnQuestion.Answers)
{
if(answer.ToLower().Trim() == correctAnswer.ToLower().Trim())
{
if(CorrectAnswers >= baseQuiz.Questions.Length)
{
baseQuiz.WinEvent(UserInstance);
return;
}
NextQuestion();
UpdateParticipent();
return;
}
if (answer.ToLower().Trim() == "quit")
{
baseQuiz.QuitEvent(UserInstance);
return;
}
}
MistakenAnswers++;
UpdateParticipent();
}
private RealTimeQuiz baseQuiz;
public User UserInstance;
public int CorrectAnswers;
public int MistakenAnswers;
public bool Quit;
public bool Won;
public QuizQuestion OnQuestion;
}
public static QuizCategory[] Categories;
public QuizQuestion[] Questions;
public bool Active;
public const int QUIZ_TIMEOUT = 5;
private Timer quizTimer;
public Participent[] Participents
{
get
{
return participents.ToArray();
}
}
private List<Participent> participents;
public RealTimeQuiz()
{
participents = new List<Participent>();
Questions = new QuizQuestion[8];
for(int i = 0; i < 8; i++)
{
QuizCategory chosenCategory = Categories[GameServer.RandomNumberGenerator.Next(0, Categories.Length)];
Questions[i] = chosenCategory.Questions[GameServer.RandomNumberGenerator.Next(0, chosenCategory.Questions.Length)];
}
Active = false;
}
private Participent getParticipent(int id)
{
foreach (Participent participent in Participents)
{
if (participent.UserInstance.Id == id)
{
return participent;
}
}
throw new KeyNotFoundException("No participent found.");
}
public Participent JoinEvent(User user)
{
try
{
return getParticipent(user.Id);
}
catch (KeyNotFoundException) { };
Participent newParticipent = new Participent(user, this);
user.InRealTimeQuiz = true;
participents.Add(newParticipent);
return newParticipent;
}
public void LeaveEvent(User user)
{
try
{
Participent partcipent = getParticipent(user.Id);
user.InRealTimeQuiz = false;
participents.Remove(partcipent);
partcipent = null;
}
catch (KeyNotFoundException) { };
}
public void QuitEvent(User user)
{
try
{
Participent partcipent = getParticipent(user.Id);
partcipent.Quit = true;
user.InRealTimeQuiz = false;
GameServer.UpdateArea(user.LoggedinClient);
}
catch (KeyNotFoundException) { };
}
public void StartEvent()
{
quizTimer = new Timer(new TimerCallback(quizTimesUp), null, QUIZ_TIMEOUT * 60 * 1000, QUIZ_TIMEOUT * 60 * 1000);
byte[] quizStartMessage = PacketBuilder.CreateChat(Messages.EventStartRealTimeQuiz, PacketBuilder.CHAT_BOTTOM_RIGHT);
foreach (GameClient client in GameServer.ConnectedClients)
if (client.LoggedIn)
client.SendPacket(quizStartMessage);
Active = true;
GameServer.QuizEvent = this;
}
public void WinEvent(User winner)
{
byte[] eventWinMessage = PacketBuilder.CreateChat(Messages.FormatEventRealTimeQuizWin(winner.Username), PacketBuilder.CHAT_BOTTOM_RIGHT);
foreach (GameClient client in GameServer.ConnectedClients)
if (client.LoggedIn)
client.SendPacket(eventWinMessage);
getParticipent(winner.Id).Won = true;
winner.TrackedItems.GetTrackedItem(Tracking.TrackableItem.QuizWin).Count++;
if (winner.TrackedItems.GetTrackedItem(Tracking.TrackableItem.QuizWin).Count >= 15)
winner.Awards.AddAward(Award.GetAwardById(54)); // Quiz Genius
if (winner.TrackedItems.GetTrackedItem(Tracking.TrackableItem.QuizWin).Count >= 25)
winner.Awards.AddAward(Award.GetAwardById(33)); // Quick Wit
stopEvent();
}
public void EndEvent()
{
byte[] eventEndMessage = PacketBuilder.CreateChat(Messages.EventEndRealTimeQuiz, PacketBuilder.CHAT_BOTTOM_RIGHT);
foreach (GameClient client in GameServer.ConnectedClients)
if(client.LoggedIn)
client.SendPacket(eventEndMessage);
stopEvent();
}
private void stopEvent()
{
foreach(Participent participent in Participents)
{
if (participent.Quit)
continue;
participent.UserInstance.InRealTimeQuiz = false;
GameServer.UpdateArea(participent.UserInstance.LoggedinClient);
int money = 0;
if (participent.Won)
money += 2500;
else
money += 250;
money += (participent.CorrectAnswers * 500);
money -= (participent.MistakenAnswers * 100);
if (money < 250)
money = 250;
if (participent.Won)
{
byte[] wonBonusMessage = PacketBuilder.CreateChat(Messages.FormatEventRealTimeQuizWinBonus(money), PacketBuilder.CHAT_BOTTOM_RIGHT);
participent.UserInstance.LoggedinClient.SendPacket(wonBonusMessage);
}
else
{
byte[] bonusMessage = PacketBuilder.CreateChat(Messages.FormatEventRealTimeQuizBonus(money), PacketBuilder.CHAT_BOTTOM_RIGHT);
participent.UserInstance.LoggedinClient.SendPacket(bonusMessage);
}
participent.UserInstance.AddMoney(money);
}
participents.Clear();
participents = null;
quizTimer.Dispose();
Active = false;
GameServer.QuizEvent = null;
}
private void quizTimesUp(object state)
{
EndEvent();
}
}
}

View file

@ -0,0 +1,118 @@
using HISP.Player;
using HISP.Server;
using System.Collections.Generic;
using System.Threading;
namespace HISP.Game.Events
{
public class RealTimeRiddle
{
public static List<RealTimeRiddle> RealTimeRiddles = new List<RealTimeRiddle>();
public RealTimeRiddle(int riddleId, string riddleText, string[] answers, int reward)
{
RiddleId = riddleId;
RiddleText = riddleText;
Answers = answers;
Reward = reward;
Active = false;
RealTimeRiddles.Add(this);
}
public int RiddleId;
public string RiddleText;
public string[] Answers;
public bool Active;
public int Reward;
public static bool LastWon = false;
private Timer riddleTimeout;
private const int RIDDLE_TIMEOUT = 5;
public static RealTimeRiddle GetRandomRiddle()
{
int randomRiddleIndex = GameServer.RandomNumberGenerator.Next(0, RealTimeRiddles.Count);
return RealTimeRiddles[randomRiddleIndex];
}
public void StartEvent()
{
Active = true;
riddleTimeout = new Timer(new TimerCallback(riddleTimedOut), null, RIDDLE_TIMEOUT * 60 * 1000, RIDDLE_TIMEOUT * 60 * 1000);
// Send riddle message to all players
foreach(GameClient client in GameServer.ConnectedClients)
{
if (client.LoggedIn)
ShowStartMessage(client);
}
}
public void ShowStartMessage(GameClient client)
{
if (!Active)
return;
byte[] riddleStartMessage = PacketBuilder.CreateChat(Messages.FormatEventRealTimeRiddleStart(RiddleText), PacketBuilder.CHAT_BOTTOM_RIGHT);
client.SendPacket(riddleStartMessage);
}
public void Win(User winner)
{
if (!Active)
return;
if (Database.HasPlayerCompletedRealTimeRiddle(RiddleId, winner.Id))
return;
LastWon = true;
Database.CompleteRealTimeRiddle(RiddleId, winner.Id);
winner.TrackedItems.GetTrackedItem(Tracking.TrackableItem.RiddleWin).Count++;
if (winner.TrackedItems.GetTrackedItem(Tracking.TrackableItem.RiddleWin).Count >= 25)
winner.Awards.AddAward(Award.GetAwardById(33)); // Quick Wit
if (winner.TrackedItems.GetTrackedItem(Tracking.TrackableItem.RiddleWin).Count >= 250)
winner.Awards.AddAward(Award.GetAwardById(34)); // Riddle Genius
winner.AddMoney(Reward);
byte[] riddleWonMessage = PacketBuilder.CreateChat(Messages.FormatEventRealTimeRiddleWonForOthers(winner.Username), PacketBuilder.CHAT_BOTTOM_RIGHT);
byte[] riddleYouWonMessage = PacketBuilder.CreateChat(Messages.FormatEventRealTimeRiddleWonForYou(Reward), PacketBuilder.CHAT_BOTTOM_RIGHT);
foreach (GameClient client in GameServer.ConnectedClients)
{
if (client.LoggedIn)
if (client.LoggedinUser.Id != winner.Id)
client.SendPacket(riddleWonMessage);
else
client.SendPacket(riddleYouWonMessage);
}
EndEvent();
}
public void EndEvent()
{
Active = false;
riddleTimeout.Dispose();
riddleTimeout = null;
}
private void riddleTimedOut(object state)
{
byte[] riddleTimedOutMessage = PacketBuilder.CreateChat(Messages.EventEndRealTimeRiddle, PacketBuilder.CHAT_BOTTOM_RIGHT);
foreach (GameClient client in GameServer.ConnectedClients)
{
if (client.LoggedIn)
client.SendPacket(riddleTimedOutMessage);
}
LastWon = false;
EndEvent();
}
public bool CheckRiddle(string message)
{
string msgCheck = message.ToLower();
foreach(string answer in Answers)
{
if (msgCheck.Contains(answer.ToLower()))
return true;
}
return false;
}
}
}

View file

@ -0,0 +1,154 @@
using HISP.Game.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using HISP.Server;
using HISP.Game.Horse;
using System.Threading;
using HISP.Player;
namespace HISP.Game.Events
{
public class TackShopGiveaway
{
public string ShopName;
public World.SpecialTile Location;
public HorseInstance HorseGiveaway;
public World.Town Town;
public bool Active = false;
public const int TACKSHOP_TIMEOUT = 1;
private Timer giveAwayTimer;
private int timesTicked = 0;
private void giveawayTick(object state)
{
timesTicked++;
if (timesTicked >= 2)
{
EndEvent();
return;
}
if (timesTicked >= 1)
{
byte[] giveAwayMessage = PacketBuilder.CreateChat(Messages.FormatEventTackShopGiveaway1Min(HorseGiveaway.Color, HorseGiveaway.Breed.Name, HorseGiveaway.Gender, ShopName, Town.Name), PacketBuilder.CHAT_BOTTOM_RIGHT);
foreach (GameClient client in GameServer.ConnectedClients)
if (client.LoggedIn)
client.SendPacket(giveAwayMessage);
}
giveAwayTimer.Change(TACKSHOP_TIMEOUT * 60 * 1000, TACKSHOP_TIMEOUT * 60 * 1000);
}
public TackShopGiveaway()
{
List<World.SpecialTile> specialTiles = new List<World.SpecialTile>();
foreach (World.SpecialTile sTile in World.SpecialTiles)
{
if (sTile.Code != null)
{
if (sTile.Code.StartsWith("STORE-"))
{
int storeId = int.Parse(sTile.Code.Split("-")[1]);
Shop shopData = Shop.GetShopById(storeId);
if (shopData.BuysItemTypes.Contains("TACK"))
{
Npc.NpcEntry[] npcShop = Npc.GetNpcByXAndY(sTile.X, sTile.Y);
if (npcShop.Length > 0)
{
specialTiles.Add(sTile);
}
}
}
}
}
string npcName = "ERROR";
string npcDesc = "OBTAINING NAME";
int shpIdx = GameServer.RandomNumberGenerator.Next(0, specialTiles.Count);
Location = specialTiles[shpIdx];
Npc.NpcEntry[] npcShops = Npc.GetNpcByXAndY(Location.X, Location.Y);
npcName = npcShops[0].Name.Split(" ")[0];
if (npcShops[0].ShortDescription.ToLower().Contains("tack"))
{
npcDesc = npcShops[0].ShortDescription.Substring(npcShops[0].ShortDescription.ToLower().IndexOf("tack"));
ShopName = npcName + "'s " + npcDesc;
}
else
{
ShopName = npcName + "'s Gear";
}
while(true)
{
int hrsIdx = GameServer.RandomNumberGenerator.Next(0, HorseInfo.Breeds.Count);
HorseInfo.Breed breed = HorseInfo.Breeds[hrsIdx];
if (breed.SpawnInArea == "none")
continue;
HorseGiveaway = new HorseInstance(breed);
HorseGiveaway.Name = "Tack Shop Giveaway";
break;
}
if (World.InTown(Location.X, Location.Y))
Town = World.GetTown(Location.X, Location.Y);
}
public void StartEvent()
{
giveAwayTimer = new Timer(new TimerCallback(giveawayTick), null, TACKSHOP_TIMEOUT * 60 * 1000, TACKSHOP_TIMEOUT * 60 * 1000);
byte[] giveAwayMessage = PacketBuilder.CreateChat(Messages.FormatEventTackShopGiveawayStart(HorseGiveaway.Color, HorseGiveaway.Breed.Name, HorseGiveaway.Gender, ShopName, Town.Name), PacketBuilder.CHAT_BOTTOM_RIGHT);
foreach (GameClient client in GameServer.ConnectedClients)
if (client.LoggedIn)
client.SendPacket(giveAwayMessage);
Active = true;
GameServer.TackShopGiveawayEvent = this;
}
public void EndEvent()
{
giveAwayTimer.Dispose();
Active = false;
GameServer.TackShopGiveawayEvent = null;
User[] usersHere = GameServer.GetUsersAt(Location.X, Location.Y, false, true);
if(usersHere.Length > 0)
{
int winIndx = GameServer.RandomNumberGenerator.Next(0, usersHere.Length);
User winner = usersHere[winIndx];
winner.HorseInventory.AddHorse(HorseGiveaway);
winner.TrackedItems.GetTrackedItem(Tracking.TrackableItem.TackShopGiveaway).Count++;
byte[] horseWonMessage = PacketBuilder.CreateChat(Messages.FormatEventTackShopGiveawayWon(winner.Username, HorseGiveaway.Breed.Name, ShopName, Town.Name, usersHere.Length), PacketBuilder.CHAT_BOTTOM_RIGHT);
foreach (GameClient client in GameServer.ConnectedClients)
if (client.LoggedIn)
client.SendPacket(horseWonMessage);
}
else
{
byte[] eventEndedMessage = PacketBuilder.CreateChat(Messages.FormatEventTackShopGiveawayEnd(ShopName, Town.Name), PacketBuilder.CHAT_BOTTOM_RIGHT);
foreach (GameClient client in GameServer.ConnectedClients)
if (client.LoggedIn)
client.SendPacket(eventEndedMessage);
}
}
}
}

View file

@ -0,0 +1,149 @@
using HISP.Game.Inventory;
using HISP.Game.Items;
using HISP.Player;
using HISP.Server;
using System.Collections.Generic;
using System.Threading;
namespace HISP.Game.Events
{
public class WaterBalloonGame
{
public WaterBalloonGame()
{
ThrownWaterBalloonMemory = new List<ThrownCounter>();
Active = false;
}
public List<ThrownCounter> ThrownWaterBalloonMemory;
public bool Active;
private Timer gameTimeout;
private const int WATER_BALLOON_GAME_TIMEOUT = 5;
public class ThrownCounter
{
public ThrownCounter(WaterBalloonGame game, User userHit, int numThrown)
{
UserHit = userHit;
NumThrown = numThrown;
baseGame = game;
game.ThrownWaterBalloonMemory.Add(this);
}
private WaterBalloonGame baseGame;
public User UserHit;
public int NumThrown;
}
public void StartEvent()
{
Active = true;
gameTimeout = new Timer(new TimerCallback(gameTimedOut), null, WATER_BALLOON_GAME_TIMEOUT * 60 * 1000, WATER_BALLOON_GAME_TIMEOUT * 60 * 1000);
byte[] gameStartMessage = PacketBuilder.CreateChat(Messages.EventStartWaterBallonGame, PacketBuilder.CHAT_BOTTOM_RIGHT);
foreach (GameClient client in GameServer.ConnectedClients)
if (client.LoggedIn)
client.SendPacket(gameStartMessage);
GameServer.AddItemToAllUsersEvenOffline(Item.WaterBalloon, 8);
}
public void EndEvent()
{
ThrownCounter[] winnerCounter = getWinners();
resetEvent();
GameServer.RemoveAllItemsOfIdInTheGame(Item.WaterBalloon);
// Build event over message
string winMsg = Messages.EventEndWaterBalloonGame;
foreach(ThrownCounter winner in winnerCounter)
{
winMsg += Messages.FormatWaterBalloonGameWinner(winner.UserHit.Username, winner.NumThrown);
}
// Send to all online users
byte[] gameWinnerAnnoucement = PacketBuilder.CreateChat(winMsg, PacketBuilder.CHAT_BOTTOM_RIGHT);
foreach (GameClient client in GameServer.ConnectedClients)
if (client.LoggedIn)
client.SendPacket(gameWinnerAnnoucement);
// payout / tell ppl they won.
foreach (ThrownCounter winner in winnerCounter)
{
byte[] youWinMsg = PacketBuilder.CreateChat(Messages.EventWonWaterBallonGame, PacketBuilder.CHAT_BOTTOM_RIGHT);
winner.UserHit.AddMoney(20000);
winner.UserHit.LoggedinClient.SendPacket(youWinMsg);
winner.UserHit.TrackedItems.GetTrackedItem(Tracking.TrackableItem.WaterbaloonGameWin).Count++;
}
}
private void gameTimedOut(object state)
{
EndEvent();
}
private void resetEvent()
{
gameTimeout.Dispose();
gameTimeout = null;
ThrownWaterBalloonMemory.Clear();
Active = false;
}
private ThrownCounter[] getWinners()
{
int maxThrown = 0;
ThrownCounter[] thrownWaterBalloonMemory = ThrownWaterBalloonMemory.ToArray();
List<ThrownCounter> winningCounter = new List<ThrownCounter>();
// Find the highest throw count
foreach(ThrownCounter throwMemory in thrownWaterBalloonMemory)
{
if(throwMemory.NumThrown >= maxThrown)
{
maxThrown = throwMemory.NumThrown;
}
}
// Find all with that throw count and add to winner list
foreach (ThrownCounter throwMemory in thrownWaterBalloonMemory)
{
if (throwMemory.NumThrown == maxThrown)
{
winningCounter.Add(throwMemory);
}
}
return winningCounter.ToArray();
}
public void LeaveEvent(User userToLeave)
{
foreach (ThrownCounter thrownMemory in ThrownWaterBalloonMemory.ToArray())
{
if (thrownMemory.UserHit.Id == userToLeave.Id)
ThrownWaterBalloonMemory.Remove(thrownMemory);
}
}
private ThrownCounter getThrownCounter(User userToGet)
{
foreach(ThrownCounter thrownMemory in ThrownWaterBalloonMemory.ToArray())
{
if (thrownMemory.UserHit.Id == userToGet.Id)
return thrownMemory;
}
return new ThrownCounter(this, userToGet, 0);
}
public void AddWaterBallon(User throwAt)
{
ThrownCounter throwCounter = getThrownCounter(throwAt);
throwCounter.NumThrown++;
}
}
}

View file

@ -0,0 +1,15 @@
using System;
namespace HISP.Game
{
// Inventory
public class InventoryException : Exception { };
public class InventoryFullException : InventoryException { };
public class InventoryMaxStackException : InventoryException { };
// Drawingroom
public class DrawingroomException : Exception { };
public class DrawingroomFullException : DrawingroomException { };
}

View file

@ -0,0 +1,634 @@
using HISP.Server;
using HISP.Game.Items;
using System.Collections.Generic;
using System.Globalization;
using HISP.Player;
namespace HISP.Game.Horse
{
public class HorseInfo
{
public enum StatType
{
AGILITY,
CONFORMATION,
ENDURANCE,
PERSONALITY,
SPEED,
STRENGTH,
INTELIGENCE
}
public class StatCalculator
{
public StatCalculator(HorseInstance horse, StatType type, User user=null)
{
baseHorse = horse;
horseStat = type;
baseUser = user;
}
private StatType horseStat;
private HorseInstance baseHorse;
private User baseUser;
public int BaseValue
{
get
{
switch (horseStat)
{
case StatType.AGILITY:
return baseHorse.Breed.BaseStats.Agility;
case StatType.CONFORMATION:
return baseHorse.Breed.BaseStats.Conformation;
case StatType.ENDURANCE:
return baseHorse.Breed.BaseStats.Endurance;
case StatType.PERSONALITY:
return baseHorse.Breed.BaseStats.Personality;
case StatType.SPEED:
return baseHorse.Breed.BaseStats.Speed;
case StatType.STRENGTH:
return baseHorse.Breed.BaseStats.Strength;
case StatType.INTELIGENCE:
return baseHorse.Breed.BaseStats.Inteligence;
default:
return 0;
}
}
}
public int MaxValue
{
get
{
return BaseValue * 2;
}
}
public int BreedValue
{
get
{
return BaseValue + BreedOffset;
}
}
public int BreedOffset
{
get
{
switch (horseStat)
{
case StatType.AGILITY:
return baseHorse.AdvancedStats.Agility;
case StatType.CONFORMATION:
return baseHorse.AdvancedStats.Conformation;
case StatType.ENDURANCE:
return baseHorse.AdvancedStats.Endurance;
case StatType.PERSONALITY:
return baseHorse.AdvancedStats.Personality;
case StatType.SPEED:
return baseHorse.AdvancedStats.Speed;
case StatType.STRENGTH:
return baseHorse.AdvancedStats.Strength;
case StatType.INTELIGENCE:
return baseHorse.AdvancedStats.Inteligence;
default:
return 0;
}
}
set
{
switch (horseStat)
{
case StatType.AGILITY:
baseHorse.AdvancedStats.Agility = value;
break;
case StatType.CONFORMATION:
baseHorse.AdvancedStats.Conformation = value;
break;
case StatType.ENDURANCE:
baseHorse.AdvancedStats.Endurance = value;
break;
case StatType.PERSONALITY:
baseHorse.AdvancedStats.Personality = value;
break;
case StatType.SPEED:
baseHorse.AdvancedStats.Speed = value;
break;
case StatType.STRENGTH:
baseHorse.AdvancedStats.Strength = value;
break;
case StatType.INTELIGENCE:
baseHorse.AdvancedStats.Inteligence = value;
break;
}
}
}
public int CompetitionGearOffset
{
get
{
if(baseUser != null)
{
int offsetBy = 0;
if(baseUser.EquipedCompetitionGear.Head != null)
offsetBy += getOffsetFrom(baseUser.EquipedCompetitionGear.Head);
if (baseUser.EquipedCompetitionGear.Body != null)
offsetBy += getOffsetFrom(baseUser.EquipedCompetitionGear.Body);
if (baseUser.EquipedCompetitionGear.Legs != null)
offsetBy += getOffsetFrom(baseUser.EquipedCompetitionGear.Legs);
if (baseUser.EquipedCompetitionGear.Feet != null)
offsetBy += getOffsetFrom(baseUser.EquipedCompetitionGear.Feet);
return offsetBy;
}
else
{
return 0;
}
}
}
public int CompanionOffset
{
get
{
if(baseHorse.Equipment.Companion != null)
return baseHorse.Equipment.Companion.GetMiscFlag(0);
else
return 0;
}
}
public int TackOffset
{
get
{
int offsetBy = 0;
if (baseHorse.Equipment.Saddle != null)
offsetBy += getOffsetFrom(baseHorse.Equipment.Saddle);
if (baseHorse.Equipment.SaddlePad != null)
offsetBy += getOffsetFrom(baseHorse.Equipment.SaddlePad);
if (baseHorse.Equipment.Bridle != null)
offsetBy += getOffsetFrom(baseHorse.Equipment.Bridle);
return offsetBy;
}
}
public int Total
{
get
{
return BreedValue + CompanionOffset + TackOffset + CompetitionGearOffset;
}
}
private int getOffsetFrom(Item.ItemInformation tackPeice)
{
int offsetBy = 0;
foreach (Item.Effects effect in tackPeice.Effects)
{
string effects = effect.EffectsWhat;
switch (effects)
{
case "AGILITY":
if (horseStat == StatType.AGILITY)
offsetBy += effect.EffectAmount;
break;
case "CONFORMATION":
if (horseStat == StatType.CONFORMATION)
offsetBy += effect.EffectAmount;
break;
case "ENDURANCE":
if (horseStat == StatType.ENDURANCE)
offsetBy += effect.EffectAmount;
break;
case "PERSONALITY":
if (horseStat == StatType.PERSONALITY)
offsetBy += effect.EffectAmount;
break;
case "SPEED":
if (horseStat == StatType.SPEED)
offsetBy += effect.EffectAmount;
break;
case "STRENGTH":
if (horseStat == StatType.STRENGTH)
offsetBy += effect.EffectAmount;
break;
case "INTELLIGENCE":
if (horseStat == StatType.INTELIGENCE)
offsetBy += effect.EffectAmount;
break;
}
}
return offsetBy;
}
}
public class AdvancedStats
{
public AdvancedStats(HorseInstance horse, int newSpeed,int newStrength, int newConformation, int newAgility, int newInteligence, int newEndurance, int newPersonality, int newHeight)
{
if(horse != null)
baseHorse = horse;
speed = newSpeed;
strength = newStrength;
conformation = newConformation;
agility = newAgility;
endurance = newEndurance;
inteligence = newInteligence;
personality = newPersonality;
height = newHeight;
}
public int Speed
{
get
{
return speed;
}
set
{
if (value > ((baseHorse.Breed.BaseStats.Speed * 2) - baseHorse.Breed.BaseStats.Speed))
value = (baseHorse.Breed.BaseStats.Speed - baseHorse.Breed.BaseStats.Speed * 2);
Database.SetHorseSpeed(baseHorse.RandomId, value);
speed = value;
}
}
public int Strength
{
get
{
return strength;
}
set
{
if (value > ((baseHorse.Breed.BaseStats.Strength * 2)- baseHorse.Breed.BaseStats.Strength))
value = ((baseHorse.Breed.BaseStats.Strength * 2) - baseHorse.Breed.BaseStats.Strength);
Database.SetHorseStrength(baseHorse.RandomId, value);
strength = value;
}
}
public int Conformation
{
get
{
return conformation;
}
set
{
if (value > ((baseHorse.Breed.BaseStats.Conformation * 2) - baseHorse.Breed.BaseStats.Conformation))
value = ((baseHorse.Breed.BaseStats.Conformation * 2) - baseHorse.Breed.BaseStats.Conformation);
Database.SetHorseConformation(baseHorse.RandomId, value);
conformation = value;
}
}
public int Agility
{
get
{
return agility;
}
set
{
if (value > ((baseHorse.Breed.BaseStats.Agility * 2) - baseHorse.Breed.BaseStats.Agility))
value = ((baseHorse.Breed.BaseStats.Agility * 2) - baseHorse.Breed.BaseStats.Agility);
Database.SetHorseAgility(baseHorse.RandomId, value);
agility = value;
}
}
public int Endurance
{
get
{
return endurance;
}
set
{
if (value > ((baseHorse.Breed.BaseStats.Endurance * 2) - baseHorse.Breed.BaseStats.Endurance))
value = ((baseHorse.Breed.BaseStats.Endurance * 2) - baseHorse.Breed.BaseStats.Endurance);
Database.SetHorseEndurance(baseHorse.RandomId, value);
endurance = value;
}
}
public int Inteligence
{
get
{
return inteligence;
}
set
{
if (value > ((baseHorse.Breed.BaseStats.Inteligence* 2) - baseHorse.Breed.BaseStats.Inteligence))
value = ((baseHorse.Breed.BaseStats.Inteligence * 2) - baseHorse.Breed.BaseStats.Inteligence);
Database.SetHorseInteligence(baseHorse.RandomId, value);
inteligence = value;
}
}
public int Personality
{
get
{
return personality;
}
set
{
if (value > ((baseHorse.Breed.BaseStats.Personality * 2) - baseHorse.Breed.BaseStats.Personality))
value = ((baseHorse.Breed.BaseStats.Personality * 2) - baseHorse.Breed.BaseStats.Personality);
Database.SetHorsePersonality(baseHorse.RandomId, value);
personality = value;
}
}
public int Height
{
get
{
return height;
}
set
{
height = value;
Database.SetHorseHeight(baseHorse.RandomId, value);
}
}
public int MinHeight;
public int MaxHeight;
private HorseInstance baseHorse;
private int speed;
private int strength;
private int conformation;
private int agility;
private int endurance;
private int inteligence;
private int personality;
private int height;
}
public class BasicStats
{
public BasicStats(HorseInstance horse, int newHealth, int newShoes, int newHunger, int newThirst, int newMood, int newGroom, int newTiredness, int newExperience)
{
baseHorse = horse;
health = newHealth;
shoes = newShoes;
hunger = newHunger;
thirst = newThirst;
mood = newMood;
groom = newGroom;
tiredness = newTiredness;
experience = newExperience;
}
public int Health
{
get
{
return health;
}
set
{
if (value > 1000)
value = 1000;
if (value < 0)
value = 0;
health = value;
Database.SetHorseHealth(baseHorse.RandomId, value);
}
}
public int Shoes
{
get
{
return shoes;
}
set
{
if (value > 1000)
value = 1000;
if (value < 0)
value = 0;
shoes = value;
Database.SetHorseShoes(baseHorse.RandomId, value);
}
}
public int Hunger {
get
{
return hunger;
}
set
{
if (value > 1000)
value = 1000;
if (value < 0)
value = 0;
hunger = value;
Database.SetHorseHunger(baseHorse.RandomId, value);
}
}
public int Thirst
{
get
{
return thirst;
}
set
{
if (value > 1000)
value = 1000;
if (value < 0)
value = 0;
thirst = value;
Database.SetHorseThirst(baseHorse.RandomId, value);
}
}
public int Mood
{
get
{
return mood;
}
set
{
// Lol turns out pinto forgot to do this and u can have negative mood :D
if (value > 1000)
value = 1000;
/*if (value < 0)
value = 0;
*/
mood = value;
Database.SetHorseMood(baseHorse.RandomId, value);
}
}
public int Groom
{
get
{
return groom;
}
set
{
if (value > 1000)
value = 1000;
if (value < 0)
value = 0;
groom = value;
Database.SetHorseGroom(baseHorse.RandomId, value);
}
}
public int Tiredness
{
get
{
return tiredness;
}
set
{
if (value > 1000)
value = 1000;
if (value < 0)
value = 0;
tiredness = value;
Database.SetHorseTiredness(baseHorse.RandomId, value);
}
}
public int Experience
{
get
{
return experience;
}
set
{
if (value < 0)
value = 0;
experience = value;
Database.SetHorseExperience(baseHorse.RandomId, value);
}
}
private HorseInstance baseHorse;
private int health;
private int shoes;
private int hunger;
private int thirst;
private int mood;
private int groom;
private int tiredness;
private int experience;
}
public class Breed
{
public int Id;
public string Name;
public string Description;
public AdvancedStats BaseStats;
public string[] Colors;
public string SpawnOn;
public string SpawnInArea;
public string Swf;
public string Type;
public string[] GenderTypes()
{
string[] options = new string[2];
if (Type == "camel")
{
options[0] = "cow";
options[1] = "bull";
}
else if (Type == "llama")
{
options[0] = "male";
options[1] = "female";
}
else
{
options[0] = "stallion";
options[1] = "mare";
}
return options;
}
}
public struct HorseEquips
{
public Item.ItemInformation Saddle;
public Item.ItemInformation SaddlePad;
public Item.ItemInformation Bridle;
public Item.ItemInformation Companion;
}
public struct Category
{
public string Name;
public string MetaOthers;
public string Meta;
}
public static string[] HorseNames;
public static List<Category> HorseCategories = new List<Category>();
public static List<Breed> Breeds = new List<Breed>();
public static string GenerateHorseName()
{
int indx = 0;
int max = HorseNames.Length;
int i = GameServer.RandomNumberGenerator.Next(indx, max);
return HorseNames[i];
}
public static double CalculateHands(int height, bool isBreedViewer)
{
if(isBreedViewer)
return ((double)height / 4.00);
else
{
int h1 = 0;
int h2 = 0;
for(int i = 0; i < height; i++)
{
h2++;
if (h2 == 4)
{
h2 = 0;
h1++;
}
}
double hands = double.Parse(h1 + "." + h2, CultureInfo.InvariantCulture); // This is terrible. dont do this.
return hands;
}
}
public static string BreedViewerSwf(HorseInstance horse, string terrainTileType)
{
double hands = CalculateHands(horse.AdvancedStats.Height, true);
string swf = "breedviewer.swf?terrain=" + terrainTileType + "&breed=" + horse.Breed.Swf + "&color=" + horse.Color + "&hands=" + hands.ToString(CultureInfo.InvariantCulture);
if (horse.Equipment.Saddle != null)
swf += "&saddle=" + horse.Equipment.Saddle.EmbedSwf;
if (horse.Equipment.SaddlePad != null)
swf += "&saddlepad=" + horse.Equipment.SaddlePad.EmbedSwf;
if (horse.Equipment.Bridle != null)
swf += "&bridle=" + horse.Equipment.Bridle.EmbedSwf;
if (horse.Equipment.Companion != null)
swf += "&companion=" + horse.Equipment.Companion.EmbedSwf;
swf += "&junk=";
return swf;
}
public static Breed GetBreedById(int id)
{
foreach(Breed breed in Breeds)
{
if (breed.Id == id)
return breed;
}
throw new KeyNotFoundException("No horse breed with id " + id);
}
}
}

View file

@ -0,0 +1,229 @@

using HISP.Security;
using HISP.Server;
namespace HISP.Game.Horse
{
public class HorseInstance
{
public HorseInstance(HorseInfo.Breed breed, int randomId = -1, string loadColor = null ,string loadName=null, string loadDescription = "", int loadSpoiled=0, string loadCategory="KEEPER", int loadMagicUsed=0, int loadAutoSell=0, int leaseTimer=0, bool loadHidden=false, int loadOwner=0)
{
RandomId = RandomID.NextRandomId(randomId);
owner = loadOwner;
if(loadName == null)
{
if (breed.Type == "camel")
{
name = "Wild Camel";
}
else if (breed.Type == "llama")
{
name = "Jungle Llama";
}
else if (breed.Type == "zebra")
{
name = "Wild Zebra";
}
else
{
name = "Wild Horse";
}
}
else
{
name = loadName;
}
if(GameServer.RandomNumberGenerator.Next(0, 100) > 50)
Gender = breed.GenderTypes()[1];
else
Gender = breed.GenderTypes()[0];
description = loadDescription;
Breed = breed;
BasicStats = new HorseInfo.BasicStats(this, 1000, 0, 1000, 1000, 500, 200, 1000, 0);
int inteligence = (GameServer.RandomNumberGenerator.Next(breed.BaseStats.Inteligence, (breed.BaseStats.Inteligence * 2)) - breed.BaseStats.Inteligence);
int personality = (GameServer.RandomNumberGenerator.Next(breed.BaseStats.Personality, (breed.BaseStats.Personality * 2)) - breed.BaseStats.Personality);
int height = GameServer.RandomNumberGenerator.Next(breed.BaseStats.MinHeight, breed.BaseStats.MaxHeight + 1);
AdvancedStats = new HorseInfo.AdvancedStats(this, 0, 0, 0, 0, inteligence, 0, personality, height);
Equipment = new HorseInfo.HorseEquips();
autosell = loadAutoSell;
category = loadCategory;
spoiled = loadSpoiled;
magicUsed = loadMagicUsed;
leaseTime = leaseTimer;
hidden = loadHidden;
if(loadColor != null)
color = loadColor;
else
color = breed.Colors[GameServer.RandomNumberGenerator.Next(0, breed.Colors.Length)];
Leaser = 0;
}
public int Leaser;
public int RandomId;
public int Owner
{
get
{
return owner;
}
set
{
owner = value;
Database.SetHorseOwner(RandomId, owner);
}
}
public bool Hidden
{
get
{
return hidden;
}
set
{
hidden = value;
Database.SetHorseHidden(RandomId, value);
}
}
public int LeaseTime
{
get
{
return leaseTime;
}
set
{
leaseTime = value;
Database.SetLeaseTime(this.RandomId, leaseTime);
}
}
public string Name
{
get
{
return name;
}
set
{
name = value.Trim();
Database.SetHorseName(this.RandomId, name);
}
}
public string Description
{
get
{
return description;
}
set
{
description = value.Trim();
Database.SetHorseDescription(this.RandomId, description);
}
}
public string Gender;
public string Color
{
get
{
return color;
}
set
{
color = value;
Database.SetHorseColor(this.RandomId, color);
}
}
public int TrainTimer
{
get
{
int timeout = Database.GetHorseTrainTimeout(this.RandomId);
if (timeout < 0)
return 0;
else
return timeout;
}
set
{
Database.SetHorseTrainTimeout(this.RandomId, value);
}
}
public HorseInfo.Breed Breed;
public HorseInfo.BasicStats BasicStats;
public HorseInfo.AdvancedStats AdvancedStats;
public HorseInfo.HorseEquips Equipment;
public int AutoSell
{
get
{
return autosell;
}
set
{
Database.SetHorseAutoSell(RandomId, value);
autosell = value;
}
}
public int Spoiled
{
get
{
return spoiled;
}
set
{
Database.SetHorseSpoiled(RandomId, value);
spoiled = value;
}
}
public int MagicUsed
{
get
{
return magicUsed;
}
set
{
Database.SetHorseMagicUsed(RandomId, value);
magicUsed = value;
}
}
public string Category
{
get
{
return category;
}
set
{
Database.SetHorseCategory(RandomId, value);
category = value;
}
}
private string color;
private int owner;
private string name;
private string description;
private int spoiled;
private int leaseTime;
private bool hidden;
private int magicUsed;
private int autosell;
private string category;
public void ChangeNameWithoutUpdatingDatabase(string newName)
{
name = newName;
}
}
}

View file

@ -0,0 +1,117 @@
using HISP.Game.Items;
using System.Collections.Generic;
namespace HISP.Game.Horse
{
public class Leaser
{
public static List<Leaser> HorseLeasers = new List<Leaser>();
public Leaser(int breedId, int saddle, int saddlePad, int bridle)
{
Breed = HorseInfo.GetBreedById(breedId);
if (saddle != -1)
Saddle = Item.GetItemById(saddle);
if (saddlePad != -1)
SaddlePad = Item.GetItemById(saddlePad);
if (bridle != -1)
Bridle = Item.GetItemById(bridle);
}
public int LeaseId;
public string ButtonId;
public string Info;
public string OnLeaseText;
public int Price;
public int Minutes;
// Horse
public HorseInfo.Breed Breed;
public string HorseName;
public string Color;
public string Gender;
public int Health;
public int Shoes;
public int Hunger;
public int Thirst;
public int Mood;
public int Groom;
public int Tiredness;
public int Experience;
public Item.ItemInformation Saddle = null;
public Item.ItemInformation SaddlePad = null;
public Item.ItemInformation Bridle = null;
public int Speed;
public int Strength;
public int Conformation;
public int Agility;
public int Inteligence;
public int Endurance;
public int Personality;
public int Height;
public HorseInstance GenerateLeaseHorse()
{
HorseInstance instance = new HorseInstance(this.Breed, loadColor: this.Color, loadCategory: "LEASED", leaseTimer: this.Minutes);
instance.Name = this.HorseName;
instance.Gender = this.Gender;
instance.Leaser = this.LeaseId;
instance.BasicStats = new HorseInfo.BasicStats(instance, Health, Shoes, Hunger, Thirst, Mood, Groom, Tiredness, Experience);
instance.AdvancedStats = new HorseInfo.AdvancedStats(instance, Speed, Strength, Conformation, Agility, Inteligence, Endurance, Personality, Height);
instance.Equipment.Saddle = this.Saddle;
instance.Equipment.SaddlePad = this.SaddlePad;
instance.Equipment.Bridle = this.Bridle;
return instance;
}
public static bool LeaserButtonIdExists(string bid)
{
foreach (Leaser leaser in HorseLeasers)
{
if (leaser.ButtonId == bid)
{
return true;
}
}
return false;
}
public static Leaser GetLeaserByButtonId(string bid)
{
foreach(Leaser leaser in HorseLeasers)
{
if(leaser.ButtonId == bid)
{
return leaser;
}
}
throw new KeyNotFoundException("No leaser with button id: " + bid + " found.");
}
public static Leaser[] GetLeasersById(int id)
{
List<Leaser> leasers = new List<Leaser>();
foreach (Leaser leaser in HorseLeasers)
{
if (leaser.LeaseId == id)
{
leasers.Add(leaser);
}
}
return leasers.ToArray();
}
}
}

View file

@ -0,0 +1,318 @@
using HISP.Player;
using HISP.Server;
using System.Collections.Generic;
namespace HISP.Game.Horse
{
public class WildHorse
{
public bool CanHorseBeHere(int x, int y, bool checkSpawnLocationValid=true)
{
// Horses cannot be in towns.
if (World.InTown(x, y))
return false;
if (World.InSpecialTile(x, y))
return false;
if (!World.InIsle(x, y))
return false;
// Check area
if(checkSpawnLocationValid)
{
if (this.Instance.Breed.SpawnInArea != null)
{
if (World.InArea(x, y))
{
if (World.GetArea(x, y).Name != this.Instance.Breed.SpawnInArea)
return false;
}
}
}
// Check Tile Type
int TileID = Map.GetTileId(x, y, false);
string TileType = Map.TerrainTiles[TileID - 1].Type;
if(checkSpawnLocationValid)
{
if (TileType != this.Instance.Breed.SpawnOn)
return false;
}
if (Map.CheckPassable(x, y)) // Can the player stand over here?
return true;
return false;
}
public WildHorse(HorseInstance horse, int MapX = -1, int MapY = -1, int despawnTimeout=1440, bool addToDatabase = true)
{
Instance = horse;
timeout = despawnTimeout;
if(MapX == -1 && MapY == -1)
{
while (true)
{
if (horse.Breed.SpawnInArea == null)
{
// Pick x/y
int tryX = GameServer.RandomNumberGenerator.Next(0, Map.Width);
int tryY = GameServer.RandomNumberGenerator.Next(0, Map.Height);
if (CanHorseBeHere(tryX, tryY))
{
x = tryX;
y = tryY;
break;
}
else
{
continue;
}
}
else
{
World.Zone zone = World.GetZoneByName(horse.Breed.SpawnInArea);
// Pick x/y in zone.
int tryX = GameServer.RandomNumberGenerator.Next(zone.StartX, zone.EndX);
int tryY = GameServer.RandomNumberGenerator.Next(zone.StartY, zone.EndY);
if (CanHorseBeHere(tryX, tryY))
{
x = tryX;
y = tryY;
break;
}
else
{
continue;
}
}
}
}
else
{
x = MapX;
y = MapY;
}
wildHorses.Add(this);
if(addToDatabase)
Database.AddWildHorse(this);
}
public void RandomWander()
{
if (GameServer.GetUsersAt(this.X, this.Y, true, true).Length > 0)
return;
int tries = 0;
while(true)
{
int direction = GameServer.RandomNumberGenerator.Next(0, 4);
int tryX = this.X;
int tryY = this.Y;
switch (direction)
{
case 0:
tryX += 1;
break;
case 1:
tryX -= 1;
break;
case 2:
tryY += 1;
break;
case 3:
tryY -= 1;
break;
}
bool check = CanHorseBeHere(this.X, this.Y); // if the horse is allready in an invalid position..
if (CanHorseBeHere(tryX, tryY, check))
{
X = tryX;
Y = tryY;
break;
}
if(tries >= 100)
{
Logger.ErrorPrint("Wild Horse: " + Instance.Name + " " + Instance.Breed.Name + " is stuck (cant move after 100 tries) at " + x.ToString() + ", " + y.ToString());
break;
}
tries++;
}
}
public void Escape()
{
for(int i = 0; i < 100; i++)
{
int tryX = X + GameServer.RandomNumberGenerator.Next(-5, 5);
int tryY = Y + GameServer.RandomNumberGenerator.Next(-5, 5);
bool check = CanHorseBeHere(this.X, this.Y); // if the horse is allready in an invalid position..
if (CanHorseBeHere(tryX, tryY, check))
{
X = tryX;
Y = tryY;
return;
}
}
Logger.ErrorPrint("Horse is stuck (cannot move after 1000 tries) " + Instance.Breed.Name + " at X" + X + " Y" + Y);
}
public void Capture(User forUser)
{
forUser.HorseInventory.AddHorse(this.Instance);
Despawn(this);
}
private static List<WildHorse> wildHorses = new List<WildHorse>();
public static WildHorse[] WildHorses
{
get
{
return wildHorses.ToArray();
}
}
public static void GenerateHorses()
{
Logger.InfoPrint("Generating horses.");
while(wildHorses.Count < 40)
{
HorseInfo.Breed horseBreed = HorseInfo.Breeds[GameServer.RandomNumberGenerator.Next(0, HorseInfo.Breeds.Count)];
if (horseBreed.Swf == "")
continue;
if (horseBreed.SpawnInArea == "none") // no unipegs >_>
continue;
HorseInstance horseInst = new HorseInstance(horseBreed);
WildHorse wildHorse = new WildHorse(horseInst);
Logger.DebugPrint("Created " + horseBreed.Name + " at X:" + wildHorse.X + ", Y:" + wildHorse.Y);
}
}
public static void Init()
{
Database.LoadWildHorses();
GenerateHorses();
}
public static WildHorse[] GetHorsesAt(int x, int y)
{
List<WildHorse> horses = new List<WildHorse>();
foreach (WildHorse wildHorse in WildHorses)
{
if (wildHorse.X == x && wildHorse.Y == y)
horses.Add(wildHorse);
}
return horses.ToArray();
}
public static bool DoesHorseExist(int randomId)
{
foreach (WildHorse wildHorse in WildHorses)
{
if (wildHorse.Instance.RandomId == randomId)
return true;
}
return false;
}
public static WildHorse GetHorseById(int randomId)
{
foreach(WildHorse wildHorse in WildHorses)
{
if (wildHorse.Instance.RandomId == randomId)
return wildHorse;
}
throw new KeyNotFoundException("No horse with id: " + randomId + " was found.");
}
public static void Despawn(WildHorse horse)
{
Database.RemoveWildHorse(horse.Instance.RandomId);
wildHorses.Remove(horse);
}
public static void Update()
{
Logger.DebugPrint("Making horses wander.");
foreach (WildHorse wildHorse in WildHorses)
{
wildHorse.Timeout -= 1;
if (GameServer.GetUsersAt(wildHorse.X, wildHorse.Y, true, true).Length > 0)
continue;
if (wildHorse.Timeout <= 0)
Despawn(wildHorse);
if (GameServer.RandomNumberGenerator.Next(0, 100) >= 25)
wildHorse.RandomWander();
}
if(WildHorses.Length < 40)
{
GenerateHorses();
}
}
public HorseInstance Instance;
public int X
{
get
{
return x;
}
set
{
Database.SetWildHorseX(this.Instance.RandomId, value);
x = value;
}
}
public int Y
{
get
{
return y;
}
set
{
Database.SetWildHorseY(this.Instance.RandomId, value);
y = value;
}
}
public int Timeout
{
get
{
return timeout;
}
set
{
Database.SetWildHorseTimeout(this.Instance.RandomId, value);
timeout = value;
}
}
private int x;
private int y;
private int timeout;
}
}

View file

@ -0,0 +1,97 @@
using HISP.Game.Horse;
using HISP.Player;
using HISP.Server;
using System.Collections.Generic;
namespace HISP.Game.Inventory
{
public class HorseInventory
{
private User baseUser;
private List<HorseInstance> horsesList = new List<HorseInstance>();
public HorseInstance[] HorseList
{
get
{
List<HorseInstance> filteredHorseList = new List<HorseInstance>();
foreach(HorseInstance horse in horsesList)
{
if (!horse.Hidden)
filteredHorseList.Add(horse);
}
return filteredHorseList.ToArray();
}
}
public HorseInventory(User user)
{
baseUser = user;
Database.LoadHorseInventory(this, baseUser.Id);
}
public void UnHide(int randomId)
{
foreach(HorseInstance inst in horsesList)
{
if (inst.RandomId == randomId)
{
inst.Hidden = false;
break;
}
}
}
public void AddHorse(HorseInstance horse, bool addToDb=true)
{
if (HorseList.Length + 1 > baseUser.MaxHorses)
throw new InventoryFullException();
horse.Owner = baseUser.Id;
if(addToDb)
Database.AddHorse(horse);
horsesList.Add(horse);
}
public void DeleteHorse(HorseInstance horse, bool removeFromDb=true)
{
if(removeFromDb)
Database.RemoveHorse(horse.RandomId);
horsesList.Remove(horse);
}
public bool HorseIdExist(int randomId)
{
try
{
GetHorseById(randomId);
return true;
}
catch(KeyNotFoundException)
{
return false;
}
}
public HorseInstance GetHorseById(int randomId)
{
foreach(HorseInstance inst in HorseList)
{
if (inst.RandomId == randomId)
return inst;
}
throw new KeyNotFoundException();
}
public HorseInstance[] GetHorsesInCategory(HorseInfo.Category category)
{
List<HorseInstance> instances = new List<HorseInstance>();
foreach(HorseInstance horse in HorseList)
{
if (horse.Category == category.Name)
{
instances.Add(horse);
}
}
return instances.ToArray();
}
}
}

View file

@ -0,0 +1,27 @@
using HISP.Game.Items;
namespace HISP.Game.Inventory
{
interface IInventory
{
void Add(ItemInstance item);
void Remove(ItemInstance item);
int Count
{
get;
}
InventoryItem[] GetItemList();
bool HasItem(int randomId);
bool HasItemId(int itemId);
InventoryItem GetItemByItemId(int itemId);
InventoryItem GetItemByRandomid(int randomId);
}
}

View file

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using HISP.Game.Items;
namespace HISP.Game.Inventory
{
public class InventoryItem
{
public InventoryItem()
{
ItemInstances = new List<ItemInstance>();
Infinite = false;
ItemId = 0;
}
public int ItemId;
public bool Infinite;
public List<ItemInstance> ItemInstances;
}
}

View file

@ -0,0 +1,180 @@
using System.Collections.Generic;
using System.Linq;
using HISP.Player;
using HISP.Server;
using HISP.Game.Items;
namespace HISP.Game.Inventory
{
public class PlayerInventory : IInventory
{
public User BaseUser;
private List<InventoryItem> inventoryItems;
public PlayerInventory(User forUser)
{
inventoryItems = new List<InventoryItem>();
BaseUser = forUser;
ItemInstance[] instances = Database.GetPlayerInventory(BaseUser.Id).ToArray();
foreach(ItemInstance instance in instances)
{
addItem(instance, false);
}
}
public int Count
{
get
{
return inventoryItems.Count;
}
}
private void addItem(ItemInstance item, bool addToDatabase)
{
if (addToDatabase)
Database.AddItemToInventory(BaseUser.Id, item);
foreach (InventoryItem invetoryItem in inventoryItems)
{
if (invetoryItem.ItemId == item.ItemId)
{
invetoryItem.ItemInstances.Add(item);
return;
}
}
InventoryItem inventoryItem = new InventoryItem();
inventoryItem.ItemId = item.ItemId;
inventoryItem.ItemInstances.Add(item);
inventoryItems.Add(inventoryItem);
}
public InventoryItem[] GetItemList()
{
return inventoryItems.OrderBy(o => o.ItemInstances[0].GetItemInfo().SortBy).ToArray();
}
public void Remove(ItemInstance item)
{
Database.RemoveItemFromInventory(BaseUser.Id, item);
foreach (InventoryItem inventoryItem in inventoryItems)
{
if(item.ItemId == inventoryItem.ItemId)
{
foreach(ItemInstance instance in inventoryItem.ItemInstances)
{
if(instance.RandomId == item.RandomId)
{
inventoryItem.ItemInstances.Remove(instance);
if (inventoryItem.ItemInstances.Count <= 0)
inventoryItems.Remove(inventoryItem);
return;
}
}
}
}
Logger.ErrorPrint("Tried to remove item : " + item.RandomId + " from inventory when it was not in it");
}
public bool HasItem(int randomId)
{
InventoryItem[] items = GetItemList();
foreach(InventoryItem item in items)
{
ItemInstance[] instances = item.ItemInstances.ToArray();
foreach(ItemInstance instance in instances)
{
if (instance.RandomId == randomId)
return true;
}
}
return false;
}
public bool HasItemId(int itemId)
{
InventoryItem[] items = GetItemList();
foreach (InventoryItem item in items)
{
if (item.ItemId == itemId)
{
return true;
}
}
return false;
}
public InventoryItem GetItemByItemId(int itemId)
{
InventoryItem[] items = GetItemList();
foreach (InventoryItem item in items)
{
if (item.ItemId == itemId)
{
return item;
}
}
throw new KeyNotFoundException("id: " + itemId + " not found in inventory");
}
public InventoryItem GetItemByRandomid(int randomId)
{
InventoryItem[] items = GetItemList();
foreach (InventoryItem item in items)
{
ItemInstance[] instances = item.ItemInstances.ToArray();
foreach (ItemInstance instance in instances)
{
if (instance.RandomId == randomId)
return item;
}
}
throw new KeyNotFoundException("random id: " + randomId + " not found in inventory");
}
public void AddWithoutDatabase(ItemInstance item)
{
addItem(item, false);
}
public void AddIgnoringFull(ItemInstance item)
{
addItem(item, true);
}
public void Add(ItemInstance item)
{
// Check if has max allready
if(HasItemId(item.ItemId))
{
InventoryItem items = GetItemByItemId(item.ItemId);
if (items.ItemInstances.Count >= ConfigReader.MAX_STACK)
{
throw new InventoryMaxStackException();
}
}
else if (Count >= BaseUser.MaxItems)
{
throw new InventoryFullException();
}
addItem(item, true);
}
}
}

View file

@ -0,0 +1,176 @@
using HISP.Game.Services;
using HISP.Server;
using HISP.Game.Items;
using System.Collections.Generic;
using System.Linq;
namespace HISP.Game.Inventory
{
public class ShopInventory : IInventory
{
private Shop baseShop;
private List<InventoryItem> inventoryItems;
public int Count
{
get
{
return inventoryItems.Count;
}
}
public ShopInventory(Shop shopkeeper)
{
baseShop = shopkeeper;
ItemInstance[] instances = Database.GetShopInventory(baseShop.Id).ToArray();
inventoryItems = new List<InventoryItem>();
foreach (ItemInstance instance in instances)
{
addItem(instance, false);
}
}
private void addItem(ItemInstance item, bool addToDatabase)
{
foreach (InventoryItem invetoryItem in inventoryItems)
{
if (invetoryItem.ItemId == item.ItemId)
{
if (invetoryItem.Infinite) // no need to add +1, theres allready infinite quanity.
return;
invetoryItem.ItemInstances.Add(item);
goto retrn;
}
}
InventoryItem inventoryItem = new InventoryItem();
inventoryItem.ItemId = item.ItemId;
inventoryItem.Infinite = false;
inventoryItem.ItemInstances.Add(item);
inventoryItems.Add(inventoryItem);
retrn:
{
if (addToDatabase)
Database.AddItemToShopInventory(baseShop.Id, item);
return;
};
}
public void AddInfinity(Item.ItemInformation itemInfo)
{
if (HasItemId(itemInfo.Id))
return;
InventoryItem inventoryItem = new InventoryItem();
inventoryItem.ItemId = itemInfo.Id;
inventoryItem.Infinite = true;
for(int i = 0; i < 25; i++) // add 25
inventoryItem.ItemInstances.Add(new ItemInstance(inventoryItem.ItemId));
inventoryItems.Add(inventoryItem);
}
public void Add(ItemInstance item)
{
addItem(item, true);
}
public InventoryItem GetItemByItemId(int itemId)
{
InventoryItem[] items = GetItemList();
foreach (InventoryItem item in items)
{
if (item.ItemId == itemId)
{
return item;
}
}
throw new KeyNotFoundException("id: " + itemId + " not found in shop inventory");
}
public InventoryItem GetItemByRandomid(int randomId)
{
InventoryItem[] items = GetItemList();
foreach (InventoryItem item in items)
{
ItemInstance[] instances = item.ItemInstances.ToArray();
foreach (ItemInstance instance in instances)
{
if (instance.RandomId == randomId)
return item;
}
}
throw new KeyNotFoundException("random id: " + randomId + " not found in shop inventory");
}
public InventoryItem[] GetItemList()
{
return inventoryItems.OrderBy(o => o.ItemInstances[0].GetItemInfo().SortBy).OrderBy(o => o.Infinite).ToArray();
}
public bool HasItem(int randomId)
{
InventoryItem[] items = GetItemList();
foreach (InventoryItem item in items)
{
ItemInstance[] instances = item.ItemInstances.ToArray();
foreach (ItemInstance instance in instances)
{
if (instance.RandomId == randomId)
return true;
}
}
return false;
}
public bool HasItemId(int itemId)
{
InventoryItem[] items = GetItemList();
foreach (InventoryItem item in items)
{
if (item.ItemId == itemId)
{
return true;
}
}
return false;
}
public void Remove(ItemInstance item)
{
foreach (InventoryItem inventoryItem in inventoryItems)
{
if (item.ItemId == inventoryItem.ItemId)
{
foreach (ItemInstance instance in inventoryItem.ItemInstances)
{
if (instance.RandomId == item.RandomId)
{
inventoryItem.ItemInstances.Remove(instance);
if (inventoryItem.ItemInstances.Count <= 0)
inventoryItems.Remove(inventoryItem);
if (!inventoryItem.Infinite) // no need to bug the database.
Database.RemoveItemFromShopInventory(baseShop.Id, item);
else
inventoryItem.ItemInstances.Add(new ItemInstance(inventoryItem.ItemId)); // Gen new item in inventory to replace it.
return;
}
}
}
}
Logger.ErrorPrint("Tried to remove item : " + item.RandomId + " from inventory when it was not in it");
}
}
}

View file

@ -0,0 +1,352 @@
using System;
using System.Collections.Generic;
using HISP.Server;
namespace HISP.Game.Items
{
public class DroppedItems
{
public class DroppedItem
{
public DroppedItem(ItemInstance itmInstance)
{
if (itmInstance == null)
throw new NullReferenceException("How could this happen?");
Instance = itmInstance;
}
public int X;
public int Y;
public int DespawnTimer;
public ItemInstance Instance;
public int Data;
}
private static List<DroppedItem> droppedItemsList = new List<DroppedItem>();
public static int GetCountOfItem(Item.ItemInformation item)
{
DroppedItem[] droppedItems = droppedItemsList.ToArray();
int count = 0;
for(int i = 0; i < droppedItems.Length; i++)
{
if (droppedItems[i] == null) // Item removed in another thread.
continue;
if(droppedItems[i].Instance.ItemId == item.Id)
{
count++;
}
}
return count;
}
public static DroppedItem[] GetItemsAt(int x, int y)
{
DroppedItem[] droppedItems = droppedItemsList.ToArray();
List<DroppedItem> items = new List<DroppedItem>();
for(int i = 0; i < droppedItems.Length; i++)
{
if (droppedItems[i] == null) // Item removed in another thread.
continue;
if (droppedItems[i].X == x && droppedItems[i].Y == y)
{
items.Add(droppedItems[i]);
}
}
return items.ToArray();
}
public static void ReadFromDatabase()
{
DroppedItem[] items = Database.GetDroppedItems();
foreach (DroppedItem droppedItem in items)
droppedItemsList.Add(droppedItem);
}
public static void RemoveDroppedItem(DroppedItem item)
{
int randomId = item.Instance.RandomId;
Database.RemoveDroppedItem(randomId);
droppedItemsList.Remove(item);
}
public static bool IsDroppedItemExist(int randomId)
{
try
{
GetDroppedItemById(randomId);
return true;
}
catch(KeyNotFoundException)
{
return false;
}
}
public static DroppedItem GetDroppedItemById(int randomId)
{
DroppedItem[] droppedItems = droppedItemsList.ToArray();
for(int i = 0; i < droppedItems.Length; i++)
{
if (droppedItems[i] == null) // Item removed in another thread.
continue;
if (droppedItems[i].Instance.RandomId == randomId)
{
return droppedItems[i];
}
}
throw new KeyNotFoundException("Random id: " + randomId.ToString() + " not found");
}
public static void DespawnItems()
{
Database.DecrementDroppedItemDespawnTimer();
Database.RemoveDespawningItems(); // GO-GO-GO-GOGOGOGO GOTTA GO FAST!!!
int itmCount = droppedItemsList.Count;
for (int i = 0; i < itmCount; i++)
{
if (droppedItemsList[i] == null) // Item removed in another thread.
continue;
droppedItemsList[i].DespawnTimer -= 5;
if(droppedItemsList[i].DespawnTimer <= 0)
{
if (GameServer.GetUsersAt(droppedItemsList[i].X, droppedItemsList[i].Y, true, true).Length > 0) // Dont despawn items players are standing on
continue;
Logger.DebugPrint("Despawned Item at " + droppedItemsList[i].X + ", " + droppedItemsList[i].Y);
droppedItemsList.Remove(droppedItemsList[i]);
itmCount = droppedItemsList.Count;
}
}
}
public static void AddItem(ItemInstance item, int x, int y, int despawnTimer=1500)
{
DroppedItem droppedItem = new DroppedItem(item);
droppedItem.X = x;
droppedItem.Y = y;
droppedItem.DespawnTimer = despawnTimer;
droppedItemsList.Add(droppedItem);
Database.AddDroppedItem(droppedItem);
}
public static void GenerateItems(bool isFirstLoad=false)
{
if (isFirstLoad)
Logger.InfoPrint("Generating items, (this may take awhile on a fresh database!)");
else
Logger.DebugPrint("Generating items.");
int newItems = 0;
foreach (Item.ItemInformation item in Item.Items)
{
int count = GetCountOfItem(item);
do
{
if (count < item.SpawnParamaters.SpawnCap)
{
count++;
int despawnTimer = 1440;
if (isFirstLoad)
despawnTimer = GameServer.RandomNumberGenerator.Next(0, 1440 + 1);
if (item.SpawnParamaters.SpawnInZone != null)
{
World.Zone spawnArea = World.GetZoneByName(item.SpawnParamaters.SpawnInZone);
while (true)
{
// Pick a random location inside the zone
int tryX = GameServer.RandomNumberGenerator.Next(spawnArea.StartX, spawnArea.EndX);
int tryY = GameServer.RandomNumberGenerator.Next(spawnArea.StartY, spawnArea.EndY);
if (World.InSpecialTile(tryX, tryY))
continue;
if (Map.CheckPassable(tryX, tryY)) // Can the player walk here?
{
int TileID = Map.GetTileId(tryX, tryY, false);
string TileType = Map.TerrainTiles[TileID - 1].Type; // Is it the right type?
if (item.SpawnParamaters.SpawnOnTileType == TileType)
{
if (GetItemsAt(tryX, tryY).Length > 25) // Max items in one tile.
continue;
ItemInstance instance = new ItemInstance(item.Id);
AddItem(instance, tryX, tryY, despawnTimer);
Logger.DebugPrint("Created Item ID: " + instance.ItemId + " in ZONE: " + spawnArea.Name + " at: X: " + tryX + " Y: " + tryY);
newItems++;
break;
}
else
{
continue;
}
}
else
{
continue;
}
}
}
else if (item.SpawnParamaters.SpawnOnSpecialTile != null)
{
while (true)
{
// Pick a random special tile
World.SpecialTile[] possileTiles = World.GetSpecialTilesByName(item.SpawnParamaters.SpawnOnSpecialTile);
World.SpecialTile spawnOn = possileTiles[GameServer.RandomNumberGenerator.Next(0, possileTiles.Length)];
if (Map.CheckPassable(spawnOn.X, spawnOn.Y))
{
if (GetItemsAt(spawnOn.X, spawnOn.Y).Length > 25) // Max items in one tile.
continue;
ItemInstance instance = new ItemInstance(item.Id);
AddItem(instance, spawnOn.X, spawnOn.Y, despawnTimer);
Logger.DebugPrint("Created Item ID: " + instance.ItemId + " at: X: " + spawnOn.X + " Y: " + spawnOn.Y);
newItems++;
break;
}
else
{
continue;
}
}
}
else if (item.SpawnParamaters.SpawnNearSpecialTile != null)
{
while (true)
{
// Pick a random special tile
World.SpecialTile[] possileTiles = World.GetSpecialTilesByName(item.SpawnParamaters.SpawnNearSpecialTile);
World.SpecialTile spawnNearTile = possileTiles[GameServer.RandomNumberGenerator.Next(0, possileTiles.Length)];
// Pick a direction to try spawn in
int direction = GameServer.RandomNumberGenerator.Next(0, 4);
int tryX = 0;
int tryY = 0;
if (direction == 0)
{
tryX = spawnNearTile.X + 1;
tryY = spawnNearTile.Y;
}
else if (direction == 1)
{
tryX = spawnNearTile.X - 1;
tryY = spawnNearTile.Y;
}
else if (direction == 3)
{
tryX = spawnNearTile.X;
tryY = spawnNearTile.Y + 1;
}
else if (direction == 4)
{
tryX = spawnNearTile.X;
tryY = spawnNearTile.Y - 1;
}
if (World.InSpecialTile(tryX, tryY))
{
World.SpecialTile tile = World.GetSpecialTile(tryX, tryY);
if (tile.Code != null)
continue;
}
if (Map.CheckPassable(tryX, tryY))
{
if (GetItemsAt(tryX, tryY).Length > 25) // Max here
continue;
ItemInstance instance = new ItemInstance(item.Id);
AddItem(instance, tryX, tryY, despawnTimer);
Logger.DebugPrint("Created Item ID: " + instance.ItemId + " at: X: " + tryX + " Y: " + tryY);
newItems++;
break;
}
else
{
continue;
}
}
}
else if (item.SpawnParamaters.SpawnOnTileType != null)
{
while (true)
{
// Pick a random location:
int tryX = GameServer.RandomNumberGenerator.Next(0, Map.Width);
int tryY = GameServer.RandomNumberGenerator.Next(0, Map.Height);
if (World.InSpecialTile(tryX, tryY))
continue;
if (Map.CheckPassable(tryX, tryY)) // Can the player walk here?
{
int TileID = Map.GetTileId(tryX, tryY, false);
string TileType = Map.TerrainTiles[TileID - 1].Type; // Is it the right type?
if (item.SpawnParamaters.SpawnOnTileType == TileType)
{
if (GetItemsAt(tryX, tryY).Length > 25) // Max here
continue;
ItemInstance instance = new ItemInstance(item.Id);
AddItem(instance, tryX, tryY, despawnTimer);
Logger.DebugPrint("Created Item ID: " + instance.ItemId + " at: X: " + tryX + " Y: " + tryY);
newItems++;
break;
}
else
{
continue;
}
}
else
{
continue;
}
}
}
}
} while (isFirstLoad && (count < item.SpawnParamaters.SpawnCap));
}
}
public static void DeleteAllItemsWithId(int itemId)
{
Database.DeleteAllDroppedItemsWithId(itemId);
foreach (DroppedItem itm in droppedItemsList.ToArray())
if (itm.Instance.ItemId == itemId)
droppedItemsList.Remove(itm);
}
public static void Init()
{
ReadFromDatabase();
GenerateItems(Database.GetDroppedItemsCount() <= 0);
}
}
}

View file

@ -0,0 +1,234 @@
using HISP.Player;
using HISP.Server;
using HISP.Game;
using System.Collections.Generic;
using HISP.Game.Inventory;
namespace HISP.Game.Items
{
public class Item
{
public struct Effects
{
public string EffectsWhat;
public int EffectAmount;
}
public struct SpawnRules
{
public int SpawnCap;
public string SpawnInZone;
public string SpawnOnTileType;
public string SpawnOnSpecialTile;
public string SpawnNearSpecialTile;
}
public class ItemInformation
{
public int Id;
public string Name;
public string PluralName;
public string Description;
public int IconId;
public int SortBy;
public int SellPrice;
public string EmbedSwf;
public bool WishingWell;
public string Type;
public int[] MiscFlags;
public Effects[] Effects;
public SpawnRules SpawnParamaters;
public int GetMiscFlag(int no)
{
if (MiscFlags.Length <= no)
return 0;
else
return MiscFlags[no];
}
}
public struct ThrowableItem
{
public int Id;
public string HitMessage;
public string ThrowMessage;
public string HitYourselfMessage;
}
public static List<ItemInformation> Items = new List<ItemInformation>();
public static List<ThrowableItem> ThrowableItems = new List<ThrowableItem>();
public static int Present;
public static int MailMessage;
public static int DorothyShoes;
public static int PawneerOrder;
public static int Telescope;
public static int Pitchfork;
public static int WishingCoin;
public static int ModSplatterball;
public static int WaterBalloon;
public static int FishingPole;
public static int Earthworm;
public static int BirthdayToken;
public static int MagicBean;
public static int MagicDroplet;
public static int StallionTradingCard;
public static int MareTradingCard;
public static int ColtTradingCard;
public static int FillyTradingCard;
public static int[] TradingCards
{
get
{
return new int[4] { StallionTradingCard, MareTradingCard, ColtTradingCard, FillyTradingCard };
}
}
public struct ItemPurchaseQueueItem
{
public int ItemId;
public int ItemCount;
}
public static void UseItem(User user, ItemInstance item)
{
if (user.Inventory.HasItem(item.RandomId))
{
InventoryItem itm = user.Inventory.GetItemByRandomid(item.RandomId);
if (itm.ItemId == Item.DorothyShoes)
{
if (World.InIsle(user.X, user.Y))
{
World.Isle isle = World.GetIsle(user.X, user.Y);
if (isle.Name == "Prison Isle")
{
byte[] dontWorkHere = PacketBuilder.CreateChat(Messages.RanchDorothyShoesPrisonIsleMessage, PacketBuilder.CHAT_BOTTOM_RIGHT);
user.LoggedinClient.SendPacket(dontWorkHere);
return;
}
}
if (user.OwnedRanch == null) // How????
{
Logger.HackerPrint(user.Username + " Tried to use Dorothy Shoes when they did *NOT* own a ranch.");
user.Inventory.Remove(itm.ItemInstances[0]);
return;
}
byte[] noPlaceLIke127001 = PacketBuilder.CreateChat(Messages.RanchDorothyShoesMessage, PacketBuilder.CHAT_BOTTOM_RIGHT);
user.LoggedinClient.SendPacket(noPlaceLIke127001);
user.Teleport(user.OwnedRanch.X, user.OwnedRanch.Y);
}
else if (itm.ItemId == Item.Telescope)
{
byte[] birdMap = PacketBuilder.CreateBirdMap(user.X, user.Y);
user.LoggedinClient.SendPacket(birdMap);
}
else
{
Logger.ErrorPrint(user.Username + "Tried to use item with undefined action- ID: " + itm.ItemId);
}
}
}
public static ItemInformation[] GetAllWishableItems()
{
List<ItemInformation> itemInfo = new List<ItemInformation>();
foreach(ItemInformation item in Items)
{
if (item.WishingWell)
itemInfo.Add(item);
}
return itemInfo.ToArray();
}
public static bool ConsumeItem(User user, ItemInformation itmInfo)
{
bool toMuch = false;
foreach (Item.Effects effect in itmInfo.Effects)
{
switch (effect.EffectsWhat)
{
case "TIREDNESS":
if (user.Tiredness + effect.EffectAmount > 1000)
toMuch = true;
user.Tiredness += effect.EffectAmount;
break;
case "THIRST":
if (user.Thirst + effect.EffectAmount > 1000)
toMuch = true;
user.Thirst += effect.EffectAmount;
break;
case "HUNGER":
if (user.Hunger + effect.EffectAmount > 1000)
toMuch = true;
user.Hunger += effect.EffectAmount;
break;
case "MOOD":
break;
default:
Logger.ErrorPrint("Unknown effect: " + effect.EffectsWhat);
break;
}
}
return toMuch;
}
public static bool IsThrowable(int id)
{
foreach(ThrowableItem itm in ThrowableItems)
{
if(itm.Id == id)
{
return true;
}
}
return false;
}
public static ThrowableItem GetThrowableItem(int id)
{
foreach (ThrowableItem itm in ThrowableItems)
{
if (itm.Id == id)
{
return itm;
}
}
throw new KeyNotFoundException("id: " + id + " is not a throwable item.");
}
public static bool ItemIdExist(int id)
{
try
{
GetItemById(id);
return true;
}
catch(KeyNotFoundException)
{
return false;
}
}
public static void DoSpecialCases()
{
Tack.GenerateTackSets();
}
public static ItemInformation GetItemById(int id)
{
foreach(ItemInformation item in Items)
{
if(item.Id == id)
{
return item;
}
}
throw new KeyNotFoundException("Item id " + id + " Not found!");
}
}
}

View file

@ -0,0 +1,27 @@
using HISP.Security;
using HISP.Game;
namespace HISP.Game.Items
{
public class ItemInstance
{
public int RandomId;
public int ItemId;
public int Data;
public Item.ItemInformation GetItemInfo()
{
return Item.GetItemById(ItemId);
}
public ItemInstance(int id,int randomId = -1, int data=0)
{
RandomId = RandomID.NextRandomId(randomId);
Data = data;
ItemId = id;
}
}
}

View file

@ -0,0 +1,148 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HISP.Server;
namespace HISP.Game.Items
{
public class Tack
{
public class TackSet
{
public TackSet()
{
tackItems = new List<Item.ItemInformation>();
}
public int IconId
{
get
{
return GetSaddle().IconId;
}
}
public string SetName;
private List<Item.ItemInformation> tackItems;
public void Add(Item.ItemInformation item)
{
Logger.DebugPrint("Added "+item.Name+" To Tack Set: "+this.SetName);
tackItems.Add(item);
}
public Item.ItemInformation GetSaddle()
{
foreach(Item.ItemInformation tackItem in TackItems)
{
if(tackItem.GetMiscFlag(0) == 1) // Saddle
return tackItem;
}
throw new KeyNotFoundException("Saddle not found.");
}
public Item.ItemInformation GetSaddlePad()
{
foreach(Item.ItemInformation tackItem in TackItems)
{
if(tackItem.GetMiscFlag(0) == 2) // SaddlePad
return tackItem;
}
throw new KeyNotFoundException("SaddlePad not found.");
}
public Item.ItemInformation GetBridle()
{
foreach(Item.ItemInformation tackItem in TackItems)
{
if(tackItem.GetMiscFlag(0) == 3) // Bridle
return tackItem;
}
throw new KeyNotFoundException("GetBridle not found.");
}
public string[] GetSwfNames()
{
string[] swfs = new string[3];
swfs[0] = GetSaddle().EmbedSwf;
swfs[1] = GetSaddlePad().EmbedSwf;
swfs[2] = GetBridle().EmbedSwf;
return swfs;
}
public Item.ItemInformation[] TackItems
{
get
{
return tackItems.ToArray();
}
}
public int SortPosition()
{
int pos = 0;
foreach(Item.ItemInformation tackitem in TackItems)
{
foreach(Item.Effects effect in tackitem.Effects)
{
pos += effect.EffectAmount;
}
}
return pos;
}
}
private static List<TackSet> tackSets = new List<TackSet>();
public static TackSet[] TackSets
{
get
{
return tackSets.ToArray();
}
}
public static TackSet GetSetByName(string name)
{
foreach(TackSet set in tackSets)
{
if(set.SetName == name)
{
return set;
}
}
throw new KeyNotFoundException("No TackSet with name: "+name+" was found.");
}
public static void GenerateTackSets()
{
foreach(Item.ItemInformation itemInfo in Item.Items)
{
if(itemInfo.Type == "TACK")
{
try
{
TackSet set = GetSetByName(Converters.CapitalizeFirstLetter(itemInfo.EmbedSwf));
set.Add(itemInfo);
}
catch(KeyNotFoundException)
{
TackSet tackSet = new TackSet();
tackSet.SetName = Converters.CapitalizeFirstLetter(itemInfo.EmbedSwf);
tackSet.Add(itemInfo);
tackSets.Add(tackSet);
}
}
}
foreach(TackSet set in TackSets)
{
if(set.TackItems.Length < 3)
{
Logger.DebugPrint("Removing set: "+set.SetName);
tackSets.Remove(set);
}
}
}
}
}

View file

@ -0,0 +1,135 @@
using System;
using System.IO;
using HISP.Server;
namespace HISP.Game
{
public class Map
{
public struct TerrainTile
{
public bool Passable;
public string Type;
}
public static int[] OverlayTileDepth;
public static int Width;
public static int Height;
public static byte[] MapData;
public static byte[] oMapData;
public static TerrainTile[] TerrainTiles;
public static int NewUserStartX;
public static int NewUserStartY;
public static int ModIsleX;
public static int ModIsleY;
public static int RulesIsleX;
public static int RulesIsleY;
public static int GetTileId(int x, int y, bool overlay)
{
int pos = ((x * Height) + y);
if ((pos <= 0 || pos >= oMapData.Length) && overlay)
return 1;
else if ((pos <= 0 || pos >= MapData.Length) && !overlay)
return 1;
else if (overlay && Treasure.IsTileBuiredTreasure(x, y))
return 193; // Burried Treasure tile.
else if (overlay && Treasure.IsTilePotOfGold(x, y))
return 186; // Pot of Gold tile.
else if (overlay && Ranch.IsRanchHere(x, y))
{
int upgradeLevel = Ranch.GetRanchAt(x, y).UpgradedLevel;
if (upgradeLevel > 7)
upgradeLevel = 7;
return 170 + upgradeLevel;
}
else if (overlay)
return oMapData[pos];
else if (!overlay)
return MapData[pos];
else // Not sure how you could even get here.
return 1;
}
public static bool CheckPassable(int x, int y)
{
int tileId = GetTileId(x, y, false) - 1;
int otileId = GetTileId(x, y, true) - 1;
bool terrainPassable = TerrainTiles[tileId].Passable;
int tileset = 0;
if (otileId > 192)
{
if (World.InIsle(x, y))
tileset = World.GetIsle(x, y).Tileset;
otileId = otileId + 64 * tileset;
}
int tileDepth = OverlayTileDepth[otileId];
bool overlayPassable = false;
if (tileDepth == 0)
overlayPassable = false;
if (tileDepth == 1)
overlayPassable = false;
if (tileDepth == 2)
overlayPassable = true;
if (tileDepth == 3)
overlayPassable = true;
if ((!terrainPassable && overlayPassable) && otileId == 0)
return false;
bool passable = false;
if (!overlayPassable)
passable = false;
if (!terrainPassable)
passable = false;
if (!passable && overlayPassable)
passable = true;
return passable;
}
public static void OpenMap()
{
if(!File.Exists(ConfigReader.MapFile))
{
Logger.ErrorPrint("Map file not found.");
return;
}
Logger.InfoPrint("Loading Map Data (" + ConfigReader.MapFile + ")");
byte[] worldMap = File.ReadAllBytes(ConfigReader.MapFile);
Width = BitConverter.ToInt32(worldMap, 0);
Height = BitConverter.ToInt32(worldMap, 4);
MapData = new byte[Width * Height];
oMapData = new byte[Width * Height];
int ii = 8;
for (int i = 0; i < MapData.Length; i++)
{
oMapData[i] = worldMap[ii];
MapData[i] = worldMap[ii+ 1];
ii += 2;
}
worldMap = null;
Logger.InfoPrint("Map Data Loaded!");
}
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,94 @@
using HISP.Player;
using HISP.Server;
using System.Collections.Generic;
namespace HISP.Game
{
public class Multiroom
{
public static List<Multiroom> Multirooms = new List<Multiroom>();
public static Multiroom GetMultiroom(int x, int y)
{
foreach (Multiroom multiroom in Multirooms)
if(multiroom.x == x && multiroom.y == y)
return multiroom;
throw new KeyNotFoundException();
}
public static bool IsMultiRoomAt(int x, int y)
{
foreach (Multiroom multiroom in Multirooms)
if (multiroom.x == x && multiroom.y == y)
return true;
return false;
}
public static void LeaveAllMultirooms(User user)
{
foreach (Multiroom room in Multirooms)
room.Leave(user);
}
public static void CreateMultirooms()
{
Logger.InfoPrint("Creating Multirooms...");
foreach(World.SpecialTile tile in World.SpecialTiles)
{
if (tile.Code != null)
{
if (tile.Code.StartsWith("MULTIROOM") || tile.Code.StartsWith("MULTIHORSES") || tile.Code.StartsWith("2PLAYER") || tile.Code.StartsWith("AUCTION"))
{
Logger.DebugPrint("Created Multiroom @ " + tile.X.ToString() + "," + tile.Y.ToString());
new Multiroom(tile.X, tile.Y);
}
}
}
}
public Multiroom(int x, int y)
{
this.x = x;
this.y = y;
Multirooms.Add(this);
}
public int x;
public int y;
public List<User> JoinedUsers = new List<User>();
public void Join(User user)
{
if (!JoinedUsers.Contains(user))
{
Logger.DebugPrint(user.Username + " Joined multiroom @ " + x.ToString() + "," + y.ToString());
JoinedUsers.Add(user);
foreach (User joinedUser in JoinedUsers)
if (joinedUser.Id != user.Id)
if(!TwoPlayer.IsPlayerInGame(joinedUser))
if(!joinedUser.ListingAuction)
GameServer.UpdateArea(joinedUser.LoggedinClient);
}
}
public void Leave(User user)
{
if(JoinedUsers.Contains(user))
{
Logger.DebugPrint(user.Username + " Left multiroom @ " + x.ToString() + "," + y.ToString());
JoinedUsers.Remove(user);
}
foreach (User joinedUser in JoinedUsers)
if (!TwoPlayer.IsPlayerInGame(joinedUser))
if (!joinedUser.ListingAuction)
GameServer.UpdateArea(joinedUser.LoggedinClient);
}
}
}

View file

@ -0,0 +1,329 @@
using HISP.Player;
using HISP.Server;
using System.Collections.Generic;
namespace HISP.Game
{
public class Npc
{
public struct NpcReply
{
public int Id;
public string ReplyText;
public int GotoChatpoint;
public int RequiresQuestIdCompleted;
public int RequiresQuestIdNotCompleted;
}
public struct NpcChat
{
public int Id;
public string ChatText;
public int ActivateQuestId;
public NpcReply[] Replies;
}
public class NpcEntry
{
public NpcEntry(int npcId, int posX, int posY, bool npcMoves, int udlrStartX=0, int udlrStartY=0)
{
id = npcId;
x = posX;
y = posY;
Moves = npcMoves;
UDLRStartX = udlrStartX;
UDLRStartY = udlrStartY;
if(Moves)
{
if(Database.HasNpcPos(id))
{
udlrScriptPos = Database.GetNpcUdlrPointer(npcId);
x = Database.GetNpcPosX(npcId);
y = Database.GetNpcPosY(npcId);
}
else
{
if(udlrStartX != 0 && udlrStartY != 0)
{
x = udlrStartX;
y = udlrStartY;
}
udlrScriptPos = 0;
Database.AddNpcPos(npcId, x, Y, udlrScriptPos);
}
}
}
private int id;
public string Name;
public string AdminDescription;
public string ShortDescription;
public string LongDescription;
public bool Moves;
private int x;
private int y;
public int Id
{
get
{
return id;
}
}
public int X
{
get
{
return x;
}
set
{
Database.SetNpcX(id, value);
x = value;
}
}
public int Y
{
get
{
return y;
}
set
{
Database.SetNpcY(id, value);
y = value;
}
}
public string StayOn;
public int RequiresQuestIdCompleted;
public int RequiresQuestIdNotCompleted;
public string UDLRScript;
public int UDLRStartX;
public int UDLRStartY;
public bool AdminOnly;
public bool LibarySearchable;
public int IconId;
private int udlrScriptPos = 0;
public int UdlrScriptPos
{
get
{
return udlrScriptPos;
}
set
{
Database.SetNpcUdlrPointer(Id, value);
udlrScriptPos = value;
}
}
private bool canNpcBeHere(int x, int y)
{
// Horses cannot be in towns.
if (World.InTown(x, y))
return false;
if (World.InSpecialTile(x, y))
return false;
// Check Tile Type
int TileID = Map.GetTileId(x, y, false);
string TileType = Map.TerrainTiles[TileID - 1].Type;
if (TileType != this.StayOn)
return false;
if (Map.CheckPassable(x, y)) // Can the player stand over here?
return true;
return false;
}
public void RandomWander()
{
if(Moves)
{
if(UDLRStartX == 0 && UDLRStartY == 0) // not scripted.
{
if (GameServer.GetUsersAt(this.X, this.Y, true, true).Length > 0)
return;
int tries = 0;
while(true)
{
int direction = GameServer.RandomNumberGenerator.Next(0, 4);
int tryX = this.X;
int tryY = this.Y;
switch (direction)
{
case 0:
tryX += 1;
break;
case 1:
tryX -= 1;
break;
case 2:
tryY += 1;
break;
case 3:
tryY -= 1;
break;
}
if (canNpcBeHere(tryX, tryY))
{
X = tryX;
Y = tryY;
break;
}
tries++;
if (tries > 100) // yo stuck lol
{
Logger.ErrorPrint("NPC: " + this.Name + " is probably stuck (cant move after 100 tries)");
break;
}
}
}
else // Is Scripted.
{
if (GameServer.GetUsersAt(this.X, this.Y, true, true).Length > 0)
return;
if (UdlrScriptPos >= UDLRScript.Length)
{
X = UDLRStartX;
Y = UDLRStartY;
UdlrScriptPos = 0;
}
switch (UDLRScript.ToLower()[UdlrScriptPos])
{
case 'u':
Logger.DebugPrint(this.Name + " Moved up: was " + X + ", " + Y + " now: " + X + ", " + (Y + 1).ToString());
Y--;
break;
case 'd':
Logger.DebugPrint(this.Name + " Moved down: was " + X + ", " + Y + " now: " + X + ", " + (Y - 1).ToString());
Y++;
break;
case 'l':
Logger.DebugPrint(this.Name + " Moved left: was " + X + ", " + Y + " now: " + (X - 1).ToString() + ", " + Y );
X--;
break;
case 'r':
Logger.DebugPrint(this.Name + " Moved right: was " + X + ", " + Y + " now: " + (X + 1).ToString() + ", " + Y);
X++;
break;
}
UdlrScriptPos++;
}
}
}
public NpcChat[] Chatpoints;
}
public static List<NpcEntry> NpcList = new List<NpcEntry>();
public static NpcReply GetNpcReply(NpcEntry npc, int id)
{
foreach (NpcChat chatpoint in npc.Chatpoints)
{
foreach (NpcReply reply in chatpoint.Replies)
{
if (reply.Id == id)
return reply;
}
}
throw new KeyNotFoundException("Npc reply with " + id + " not found!");
}
public static NpcReply GetNpcReply(NpcChat chatpoint, int id)
{
foreach(NpcReply reply in chatpoint.Replies)
{
if (reply.Id == id)
return reply;
}
throw new KeyNotFoundException("Npc reply with " + id + " not found!");
}
public static NpcChat GetNpcChatpoint(NpcEntry npc, int chatpointId)
{
foreach(Npc.NpcChat chatpoint in npc.Chatpoints)
{
if(chatpoint.Id == chatpointId)
{
return chatpoint;
}
}
return npc.Chatpoints[0];
}
public static int GetDefaultChatpoint(User user, NpcEntry npc)
{
if (Database.HasNpcStartpointSet(user.Id, npc.Id))
return Database.GetNpcStartPoint(user.Id, npc.Id);
else
return 0;
}
public static void SetDefaultChatpoint(User user, NpcEntry npc, int chatpointId)
{
if (Database.HasNpcStartpointSet(user.Id, npc.Id))
Database.SetNpcStartPoint(user.Id, npc.Id, chatpointId);
else
Database.AddNpcStartPoint(user.Id, npc.Id, chatpointId);
}
public static bool NpcExists(int id)
{
try
{
GetNpcById(id);
return true;
}
catch (KeyNotFoundException)
{
return false;
}
}
public static NpcEntry GetNpcById(int id)
{
foreach(NpcEntry npc in NpcList)
{
if (npc.Id == id)
return npc;
}
throw new KeyNotFoundException("Npc id: " + id + " not found!");
}
public static void WanderNpcs()
{
Logger.DebugPrint("Making NPC's randomly wander.");
foreach(NpcEntry npc in NpcList)
{
npc.RandomWander();
}
}
public static NpcEntry[] GetNpcByXAndY(int x, int y)
{
List<NpcEntry> npcs = new List<NpcEntry>();
foreach(NpcEntry npc in NpcList)
{
if (npc.X == x && npc.Y == y)
npcs.Add(npc);
}
return npcs.ToArray();
}
}
}

View file

@ -0,0 +1,384 @@
using System;
using System.Collections.Generic;
using System.Linq;
using HISP.Game.Inventory;
using HISP.Player;
using HISP.Server;
using HISP.Game.Items;
namespace HISP.Game
{
public class Quest
{
public const string Shovel = "SHOVEL";
public const string Binoculars = "BINOCS";
public const string Rake = "RAKE";
public const string MagnifyingGlass = "MAGNIFY";
public struct QuestItemInfo
{
public int ItemId;
public int Quantity;
}
public struct QuestAltActivation
{
public string Type;
public int ActivateX;
public int ActivateY;
}
public struct QuestEntry
{
public int Id;
public string Notes;
public string Title;
public int[] RequiresQuestIdCompleteStatsMenu; // Not sure what this is for.
public QuestAltActivation AltActivation;
public bool Tracked; // Should we track how many times the player has completed this quest.
// Fail Settings
public int MaxRepeats;
public int MoneyCost;
public QuestItemInfo[] ItemsRequired;
public string FailNpcChat;
public int AwardRequired;
public int[] RequiresQuestIdCompleted;
public int[] RequiresQuestIdNotCompleted;
// Success Settings
public int MoneyEarned;
public QuestItemInfo[] ItemsEarned;
public int QuestPointsEarned;
public int SetNpcChatpoint;
public int GotoNpcChatpoint;
public int WarpX;
public int WarpY;
public string SuccessMessage;
public string SuccessNpcChat;
public bool HideReplyOnFail;
public string Difficulty;
public string Author;
public int ChainedQuestId;
public bool Minigame;
}
public static List<QuestEntry> QuestList = new List<QuestEntry>();
public static int GetTotalQuestPoints()
{
int totalQp = 0;
QuestEntry[] quests = GetPublicQuestList();
foreach (QuestEntry quest in quests)
{
totalQp += quest.QuestPointsEarned;
}
return totalQp;
}
public static int GetTotalQuestsComplete(User user)
{
QuestEntry[] questList = GetPublicQuestList();
int totalComplete = 0;
foreach (QuestEntry quest in questList)
{
if (user.Quests.GetTrackedQuestAmount(quest.Id) > 0)
totalComplete++;
}
return totalComplete;
}
public static QuestEntry[] GetPublicQuestList()
{
QuestEntry[] quests = QuestList.OrderBy(o => o.Title).ToArray();
List<QuestEntry> sortedQuests = new List<QuestEntry>();
foreach (QuestEntry quest in quests)
{
if (quest.Title != null)
sortedQuests.Add(quest);
}
return sortedQuests.ToArray();
}
public class QuestResult
{
public QuestResult()
{
NpcChat = null;
SetChatpoint = -1;
GotoChatpoint = -1;
HideRepliesOnFail = false;
QuestCompleted = false;
}
public string NpcChat;
public int SetChatpoint;
public int GotoChatpoint;
public bool HideRepliesOnFail;
public bool QuestCompleted;
}
public static bool CanComplete(User user, QuestEntry quest)
{
// Has completed other required quests?
foreach (int questId in quest.RequiresQuestIdCompleted)
if (user.Quests.GetTrackedQuestAmount(questId) < 1)
return false;
// Has NOT competed other MUST NOT BE required quests
foreach (int questId in quest.RequiresQuestIdNotCompleted)
if (user.Quests.GetTrackedQuestAmount(questId) > 1)
return false;
if (quest.Tracked)
{
// Has allready tracked this quest?
if (user.Quests.GetTrackedQuestAmount(quest.Id) >= quest.MaxRepeats)
return false;
}
// Check if user has award unlocked
if (quest.AwardRequired != 0)
if (!user.Awards.HasAward(Award.GetAwardById(quest.AwardRequired)))
return false;
// Check if i have required items
foreach (QuestItemInfo itemInfo in quest.ItemsRequired)
{
bool hasThisItem = false;
InventoryItem[] items = user.Inventory.GetItemList();
foreach (InventoryItem item in items)
{
if (item.ItemId == itemInfo.ItemId && item.ItemInstances.Count >= itemInfo.Quantity)
{
hasThisItem = true;
break;
}
}
if (!hasThisItem)
return false;
}
// Have enough money?
if (user.Money < quest.MoneyCost)
return false;
return true;
}
public static QuestResult CompleteQuest(User user, QuestEntry quest, bool npcActivation = false, QuestResult res=null)
{
if(res == null)
res = new QuestResult();
// Take Items
foreach (QuestItemInfo itemInfo in quest.ItemsRequired)
{
InventoryItem itm = user.Inventory.GetItemByItemId(itemInfo.ItemId);
for (int i = 0; i < itemInfo.Quantity; i++)
user.Inventory.Remove(itm.ItemInstances[0]);
}
// Take Money
user.TakeMoney(quest.MoneyCost);
// Give money
user.AddMoney(quest.MoneyEarned);
// Give items
foreach (QuestItemInfo itemInfo in quest.ItemsEarned)
{
for (int i = 0; i < itemInfo.Quantity; i++)
{
ItemInstance itm = new ItemInstance(itemInfo.ItemId);
Item.ItemInformation itemInformation = itm.GetItemInfo();
if (itemInformation.Type == "CONCEPTUAL")
Item.ConsumeItem(user, itemInformation);
else
user.Inventory.AddIgnoringFull(itm);
}
}
if (quest.WarpX != 0 && quest.WarpY != 0)
user.Teleport(quest.WarpX, quest.WarpY);
// Give quest points
user.QuestPoints += quest.QuestPointsEarned;
res.QuestCompleted = true;
if (npcActivation)
{
if (quest.SuccessNpcChat != null && quest.SuccessNpcChat != "")
res.NpcChat = quest.SuccessNpcChat;
if(quest.SetNpcChatpoint != -1)
res.SetChatpoint = quest.SetNpcChatpoint;
if(quest.GotoNpcChatpoint != -1)
res.GotoChatpoint = quest.GotoNpcChatpoint;
}
if (quest.Tracked)
user.Quests.TrackQuest(quest.Id);
if (quest.ChainedQuestId != 0)
res = ActivateQuest(user, Quest.GetQuestById(quest.ChainedQuestId), npcActivation, res);
if (quest.SuccessMessage != null)
{
byte[] ChatPacket = PacketBuilder.CreateChat(quest.SuccessMessage, PacketBuilder.CHAT_BOTTOM_RIGHT);
user.LoggedinClient.SendPacket(ChatPacket);
}
if (quest.SuccessNpcChat != null)
{
if (!npcActivation)
{
byte[] ChatPacket = PacketBuilder.CreateChat(quest.SuccessNpcChat, PacketBuilder.CHAT_BOTTOM_RIGHT);
user.LoggedinClient.SendPacket(ChatPacket);
}
}
// Check if award unlocked
int questPointsPercent = Convert.ToInt32(Math.Floor(((decimal)user.QuestPoints / (decimal)GetTotalQuestPoints()) * (decimal)100.0));
if (questPointsPercent >= 25)
user.Awards.AddAward(Award.GetAwardById(1)); // 25% Quest Completion Award.
if (questPointsPercent >= 50)
user.Awards.AddAward(Award.GetAwardById(2)); // 50% Quest Completion Award.
if (questPointsPercent >= 75)
user.Awards.AddAward(Award.GetAwardById(3)); // 75% Quest Completion Award.
if (questPointsPercent >= 100)
user.Awards.AddAward(Award.GetAwardById(4)); // 100% Quest Completion Award.
// Is cloud isles quest?
if (quest.Id == 1373)
{
byte[] swfLoadPacket = PacketBuilder.CreateSwfModulePacket("ballooncutscene", PacketBuilder.PACKET_SWF_CUTSCENE);
user.LoggedinClient.SendPacket(swfLoadPacket);
}
return res;
}
public static QuestResult FailQuest(User user, QuestEntry quest, bool npcActivation = false, QuestResult res=null)
{
if(res == null)
res = new QuestResult();
res.QuestCompleted = false;
if(npcActivation)
{
if(quest.GotoNpcChatpoint != -1)
res.GotoChatpoint = quest.GotoNpcChatpoint;
if(quest.HideReplyOnFail != false)
res.HideRepliesOnFail = quest.HideReplyOnFail;
if(res.SetChatpoint != -1)
res.SetChatpoint = quest.SetNpcChatpoint;
}
if (quest.FailNpcChat != null)
{
if (!npcActivation)
{
byte[] ChatPacket = PacketBuilder.CreateChat(quest.FailNpcChat, PacketBuilder.CHAT_BOTTOM_RIGHT);
user.LoggedinClient.SendPacket(ChatPacket);
}
else
{
if(quest.FailNpcChat != null)
{
if(npcActivation)
{
if (quest.FailNpcChat != "")
{
res.NpcChat = quest.FailNpcChat;
}
}
}
}
}
return res;
}
public static QuestResult ActivateQuest(User user, QuestEntry quest, bool npcActivation = false, QuestResult res=null)
{
if (CanComplete(user, quest))
{
return CompleteQuest(user, quest, npcActivation, res);
}
else
{
return FailQuest(user, quest, npcActivation, res);
}
}
public static bool DoesQuestExist(int id)
{
try
{
GetQuestById(id);
return true;
}
catch(KeyNotFoundException)
{
return false;
}
}
public static QuestEntry GetQuestById(int id)
{
foreach(QuestEntry quest in QuestList)
{
if(quest.Id == id)
{
return quest;
}
}
throw new KeyNotFoundException("Quest Id: " + id + " Dont exist.");
}
public static bool UseTool(User user, string tool, int x, int y)
{
if (tool == Quest.Shovel)
{
// check Treasures
if (Treasure.IsTileTreasure(x, y))
{
Treasure treasure = Treasure.GetTreasureAt(x, y);
if(treasure.Type == "BURIED")
treasure.CollectTreasure(user);
return true;
}
}
QuestResult result = null;
foreach (QuestEntry quest in QuestList)
{
if (quest.AltActivation.Type == tool && quest.AltActivation.ActivateX == x && quest.AltActivation.ActivateY == y)
{
result = ActivateQuest(user, quest, true, result);
if(result.QuestCompleted)
{
if(result.NpcChat != null)
{
byte[] ChatPacket = PacketBuilder.CreateChat(result.NpcChat, PacketBuilder.CHAT_BOTTOM_RIGHT);
user.LoggedinClient.SendPacket(ChatPacket);
}
return true;
}
}
}
if(result != null)
{
if (result.NpcChat != null)
{
byte[] ChatPacket = PacketBuilder.CreateChat(result.NpcChat, PacketBuilder.CHAT_BOTTOM_RIGHT);
user.LoggedinClient.SendPacket(ChatPacket);
}
return true;
}
return false;
}
}
}

View file

@ -0,0 +1,482 @@
using HISP.Game.Inventory;
using HISP.Game.Items;
using HISP.Player;
using HISP.Server;
using System;
using System.Collections.Generic;
namespace HISP.Game
{
public class Ranch
{
public class RanchUpgrade
{
public static List<RanchUpgrade> RanchUpgrades = new List<RanchUpgrade>();
public int Id;
public int Cost;
public string Title;
public string Description;
public int Limit;
public static bool RanchUpgradeExists(int id)
{
foreach (RanchUpgrade rachUpgrade in RanchUpgrades)
{
if (rachUpgrade.Id == id)
return true;
}
return false;
}
public static RanchUpgrade GetRanchUpgradeById(int id)
{
foreach (RanchUpgrade rachUpgrade in RanchUpgrades)
{
if (rachUpgrade.Id == id)
return rachUpgrade;
}
throw new KeyNotFoundException("No ranch found.");
}
}
public class RanchBuilding
{
public static List<RanchBuilding> RanchBuildings = new List<RanchBuilding>();
public int Id;
public int Cost;
public string Title;
public string Description;
public static bool RanchBuildingExists(int id)
{
foreach (RanchBuilding ranchBuilding in RanchBuildings)
{
if (ranchBuilding.Id == id)
return true;
}
return false;
}
public static RanchBuilding GetRanchBuildingById(int id)
{
foreach(RanchBuilding ranchBuilding in RanchBuildings)
{
if (ranchBuilding.Id == id)
return ranchBuilding;
}
throw new KeyNotFoundException("No ranch found.");
}
public int GetTeardownPrice()
{
return (int)Math.Round((float)this.Cost / (100 / 35.0));
}
}
public static List<Ranch> Ranches = new List<Ranch>();
public int X;
public int Y;
public int Id;
public int Value;
private int ownerId;
private int upgradedLevel;
private int investedMoney;
private string title;
private string description;
public int GetSellPrice()
{
return (int)Math.Round((float)this.InvestedMoney / (100 / 75.0));
}
private void removeDorothyShoes(int Id)
{
if (Id == -1)
return;
if(GameServer.IsUserOnline(Id))
{
User user = GameServer.GetUserById(Id);
user.OwnedRanch = null;
InventoryItem items = user.Inventory.GetItemByItemId(Item.DorothyShoes);
foreach (ItemInstance itm in items.ItemInstances.ToArray())
{
user.Inventory.Remove(itm);
}
}
else
{
Database.RemoveAllItemTypesFromPlayerInventory(this.Id, Item.DorothyShoes);
}
}
private void deleteRanch()
{
Database.DeleteRanchOwner(this.Id);
removeDorothyShoes(this.ownerId);
resetRanch();
}
private void resetRanch()
{
title = "";
description = "";
investedMoney = 0;
upgradedLevel = 0;
ownerId = -1;
for (int i = 0; i < 16; i++)
buildings[i] = null;
}
public int OwnerId
{
get
{
if(ownerId != -1)
{
if (ConfigReader.AllUsersSubbed || Database.IsUserAdmin(ownerId))
return ownerId;
int subExp = Database.GetUserSubscriptionExpireDate(ownerId);
DateTime expTime = Converters.UnixTimeStampToDateTime(subExp);
if ((DateTime.UtcNow.Date - expTime.Date).Days >= 30)
{
int price = GetSellPrice();
try
{
checked
{
Database.SetPlayerMoney(Database.GetPlayerMoney(ownerId) + price, ownerId);
}
}
catch (OverflowException)
{
Database.SetPlayerMoney(2147483647, ownerId);;
}
Database.AddMessageToQueue(ownerId, Messages.FormatRanchForcefullySoldMessage(price));
deleteRanch();
return -1;
}
}
return ownerId;
}
set
{
if (value == -1)
{
deleteRanch();
}
else
{
if(Database.IsRanchOwned(this.Id))
{
Database.SetRanchOwner(this.Id, ownerId);
removeDorothyShoes(ownerId);
}
else
{
resetRanch();
Database.AddRanch(this.Id, value, "", "", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
}
ownerId = value;
}
}
public int UpgradedLevel
{
get
{
return upgradedLevel;
}
set
{
upgradedLevel = value;
Database.SetRanchUpgradeLevel(Id, value);
}
}
public int InvestedMoney
{
get
{
return investedMoney;
}
set
{
investedMoney = value;
Database.SetRanchInvestment(Id, value);
}
}
public string Title
{
get
{
return title;
}
set
{
title = value.Trim();
Database.SetRanchTitle(Id, title);
}
}
public string Description
{
get
{
return description;
}
set
{
description = value.Trim();
Database.SetRanchDescription(Id, value);
}
}
private RanchBuilding[] buildings = new RanchBuilding[16];
public int GetBuildingCount(int buildingId)
{
int count = 0;
foreach(RanchBuilding building in buildings)
{
if(building != null)
if (building.Id == buildingId)
count++;
}
return count;
}
private void updateBuildings()
{
if (buildings[0] != null)
Database.SetRanchBuilding1(this.Id, buildings[0].Id);
else
Database.SetRanchBuilding1(this.Id, 0);
if (buildings[1] != null)
Database.SetRanchBuilding2(this.Id, buildings[1].Id);
else
Database.SetRanchBuilding2(this.Id, 0);
if (buildings[2] != null)
Database.SetRanchBuilding3(this.Id, buildings[2].Id);
else
Database.SetRanchBuilding3(this.Id, 0);
if (buildings[3] != null)
Database.SetRanchBuilding4(this.Id, buildings[3].Id);
else
Database.SetRanchBuilding4(this.Id, 0);
if (buildings[4] != null)
Database.SetRanchBuilding5(this.Id, buildings[4].Id);
else
Database.SetRanchBuilding5(this.Id, 0);
if (buildings[5] != null)
Database.SetRanchBuilding6(this.Id, buildings[5].Id);
else
Database.SetRanchBuilding6(this.Id, 0);
if (buildings[6] != null)
Database.SetRanchBuilding7(this.Id, buildings[6].Id);
else
Database.SetRanchBuilding7(this.Id, 0);
if (buildings[7] != null)
Database.SetRanchBuilding8(this.Id, buildings[7].Id);
else
Database.SetRanchBuilding8(this.Id, 0);
if (buildings[8] != null)
Database.SetRanchBuilding9(this.Id, buildings[8].Id);
else
Database.SetRanchBuilding9(this.Id, 0);
if (buildings[9] != null)
Database.SetRanchBuilding10(this.Id, buildings[9].Id);
else
Database.SetRanchBuilding10(this.Id, 0);
if (buildings[10] != null)
Database.SetRanchBuilding11(this.Id, buildings[10].Id);
else
Database.SetRanchBuilding11(this.Id, 0);
if (buildings[11] != null)
Database.SetRanchBuilding12(this.Id, buildings[11].Id);
else
Database.SetRanchBuilding12(this.Id, 0);
if (buildings[12] != null)
Database.SetRanchBuilding13(this.Id, buildings[12].Id);
else
Database.SetRanchBuilding13(this.Id, 0);
if (buildings[13] != null)
Database.SetRanchBuilding14(this.Id, buildings[13].Id);
else
Database.SetRanchBuilding14(this.Id, 0);
if (buildings[14] != null)
Database.SetRanchBuilding15(this.Id, buildings[14].Id);
else
Database.SetRanchBuilding15(this.Id, 0);
if (buildings[15] != null)
Database.SetRanchBuilding16(this.Id, buildings[15].Id);
else
Database.SetRanchBuilding16(this.Id, 0);
}
public RanchBuilding GetBuilding(int buildingId)
{
return buildings[buildingId];
}
public void SetBuilding(int buildingId, RanchBuilding value)
{
buildings[buildingId] = value;
updateBuildings();
}
public string GetSwf(bool mine)
{
string swf = "ranchviewer.swf?H=" + (upgradedLevel+1).ToString();
for(int i = 0; i < buildings.Length; i++)
{
swf += "&B" + (i+1).ToString() + "=";
if (buildings[i] != null)
{
swf += buildings[i].Id.ToString();
}
}
if (mine)
swf += "&MINE=1";
return swf;
}
public Ranch(int x, int y, int id, int value)
{
X = x;
Y = y;
Id = id;
Value = value;
title = "";
description = "";
upgradedLevel = 0;
ownerId = -1;
investedMoney = 0;
for (int i = 0; i < 16; i++)
buildings[i] = null;
bool owned = Database.IsRanchOwned(id);
if (owned)
{
upgradedLevel = Database.GetRanchUpgradeLevel(id);
title = Database.GetRanchTitle(id);
description = Database.GetRanchDescription(id);
ownerId = Database.GetRanchOwner(id);
int b1 = Database.GetRanchBuilding1(id);
int b2 = Database.GetRanchBuilding2(id);
int b3 = Database.GetRanchBuilding3(id);
int b4 = Database.GetRanchBuilding4(id);
int b5 = Database.GetRanchBuilding5(id);
int b6 = Database.GetRanchBuilding6(id);
int b7 = Database.GetRanchBuilding7(id);
int b8 = Database.GetRanchBuilding8(id);
int b9 = Database.GetRanchBuilding9(id);
int b10 = Database.GetRanchBuilding10(id);
int b11 = Database.GetRanchBuilding11(id);
int b12 = Database.GetRanchBuilding12(id);
int b13 = Database.GetRanchBuilding13(id);
int b14 = Database.GetRanchBuilding14(id);
int b15 = Database.GetRanchBuilding15(id);
int b16 = Database.GetRanchBuilding16(id);
if (RanchBuilding.RanchBuildingExists(b1))
buildings[0] = RanchBuilding.GetRanchBuildingById(b1);
if (RanchBuilding.RanchBuildingExists(b2))
buildings[1] = RanchBuilding.GetRanchBuildingById(b2);
if (RanchBuilding.RanchBuildingExists(b3))
buildings[2] = RanchBuilding.GetRanchBuildingById(b3);
if (RanchBuilding.RanchBuildingExists(b4))
buildings[3] = RanchBuilding.GetRanchBuildingById(b4);
if (RanchBuilding.RanchBuildingExists(b5))
buildings[4] = RanchBuilding.GetRanchBuildingById(b5);
if (RanchBuilding.RanchBuildingExists(b6))
buildings[5] = RanchBuilding.GetRanchBuildingById(b6);
if (RanchBuilding.RanchBuildingExists(b7))
buildings[6] = RanchBuilding.GetRanchBuildingById(b7);
if (RanchBuilding.RanchBuildingExists(b8))
buildings[7] = RanchBuilding.GetRanchBuildingById(b8);
if (RanchBuilding.RanchBuildingExists(b9))
buildings[8] = RanchBuilding.GetRanchBuildingById(b9);
if (RanchBuilding.RanchBuildingExists(b10))
buildings[9] = RanchBuilding.GetRanchBuildingById(b10);
if (RanchBuilding.RanchBuildingExists(b11))
buildings[10] = RanchBuilding.GetRanchBuildingById(b11);
if (RanchBuilding.RanchBuildingExists(b12))
buildings[11] = RanchBuilding.GetRanchBuildingById(b12);
if (RanchBuilding.RanchBuildingExists(b13))
buildings[12] = RanchBuilding.GetRanchBuildingById(b13);
if (RanchBuilding.RanchBuildingExists(b14))
buildings[13] = RanchBuilding.GetRanchBuildingById(b14);
if (RanchBuilding.RanchBuildingExists(b15))
buildings[14] = RanchBuilding.GetRanchBuildingById(b15);
if (RanchBuilding.RanchBuildingExists(b16))
buildings[15] = RanchBuilding.GetRanchBuildingById(b16);
InvestedMoney = Database.GetRanchInvestment(id);
}
}
public RanchUpgrade GetRanchUpgrade()
{
return RanchUpgrade.GetRanchUpgradeById(this.upgradedLevel + 1);
}
public static bool IsRanchHere(int x, int y)
{
foreach (Ranch ranch in Ranches)
{
if (ranch.X == x && ranch.Y == y)
return true;
}
return false;
}
public static bool RanchExists(int ranchId)
{
foreach (Ranch ranch in Ranches)
{
if (ranch.Id == ranchId)
return true;
}
return false;
}
public static Ranch GetRanchById(int ranchId)
{
foreach (Ranch ranch in Ranches)
{
if (ranch.Id == ranchId)
return ranch;
}
throw new KeyNotFoundException("No Ranch with id " + ranchId);
}
public static Ranch GetRanchAt(int x, int y)
{
foreach(Ranch ranch in Ranches)
{
if (ranch.X == x && ranch.Y == y)
return ranch;
}
throw new KeyNotFoundException("No Ranch found at x" + x + " y" + y);
}
public static bool IsRanchOwned(int playerId)
{
foreach (Ranch ranch in Ranches)
{
if (ranch.OwnerId == playerId)
{
return true;
}
}
return false;
}
public static Ranch GetRanchOwnedBy(int playerId)
{
foreach(Ranch ranch in Ranches)
{
if(ranch.OwnerId == playerId)
{
return ranch;
}
}
throw new KeyNotFoundException("Player " + playerId + " does not own a ranch.");
}
}
}

View file

@ -0,0 +1,83 @@
using HISP.Player;
using HISP.Server;
using System.Collections.Generic;
namespace HISP.Game
{
public class Riddler
{
private static List<Riddler> riddlerRiddles = new List<Riddler>();
public static Riddler[] Riddles
{
get
{
return riddlerRiddles.ToArray();
}
}
public Riddler(int id, string riddle, string[] answers, string reason)
{
Id = id;
Riddle = riddle;
Answers = answers;
Reason = reason;
riddlerRiddles.Add(this);
}
public int Id;
public string Riddle;
public string[] Answers;
public string Reason;
public void AnswerSuccess(User user)
{
if (!Database.HasPlayerCompletedRiddle(this.Id, user.Id))
Database.CompleteRiddle(this.Id, user.Id);
byte[] riddleAnswerCorrectPacket = PacketBuilder.CreateChat(Messages.FormatRiddlerAnswerCorrect(this.Reason), PacketBuilder.CHAT_BOTTOM_RIGHT);
user.LoggedinClient.SendPacket(riddleAnswerCorrectPacket);
user.AddMoney(10000);
if(HasCompletedAllRiddles(user))
user.Awards.AddAward(Award.GetAwardById(11)); // Riddlers Riddles
}
public void AnswerFail(User user)
{
byte[] riddleIncorrect = PacketBuilder.CreateChat(Messages.RiddlerIncorrectAnswer, PacketBuilder.CHAT_BOTTOM_RIGHT);
user.LoggedinClient.SendPacket(riddleIncorrect);
}
public bool CheckAnswer(User user, string txt)
{
foreach(string Answer in Answers)
{
if(Answer.ToLower() == txt.ToLower())
{
AnswerSuccess(user);
return true;
}
}
AnswerFail(user);
return false;
}
public static bool HasCompletedAllRiddles(User user)
{
if (Database.TotalRiddlesCompletedByPlayer(user.Id) >= Riddles.Length)
return true;
return false;
}
public static Riddler GetRandomRiddle(User user)
{
while(true)
{
int rng = GameServer.RandomNumberGenerator.Next(0, Riddles.Length);
if (Database.HasPlayerCompletedRiddle(Riddles[rng].Id, user.Id))
{
continue;
}
return Riddles[rng];
}
}
}
}

View file

@ -0,0 +1,354 @@
using HISP.Game.Horse;
using HISP.Player;
using HISP.Security;
using HISP.Server;
using System.Collections.Generic;
namespace HISP.Game.Services
{
public class Auction
{
public static List<Auction> AuctionRooms = new List<Auction>();
public Auction(int id)
{
RoomId = id;
AuctionEntries = new List<AuctionEntry>();
Database.LoadAuctionRoom(this, RoomId);
}
public class AuctionBid
{
public const int MAX_BID = 2000000000;
public User BidUser;
public AuctionEntry AuctionItem;
public int BidAmount;
public void PlaceBid(int bidAmount)
{
if(BidUser.HorseInventory.HorseList.Length >= BidUser.MaxHorses)
{
byte[] tooManyHorses = PacketBuilder.CreateChat(Messages.AuctionYouHaveTooManyHorses, PacketBuilder.CHAT_BOTTOM_RIGHT);
BidUser.LoggedinClient.SendPacket(tooManyHorses);
return;
}
string yourBidRaisedTo = Messages.FormatAuctionBidRaised(BidAmount, BidAmount + bidAmount);
if(BidAmount >= MAX_BID)
{
byte[] maxBidReached = PacketBuilder.CreateChat(Messages.AuctionBidMax, PacketBuilder.CHAT_BOTTOM_RIGHT);
BidUser.LoggedinClient.SendPacket(maxBidReached);
return;
}
if (BidAmount + bidAmount > BidUser.Money && (AuctionItem.OwnerId != BidUser.Id))
{
byte[] cantAffordBid = PacketBuilder.CreateChat(Messages.AuctionCantAffordBid, PacketBuilder.CHAT_BOTTOM_RIGHT);
BidUser.LoggedinClient.SendPacket(cantAffordBid);
return;
}
BidAmount += bidAmount;
if(BidAmount > MAX_BID) // no u
{
yourBidRaisedTo = Messages.FormatAuctionBidRaised(BidAmount, MAX_BID);
BidAmount = MAX_BID;
}
if (BidAmount > AuctionItem.HighestBid)
{
foreach(Auction room in AuctionRooms)
{
foreach(Auction.AuctionEntry entry in room.AuctionEntries)
{
if(entry.RandomId != AuctionItem.RandomId && entry.HighestBidder == BidUser.Id)
{
byte[] cantWinTooMuch = PacketBuilder.CreateChat(Messages.AuctionOnlyOneWinningBidAllowed, PacketBuilder.CHAT_BOTTOM_RIGHT);
BidUser.LoggedinClient.SendPacket(cantWinTooMuch);
return;
}
}
}
int oldBid = AuctionItem.HighestBid;
AuctionItem.HighestBid = BidAmount;
if(AuctionItem.HighestBidder != BidUser.Id && oldBid > 0)
{
if (GameServer.IsUserOnline(AuctionItem.HighestBidder))
{
User oldBidder = GameServer.GetUserById(AuctionItem.HighestBidder);
byte[] outbidMessage = PacketBuilder.CreateChat(Messages.FormatAuctionYourOutbidBy(BidUser.Username, AuctionItem.HighestBid), PacketBuilder.CHAT_BOTTOM_RIGHT);
oldBidder.LoggedinClient.SendPacket(outbidMessage);
}
}
AuctionItem.HighestBidder = BidUser.Id;
yourBidRaisedTo += Messages.AuctionTopBid;
}
else
{
yourBidRaisedTo += Messages.AuctionExistingBidHigher;
}
byte[] bidPlacedMsg = PacketBuilder.CreateChat(yourBidRaisedTo, PacketBuilder.CHAT_BOTTOM_RIGHT);
BidUser.LoggedinClient.SendPacket(bidPlacedMsg);
}
}
public class AuctionEntry
{
public AuctionEntry(int timeRemaining, int highestBid, int highestBidder, int randomId=-1)
{
RandomId = RandomID.NextRandomId(randomId);
this.timeRemaining = timeRemaining;
this.highestBid = highestBid;
this.highestBidder = highestBidder;
}
public HorseInstance Horse;
public int OwnerId;
public List<AuctionBid> Bidders = new List<AuctionBid>();
public bool Completed
{
get
{
return done;
}
set
{
done = value;
if(done)
{
Horse.Owner = highestBidder;
Horse.Hidden = false;
if(OwnerId == highestBidder)
{
if(GameServer.IsUserOnline(OwnerId))
{
User auctionRunner = GameServer.GetUserById(highestBidder);
auctionRunner.HorseInventory.UnHide(Horse.RandomId);
byte[] notSold = PacketBuilder.CreateChat(Messages.AuctionNoHorseBrought, PacketBuilder.CHAT_BOTTOM_RIGHT);
auctionRunner.LoggedinClient.SendPacket(notSold);
}
return;
}
if(GameServer.IsUserOnline(highestBidder))
{
User userWon = GameServer.GetUserById(highestBidder);
byte[] wonAuction = PacketBuilder.CreateChat(Messages.FormatAuctionBroughtHorse(highestBid), PacketBuilder.CHAT_BOTTOM_RIGHT);
userWon.LoggedinClient.SendPacket(wonAuction);
userWon.TakeMoney(highestBid);
userWon.HorseInventory.AddHorse(Horse, false);
}
else
{
Database.SetPlayerMoney(Database.GetPlayerMoney(highestBidder) - highestBid, highestBidder);
}
if(GameServer.IsUserOnline(OwnerId))
{
User userSold = GameServer.GetUserById(OwnerId);
byte[] horseSold = PacketBuilder.CreateChat(Messages.FormatAuctionHorseSold(highestBid), PacketBuilder.CHAT_BOTTOM_RIGHT);
userSold.LoggedinClient.SendPacket(horseSold);
userSold.AddMoney(highestBid);
userSold.HorseInventory.DeleteHorse(Horse, false);
}
else
{
Database.SetPlayerMoney(Database.GetPlayerMoney(OwnerId) + highestBid, OwnerId);
}
}
Database.SetAuctionDone(RandomId, done);
foreach(AuctionBid bid in Bidders) // Cleanup some stuffs
{
if(bid.BidUser != null)
bid.BidUser.Bids.Remove(bid);
}
Bidders.Clear();
}
}
public void Bid(User bidder, int bidAmount)
{
foreach(AuctionBid bid in bidder.Bids)
{
if (bid.AuctionItem.RandomId == this.RandomId)
{
bid.PlaceBid(bidAmount);
auctionRoomPlacedIn.UpdateAuctionRoom();
return;
}
}
AuctionBid newBid = new AuctionBid();
newBid.AuctionItem = this;
newBid.BidUser = bidder;
if (HighestBidder == bidder.Id)
newBid.BidAmount = HighestBid;
else
newBid.BidAmount = 0;
newBid.PlaceBid(bidAmount);
bidder.Bids.Add(newBid);
Bidders.Add(newBid);
auctionRoomPlacedIn.UpdateAuctionRoom();
}
public Auction auctionRoomPlacedIn;
public int RandomId;
private int timeRemaining;
private bool done;
private int highestBid;
private int highestBidder;
public int TimeRemaining
{
get
{
return timeRemaining;
}
set
{
timeRemaining = value;
Database.SetAuctionTimeout(RandomId, value);
}
}
public int HighestBid
{
get
{
return highestBid;
}
set
{
highestBid = value;
Database.SetAuctionHighestBid(RandomId, value);
}
}
public int HighestBidder
{
get
{
return highestBidder;
}
set
{
highestBidder = value;
Database.SetAuctionHighestBidder(RandomId, value);
}
}
}
public void UpdateAuctionRoom()
{
foreach (World.SpecialTile tile in World.SpecialTiles)
{
if (tile.Code != null)
{
if (tile.Code.StartsWith("AUCTION-"))
{
int id = int.Parse(tile.Code.Split('-')[1]);
if (id == this.RoomId)
{
GameServer.UpdateAreaForAll(tile.X, tile.Y);
}
}
}
}
}
public void DeleteEntry(AuctionEntry entry)
{
Database.DeleteAuctionRoom(entry.RandomId);
AuctionEntries.Remove(entry);
}
public void AddEntry(AuctionEntry entry)
{
entry.auctionRoomPlacedIn = this;
Database.AddAuctionRoom(entry, this.RoomId);
AuctionEntries.Add(entry);
}
public List<AuctionEntry> AuctionEntries;
public int RoomId;
public bool HasAuctionEntry(int randomId)
{
foreach (AuctionEntry entry in AuctionEntries)
{
if (entry.RandomId == randomId)
{
return true;
}
}
return false;
}
public AuctionEntry GetAuctionEntry(int randomId)
{
foreach(AuctionEntry entry in AuctionEntries)
{
if(entry.RandomId == randomId)
{
return entry;
}
}
throw new KeyNotFoundException("Auction Entry with RandomID: " + randomId + " NOT FOUND");
}
public bool HasUserPlacedAuctionAllready(User user)
{
foreach(AuctionEntry entry in AuctionEntries)
{
if (entry.OwnerId == user.Id)
return true;
}
return false;
}
public static Auction GetAuctionRoomById(int roomId)
{
foreach(Auction auction in AuctionRooms)
{
if(auction.RoomId == roomId)
{
return auction;
}
}
throw new KeyNotFoundException("Auction with roomID " + roomId + " NOT FOUND!");
}
public static void LoadAllAuctionRooms()
{
foreach(World.SpecialTile tile in World.SpecialTiles)
{
if(tile.Code != null)
{
if(tile.Code.StartsWith("AUCTION-"))
{
int code = int.Parse(tile.Code.Split('-')[1]);
Auction loadAuctionRoom = new Auction(code);
AuctionRooms.Add(loadAuctionRoom);
Logger.InfoPrint("Loading Auction Room: " + code.ToString());
}
}
}
}
}
}

View file

@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HISP.Game.Services
{
public class Barn
{
public Barn(int id, double tiredCost, double hungerCost, double thirstCost)
{
this.Id = id;
this.TiredCost = tiredCost;
this.HungerCost = hungerCost;
this.ThirstCost = thirstCost;
barns.Add(this);
}
private static List<Barn> barns = new List<Barn>();
public static Barn[] Barns
{
get
{
return barns.ToArray();
}
}
public int Id;
public double TiredCost;
public double HungerCost;
public double ThirstCost;
public int CalculatePrice(int tiredness, int hunger, int thirst)
{
double tiredPrice = (1000.0 - (double)tiredness) * TiredCost;
double hungerPrice = (1000.0 - (double)hunger) * HungerCost;
double thirstPrice = (1000.0 - (double)thirst) * ThirstCost;
return Convert.ToInt32(Math.Round(tiredPrice + hungerPrice + thirstPrice));
}
public static Barn GetBarnById(int id)
{
foreach (Barn barn in Barns)
if (barn.Id == id)
return barn;
throw new KeyNotFoundException("Barn id: " + id.ToString() + " Not found!");
}
}
}

View file

@ -0,0 +1,42 @@
using System.Collections.Generic;
namespace HISP.Game.Services
{
public class Farrier
{
private static List<Farrier> farriers = new List<Farrier>();
public static Farrier[] Farriers
{
get
{
return farriers.ToArray();
}
}
public int Id;
public int SteelShoesAmount;
public int SteelCost;
public int IronShoesAmount;
public int IronCost;
public Farrier(int id, int steelShoesInc, int steelCost, int ironShoesInc, int ironCost)
{
this.Id = id;
this.SteelShoesAmount = steelShoesInc;
this.SteelCost = steelCost;
this.IronShoesAmount = ironShoesInc;
this.IronCost = ironCost;
farriers.Add(this);
}
public static Farrier GetFarrierById(int id)
{
foreach (Farrier farrier in Farriers)
if (farrier.Id == id)
return farrier;
throw new KeyNotFoundException("No farrier with id: " + id + " found.");
}
}
}

View file

@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
namespace HISP.Game.Services
{
public class Groomer
{
public static List<Groomer> Groomers = new List<Groomer>();
public Groomer(int id, double price, int max)
{
Id = id;
PriceMultiplier = price;
Max = max;
Groomers.Add(this);
}
public int Id;
public double PriceMultiplier;
public int Max;
public int CalculatePrice(int groom)
{
double price = ((double)Max - (double)groom) * PriceMultiplier;
return Convert.ToInt32(Math.Round(price));
}
public static Groomer GetGroomerById(int id)
{
foreach (Groomer groomer in Groomers)
{
if (id == groomer.Id)
return groomer;
}
throw new KeyNotFoundException("Groomer with id: " + id + " Not found.");
}
}
}

View file

@ -0,0 +1,86 @@
using HISP.Player;
using HISP.Game.Items;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HISP.Game.Services
{
public class Inn
{
private static List<Inn> listInns = new List<Inn>();
public static Inn[] Inns
{
get
{
return listInns.ToArray();
}
}
public int Id;
public Item.ItemInformation[] RestsOffered;
public Item.ItemInformation[] MealsOffered;
public int BuyPercentage;
public int CalculateBuyCost(Item.ItemInformation item)
{
return (int)Math.Floor((float)item.SellPrice * (100.0 / (float)BuyPercentage));
}
public Item.ItemInformation GetStockedItem(int itemId)
{
// Check if inn stock..
foreach(Item.ItemInformation offering in RestsOffered)
{
if (offering.Id == itemId)
return offering;
}
foreach (Item.ItemInformation offering in MealsOffered)
{
if (offering.Id == itemId)
return offering;
}
throw new KeyNotFoundException("Item is not stocked by this inn.");
}
public Inn(int id, int[] restsOffered, int[] mealsOffered, int buyPercentage)
{
Id = id;
List<Item.ItemInformation> itemInfos = new List<Item.ItemInformation>();
foreach(int itemId in restsOffered)
{
itemInfos.Add(Item.GetItemById(itemId));
}
RestsOffered = itemInfos.ToArray();
itemInfos.Clear();
foreach (int itemId in mealsOffered)
{
itemInfos.Add(Item.GetItemById(itemId));
}
MealsOffered = itemInfos.ToArray();
itemInfos.Clear();
itemInfos = null;
BuyPercentage = buyPercentage;
listInns.Add(this);
}
public static Inn GetInnById(int id)
{
foreach (Inn inn in Inns)
if (inn.Id == id)
return inn;
throw new KeyNotFoundException("Inn " + id + " doesnt exist.");
}
}
}

View file

@ -0,0 +1,57 @@
using HISP.Game.Horse;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HISP.Game.Services
{
public class Pawneer
{
public Pawneer(int breedId, int basePrice)
{
BreedId = breedId;
BasePrice = basePrice;
}
public static List<Pawneer> PawneerPriceModels = new List<Pawneer>();
public int BreedId;
public int BasePrice;
public static int GetPawneerBasePriceForHorse(HorseInfo.Breed breed)
{
foreach (Pawneer ppm in PawneerPriceModels)
{
if (ppm.BreedId == breed.Id)
{
return ppm.BasePrice;
}
}
throw new Exception("No pawneeer base price found >_> for breed #" + breed.Id + " " + breed.Name);
}
public static int CalculateTotalPrice(HorseInstance horse)
{
HorseInfo.StatCalculator speedStat = new HorseInfo.StatCalculator(horse, HorseInfo.StatType.SPEED);
HorseInfo.StatCalculator strengthStat = new HorseInfo.StatCalculator(horse, HorseInfo.StatType.STRENGTH);
HorseInfo.StatCalculator conformationStat = new HorseInfo.StatCalculator(horse, HorseInfo.StatType.CONFORMATION);
HorseInfo.StatCalculator agilityStat = new HorseInfo.StatCalculator(horse, HorseInfo.StatType.AGILITY);
HorseInfo.StatCalculator enduranceStat = new HorseInfo.StatCalculator(horse, HorseInfo.StatType.ENDURANCE);
int basePrice = GetPawneerBasePriceForHorse(horse.Breed);
int additionalPrice = speedStat.BreedOffset * 350;
additionalPrice += strengthStat.BreedOffset * 350;
additionalPrice += conformationStat.BreedOffset * 350;
additionalPrice += agilityStat.BreedOffset * 350;
additionalPrice += enduranceStat.BreedOffset * 350;
additionalPrice += horse.BasicStats.Health * 40;
additionalPrice += horse.BasicStats.Shoes * 20;
int price = basePrice + additionalPrice;
return price;
}
}
}

View file

@ -0,0 +1,65 @@
using HISP.Game.Inventory;
using HISP.Server;
using HISP.Game.Items;
using System;
using System.Collections.Generic;
namespace HISP.Game.Services
{
public class Shop
{
public int Id;
public string[] BuysItemTypes;
public int BuyPricePercentage;
public int SellPricePercentage;
public ShopInventory Inventory;
public Shop(int[] infiniteStocks)
{
this.Inventory = new ShopInventory(this);
foreach(int stock in infiniteStocks)
{
if (Item.ItemIdExist(stock))
this.Inventory.AddInfinity(Item.GetItemById(stock));
else
Logger.WarnPrint("Item ID: " + stock + " Does not exist.");
}
Shop.ShopList.Add(this);
}
public int CalculateBuyCost(Item.ItemInformation item)
{
return (int)Math.Round((float)item.SellPrice * (100.0 / (float)BuyPricePercentage));
}
public int CalculateSellCost(Item.ItemInformation item)
{
return (int)Math.Round((float)item.SellPrice * (100.0 / (float)SellPricePercentage));
}
public bool CanSell(Item.ItemInformation item)
{
foreach(string ItemType in BuysItemTypes)
{
if(ItemType == item.Type)
{
return true;
}
}
return false;
}
// Static Functions
public static List<Shop> ShopList = new List<Shop>();
public static Shop GetShopById(int id)
{
foreach(Shop shop in ShopList)
{
if (shop.Id == id)
return shop;
}
throw new KeyNotFoundException("no shop with id: " + id + " found.");
}
}
}

View file

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HISP.Game.Services
{
public class Trainer
{
public static List<Trainer> Trainers = new List<Trainer>();
public int Id;
public string ImprovesStat;
public int ImprovesAmount;
public int ThirstCost;
public int MoodCost;
public int HungerCost;
public int MoneyCost;
public int ExperienceGained;
public static Trainer GetTrainerById(int id)
{
foreach (Trainer trainer in Trainers)
if (trainer.Id == id)
return trainer;
throw new KeyNotFoundException("Trainer " + id + " not found");
}
}
}

View file

@ -0,0 +1,53 @@
using System.Collections.Generic;
namespace HISP.Game.Services
{
public class Transport
{
public struct TransportLocation
{
public int Id;
public int Cost;
public int GotoX;
public int GotoY;
public string Type;
public string LocationTitle;
}
public struct TransportPoint
{
public int X;
public int Y;
public int[] Locations;
}
public static List<TransportPoint> TransportPoints = new List<TransportPoint>();
public static List<TransportLocation> TransportLocations = new List<TransportLocation>();
public static TransportPoint GetTransportPoint(int x, int y)
{
foreach(TransportPoint transportPoint in TransportPoints)
{
if (transportPoint.X == x && transportPoint.Y == y)
{
return transportPoint;
}
}
throw new KeyNotFoundException("Cannot find transport point at x:" + x + "y:" + y);
}
public static TransportLocation GetTransportLocation(int id)
{
foreach (TransportLocation transportLocation in TransportLocations)
{
if (transportLocation.Id == id)
{
return transportLocation;
}
}
throw new KeyNotFoundException("Cannot find transport location at Id:" + id);
}
}
}

View file

@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HISP.Game.Services
{
public class Vet
{
public static List<Vet> Vets = new List<Vet>();
public Vet(int id, double price)
{
Id = id;
PriceMultiplier = price;
Vets.Add(this);
}
public int Id;
public double PriceMultiplier;
public int CalculatePrice(int health)
{
double price = (1000.0 - (double)health) * PriceMultiplier;
return Convert.ToInt32(Math.Round(price));
}
public static Vet GetVetById(int id)
{
foreach(Vet vet in Vets)
{
if (id == vet.Id)
return vet;
}
throw new KeyNotFoundException("Vet with id: " + id + " Not found.");
}
}
}

View file

@ -0,0 +1,75 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HISP.Game.Services
{
public class Workshop
{
public Workshop()
{
CraftableItems = new List<CraftableItem>();
}
public class RequiredItem
{
public int RequiredItemId;
public int RequiredItemCount;
}
public class CraftableItem
{
public CraftableItem()
{
RequiredItems = new List<RequiredItem>();
}
public int Id;
public int GiveItemId;
public int MoneyCost;
public List<RequiredItem> RequiredItems;
}
public int X;
public int Y;
public List<CraftableItem> CraftableItems;
public static List<Workshop> Workshops = new List<Workshop>();
public static Workshop GetWorkshopAt(int x, int y)
{
foreach(Workshop wkShop in Workshops)
{
if(wkShop.X == x && wkShop.Y == y)
{
return wkShop;
}
}
throw new KeyNotFoundException("No workshop found.");
}
public static bool CraftIdExists(int id)
{
try
{
GetCraftId(id);
return true;
}
catch(KeyNotFoundException)
{
return false;
}
}
public static CraftableItem GetCraftId(int id)
{
foreach(Workshop wkShop in Workshops)
{
foreach(CraftableItem crftItem in wkShop.CraftableItems)
{
if (crftItem.Id == id)
return crftItem;
}
}
throw new KeyNotFoundException("No craft id " + id + " was found.");
}
}
}

View file

@ -0,0 +1,161 @@
using HISP.Server;
using System.Collections.Generic;
namespace HISP.Game.SwfModules
{
public class Brickpoet
{
public struct PoetryEntry {
public int Id;
public string Word;
public int Room;
}
public class PoetryPeice
{
public PoetryPeice(int PoetId, int RoomId, string PeiceWord)
{
if(!Database.GetPoetExist(PoetId, RoomId))
{
Id = PoetId;
x = GameServer.RandomNumberGenerator.Next(0, 365);
y = GameServer.RandomNumberGenerator.Next(0, 280);
Word = PeiceWord;
roomId = RoomId;
Database.AddPoetWord(PoetId, x, y, RoomId);
}
else
{
Id = PoetId;
roomId = RoomId;
Word = PeiceWord;
x = Database.GetPoetPositionX(Id, roomId);
y = Database.GetPoetPositionY(Id, roomId);
}
}
public int Id;
public int RoomId
{
get
{
return roomId;
}
}
public int X
{
get
{
return x;
}
set
{
Database.SetPoetPosition(Id, value, y, roomId);
x = value;
}
}
public int Y
{
get
{
return y;
}
set
{
Database.SetPoetPosition(Id, x, value, roomId);
y = value;
}
}
public string Word;
private int x;
private int y;
private int roomId;
}
public static List<PoetryEntry> PoetList = new List<PoetryEntry>();
private static List<PoetryPeice[]> poetryRooms = new List<PoetryPeice[]>();
public static PoetryPeice[][] PoetryRooms
{
get
{
return poetryRooms.ToArray();
}
}
private static PoetryEntry[] getPoetsInRoom(int roomId)
{
List<PoetryEntry> entries = new List<PoetryEntry>();
foreach(PoetryEntry poet in PoetList.ToArray())
{
if(poet.Room == roomId)
{
entries.Add(poet);
}
}
return entries.ToArray();
}
private static PoetryPeice[] getPoetryRoom(int roomId)
{
PoetryEntry[] poetryEntries = getPoetsInRoom(roomId);
List<PoetryPeice> peices = new List<PoetryPeice>();
foreach (PoetryEntry poetryEntry in poetryEntries)
{
PoetryPeice peice = new PoetryPeice(poetryEntry.Id, roomId, poetryEntry.Word);
peices.Add(peice);
}
return peices.ToArray();
}
public static PoetryPeice[] GetPoetryRoom(int roomId)
{
foreach(PoetryPeice[] peices in PoetryRooms)
{
if (peices[0].RoomId == roomId)
return peices;
}
throw new KeyNotFoundException("No poetry room of id: " + roomId + " exists.");
}
public static PoetryPeice GetPoetryPeice(PoetryPeice[] room, int id)
{
foreach(PoetryPeice peice in room)
{
if (peice.Id == id)
return peice;
}
throw new KeyNotFoundException("Peice with id: " + id + " not found in room.");
}
public static void LoadPoetryRooms()
{
List<int> rooms = new List<int>();
foreach(PoetryEntry entry in PoetList)
{
if (!rooms.Contains(entry.Room))
rooms.Add(entry.Room);
}
foreach(int room in rooms)
{
Logger.InfoPrint("Loading poetry room: " + room.ToString());
poetryRooms.Add(getPoetryRoom(room));
if (!Database.LastPlayerExist("P" + room))
Database.AddLastPlayer("P" + room, -1);
}
}
}
}

View file

@ -0,0 +1,84 @@
using HISP.Server;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HISP.Game.SwfModules
{
class Drawingroom
{
private static List<Drawingroom> drawingRooms = new List<Drawingroom>();
public static Drawingroom[] DrawingRooms
{
get
{
return drawingRooms.ToArray();
}
}
private string drawing;
public string Drawing
{
get
{
return drawing;
}
set
{
if(value.Length < 65535)
{
Database.SetDrawingRoomDrawing(Id, value);
drawing = value;
}
else
{
throw new DrawingroomFullException();
}
}
}
public int Id;
public Drawingroom(int roomId)
{
if (!Database.DrawingRoomExists(roomId))
{
Database.CreateDrawingRoom(roomId);
Database.SetLastPlayer("D" + roomId.ToString(), -1);
}
drawing = Database.GetDrawingRoomDrawing(roomId);
Id = roomId;
drawingRooms.Add(this);
}
public static void LoadAllDrawingRooms()
{
// iterate over every special tile
foreach(World.SpecialTile tile in World.SpecialTiles)
{
if(tile.Code != null)
{
if (tile.Code.StartsWith("MULTIROOM-D"))
{
int roomId = int.Parse(tile.Code.Substring(11));
Logger.InfoPrint("Loading Drawing Room ID: " + roomId.ToString());
Drawingroom room = new Drawingroom(roomId);
}
}
}
}
public static Drawingroom GetDrawingRoomById(int id)
{
foreach(Drawingroom room in DrawingRooms)
{
if (room.Id == id)
return room;
}
throw new KeyNotFoundException("Room with id: " + id + " not found.");
}
}
}

View file

@ -0,0 +1,119 @@
using HISP.Server;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HISP.Game.SwfModules
{
public class Dressup
{
public static List<DressupRoom> DressupRooms = new List<DressupRoom>();
public class DressupRoom
{
public DressupRoom(int roomId)
{
RoomId = roomId;
DressupPeices = new List<DressupPeice>();
DressupPeice[] peices = Database.LoadDressupRoom(this);
foreach (DressupPeice peice in peices)
DressupPeices.Add(peice);
DressupRooms.Add(this);
}
public int RoomId;
public List<DressupPeice> DressupPeices;
public DressupPeice GetDressupPeice(int peiceId)
{
foreach(DressupPeice peice in DressupPeices)
{
if (peice.PeiceId == peiceId)
return peice;
}
// Else create peice
DressupPeice dPeice = new DressupPeice(this, peiceId, 0, 0, false, true);
DressupPeices.Add(dPeice);
return dPeice;
}
}
public class DressupPeice
{
public DressupPeice(DressupRoom room,int peiceId, int x, int y, bool active, bool createNew)
{
this.baseRoom = room;
this.PeiceId = peiceId;
this.x = x;
this.y = y;
this.active = active;
if (createNew)
Database.CreateDressupRoomPeice(room.RoomId, peiceId, active, x, y);
}
public DressupRoom baseRoom;
public int PeiceId;
public int X
{
get
{
return x;
}
set
{
Database.SetDressupRoomPeiceX(baseRoom.RoomId, PeiceId, value);
x = value;
}
}
public int Y
{
get
{
return y;
}
set
{
Database.SetDressupRoomPeiceY(baseRoom.RoomId, PeiceId, value);
y = value;
}
}
public bool Active
{
get
{
return active;
}
set
{
Database.SetDressupRoomPeiceActive(baseRoom.RoomId, PeiceId, value);
active = value;
}
}
private int x;
private int y;
private bool active;
}
public static DressupRoom GetDressupRoom(int roomId)
{
foreach(DressupRoom sRoom in DressupRooms)
{
if (sRoom.RoomId == roomId)
return sRoom;
}
// Else create room
DressupRoom room = new DressupRoom(roomId);
return room;
}
}
}

View file

@ -0,0 +1,117 @@
using HISP.Player;
using HISP.Server;
using System.Collections.Generic;
namespace HISP.Game
{
public class Tracking
{
public enum TrackableItem
{
PirateTreasure,
Transport,
HorseCapture,
Crafting,
WishingWell,
Training,
ArenaLoss,
Trading,
HorseLease,
AutoSells,
PegasusTeamup,
TackShopGiveaway,
QuizWin,
RiddleWin,
IsleCardsGameWin,
HorsePawn,
WaterbaloonGameWin,
UnicornTeamup,
PotOfGold,
GameUpdates,
UnipegTeamup
}
public class TrackedItem
{
public TrackedItem(User sbaseUser, TrackableItem what, int itmcount)
{
What = what;
count = itmcount;
baseUser = sbaseUser;
}
public TrackableItem What;
public int Count
{
get
{
return count;
}
set
{
Database.SetTrackedItemCount(baseUser.Id, What, value);
count = value;
}
}
private int count;
private User baseUser;
}
private List<TrackedItem> trackingItems = new List<TrackedItem>();
private User baseUser;
public TrackedItem[] TrackingItems
{
get
{
return trackingItems.ToArray();
}
}
public Tracking(User user)
{
baseUser = user;
for(int i = 0; i < 20; i++)
{
TrackableItem item = (TrackableItem)i;
if(Database.HasTrackedItem(user.Id, item))
{
TrackedItem trackedItem = new TrackedItem(baseUser, item, Database.GetTrackedCount(user.Id, item));
trackingItems.Add(trackedItem);
}
}
}
public TrackedItem GetTrackedItem(TrackableItem what)
{
foreach(TrackedItem trackedItem in TrackingItems)
{
if (trackedItem.What == what)
return trackedItem;
}
// if it doesnt exist- create it
TrackedItem item = new TrackedItem(baseUser, what, 0);
Database.AddTrackedItem(baseUser.Id, what, 0);
trackingItems.Add(item);
return item;
}
public struct TrackedItemStatsMenu
{
public string What;
public string Value;
}
public static List<TrackedItemStatsMenu> TrackedItemsStatsMenu = new List<TrackedItemStatsMenu>();
public static string GetTrackedItemsStatsMenuName(TrackableItem item)
{
foreach(TrackedItemStatsMenu trackedItem in TrackedItemsStatsMenu)
{
if (trackedItem.What == item.ToString())
return trackedItem.Value;
}
throw new KeyNotFoundException("no such tracked item found.");
}
}
}

View file

@ -0,0 +1,243 @@
using HISP.Player;
using HISP.Server;
using System.Collections.Generic;
namespace HISP.Game
{
public class Treasure
{
private static List<Treasure> treasures = new List<Treasure>();
public static Treasure[] Treasures
{
get
{
return treasures.ToArray();
}
}
private int value;
public int RandomId;
public int X;
public int Y;
public int Value
{
get
{
return value;
}
set
{
this.value = value;
Database.SetTreasureValue(RandomId, value);
}
}
public string Type;
public Treasure(int x, int y, string type, int randomId = -1, int moneyValue=-1)
{
RandomId = Security.RandomID.NextRandomId(randomId);
if(type == "BURIED")
{
if(moneyValue == -1)
value = GameServer.RandomNumberGenerator.Next(100,1500);
}
else if(type == "RAINBOW")
{
if (moneyValue == -1)
value = GameServer.RandomNumberGenerator.Next(10000, 30000);
}
if (moneyValue != -1)
value = moneyValue;
X = x;
Y = y;
Type = type;
}
public static int NumberOfPirates()
{
int count = 0;
foreach (Treasure treasure in Treasures)
{
if (treasure.Type == "BURIED")
count++;
}
return count;
}
public static int NumberOfRainbows()
{
int count = 0;
foreach(Treasure treasure in Treasures)
{
if (treasure.Type == "RAINBOW")
count++;
}
return count;
}
public static bool IsTileTreasure(int x, int y)
{
foreach (Treasure treasure in Treasures)
{
if (treasure.X == x && treasure.Y == y)
return true;
}
return false;
}
public static bool IsTileBuiredTreasure(int x, int y)
{
foreach (Treasure treasure in Treasures)
{
if (treasure.Type == "BURIED")
{
if (treasure.X == x && treasure.Y == y)
return true;
}
}
return false;
}
public static bool IsTilePotOfGold(int x, int y)
{
foreach(Treasure treasure in Treasures)
{
if(treasure.Type == "RAINBOW")
{
if (treasure.X == x && treasure.Y == y)
return true;
}
}
return false;
}
public static Treasure GetTreasureAt(int x, int y)
{
foreach (Treasure treasure in Treasures)
{
if (treasure.X == x && treasure.Y == y)
return treasure;
}
throw new KeyNotFoundException("NO Treasure at " + x + "," + y);
}
public static void AddValue()
{
foreach(Treasure treasure in treasures)
{
treasure.Value += 1;
}
}
public void CollectTreasure(User user)
{
treasures.Remove(this);
Database.DeleteTreasure(this.RandomId);
GenerateTreasure();
byte[] MovementPacket = PacketBuilder.CreateMovementPacket(user.X, user.Y, user.CharacterId, user.Facing, PacketBuilder.DIRECTION_TELEPORT, true);
user.LoggedinClient.SendPacket(MovementPacket);
user.AddMoney(Value);
if(this.Type == "BURIED")
{
byte[] treasureReceivedPacket = PacketBuilder.CreateChat(Messages.FormatPirateTreasure(this.Value), PacketBuilder.CHAT_BOTTOM_RIGHT);
user.LoggedinClient.SendPacket(treasureReceivedPacket);
user.TrackedItems.GetTrackedItem(Tracking.TrackableItem.PirateTreasure).Count++;
if(user.TrackedItems.GetTrackedItem(Tracking.TrackableItem.PirateTreasure).Count >= 10)
user.Awards.AddAward(Award.GetAwardById(18)); // Pirate Tracker
if (user.TrackedItems.GetTrackedItem(Tracking.TrackableItem.PirateTreasure).Count >= 100)
user.Awards.AddAward(Award.GetAwardById(19)); // Pirate Stalker
}
else if(this.Type == "RAINBOW")
{
byte[] treasureReceivedPacket = PacketBuilder.CreateChat(Messages.FormatPotOfGold(this.Value), PacketBuilder.CHAT_BOTTOM_RIGHT);
user.LoggedinClient.SendPacket(treasureReceivedPacket);
user.TrackedItems.GetTrackedItem(Tracking.TrackableItem.PotOfGold).Count++;
if (user.TrackedItems.GetTrackedItem(Tracking.TrackableItem.PotOfGold).Count >= 3)
user.Awards.AddAward(Award.GetAwardById(20)); // Leprechaun
if (user.TrackedItems.GetTrackedItem(Tracking.TrackableItem.PirateTreasure).Count >= 20)
user.Awards.AddAward(Award.GetAwardById(21)); // Lucky Leprechaun
}
}
public static void GenerateTreasure()
{
while(NumberOfPirates() < 5)
{
// Pick x/y
int tryX = GameServer.RandomNumberGenerator.Next(0, Map.Width);
int tryY = GameServer.RandomNumberGenerator.Next(0, Map.Height);
if (!Map.CheckPassable(tryX, tryY)) // can the player walk here?
continue;
if (World.InTown(tryX, tryY)) // in a town?
continue;
if (Map.GetTileId(tryX, tryY, true) != 1) // is there allready an overlay here?
continue;
if (Map.TerrainTiles[Map.GetTileId(tryX, tryY, false) - 1].Type != "BEACH")
continue;
// Create Treasure
Treasure treasure = new Treasure(tryX, tryY, "BURIED");
treasures.Add(treasure);
Database.AddTreasure(treasure.RandomId, treasure.X, treasure.Y, treasure.Value, treasure.Type);
Logger.DebugPrint("Created Pirate Treasure at " + treasure.X + "," + treasure.Y + " with value: " + treasure.Value);
}
while (NumberOfRainbows() < 1)
{
// Pick x/y
int tryX = GameServer.RandomNumberGenerator.Next(0, Map.Width);
int tryY = GameServer.RandomNumberGenerator.Next(0, Map.Height);
if (!Map.CheckPassable(tryX, tryY)) // can the player walk here?
continue;
if (World.InTown(tryX, tryY)) // in a town?
continue;
if (Map.GetTileId(tryX, tryY, true) != 1) // is there allready an overlay here?
continue;
if (Map.TerrainTiles[Map.GetTileId(tryX, tryY, false) - 1].Type != "GRASS" && Map.TerrainTiles[Map.GetTileId(tryX, tryY, false) - 1].Type != "BEACH") // Grass and BEACH tiles only.
continue;
// Create Treasure
Treasure treasure = new Treasure(tryX, tryY, "RAINBOW");
treasures.Add(treasure);
Database.AddTreasure(treasure.RandomId, treasure.X, treasure.Y, treasure.Value, treasure.Type);
Logger.DebugPrint("Created Pot of Gold at " + treasure.X + "," + treasure.Y + " with value: " + treasure.Value);
}
}
public static void Init()
{
Treasure[] treasuresLst = Database.GetTreasures();
foreach (Treasure treasure in treasuresLst)
{
treasures.Add(treasure);
}
GenerateTreasure();
}
}
}

View file

@ -0,0 +1,228 @@
using HISP.Player;
using HISP.Security;
using HISP.Server;
using System.Collections.Generic;
using System.Threading;
namespace HISP.Game
{
public class TwoPlayer
{
public static List<TwoPlayer> TwoPlayerGames = new List<TwoPlayer>();
public static void TwoPlayerRemove(User user)
{
foreach(TwoPlayer twoPlayerGame in TwoPlayerGames.ToArray())
{
if((twoPlayerGame.Invitee.Id == user.Id))
{
twoPlayerGame.CloseGame(user, true);
}
}
}
public static bool IsPlayerInvitingPlayer(User sender, User checkInvites)
{
foreach (TwoPlayer twoPlayerGame in TwoPlayerGames.ToArray())
{
if ((twoPlayerGame.Invitee.Id == sender.Id && twoPlayerGame.Inviting.Id == checkInvites.Id) && !twoPlayerGame.Accepted)
{
return true;
}
}
return false;
}
public static TwoPlayer GetGameInvitingPlayer(User sender, User checkInvites)
{
foreach (TwoPlayer twoPlayerGame in TwoPlayerGames.ToArray())
{
if ((twoPlayerGame.Invitee.Id == sender.Id && twoPlayerGame.Inviting.Id == checkInvites.Id) && !twoPlayerGame.Accepted)
{
return twoPlayerGame;
}
}
throw new KeyNotFoundException("not found.");
}
public static bool IsPlayerInGame(User user)
{
foreach (TwoPlayer twoPlayerGame in TwoPlayerGames.ToArray())
{
if ((twoPlayerGame.Invitee.Id == user.Id || twoPlayerGame.Inviting.Id == user.Id) && twoPlayerGame.Accepted)
{
return true;
}
}
return false;
}
public static TwoPlayer GetTwoPlayerGameInProgress(User user)
{
foreach (TwoPlayer twoPlayerGame in TwoPlayerGames.ToArray())
{
if ((twoPlayerGame.Invitee.Id == user.Id || twoPlayerGame.Inviting.Id == user.Id) && twoPlayerGame.Accepted)
{
return twoPlayerGame;
}
}
throw new KeyNotFoundException("No game found");
}
public TwoPlayer(User inviting, User invitee, bool accepted, int randomId=-1)
{
RandomId = RandomID.NextRandomId(randomId);
Inviting = inviting;
Invitee = invitee;
Accepted = accepted;
PosX = Invitee.X;
PosY = Invitee.Y;
byte[] youHaveInvited = PacketBuilder.CreateChat(Messages.Format2PlayerYouInvited(inviting.Username), PacketBuilder.CHAT_BOTTOM_RIGHT);
byte[] yourInvited = PacketBuilder.CreateChat(Messages.Format2PlayerYourInvited(invitee.Username), PacketBuilder.CHAT_BOTTOM_RIGHT);
Invitee.LoggedinClient.SendPacket(youHaveInvited);
Inviting.LoggedinClient.SendPacket(yourInvited);
deleteTimer = new Timer(new TimerCallback(deleteTwoPlayer), null, 2 * 60 * 1000, 2 * 60 * 1000);
TwoPlayerGames.Add(this);
update();
if (Multiroom.IsMultiRoomAt(PosX, PosY))
{
this.Multiroom = Multiroom.GetMultiroom(PosX, PosY);
}
}
private void deleteTwoPlayer(object state)
{
if (!Accepted)
{
Accepted = false;
Invitee.MetaPriority = false;
Inviting.MetaPriority = false;
update();
TwoPlayerGames.Remove(this);
}
deleteTimer.Dispose();
}
private void update()
{
GameServer.UpdateArea(Invitee.LoggedinClient);
GameServer.UpdateArea(Inviting.LoggedinClient);
}
private void updateOthers()
{
foreach(User user in this.Multiroom.JoinedUsers.ToArray())
if (IsPlayerInGame(user))
if(user.Id != Invitee.Id && user.Id != Inviting.Id)
GameServer.UpdateArea(user.LoggedinClient);
}
public void UpdateAll()
{
update();
updateOthers();
}
private string buildSwf(int playerNumb)
{
if(World.InSpecialTile(PosX, PosY))
{
World.SpecialTile tile = World.GetSpecialTile(PosX, PosY);
if(tile.Code != null)
{
if(tile.Code.StartsWith("2PLAYER-"))
{
string swf = tile.Code.Split('-')[1].ToLower();
if (!swf.Contains(".swf"))
swf += ".swf";
if (swf.Contains("?"))
swf += "&";
else
swf += "?";
swf += "playernum=" + playerNumb.ToString();
return swf;
}
}
}
return "test";
}
public int RandomId = 0;
public User Inviting = null;
public User Invitee = null;
public bool Accepted = false;
public Multiroom Multiroom;
public int PosX;
public int PosY;
private Timer deleteTimer;
public void Accept(User user)
{
if(user.Id == Inviting.Id)
{
Accepted = true;
deleteTimer.Dispose();
UpdateAll();
byte[] startingUpGameInvitee = PacketBuilder.CreateChat(Messages.Format2PlayerStartingGame(Inviting.Username), PacketBuilder.CHAT_BOTTOM_RIGHT);
byte[] startingUpGameInvited = PacketBuilder.CreateChat(Messages.Format2PlayerStartingGame(Invitee.Username), PacketBuilder.CHAT_BOTTOM_RIGHT);
Invitee.LoggedinClient.SendPacket(startingUpGameInvitee);
Inviting.LoggedinClient.SendPacket(startingUpGameInvited);
byte[] loadSwfInvitee = PacketBuilder.CreateSwfModulePacket(buildSwf(2), PacketBuilder.PACKET_SWF_MODULE_FORCE);
byte[] loadSwfInvited = PacketBuilder.CreateSwfModulePacket(buildSwf(1), PacketBuilder.PACKET_SWF_MODULE_FORCE);
Invitee.LoggedinClient.SendPacket(loadSwfInvitee);
Inviting.LoggedinClient.SendPacket(loadSwfInvited);
}
}
public void CloseGame(User userWhoClosed, bool closeSilently=false)
{
if(userWhoClosed.Id == Inviting.Id || userWhoClosed.Id == Invitee.Id && Accepted)
{
Accepted = false;
if(!closeSilently)
{
byte[] gameClosedByOther = PacketBuilder.CreateChat(Messages.TwoPlayerGameClosedOther, PacketBuilder.CHAT_BOTTOM_RIGHT);
byte[] gameClosed = PacketBuilder.CreateChat(Messages.TwoPlayerGameClosed, PacketBuilder.CHAT_BOTTOM_RIGHT);
if (userWhoClosed.Id == Inviting.Id)
{
Invitee.LoggedinClient.SendPacket(gameClosedByOther);
Inviting.LoggedinClient.SendPacket(gameClosed);
}
else if (userWhoClosed.Id == Invitee.Id)
{
Invitee.LoggedinClient.SendPacket(gameClosed);
Inviting.LoggedinClient.SendPacket(gameClosedByOther);
}
}
Invitee.MetaPriority = false;
Inviting.MetaPriority = false;
if (!closeSilently)
UpdateAll();
else
updateOthers();
TwoPlayerGames.Remove(this);
}
}
}
}

View file

@ -0,0 +1,388 @@
using System;
using System.Collections.Generic;
using HISP.Player;
using HISP.Server;
namespace HISP.Game
{
public class World
{
private static Waypoint getWaypoint(string find)
{
foreach(Waypoint waypoint in Waypoints)
{
if(waypoint.Name == find)
return waypoint;
}
throw new KeyNotFoundException("Waypoint with name "+find+" not found.");
}
public struct Waypoint
{
public string Name;
public int PosX;
public int PosY;
public string Type;
public string Description;
public string[] WeatherTypesAvalible;
}
public class Isle
{
public int StartX;
public int EndX;
public int StartY;
public int EndY;
public int Tileset;
public string Name;
public string SelectRandomWeather()
{
Waypoint point;
try
{
point = GetWaypoint();
}
catch (KeyNotFoundException)
{
return "SUNNY";
}
int intWeatherType = GameServer.RandomNumberGenerator.Next(0, point.WeatherTypesAvalible.Length);
string weather = point.WeatherTypesAvalible[intWeatherType];
return weather;
}
public string Weather
{
get
{
if (!Database.WeatherExists(Name))
{
string weather = SelectRandomWeather();
Database.InsertWeather(Name, weather);
return weather;
}
else
{
return Database.GetWeather(Name);
}
}
set
{
Database.SetWeather(Name, value);
foreach(User user in GameServer.GetUsersInIsle(this,true,true))
{
GameServer.UpdateWorld(user.LoggedinClient);
}
}
}
public Waypoint GetWaypoint()
{
return getWaypoint(this.Name);
}
}
public class Town
{
public int StartX;
public int EndX;
public int StartY;
public int EndY;
public string Name;
public string SelectRandomWeather()
{
Waypoint point;
try
{
point = GetWaypoint();
}
catch (KeyNotFoundException)
{
return "SUNNY";
}
int intWeatherType = GameServer.RandomNumberGenerator.Next(0, point.WeatherTypesAvalible.Length);
string weather = point.WeatherTypesAvalible[intWeatherType];
return weather;
}
public string Weather
{
get
{
if (!Database.WeatherExists(Name))
{
string weather = SelectRandomWeather();
Database.InsertWeather(Name, weather);
return weather;
}
else
{
return Database.GetWeather(Name);
}
}
set
{
Database.SetWeather(Name, value);
foreach (User user in GameServer.GetUsersInTown(this, true, true))
{
GameServer.UpdateArea(user.LoggedinClient);
}
}
}
public Waypoint GetWaypoint()
{
return getWaypoint(this.Name);
}
}
public struct Area
{
public int StartX;
public int EndX;
public int StartY;
public int EndY;
public string Name;
}
public struct Zone
{
public int StartX;
public int EndX;
public int StartY;
public int EndY;
public string Name;
}
public class Time
{
public double PreciseMinutes;
public int Minutes
{
get
{
return Convert.ToInt32(Math.Floor(PreciseMinutes));
}
}
public int Days;
public int Years;
}
public struct SpecialTile
{
public int X;
public int Y;
public string Title;
public string Description;
public string Code;
public int ExitX;
public int ExitY;
public string AutoplaySwf;
public string TypeFlag;
}
public static Time ServerTime = new Time();
public static int StartDate;
public static List<Waypoint> Waypoints = new List<Waypoint>();
public static List<Isle> Isles = new List<Isle>();
public static List<Town> Towns = new List<Town>();
public static List<Area> Areas = new List<Area>();
public static List<Zone> Zones = new List<Zone>();
public static List<SpecialTile> SpecialTiles = new List<SpecialTile>();
public static void TickWorldClock()
{
ServerTime.PreciseMinutes += 0.1;
if (ServerTime.Minutes > 1440) // 1 day
{
ServerTime.Days += 1;
ServerTime.PreciseMinutes = 0.0;
Database.DoIntrestPayments(ConfigReader.IntrestRate);
}
if (ServerTime.Days > 365) // 1 year!
{
ServerTime.Days = 0;
ServerTime.Years += 1;
}
}
public static void ReadWorldData()
{
Logger.DebugPrint("Reading time from database...");
ServerTime.PreciseMinutes = Database.GetServerTime();
ServerTime.Days = Database.GetServerDay();
ServerTime.Years = Database.GetServerYear();
StartDate = Database.GetServerStartTime();
Logger.InfoPrint("It is " + ServerTime.Minutes / 60 + ":" + ServerTime.Minutes % 60 + " on Day " + ServerTime.Days + " in Year " + ServerTime.Years + "!!!");
}
public static bool InZone(int x, int y)
{
try
{
GetZone(x, y);
return true;
}
catch (KeyNotFoundException)
{
return false;
}
}
public static bool InArea(int x, int y)
{
try
{
GetArea(x, y);
return true;
}
catch (KeyNotFoundException)
{
return false;
}
}
public static bool InTown(int x, int y)
{
try
{
GetTown(x, y);
return true;
}
catch (KeyNotFoundException)
{
return false;
}
}
public static bool InSpecialTile(int x, int y)
{
try
{
GetSpecialTile(x, y);
return true;
}
catch (KeyNotFoundException)
{
return false;
}
}
public static bool InIsle(int x, int y)
{
try
{
GetIsle(x, y);
return true;
}
catch(KeyNotFoundException)
{
return false;
}
}
public static Zone GetZoneByName(string name)
{
foreach(Zone zone in Zones)
{
if (zone.Name == name)
return zone;
}
throw new KeyNotFoundException("Zone not found.");
}
public static SpecialTile[] GetSpecialTilesByName(string name)
{
List<SpecialTile> tiles = new List<SpecialTile>();
foreach(SpecialTile tile in SpecialTiles)
{
if(tile.Title == name)
{
tiles.Add(tile);
}
}
return tiles.ToArray();
}
public static SpecialTile GetSpecialTile(int x, int y)
{
foreach(SpecialTile specialTile in SpecialTiles)
{
if(specialTile.X == x && specialTile.Y == y)
{
return specialTile;
}
}
throw new KeyNotFoundException("x,y not in a special tile!");
}
public static Isle GetIsle(int x, int y)
{
foreach(Isle isle in Isles)
{
if (isle.StartX <= x && isle.EndX >= x && isle.StartY <= y && isle.EndY >= y)
{
return isle;
}
}
throw new KeyNotFoundException("x,y not in an isle!");
}
public static Zone GetZone(int x, int y)
{
foreach (Zone zone in Zones)
{
if (zone.StartX <= x && zone.EndX >= x && zone.StartY <= y && zone.EndY >= y)
{
return zone;
}
}
throw new KeyNotFoundException("x,y not in an zone!");
}
public static Area GetArea(int x, int y)
{
foreach (Area area in Areas)
{
if (area.StartX <= x && area.EndX >= x && area.StartY <= y && area.EndY >= y)
{
return area;
}
}
throw new KeyNotFoundException("x,y not in an area!");
}
public static Town GetTown(int x, int y)
{
foreach (Town town in Towns)
{
if (town.StartX <= x && town.EndX >= x && town.StartY <= y && town.EndY >= y)
{
return town;
}
}
throw new KeyNotFoundException("x,y not in a town!");
}
public static bool CanDropItems(int x, int y)
{
if (World.InSpecialTile(x, y))
{
World.SpecialTile tile = World.GetSpecialTile(x, y);
if (tile.Code != null)
return false;
}
return true;
}
}
}

View file

@ -0,0 +1,86 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<RootNamespace>HISP</RootNamespace>
<LangVersion>8.0</LangVersion>
<Platforms>x64;x86;ARM;ARM64;AnyCPU</Platforms>
<Configurations>Windows;Debug;Linux;MacOS</Configurations>
</PropertyGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<Content Include="icon.ico" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="MySqlConnector" Version="1.3.10" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
</ItemGroup>
<PropertyGroup>
<PostBuildEvent Condition="'$(OS)' == 'Windows_NT'">
copy "$(SolutionDir)..\DataCollection\gamedata.json" "$(TargetDir)gamedata.json" /Y
copy "$(SolutionDir)..\DataCollection\HI1.MAP" "$(TargetDir)HI1.MAP" /Y
</PostBuildEvent>
<PostBuildEvent Condition="'$(OS)' != 'Windows_NT'">
cp -f "$(MSBuildThisFileDirectory)../../DataCollection/gamedata.json" "$(TargetDir)gamedata.json"
cp -f "$(MSBuildThisFileDirectory)../../DataCollection/HI1.MAP" "$(TargetDir)HI1.MAP"
</PostBuildEvent>
</PropertyGroup>
<PropertyGroup>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<NoWin32Manifest>true</NoWin32Manifest>
<ApplicationIcon>icon.ico</ApplicationIcon>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Windows|x86'">
<ApplicationIcon>icon.ico</ApplicationIcon>
<TargetFramework>net5.0</TargetFramework>
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
<Optimize>true</Optimize>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Windows|x64'">
<ApplicationIcon>icon.ico</ApplicationIcon>
<TargetFramework>net5.0</TargetFramework>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<Optimize>true</Optimize>
<PlatformTarget>x64</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Linux|x64'">
<TargetFramework>net5.0</TargetFramework>
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
<Optimize>true</Optimize>
<PlatformTarget>x64</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='MacOS|x64'">
<TargetFramework>net5.0</TargetFramework>
<RuntimeIdentifier>osx-x64</RuntimeIdentifier>
<Optimize>true</Optimize>
<PlatformTarget>x64</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Linux|ARM'">
<TargetFramework>net5.0</TargetFramework>
<RuntimeIdentifier>linux-arm</RuntimeIdentifier>
<Optimize>true</Optimize>
<PlatformTarget>ARM</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Linux|ARM64'">
<TargetFramework>net5.0</TargetFramework>
<RuntimeIdentifier>linux-arm64</RuntimeIdentifier>
<Optimize>true</Optimize>
<PlatformTarget>ARM64</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='All|Any CPU'">
<TargetFramework>net5.0</TargetFramework>
<RuntimeIdentifiers>win-x86;win-x64;win-arm;win-arm64;linux-x64;linux-arm;linux-arm64;osx-x64</RuntimeIdentifiers>
<Optimize>true</Optimize>
</PropertyGroup>
</Project>

View file

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ActiveDebugProfile>HorseIsleServer</ActiveDebugProfile>
<_LastSelectedProfileId>C:\Users\SilicaAndPina\Documents\HISP\HorseIsleServer\HorseIsleServer\Properties\PublishProfiles\FolderProfile.pubxml</_LastSelectedProfileId>
</PropertyGroup>
</Project>

View file

@ -0,0 +1,97 @@
using HISP.Server;
using System;
using System.Collections.Generic;
namespace HISP.Player
{
public class Award
{
public struct AwardEntry
{
public int Id;
public int Sort;
public string Title;
public int IconId;
public int MoneyBonus;
public string CompletionText;
public string Description;
}
public static AwardEntry[] GlobalAwardList;
public static AwardEntry GetAwardById(int id)
{
try
{
AwardEntry award = GlobalAwardList[id - 1];
if (award.Id == id)
return award;
}
catch (Exception) { };
foreach(AwardEntry award in GlobalAwardList)
{
if (award.Id == id)
return award;
}
throw new KeyNotFoundException("Award ID " + id + " Does not exist.");
}
private List<AwardEntry> awardsEarned;
private User baseUser;
public AwardEntry[] AwardsEarned
{
get
{
return awardsEarned.ToArray();
}
}
public bool HasAward(AwardEntry award)
{
foreach(AwardEntry awardEntry in AwardsEarned)
{
if (awardEntry.Id == award.Id)
return true;
}
return false;
}
public void AddAward(AwardEntry award,bool addToDatabase=true)
{
if (HasAward(award))
return;
if (addToDatabase)
{
Database.AddAward(baseUser.Id, award.Id);
baseUser.AddMoney(award.MoneyBonus);
byte[] chatPacket = PacketBuilder.CreateChat(award.CompletionText, PacketBuilder.CHAT_BOTTOM_RIGHT);
baseUser.LoggedinClient.SendPacket(chatPacket);
}
awardsEarned.Add(award);
}
public Award(User user)
{
baseUser = user;
int[] awards = Database.GetAwards(user.Id);
awardsEarned = new List<AwardEntry>();
foreach (int awardid in awards)
{
AddAward(GetAwardById(awardid), false);
}
}
}
}

View file

@ -0,0 +1,91 @@
using HISP.Server;
using System;
using System.Threading;
namespace HISP.Player
{
public class Dance : IDisposable
{
public const int DanceSpeed = 1000;
private Timer danceTimer;
public string Moves;
public int MoveIndex;
private User baseUser;
public Dance(User BaseUser, string DanceMoves)
{
baseUser = BaseUser;
baseUser.ActiveDance = this;
Moves = DanceMoves.ToLower();
MoveIndex = -1;
danceTimer = new Timer(new TimerCallback(onDanceTick), null, DanceSpeed, DanceSpeed);
}
private void onDanceTick(object state)
{
MoveIndex++;
if (MoveIndex >= Moves.Length)
goto done;
int onHorse = 0;
int facing = baseUser.Facing;
while (facing >= 5)
{
facing -= 5;
onHorse++;
}
char moveInDir = Moves[MoveIndex];
int direction;
switch(moveInDir)
{
case 'u':
direction = PacketBuilder.DIRECTION_UP;
break;
case 'd':
direction = PacketBuilder.DIRECTION_DOWN;
break;
case 'l':
direction = PacketBuilder.DIRECTION_LEFT;
break;
case 'r':
direction = PacketBuilder.DIRECTION_RIGHT;
break;
default:
goto done;
}
baseUser.Facing = direction + (onHorse * 5);
byte[] moveResponse = PacketBuilder.CreateMovementPacket(baseUser.X, baseUser.Y, baseUser.CharacterId, baseUser.Facing, PacketBuilder.DIRECTION_NONE, false);
baseUser.LoggedinClient.SendPacket(moveResponse);
GameServer.UpdateUserFacingAndLocation(baseUser);
done:;
if (MoveIndex < Moves.Length)
{
danceTimer.Change(DanceSpeed, DanceSpeed);
}
else
{
this.Dispose();
}
}
public void Dispose()
{
baseUser.ActiveDance = null;
baseUser = null;
Moves = null;
danceTimer.Dispose();
danceTimer = null;
MoveIndex = -1;
}
}
}

View file

@ -0,0 +1,117 @@
using HISP.Game;
using HISP.Server;
using HISP.Game.Items;
namespace HISP.Player.Equips
{
public class CompetitionGear
{
public const int MISC_FLAG_HEAD = 1;
public const int MISC_FLAG_BODY = 2;
public const int MISC_FLAG_LEGS = 3;
public const int MISC_FLAG_FEET = 4;
private int playerId;
public CompetitionGear(int PlayerId)
{
playerId = PlayerId;
if (!Database.HasCompetitionGear(PlayerId))
Database.InitCompetitionGear(PlayerId);
int itemId = Database.GetCompetitionGearHeadPeice(PlayerId);
if (itemId != 0)
head = Item.GetItemById(itemId);
itemId = Database.GetCompetitionGearBodyPeice(PlayerId);
if (itemId != 0)
body = Item.GetItemById(itemId);
itemId = Database.GetCompetitionGearLegPeice(PlayerId);
if (itemId != 0)
legs = Item.GetItemById(itemId);
itemId = Database.GetCompetitionGearFeetPeice(PlayerId);
if (itemId != 0)
feet = Item.GetItemById(itemId);
}
public Item.ItemInformation Head
{
get
{
return head;
}
set
{
if (value == null)
{
head = null;
Database.SetCompetitionGearHeadPeice(playerId, 0);
return;
}
Database.SetCompetitionGearHeadPeice(playerId, value.Id);
head = value;
}
}
public Item.ItemInformation Body
{
get
{
return body;
}
set
{
if (value == null)
{
body = null;
Database.SetCompetitionGearBodyPeice(playerId, 0);
return;
}
Database.SetCompetitionGearBodyPeice(playerId, value.Id);
body = value;
}
}
public Item.ItemInformation Legs
{
get
{
return legs;
}
set
{
if (value == null)
{
legs = null;
Database.SetCompetitionGearLegPeice(playerId, 0);
return;
}
Database.SetCompetitionGearLegPeice(playerId, value.Id);
legs = value;
}
}
public Item.ItemInformation Feet
{
get
{
return feet;
}
set
{
if (value == null)
{
feet = null;
Database.SetCompetitionGearFeetPeice(playerId, 0);
return;
}
Database.SetCompetitionGearFeetPeice(playerId, value.Id);
feet = value;
}
}
private Item.ItemInformation head;
private Item.ItemInformation body;
private Item.ItemInformation legs;
private Item.ItemInformation feet;
}
}

View file

@ -0,0 +1,113 @@
using HISP.Game;
using HISP.Server;
using HISP.Game.Items;
namespace HISP.Player.Equips
{
public class Jewelry
{
private int playerId;
public Jewelry(int PlayerId)
{
playerId = PlayerId;
if (!Database.HasJewelry(PlayerId))
Database.InitJewelry(PlayerId);
int itemId = Database.GetJewelrySlot1(PlayerId);
if (itemId != 0)
slot1 = Item.GetItemById(itemId);
itemId = Database.GetJewelrySlot2(PlayerId);
if (itemId != 0)
slot2 = Item.GetItemById(itemId);
itemId = Database.GetJewelrySlot3(PlayerId);
if (itemId != 0)
slot3 = Item.GetItemById(itemId);
itemId = Database.GetJewelrySlot4(PlayerId);
if (itemId != 0)
slot4 = Item.GetItemById(itemId);
}
public Item.ItemInformation Slot1
{
get
{
return slot1;
}
set
{
if (value == null)
{
slot1 = null;
Database.SetJewelrySlot1(playerId, 0);
return;
}
Database.SetJewelrySlot1(playerId, value.Id);
slot1 = value;
}
}
public Item.ItemInformation Slot2
{
get
{
return slot2;
}
set
{
if (value == null)
{
slot2 = null;
Database.SetJewelrySlot2(playerId, 0);
return;
}
Database.SetJewelrySlot2(playerId, value.Id);
slot2 = value;
}
}
public Item.ItemInformation Slot3
{
get
{
return slot3;
}
set
{
if (value == null)
{
slot3 = null;
Database.SetJewelrySlot3(playerId, 0);
return;
}
Database.SetJewelrySlot3(playerId, value.Id);
slot3 = value;
}
}
public Item.ItemInformation Slot4
{
get
{
return slot4;
}
set
{
if (value == null)
{
slot4 = null;
Database.SetJewelrySlot4(playerId, 0);
return;
}
Database.SetJewelrySlot4(playerId, value.Id);
slot4 = value;
}
}
private Item.ItemInformation slot1;
private Item.ItemInformation slot2;
private Item.ItemInformation slot3;
private Item.ItemInformation slot4;
}
}

View file

@ -0,0 +1,107 @@
using System.Collections.Generic;
using HISP.Game;
using HISP.Server;
namespace HISP.Player
{
public class Friends
{
private User baseUser;
public List<int> List;
public int Count
{
get
{
return List.Count;
}
}
public Friends(User user)
{
baseUser = user;
List = new List<int>();
int[] friends = Database.GetBuddyList(user.Id);
foreach(int friendId in friends)
{
List.Add(friendId);
}
}
public bool IsFriend(int friendUserId)
{
foreach (int userId in List)
if (userId == friendUserId)
return true;
return false;
}
public void RemoveFriend(int userid)
{
Database.RemoveBuddy(baseUser.Id, userid);
// Remove buddy from there list if they are logged in
try
{
User removeFrom = GameServer.GetUserById(userid);
removeFrom.Friends.List.Remove(baseUser.Id);
}
catch (KeyNotFoundException) { /* User is offline, remove from database is sufficent */ };
baseUser.Friends.List.Remove(userid);
}
public void AddFriend(User userToFriend)
{
if(baseUser.MuteBuddy)
{
byte[] cantFriend = PacketBuilder.CreateChat(Messages.CantSendBuddyRequestWhileMuted, PacketBuilder.CHAT_BOTTOM_RIGHT);
baseUser.LoggedinClient.SendPacket(cantFriend);
return;
}
else if(userToFriend.MuteBuddyRequests)
{
byte[] cantFriend = PacketBuilder.CreateChat(Messages.PlayerIgnoringAllBuddyRequests, PacketBuilder.CHAT_BOTTOM_RIGHT);
baseUser.LoggedinClient.SendPacket(cantFriend);
return;
}
else if(userToFriend.MutePlayer.IsUserMuted(userToFriend))
{
byte[] cantFriend = PacketBuilder.CreateChat(Messages.PlayerIgnoringYourBuddyRequests, PacketBuilder.CHAT_BOTTOM_RIGHT);
baseUser.LoggedinClient.SendPacket(cantFriend);
return;
}
if (userToFriend.PendingBuddyRequestTo == baseUser)
{
Database.AddBuddy(baseUser.Id, userToFriend.Id);
List.Add(userToFriend.Id);
userToFriend.Friends.List.Add(baseUser.Id);
byte[] nowFriendsMsg = PacketBuilder.CreateChat(Messages.FormatAddBuddyConfirmed(userToFriend.Username), PacketBuilder.CHAT_BOTTOM_RIGHT);
byte[] nowFriendsOther = PacketBuilder.CreateChat(Messages.FormatAddBuddyConfirmed(baseUser.Username), PacketBuilder.CHAT_BOTTOM_RIGHT);
userToFriend.LoggedinClient.SendPacket(nowFriendsOther);
baseUser.LoggedinClient.SendPacket(nowFriendsMsg);
GameServer.UpdateArea(baseUser.LoggedinClient);
GameServer.UpdateArea(userToFriend.LoggedinClient);
}
else
{
baseUser.PendingBuddyRequestTo = userToFriend;
byte[] pendingMsg = PacketBuilder.CreateChat(Messages.AddBuddyPending, PacketBuilder.CHAT_BOTTOM_RIGHT);
byte[] pendingMsgOther = PacketBuilder.CreateChat(Messages.FormatAddBuddyPendingOther(baseUser.Username), PacketBuilder.CHAT_BOTTOM_RIGHT);
baseUser.LoggedinClient.SendPacket(pendingMsg);
if(!userToFriend.MuteBuddyRequests && !userToFriend.MuteAll)
userToFriend.LoggedinClient.SendPacket(pendingMsgOther);
}
}
}
}

View file

@ -0,0 +1,186 @@
using HISP.Server;
using System.Collections.Generic;
namespace HISP.Player
{
public class Highscore
{
public class HighscoreTableEntry
{
public int UserId;
public string GameName;
public int Wins;
public int Looses;
public int TimesPlayed;
public int Score;
public string Type;
}
public HighscoreTableEntry[] HighscoreList
{
get
{
return highScoreList.ToArray();
}
}
private User baseUser;
private List<HighscoreTableEntry> highScoreList = new List<HighscoreTableEntry>();
public Highscore(User user)
{
baseUser = user;
HighscoreTableEntry[] highscores = Database.GetPlayerHighScores(user.Id);
foreach (HighscoreTableEntry highscore in highscores)
highScoreList.Add(highscore);
}
public HighscoreTableEntry GetHighscore(string gameTitle)
{
foreach (HighscoreTableEntry highscore in HighscoreList)
{
if (highscore.GameName == gameTitle)
{
return highscore;
}
}
throw new KeyNotFoundException("Highscore for " + gameTitle + " Not found.");
}
public bool HasHighscore(string gameTitle)
{
foreach(HighscoreTableEntry highscore in HighscoreList)
{
if(highscore.GameName == gameTitle)
{
return true;
}
}
return false;
}
public bool Loose(string gameTitle)
{
bool isNewScore = true;
if (!HasHighscore(gameTitle))
{
Database.AddNewWinner(baseUser.Id, gameTitle, 0, 1);
HighscoreTableEntry newHighscore = new HighscoreTableEntry();
newHighscore.UserId = baseUser.Id;
newHighscore.GameName = gameTitle;
newHighscore.Wins = 0;
newHighscore.Looses = 0;
newHighscore.TimesPlayed = 1;
newHighscore.Wins = 0;
newHighscore.Looses = 1;
newHighscore.Type = "WINLOSS";
highScoreList.Add(newHighscore);
return isNewScore;
}
else
{
Database.UpdateHighscoreLooseGame(baseUser.Id, gameTitle);
for (int i = 0; i < highScoreList.Count; i++)
{
if (highScoreList[i].GameName == gameTitle)
{
highScoreList[i].TimesPlayed += 1;
highScoreList[i].Looses++;
}
}
return isNewScore;
}
}
public bool Win(string gameTitle)
{
bool isNewScore = true;
if (!HasHighscore(gameTitle))
{
Database.AddNewWinner(baseUser.Id, gameTitle, 1, 0);
HighscoreTableEntry newHighscore = new HighscoreTableEntry();
newHighscore.UserId = baseUser.Id;
newHighscore.GameName = gameTitle;
newHighscore.Wins = 0;
newHighscore.Looses = 0;
newHighscore.TimesPlayed = 1;
newHighscore.Wins = 1;
newHighscore.Looses = 0;
newHighscore.Type = "WINLOSS";
highScoreList.Add(newHighscore);
return isNewScore;
}
else
{
Database.UpdateHighscoreWinGame(baseUser.Id, gameTitle);
for (int i = 0; i < highScoreList.Count; i++)
{
if (highScoreList[i].GameName == gameTitle)
{
highScoreList[i].TimesPlayed += 1;
highScoreList[i].Wins++;
}
}
return isNewScore;
}
}
public bool UpdateHighscore(string gameTitle, int score, bool time)
{
bool isNewScore = true;
if (!HasHighscore(gameTitle))
{
string type = time ? "TIME" : "SCORE";
Database.AddNewHighscore(baseUser.Id, gameTitle, score, type);
HighscoreTableEntry newHighscore = new HighscoreTableEntry();
newHighscore.UserId = baseUser.Id;
newHighscore.GameName = gameTitle;
newHighscore.Wins = 0;
newHighscore.Looses = 0;
newHighscore.TimesPlayed = 1;
newHighscore.Score = score;
newHighscore.Type = type;
highScoreList.Add(newHighscore);
return isNewScore;
}
else
{
int currentScore = GetHighscore(gameTitle).Score;
if (score < currentScore)
{
score = currentScore;
isNewScore = false;
}
Database.UpdateHighscore(baseUser.Id, gameTitle, score);
for(int i = 0; i < highScoreList.Count; i++)
{
if(highScoreList[i].GameName == gameTitle)
{
highScoreList[i].TimesPlayed += 1;
highScoreList[i].Score = score;
}
}
return isNewScore;
}
}
}
}

View file

@ -0,0 +1,123 @@
using HISP.Game;
using HISP.Game.Inventory;
using HISP.Game.Items;
using HISP.Server;
using System.Collections.Generic;
namespace HISP.Player
{
public class Mailbox
{
private User baseUser;
private List<Mail> mails = new List<Mail>();
public int MailCount
{
get
{
return MailMessages.Length;
}
}
public int UnreadMailCount
{
get
{
int i = 0;
foreach (Mail mail in MailMessages)
{
if (!mail.Read)
{
i++;
}
}
return i;
}
}
public Mail[] MailMessages
{
get
{
return mails.ToArray();
}
}
public class Mail
{
public int RandomId;
public bool Read;
public int FromUser;
public int ToUser;
public string Subject;
public string Message;
public int Timestamp;
}
public void RipUpMessage(Mail message)
{
Database.DeleteMail(message.RandomId);
mails.Remove(message);
InventoryItem item = baseUser.Inventory.GetItemByItemId(Item.MailMessage);
foreach(ItemInstance instance in item.ItemInstances)
{
if (instance.Data == message.RandomId)
{
baseUser.Inventory.Remove(instance);
break;
}
}
byte[] rippedUpMessage = PacketBuilder.CreateChat(Messages.MailRippedMessage, PacketBuilder.CHAT_BOTTOM_RIGHT);
baseUser.LoggedinClient.SendPacket(rippedUpMessage);
GameServer.UpdateInventory(baseUser.LoggedinClient);
}
public void ReadAllMail()
{
Database.ReadAllMail(baseUser.Id);
for (int i = 0; i < MailCount; i++)
{
if(!mails[i].Read)
{
ItemInstance mailMessageFromPlayer = new ItemInstance(Item.MailMessage, -1, mails[i].RandomId);
baseUser.Inventory.AddIgnoringFull(mailMessageFromPlayer);
}
mails[i].Read = true;
}
GameServer.UpdatePlayer(baseUser.LoggedinClient);
}
public void AddMail(Mail mailMessage)
{
mails.Add(mailMessage);
Database.AddMail(mailMessage.RandomId, mailMessage.ToUser, mailMessage.FromUser, mailMessage.Subject, mailMessage.Message, mailMessage.Timestamp, mailMessage.Read);
}
public bool MessageExists(int randomId)
{
foreach (Mail mail in MailMessages)
{
if (mail.RandomId == randomId)
return true;
}
return false;
}
public Mail GetMessageByRandomId(int randomId)
{
foreach(Mail mail in MailMessages)
{
if (mail.RandomId == randomId)
return mail;
}
throw new KeyNotFoundException("Mail w id " + randomId + " NOT FOUND.");
}
public Mailbox(User user)
{
baseUser = user;
Mail[] mailMessages = Database.LoadMailbox(user.Id);
foreach (Mail mailMessage in mailMessages)
mails.Add(mailMessage);
}
}
}

View file

@ -0,0 +1,40 @@
using HISP.Server;
using System.Collections.Generic;
namespace HISP.Player
{
public class MutedPlayers
{
private User baseUser;
private List<int> userIds;
public MutedPlayers(User BaseUser)
{
userIds = new List<int>();
baseUser = BaseUser;
int[] userids = Database.GetMutedPlayers(BaseUser.Id);
foreach (int userid in userids)
userIds.Add(userid);
}
public bool IsUserMuted(User user)
{
return userIds.Contains(user.Id);
}
public void MuteUser(User user)
{
userIds.Add(user.Id);
Database.AddMutedPlayer(baseUser.Id, user.Id);
}
public void UnmuteUser(User user)
{
userIds.Remove(user.Id);
Database.DeleteMutedPlayer(baseUser.Id, user.Id);
}
}
}

View file

@ -0,0 +1,53 @@
using System.Collections.Generic;
using HISP.Server;
namespace HISP.Player
{
public class PlayerQuests
{
private List<TrackedQuest> trackedQuests = new List<TrackedQuest>();
public User BaseUser;
public TrackedQuest[] QuestList
{
get
{
return trackedQuests.ToArray();
}
}
public void Add(int questId, int timesCompleted)
{
TrackedQuest quest = new TrackedQuest(BaseUser.Id, questId, 0);
quest.TimesCompleted = timesCompleted;
trackedQuests.Add(quest);
}
public int GetTrackedQuestAmount(int questId)
{
foreach(TrackedQuest quest in QuestList)
{
if (quest.QuestId == questId)
return quest.TimesCompleted;
}
return 0;
}
public void TrackQuest(int questId)
{
foreach (TrackedQuest quest in QuestList)
{
if (quest.QuestId == questId)
{
quest.TimesCompleted++;
return;
}
}
Add(questId, 1);
}
public PlayerQuests(User user)
{
BaseUser = user;
TrackedQuest[] quests = Database.GetTrackedQuests(user.Id);
foreach (TrackedQuest quest in quests)
trackedQuests.Add(quest);
}
}
}

View file

@ -0,0 +1,30 @@
using System;
using HISP.Server;
namespace HISP
{
public class TrackedQuest
{
public TrackedQuest(int playerID, int questID, int timesComplete)
{
playerId = playerID;
QuestId = questID;
timesCompleted = timesComplete;
}
public int QuestId;
private int playerId;
public int TimesCompleted
{
get
{
return timesCompleted;
}
set
{
Database.SetTrackedQuestCompletedCount(playerId, QuestId, value);
timesCompleted = value;
}
}
private int timesCompleted;
}
}

View file

@ -0,0 +1,251 @@
using HISP.Game;
using HISP.Game.Horse;
using HISP.Game.Inventory;
using HISP.Game.Items;
using HISP.Security;
using HISP.Server;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HISP.Player
{
public class Trade
{
public Trade(User me)
{
RandomId = RandomID.NextRandomId();
Trader = me;
}
public int RandomId;
public User Trader;
public Trade OtherTrade;
public string Stage = "OPEN";
public int MoneyOffered = 0;
public List<HorseInstance> HorsesOffered = new List<HorseInstance>();
public List<ItemInstance[]> ItemsOffered = new List<ItemInstance[]>();
private void endTrade()
{
Trader.PendingTradeTo = 0;
Trader.TradingWith = null;
OtherTrade.Trader.PendingTradeTo = 0;
OtherTrade.Trader.TradingWith = null;
GameServer.UpdateArea(Trader.LoggedinClient);
GameServer.UpdateArea(OtherTrade.Trader.LoggedinClient);
}
public void CompleteTrade()
{
bool fail = false;
// Check hell
if (OtherTrade.Trader.Money < 0)
{
byte[] otherNegativeMoneyNotAllowed = PacketBuilder.CreateChat(Messages.TradeOtherPlayerHasNegativeMoney, PacketBuilder.CHAT_BOTTOM_RIGHT);
Trader.LoggedinClient.SendPacket(otherNegativeMoneyNotAllowed);
fail = true;
}
if (Trader.Money < 0)
{
byte[] negativeMoneyNotAllowed = PacketBuilder.CreateChat(Messages.TradeYouHaveNegativeMoney, PacketBuilder.CHAT_BOTTOM_RIGHT);
Trader.LoggedinClient.SendPacket(negativeMoneyNotAllowed);
fail = true;
}
if (OtherTrade.Trader.Bids.Count > 0)
{
byte[] tradeNotAllowedWhileOtherBidding = PacketBuilder.CreateChat(Messages.TradeNotAllowedWhileOtherBidding, PacketBuilder.CHAT_BOTTOM_RIGHT);
Trader.LoggedinClient.SendPacket(tradeNotAllowedWhileOtherBidding);
fail = true;
}
if (Trader.Bids.Count > 0)
{
byte[] tradeNotAllowedWhileBidding = PacketBuilder.CreateChat(Messages.TradeNotAllowedWhileBidding, PacketBuilder.CHAT_BOTTOM_RIGHT);
Trader.LoggedinClient.SendPacket(tradeNotAllowedWhileBidding);
fail = true;
}
if (OtherTrade.Trader.HorseInventory.HorseList.Length + HorsesOffered.Count > OtherTrade.Trader.MaxHorses)
{
byte[] tradeYouHaveTooManyHorses = PacketBuilder.CreateChat(Messages.TradeYouCantHandleMoreHorses, PacketBuilder.CHAT_BOTTOM_RIGHT);
Trader.LoggedinClient.SendPacket(tradeYouHaveTooManyHorses);
fail = true;
}
if (Trader.HorseInventory.HorseList.Length + OtherTrade.HorsesOffered.Count > Trader.MaxHorses)
{
byte[] tradeYouHaveTooManyHorses = PacketBuilder.CreateChat(Messages.TradeYouCantHandleMoreHorses, PacketBuilder.CHAT_BOTTOM_RIGHT);
Trader.LoggedinClient.SendPacket(tradeYouHaveTooManyHorses);
fail = true;
}
if(OtherTrade.Trader.Money + MoneyOffered > 2100000000)
{
byte[] tradeOtherHasTooMuchMoney = PacketBuilder.CreateChat(Messages.TradeWillGiveOtherTooMuchMoney, PacketBuilder.CHAT_BOTTOM_RIGHT);
Trader.LoggedinClient.SendPacket(tradeOtherHasTooMuchMoney);
fail = true;
}
if(Trader.Money + OtherTrade.MoneyOffered > 2100000000)
{
byte[] tradeYouHasTooMuchMoney = PacketBuilder.CreateChat(Messages.TradeWillGiveYouTooMuchMoney, PacketBuilder.CHAT_BOTTOM_RIGHT);
Trader.LoggedinClient.SendPacket(tradeYouHasTooMuchMoney);
fail = true;
}
/*
* Item Checks
*/
bool itemYouFail = false;
foreach (ItemInstance[] inst in OtherTrade.ItemsOffered)
{
if (Trader.Inventory.HasItemId(inst[0].ItemId))
{
InventoryItem items = Trader.Inventory.GetItemByItemId(inst[0].ItemId);
if (items.ItemInstances.Count + inst.Length >= ConfigReader.MAX_STACK)
{
itemYouFail = true;
}
}
}
if (itemYouFail)
{
fail = true;
byte[] tradeTooManyItems = PacketBuilder.CreateChat(Messages.TradeYouCantCarryMoreItems, PacketBuilder.CHAT_BOTTOM_RIGHT);
Trader.LoggedinClient.SendPacket(tradeTooManyItems);
}
bool itemOtherFail = false;
foreach (ItemInstance[] inst in ItemsOffered)
{
if (OtherTrade.Trader.Inventory.HasItemId(inst[0].ItemId))
{
InventoryItem items = OtherTrade.Trader.Inventory.GetItemByItemId(inst[0].ItemId);
if (items.ItemInstances.Count + inst.Length >= ConfigReader.MAX_STACK)
{
itemOtherFail = true;
}
}
}
if (itemOtherFail)
{
fail = true;
byte[] tradeTooManyItems = PacketBuilder.CreateChat(Messages.TradeOtherCantCarryMoreItems, PacketBuilder.CHAT_BOTTOM_RIGHT);
Trader.LoggedinClient.SendPacket(tradeTooManyItems);
}
if (fail)
goto cancelTrade;
else
goto acceptTrade;
acceptTrade:;
byte[] tradeAccepted = PacketBuilder.CreateChat(Messages.TradeAcceptedMessage, PacketBuilder.CHAT_BOTTOM_RIGHT);
Trader.LoggedinClient.SendPacket(tradeAccepted);
if (MoneyOffered > 0) // Transfer Money
{
Trader.TakeMoney(MoneyOffered);
byte[] tradeSpentMoney = PacketBuilder.CreateChat(Messages.FormatTradeYouSpent(MoneyOffered), PacketBuilder.CHAT_BOTTOM_RIGHT);
Trader.LoggedinClient.SendPacket(tradeSpentMoney);
}
if(OtherTrade.MoneyOffered > 0)
{
Trader.AddMoney(OtherTrade.MoneyOffered);
byte[] tradeReceivedMoney = PacketBuilder.CreateChat(Messages.FormatTradeYouReceived(OtherTrade.MoneyOffered), PacketBuilder.CHAT_BOTTOM_RIGHT);
Trader.LoggedinClient.SendPacket(tradeReceivedMoney);
}
foreach (HorseInstance inst in HorsesOffered) // Transfer Horses
{
inst.Owner = OtherTrade.Trader.Id;
// Dismount horse if its traded
if (Trader.CurrentlyRidingHorse != null)
{
if (Trader.CurrentlyRidingHorse.RandomId == inst.RandomId)
{
byte[] disMounted = PacketBuilder.CreateChat(Messages.TradeRiddenHorse, PacketBuilder.CHAT_BOTTOM_RIGHT);
Trader.Facing %= 5;
Trader.CurrentlyRidingHorse = null;
Trader.LoggedinClient.SendPacket(disMounted);
}
}
Trader.HorseInventory.DeleteHorse(inst, false);
OtherTrade.Trader.HorseInventory.AddHorse(inst, false);
}
foreach (ItemInstance[] item in ItemsOffered) // Transfer Items
{
foreach (ItemInstance itm in item)
{
Trader.Inventory.Remove(itm);
OtherTrade.Trader.Inventory.Add(itm);
}
}
Trader.TrackedItems.GetTrackedItem(Tracking.TrackableItem.Trading).Count++;
if (Trader.TrackedItems.GetTrackedItem(Tracking.TrackableItem.Trading).Count >= 100)
Trader.Awards.AddAward(Award.GetAwardById(29)); // Trader
if (Trader.TrackedItems.GetTrackedItem(Tracking.TrackableItem.Trading).Count >= 1000)
Trader.Awards.AddAward(Award.GetAwardById(50)); // Pro Trader
endTrade();
return;
cancelTrade:;
InteruptTrade();
return;
}
public void InteruptTrade()
{
byte[] tradeCanceled = PacketBuilder.CreateChat(Messages.TradeCanceledInterupted, PacketBuilder.CHAT_BOTTOM_RIGHT);
Trader.LoggedinClient.SendPacket(tradeCanceled);
endTrade();
}
public void AcceptTrade()
{
byte[] waitingForAccept = PacketBuilder.CreateChat(Messages.TradeWaitingForOthersToAcceptMessage, PacketBuilder.CHAT_BOTTOM_RIGHT);
Trader.LoggedinClient.SendPacket(waitingForAccept);
if (OtherTrade.Stage == "ACCEPTED")
{
CompleteTrade();
OtherTrade.CompleteTrade();
}
Stage = "ACCEPTED";
}
public void CancelTrade()
{
byte[] tradeCanceled = PacketBuilder.CreateChat(Messages.TradeCanceledByYouMessage, PacketBuilder.CHAT_BOTTOM_RIGHT);
Trader.LoggedinClient.SendPacket(tradeCanceled);
byte[] tradeCanceledOther = PacketBuilder.CreateChat(Messages.FormatTradeCanceledByPlayer(Trader.Username), PacketBuilder.CHAT_BOTTOM_RIGHT);
OtherTrade.Trader.LoggedinClient.SendPacket(tradeCanceledOther);
endTrade();
}
public void CancelTradeMoved()
{
byte[] playerMoved = PacketBuilder.CreateChat(Messages.TradeCanceledBecuasePlayerMovedMessage, PacketBuilder.CHAT_BOTTOM_RIGHT);
Trader.LoggedinClient.SendPacket(playerMoved);
OtherTrade.Trader.LoggedinClient.SendPacket(playerMoved);
endTrade();
}
}
}

View file

@ -0,0 +1,676 @@
using System;
using System.Collections.Generic;
using HISP.Game;
using HISP.Server;
using HISP.Player.Equips;
using HISP.Game.Services;
using HISP.Game.Inventory;
using HISP.Game.Horse;
using System.Linq;
namespace HISP.Player
{
public class User
{
public int Id;
public string Username;
public bool Administrator;
public bool Moderator;
public bool NewPlayer = false;
public GameClient LoggedinClient;
public CompetitionGear EquipedCompetitionGear;
public Jewelry EquipedJewelry;
public bool MuteAds = false;
public bool MuteGlobal = false;
public bool MuteIsland = false;
public bool MuteNear = false;
public bool MuteHere = false;
public bool MuteBuddy = false;
public bool MutePrivateMessage = false;
public bool MuteBuddyRequests = false;
public bool MuteSocials = false;
public bool MuteAll = false;
public bool MuteLogins = false;
public bool NoClip = false;
public string Gender;
public bool MetaPriority = false;
public List<Auction.AuctionBid> Bids = new List<Auction.AuctionBid>();
public bool Idle;
public int Facing;
public int MaxItems
{
get
{
int baseValue = 40;
if (Subscribed)
{
if (OwnedRanch != null)
{
baseValue += 20 * OwnedRanch.GetBuildingCount(4); // Shed
if (baseValue > 80) // 2 sheds max!
baseValue = 80;
}
}
return baseValue;
}
}
public int MaxHorses
{
get
{
if (Subscribed)
{
int baseValue = 11;
if(OwnedRanch != null)
{
baseValue += OwnedRanch.GetBuildingCount(1) * 4; // Barn
baseValue += OwnedRanch.GetBuildingCount(10) * 8; // Big Barn
baseValue += OwnedRanch.GetBuildingCount(11) * 12; // Gold Barn
}
return baseValue;
}
return 7; // will change when ranches are implemented.
}
}
public HorseInfo.Breed PawneerOrderBreed = null;
public string PawneerOrderColor = "";
public string PawneerOrderGender = "";
public bool InRealTimeQuiz = false;
public int PendingTradeTo;
public Mailbox MailBox;
public Friends Friends;
public string Password; // For chat filter.
public PlayerInventory Inventory;
public Npc.NpcEntry LastTalkedToNpc;
public Shop LastShoppedAt;
public Inn LastVisitedInn;
public HorseInventory HorseInventory;
public HorseInstance LastViewedHorse;
public HorseInstance LastViewedHorseOther;
public int LastRiddenHorse = 0;
public HorseInstance CurrentlyRidingHorse;
public Tracking TrackedItems;
public Ranch OwnedRanch = null;
public PlayerQuests Quests;
public Highscore Highscores;
public MutedPlayers MutePlayer;
public Riddler LastRiddle;
public Award Awards;
public User SocializingWith;
public List<User> BeingSocializedBy = new List<User>();
public User PendingBuddyRequestTo;
public Dance ActiveDance;
public bool CanUseAdsChat = true;
public int CapturingHorseId;
public DateTime LoginTime;
public string LastSeenWeather;
public string AutoReplyText = "";
public int LastClickedRanchBuilding = 0;
public bool ListingAuction = false;
public int TotalGlobalChatMessages = 1;
public void TakeMoney(int amount)
{
int money = Money;
money -= amount;
Database.SetPlayerMoney(money, Id);
GameServer.UpdatePlayer(LoggedinClient);
}
public void AddMoney(int amount)
{
int money = Money;
try
{
checked
{
money += amount;
}
}
catch(OverflowException)
{
money = 2147483647;
}
Database.SetPlayerMoney(money, Id);
GameServer.UpdatePlayer(LoggedinClient);
}
public string GetWeatherSeen()
{
string weather = "SUNNY";
if (World.InTown(this.X, this.Y))
weather = World.GetTown(this.X, this.Y).Weather;
if (World.InIsle(this.X, this.Y))
weather = World.GetIsle(this.X, this.Y).Weather;
LastSeenWeather = weather;
return weather;
}
public void DoRanchActions()
{
if(OwnedRanch != null)
{
Tiredness = 1000; // All ranches fully rest you.
if(OwnedRanch.GetBuildingCount(2) > 0)
{
Thirst = 1000;
foreach (HorseInstance horse in HorseInventory.HorseList)
horse.BasicStats.Thirst = 1000;
}
if (OwnedRanch.GetBuildingCount(3) > 0)
{
foreach (HorseInstance horse in HorseInventory.HorseList)
horse.BasicStats.Hunger = 1000;
}
if(OwnedRanch.GetBuildingCount(9) > 0)
{
Hunger = 1000;
}
if( (OwnedRanch.GetBuildingCount(1) > 0)|| (OwnedRanch.GetBuildingCount(10) > 0) || (OwnedRanch.GetBuildingCount(11) > 0))
{
foreach (HorseInstance horse in HorseInventory.HorseList)
horse.BasicStats.Tiredness = 1000;
}
}
}
public DateTime SubscribedUntil
{
get
{
return Converters.UnixTimeStampToDateTime(subscribedUntil);
}
}
public int FreeMinutes
{
get
{
int freeTime = Database.GetFreeTime(Id);
return freeTime;
}
set
{
Database.SetFreeTime(Id, value);
}
}
public bool Subscribed
{
get
{
if (ConfigReader.AllUsersSubbed)
return true;
if (Administrator)
return true;
int Timestamp = Convert.ToInt32(new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds());
if(Timestamp > subscribedUntil && subscribed) // sub expired.
{
Logger.InfoPrint(Username + "'s Subscription expired. (timestamp now: " + Timestamp + " exp date: " + subscribedUntil+" )");
Database.SetUserSubscriptionStatus(this.Id, false);
subscribed = false;
}
return subscribed;
}
set
{
Database.SetUserSubscriptionStatus(this.Id, value);
}
}
public bool Stealth
{
get
{
return stealth;
}
set
{
if (value)
Database.RemoveOnlineUser(this.Id);
else
Database.AddOnlineUser(this.Id, this.Administrator, this.Moderator, this.Subscribed, this.NewPlayer);
stealth = value;
}
}
public int ChatViolations
{
get
{
return chatViolations;
}
set
{
Database.SetChatViolations(value,Id);
chatViolations = value;
}
}
public string PrivateNotes
{
get
{
return privateNotes;
}
set
{
privateNotes = value.Trim();
Database.SetPlayerNotes(Id, privateNotes);
}
}
public string ProfilePage {
get
{
return profilePage;
}
set
{
profilePage = value.TrimEnd();
Database.SetPlayerProfile(profilePage, Id);
}
}
public int Money
{
get
{
return Database.GetPlayerMoney(Id);
}
}
public int Experience
{
get
{
return experience;
}
set
{
Database.SetExperience(Id, value);
experience = value;
}
}
public int QuestPoints
{
get
{
return questPoints;
}
set
{
Database.SetPlayerQuestPoints(value, Id);
questPoints = value;
}
}
public double BankInterest
{
get
{
return Database.GetPlayerBankInterest(Id);
}
set
{
if (value > 9999999999.9999)
value = 9999999999.9999;
Database.SetPlayerBankInterest(value, Id);
}
}
public double BankMoney
{
get
{
return bankMoney;
}
set
{
if (value > 9999999999.9999)
value = 9999999999.9999;
Database.SetPlayerBankMoney(value, Id);
bankMoney = value;
BankInterest = value;
}
}
public int X
{
get
{
return x;
}
set
{
Database.SetPlayerX(value, Id);
x = value;
}
}
public int Y
{
get
{
return y;
}
set
{
Database.SetPlayerY(value, Id);
y = value;
}
}
public int CharacterId
{
get
{
return charId;
}
set
{
Database.SetPlayerCharId(value, Id);
charId = value;
}
}
public int Hunger
{
get
{
return hunger;
}
set
{
if (value >= 1000)
value = 1000;
if (value <= 0)
value = 0;
Database.SetPlayerHunger(Id, value);
hunger = value;
}
}
public int Thirst
{
get
{
return thirst;
}
set
{
if (value >= 1000)
value = 1000;
if (value <= 0)
value = 0;
Database.SetPlayerThirst(Id, value);
thirst = value;
}
}
public int Tiredness
{
get
{
return tired;
}
set
{
if (value >= 1000)
value = 1000;
if (value <= 0)
value = 0;
Database.SetPlayerTiredness(Id, value);
tired = value;
}
}
private int chatViolations;
private int charId;
private int subscribedUntil;
private bool subscribed;
private string profilePage;
private string privateNotes;
private int x;
private bool stealth = false;
private int y;
private int questPoints;
private double bankMoney;
private int experience;
private int hunger;
private int thirst;
private int tired;
public Trade TradingWith = null;
public int AttemptingToOfferItem;
public bool TradeMenuPriority = false;
public byte[] SecCodeSeeds = new byte[3];
public int SecCodeInc = 0;
public int SecCodeCount = 0;
public int GetPlayerListIcon()
{
int icon = -1;
if (NewPlayer)
icon = Messages.NewUserIcon;
if (Subscribed)
{
int months = (DateTime.UtcNow.Month - SubscribedUntil.Month) + 12 * (DateTime.UtcNow.Year - SubscribedUntil.Year);
if (months <= 1)
icon = Messages.MonthSubscriptionIcon;
else if (months <= 3)
icon = Messages.ThreeMonthSubscripitionIcon;
else
icon = Messages.YearSubscriptionIcon;
}
if (Moderator)
icon = Messages.ModeratorIcon;
if (Administrator)
icon = Messages.AdminIcon;
return icon;
}
public void Teleport(int newX, int newY)
{
Logger.DebugPrint("Teleporting: " + Username + " to: " + newX.ToString() + "," + newY.ToString());
User[] onScreenBefore = GameServer.GetOnScreenUsers(X, Y, true, true);
X = newX;
Y = newY;
byte[] MovementPacket = PacketBuilder.CreateMovementPacket(X, Y, CharacterId, Facing, PacketBuilder.DIRECTION_TELEPORT, true);
LoggedinClient.SendPacket(MovementPacket);
GameServer.UpdateWeather(LoggedinClient);
User[] onScreenNow = GameServer.GetOnScreenUsers(X, Y, true, true);
User[] goneOffScreen = onScreenBefore.Except(onScreenNow).ToArray();
User[] goneOnScreen = onScreenNow.Except(onScreenBefore).ToArray();
foreach(User offScreenUsers in goneOffScreen)
{
if (offScreenUsers.Id == this.Id)
continue;
byte[] playerInfoBytes = PacketBuilder.CreatePlayerInfoUpdateOrCreate(1000 + 4, 1000 + 1, Facing, CharacterId, Username);
offScreenUsers.LoggedinClient.SendPacket(playerInfoBytes);
}
foreach (User onScreenUsers in goneOnScreen)
{
if (onScreenUsers.Id == this.Id)
continue;
byte[] playerInfoBytes = PacketBuilder.CreatePlayerInfoUpdateOrCreate(onScreenUsers.X, onScreenUsers.Y, onScreenUsers.Facing, onScreenUsers.CharacterId, onScreenUsers.Username);
LoggedinClient.SendPacket(playerInfoBytes);
}
// Players now offscreen tell the client is at 1000,1000.
/* foreach (User onScreenBeforeUser in onScreenBefore)
{
bool found = false;
foreach (User onScreenNowUser in onScreenNow)
{
if (onScreenNowUser.Id == onScreenBeforeUser.Id)
{
found = true;
break;
}
}
if (!found)
{
byte[] playerInfoBytes = PacketBuilder.CreatePlayerInfoUpdateOrCreate(1000 + 4, 1000 + 1, Facing, CharacterId, Username);
onScreenBeforeUser.LoggedinClient.SendPacket(playerInfoBytes);
}
}
// Players now onscreen tell the client there real pos
foreach (User onScreenNowUser in onScreenNow)
{
bool found = false;
foreach (User onScreenBeforeUser in onScreenBefore)
{
if (onScreenNowUser.Id == onScreenBeforeUser.Id)
{
found = true;
break;
}
}
if (!found)
{
byte[] playerInfoBytes = PacketBuilder.CreatePlayerInfoUpdateOrCreate(onScreenNowUser.X, onScreenNowUser.Y, onScreenNowUser.Facing, onScreenNowUser.CharacterId, onScreenNowUser.Username);
LoggedinClient.SendPacket(playerInfoBytes);
}
}
*/
GameServer.Update(LoggedinClient);
}
public byte[] GenerateSecCode()
{
var i = 0;
SecCodeCount++;
SecCodeSeeds[SecCodeCount % 3] = (byte)(SecCodeSeeds[SecCodeCount % 3] + SecCodeInc);
SecCodeSeeds[SecCodeCount % 3] = (byte)(SecCodeSeeds[SecCodeCount % 3] % 92);
i = SecCodeSeeds[0] + SecCodeSeeds[1] * SecCodeSeeds[2] - SecCodeSeeds[1];
i = Math.Abs(i);
i = i % 92;
byte[] SecCode = new byte[4];
SecCode[0] = (byte)(SecCodeSeeds[0] + 33);
SecCode[1] = (byte)(SecCodeSeeds[1] + 33);
SecCode[2] = (byte)(SecCodeSeeds[2] + 33);
SecCode[3] = (byte)(i + 33);
Logger.DebugPrint("Expecting "+Username+" To send Sec Code: "+BitConverter.ToString(SecCode).Replace("-", " "));
return SecCode;
}
public User(GameClient baseClient, int UserId)
{
if (!Database.CheckUserExist(UserId))
throw new KeyNotFoundException("User " + UserId + " not found in database!");
if (!Database.CheckUserExtExists(UserId))
{
Database.CreateUserExt(UserId);
NewPlayer = true;
}
EquipedCompetitionGear = new CompetitionGear(UserId);
EquipedJewelry = new Jewelry(UserId);
Id = UserId;
Username = Database.GetUsername(UserId);
Administrator = Database.CheckUserIsAdmin(Username);
Moderator = Database.CheckUserIsModerator(Username);
chatViolations = Database.GetChatViolations(UserId);
x = Database.GetPlayerX(UserId);
y = Database.GetPlayerY(UserId);
charId = Database.GetPlayerCharId(UserId);
Facing = PacketBuilder.DIRECTION_DOWN;
experience = Database.GetExperience(UserId);
//money = Database.GetPlayerMoney(UserId);
bankMoney = Database.GetPlayerBankMoney(UserId);
questPoints = Database.GetPlayerQuestPoints(UserId);
subscribed = Database.IsUserSubscribed(UserId);
subscribedUntil = Database.GetUserSubscriptionExpireDate(UserId);
profilePage = Database.GetPlayerProfile(UserId);
privateNotes = Database.GetPlayerNotes(UserId);
hunger = Database.GetPlayerHunger(UserId);
thirst = Database.GetPlayerThirst(UserId);
tired = Database.GetPlayerTiredness(UserId);
if(Ranch.IsRanchOwned(this.Id))
{
OwnedRanch = Ranch.GetRanchOwnedBy(this.Id);
}
Gender = Database.GetGender(UserId);
MailBox = new Mailbox(this);
Highscores = new Highscore(this);
Awards = new Award(this);
MutePlayer = new MutedPlayers(this);
TrackedItems = new Tracking(this);
HorseInventory = new HorseInventory(this);
// Generate SecCodes
SecCodeSeeds[0] = (byte)GameServer.RandomNumberGenerator.Next(40, 60);
SecCodeSeeds[1] = (byte)GameServer.RandomNumberGenerator.Next(40, 60);
SecCodeSeeds[2] = (byte)GameServer.RandomNumberGenerator.Next(40, 60);
SecCodeInc = (byte)GameServer.RandomNumberGenerator.Next(40, 60);
Friends = new Friends(this);
LoginTime = DateTime.UtcNow;
LoggedinClient = baseClient;
Inventory = new PlayerInventory(this);
Quests = new PlayerQuests(this);
// Get auctions
foreach(Auction auction in Auction.AuctionRooms)
{
foreach(Auction.AuctionEntry auctionEntry in auction.AuctionEntries)
{
if(auctionEntry.HighestBidder == this.Id)
{
Auction.AuctionBid bid = new Auction.AuctionBid();
bid.BidUser = this;
bid.BidAmount = auctionEntry.HighestBid;
bid.AuctionItem = auctionEntry;
if(bid.BidAmount > 0)
{
Bids.Add(bid);
auctionEntry.Bidders.Add(bid);
}
}
}
}
}
}
}

View file

@ -0,0 +1,59 @@
using System;
using HISP.Game;
using HISP.Game.Items;
using HISP.Game.Horse;
using HISP.Game.SwfModules;
using HISP.Security;
using HISP.Server;
using HISP.Game.Services;
using System.IO;
namespace HISP
{
public class Program
{
static void Main(string[] args)
{
#if (!DEBUG)
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
#endif
Console.Title = "HISP - HorseIsleServer Emulator";
ConfigReader.OpenConfig();
CrossDomainPolicy.GetPolicy();
Database.OpenDatabase();
GameDataJson.ReadGamedata();
Map.OpenMap();
World.ReadWorldData();
Treasure.Init();
DroppedItems.Init();
WildHorse.Init();
Drawingroom.LoadAllDrawingRooms();
Brickpoet.LoadPoetryRooms();
Multiroom.CreateMultirooms();
Auction.LoadAllAuctionRooms();
Item.DoSpecialCases();
GameServer.StartServer();
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Exception execpt = (Exception)e.ExceptionObject;
Logger.ErrorPrint("HISP HAS CRASHED :(");
Logger.ErrorPrint("Unhandled Exception: " + execpt.ToString());
Logger.ErrorPrint(execpt.Message);
Logger.ErrorPrint("");
Logger.ErrorPrint(execpt.StackTrace);
while (true) { };
}
}
}

View file

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("HorseIsleServer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HorseIsleServer")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c48cbd82-ab30-494a-8ffa-4de7069b5827")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View file

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project ToolsVersion="4.0">
<PropertyGroup>
<Configuration>Linux</Configuration>
<Platform>x64</Platform>
<PublishDir>bin\x64\Linux\net5.0\linux-x64\publish\</PublishDir>
<PublishProtocol>FileSystem</PublishProtocol>
<TargetFramework>net5.0</TargetFramework>
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
<SelfContained>True</SelfContained>
<PublishSingleFile>True</PublishSingleFile>
<PublishReadyToRun>True</PublishReadyToRun>
<PublishTrimmed>True</PublishTrimmed>
</PropertyGroup>
</Project>

View file

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project ToolsVersion="4.0">
<PropertyGroup>
<Configuration>Linux</Configuration>
<Platform>ARM</Platform>
<PublishDir>bin\ARM\Linux\net5.0\linux-arm\publish\</PublishDir>
<PublishProtocol>FileSystem</PublishProtocol>
<TargetFramework>net5.0</TargetFramework>
<RuntimeIdentifier>linux-arm</RuntimeIdentifier>
<SelfContained>True</SelfContained>
<PublishSingleFile>True</PublishSingleFile>
<PublishReadyToRun>True</PublishReadyToRun>
<PublishTrimmed>True</PublishTrimmed>
</PropertyGroup>
</Project>

View file

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project ToolsVersion="4.0">
<PropertyGroup>
<Configuration>Linux</Configuration>
<Platform>ARM64</Platform>
<PublishDir>bin\ARM64\Linux\net5.0\linux-arm64\publish\</PublishDir>
<PublishProtocol>FileSystem</PublishProtocol>
<TargetFramework>net5.0</TargetFramework>
<RuntimeIdentifier>linux-arm64</RuntimeIdentifier>
<SelfContained>True</SelfContained>
<PublishSingleFile>True</PublishSingleFile>
<PublishReadyToRun>True</PublishReadyToRun>
<PublishTrimmed>True</PublishTrimmed>
</PropertyGroup>
</Project>

View file

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project ToolsVersion="4.0">
<PropertyGroup>
<Configuration>MacOS</Configuration>
<Platform>x64</Platform>
<PublishDir>bin\x64\MacOS\net5.0\osx-x64\publish\</PublishDir>
<PublishProtocol>FileSystem</PublishProtocol>
<TargetFramework>net5.0</TargetFramework>
<RuntimeIdentifier>osx-x64</RuntimeIdentifier>
<SelfContained>True</SelfContained>
<PublishSingleFile>True</PublishSingleFile>
<PublishReadyToRun>True</PublishReadyToRun>
<PublishTrimmed>True</PublishTrimmed>
</PropertyGroup>
</Project>

View file

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project ToolsVersion="4.0">
<PropertyGroup>
<Configuration>Windows</Configuration>
<Platform>x86</Platform>
<PublishDir>bin\x86\Windows\net5.0\win-x86\publish\</PublishDir>
<PublishProtocol>FileSystem</PublishProtocol>
<TargetFramework>net5.0</TargetFramework>
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
<SelfContained>True</SelfContained>
<PublishSingleFile>True</PublishSingleFile>
<PublishReadyToRun>True</PublishReadyToRun>
<PublishTrimmed>True</PublishTrimmed>
</PropertyGroup>
</Project>

View file

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project ToolsVersion="4.0">
<PropertyGroup>
<Configuration>Windows</Configuration>
<Platform>x64</Platform>
<PublishDir>bin\x64\Windows\net5.0\win-x64\publish\</PublishDir>
<PublishProtocol>FileSystem</PublishProtocol>
<TargetFramework>net5.0</TargetFramework>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<SelfContained>True</SelfContained>
<PublishSingleFile>True</PublishSingleFile>
<PublishReadyToRun>True</PublishReadyToRun>
<PublishTrimmed>True</PublishTrimmed>
</PropertyGroup>
</Project>

View file

@ -0,0 +1,108 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace HISP.Properties {
using System;
/// <summary>
/// A strongly-typed resource public class, for looking up localized strings, etc.
/// </summary>
// This public class was auto-generated by the StronglyTypedResourceBuilder
// public class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this public class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("HISP.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource public class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to &lt;cross-domain-policy&gt;
/// &lt;allow-access-from domain=&quot;*&quot; to-ports=&quot;12321&quot; secure=&quot;false&quot;/&gt;
///&lt;/cross-domain-policy&gt;.
/// </summary>
internal static string DefaultCrossDomain {
get {
return ResourceManager.GetString("DefaultCrossDomain", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to # HorseIsleServer Default Configuration File
///
///# Ip address the server will bind to (default: 0.0.0.0 ALL INTERFACES)
///ip=0.0.0.0
///# Port the server will bind to (default: 12321)
///port=12321
///
///# MariaDB Database
///db_ip=127.0.0.1
///db_name=beta
///db_username=root
///db_password=test123
///db_port=3306
///
///# Map Data
///map=HI1.MAP
///
///# JSON Format Data
///
///gamedata=gamedata.json
///
///# Cross-Domain Policy File
///crossdomain=CrossDomainPolicy.xml
///
///# Red Text Stating &quot;Todays Note:&quot;
///motd=April 11, 2020. New breed, C [rest of string was truncated]&quot;;.
/// </summary>
internal static string DefaultServerProperties {
get {
return ResourceManager.GetString("DefaultServerProperties", resourceCulture);
}
}
}
}

View file

@ -0,0 +1,127 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="DefaultCrossDomain" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\default_cross_domain.xml;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252</value>
</data>
<data name="DefaultServerProperties" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\server.properties;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252</value>
</data>
</root>

View file

@ -0,0 +1,7 @@
{
"profiles": {
"HorseIsleServer": {
"commandName": "Project"
}
}
}

View file

@ -0,0 +1,3 @@
<cross-domain-policy>
<allow-access-from domain="*" to-ports="12321" secure="false"/>
</cross-domain-policy>

View file

@ -0,0 +1,52 @@
# HISP Default Configuration File
# Ip address the server will bind to (default: 0.0.0.0 ALL INTERFACES)
ip=0.0.0.0
# Port the server will bind to (default: 12321)
port=12321
# MariaDB Database
db_ip=127.0.0.1
db_name=beta
db_username=root
db_password=test123
db_port=3306
# Map Data
map=HI1.MAP
# JSON Format Data
gamedata=gamedata.json
# Cross-Domain Policy File
crossdomain=CrossDomainPolicy.xml
# Red Text Stating "Todays Note:"
motd=April 11, 2020. New breed, Camarillo White Horse. Two new quests.
# Chat Filter Settings
# Wether to block 'bad' words
# ex 'Fuck You!' gets blocked
enable_word_filter=true
# Wether to expand slang.
# ex 'lol' becomes '*laughing out loud!*'
# (NOTE: This feature is also used to filter some less-'bad' words disabling it will allow users to say them!)
enable_corrections=true
# Include non-violations
# stuff like blocking you from saying your password in chat
# and FULL CAPS messages.
non_violation=true
# Wether or not to consider all users "Subscribers"
all_users_subscribed=false
# Equation is: BANK_BALANCE * (1/INTREST_RATE);
# on All servers except Black its 3333, on black its 1000.
# but of course you can make it whatever you want
intrest_rate=3333
# Should print extra debug logs
debug=false

View file

@ -0,0 +1,87 @@
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using HISP.Server;
namespace HISP.Security
{
public class Authentication
{
public static string DecryptLogin(string encpass)
{
string decrypt = "";
string ROTPOOL = "bl7Jgk61IZdnY mfDN5zjM2XLqTCty4WSEoKR3BFVQsaUhHOAx0rPwp9uc8iGve";
string POSPOOL = "DQc3uxiGsKZatMmOS5qYveN71zoPTk8yU0H2w9VjprBXWn l4FJd6IRbhgACfEL";
string ROTPOOL2 = "evGi8cu9pwPr0xAOHhUasQVFB3RKoESW4ytCTqLX2Mjz5NDfm YndZI16kgJ7lb";
int i = 0;
int ii = 0;
while (i < encpass.Length)
{
int ROT = ROTPOOL.IndexOf(encpass[i].ToString());
int POS = POSPOOL.IndexOf(encpass[i + 1].ToString());
POS -= (ROT + ii);
if (POS < 0)
{
POS = (POS / -1) - 1;
while (POS >= ROTPOOL.Length)
{
POS -= ROTPOOL.Length;
}
decrypt += ROTPOOL2[POS];
}
else
{
while (POS >= ROTPOOL.Length)
{
POS -= ROTPOOL.Length;
}
decrypt += ROTPOOL[POS];
}
i += 2;
ii += 1;
}
return decrypt.Replace(" ", "");
}
public static byte[] HashAndSalt(string plaintext, byte[] salt)
{
byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);
SHA512 sha512 = new SHA512Managed();
byte[] hash = sha512.ComputeHash(plaintextBytes);
for (int i = 0; i < hash.Length; i++)
{
hash[i] ^= salt[i];
}
byte[] finalHash = sha512.ComputeHash(hash);
return finalHash;
}
public static bool CheckPassword(string username, string password)
{
if(Database.CheckUserExist(username))
{
byte[] expectedPassword = Database.GetPasswordHash(username);
byte[] salt = Database.GetPasswordSalt(username);
byte[] hashedPassword = HashAndSalt(password, salt);
if (Enumerable.SequenceEqual(expectedPassword, hashedPassword))
return true;
}
return false;
}
}
}

View file

@ -0,0 +1,35 @@
using System.Collections.Generic;
namespace HISP.Security
{
public class BBCode
{
public BBCode(string tag, string meta)
{
this.Tag = tag;
this.MetaTranslation = meta;
bbcodeTranslations.Add(this);
}
private static List<BBCode> bbcodeTranslations = new List<BBCode>();
public string Tag;
public string MetaTranslation;
public static string EncodeMetaToBBCode(string message)
{
foreach (BBCode code in bbcodeTranslations)
{
message = message.Replace(code.MetaTranslation, code.Tag);
}
return message;
}
public static string EncodeBBCodeToMeta(string message)
{
foreach(BBCode code in bbcodeTranslations)
{
message = message.Replace(code.Tag, code.MetaTranslation);
message = message.Replace(code.Tag.ToUpper(), code.MetaTranslation);
}
return message;
}
}
}

View file

@ -0,0 +1,30 @@
using HISP.Properties;
using System;
using System.IO;
using HISP.Server;
namespace HISP.Security
{
public class CrossDomainPolicy
{
public static byte[] GetPolicy()
{
if (!File.Exists(ConfigReader.CrossDomainPolicyFile)) {
if (ConfigReader.Debug)
Console.WriteLine("[DEBUG] Cross-Domain-Policy file not found, using default");
File.WriteAllText(ConfigReader.CrossDomainPolicyFile, Resources.DefaultCrossDomain);
}
MemoryStream ms = new MemoryStream();
byte[] policyFileBytes = File.ReadAllBytes(ConfigReader.CrossDomainPolicyFile);
ms.Write(policyFileBytes, 0x00, policyFileBytes.Length);
ms.WriteByte(0x00);
ms.Seek(0x00, SeekOrigin.Begin);
byte[] policyFileData = ms.ToArray();
ms.Close();
return policyFileData;
}
}
}

View file

@ -0,0 +1,22 @@
using System;
namespace HISP.Security
{
public class RandomID
{
private static int prevId = 0;
public static int NextRandomId(int randomId=-1)
{
int rndmId = 0;
if (randomId == -1)
rndmId = prevId+1;
else
rndmId = randomId;
if (rndmId >= prevId)
prevId = rndmId;
return rndmId;
}
}
}

View file

@ -0,0 +1,125 @@
using HISP.Properties;
using System.IO;
namespace HISP.Server
{
public class ConfigReader
{
public static int Port;
public static string BindIP = "0.0.0.0";
public static string DatabaseIP;
public static string DatabaseUsername;
public static string DatabaseName;
public static string DatabasePassword;
public static int DatabasePort;
public static int IntrestRate;
public static string Motd;
public static string MapFile;
public static string GameDataFile;
public static string CrossDomainPolicyFile;
public static bool Debug = false;
public static bool AllUsersSubbed = false;
public static bool BadWords = true;
public static bool DoCorrections = true;
public static bool DoNonViolations = true;
public const int MAX_STACK = 50;
private static string ConfigurationFileName = "server.properties";
public static void OpenConfig()
{
if (!File.Exists(ConfigurationFileName))
{
Logger.WarnPrint(ConfigurationFileName+" not found! writing default.");
File.WriteAllText(ConfigurationFileName,Resources.DefaultServerProperties);
Logger.InfoPrint("! Its very likely database connection will fail...");
}
string[] configFile = File.ReadAllLines(ConfigurationFileName);
foreach (string setting in configFile)
{
/*
* Avoid crashing.
*/
if (setting.Length < 1)
continue;
if (setting[0] == '#')
continue;
if (!setting.Contains("="))
continue;
string[] dataPair = setting.Split('=');
string key = dataPair[0];
string data = dataPair[1];
/*
* Parse configuration file
*/
switch (key)
{
case "port":
Port = int.Parse(data);
break;
case "ip":
BindIP = data;
break;
case "db_ip":
DatabaseIP = data;
break;
case "db_username":
DatabaseUsername = data;
break;
case "db_password":
DatabasePassword = data;
break;
case "db_name":
DatabaseName = data;
break;
case "db_port":
DatabasePort = int.Parse(data);
break;
case "map":
MapFile = data;
break;
case "motd":
Motd = data;
break;
case "gamedata":
GameDataFile = data;
break;
case "crossdomain":
CrossDomainPolicyFile = data;
break;
case "all_users_subscribed":
AllUsersSubbed = data == "true";
break;
case "enable_corrections":
DoCorrections = data == "true";
break;
case "non_violation":
DoNonViolations = data == "true";
break;
case "enable_word_filter":
BadWords = data == "true";
break;
case "intrest_rate":
IntrestRate = int.Parse(data);
break;
case "debug":
Debug = data == "true";
break;
}
}
}
}
}

View file

@ -0,0 +1,50 @@
using System;
namespace HISP.Server
{
public class Converters
{
// Thanks Stackoverflow (https://stackoverflow.com/questions/321370/how-can-i-convert-a-hex-string-to-a-byte-array)
private static int getHexVal(char hex)
{
int val = (int)hex;
return val - (val < 58 ? 48 : (val < 97 ? 55 : 87));
}
public static byte[] StringToByteArray(string hex)
{
if (hex.Length % 2 == 1)
throw new ArgumentException("The binary key cannot have an odd number of digits");
byte[] arr = new byte[hex.Length >> 1];
for (int i = 0; i < hex.Length >> 1; ++i)
{
arr[i] = (byte)((getHexVal(hex[i << 1]) << 4) + (getHexVal(hex[(i << 1) + 1])));
}
return arr;
}
public static double PointsToDistance(int x1, int y1, int x2, int y2)
{
return Math.Sqrt(Math.Pow((x2 - x1), 2) + Math.Pow((y2 - y1), 2));
}
public static string CapitalizeFirstLetter(string str)
{
char firstChar = char.ToUpper(str[0]);
return firstChar + str.Substring(1);
}
public static DateTime UnixTimeStampToDateTime(double unixTimeStamp)
{
// Unix timestamp is seconds past epoch
System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).ToUniversalTime();
return dtDateTime;
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,503 @@
using System;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using HISP.Player;
using HISP.Game;
using HISP.Game.Horse;
using HISP.Game.Events;
namespace HISP.Server
{
public class GameClient
{
public Socket ClientSocket;
public string RemoteIp;
private bool loggedIn = false;
public bool LoggedIn
{
get
{
bool login = loggedIn;
if (LoggedinUser == null)
return false;
if (LoggedinUser.LoggedinClient == null)
return false;
return login;
}
set
{
loggedIn = value;
}
}
public User LoggedinUser;
private Thread recvPackets;
private Timer inactivityTimer;
private Timer warnTimer;
private Timer kickTimer;
private Timer minuteTimer;
private bool isDisconnecting = false;
private int keepAliveInterval = 60 * 1000;
private int totalMinutesElapsed = 0;
private int oneMinute = 60 * 1000;
private int warnInterval = GameServer.IdleWarning * 60 * 1000;
private int kickInterval = GameServer.IdleTimeout * 60 * 1000;
private bool dcLock = false;
private void minuteTimerTick(object state)
{
dcLock = true;
totalMinutesElapsed++;
if (LoggedIn)
{
LoggedinUser.CanUseAdsChat = true;
LoggedinUser.FreeMinutes -= 1;
if(totalMinutesElapsed % 2 == 0)
{
LoggedinUser.TotalGlobalChatMessages++;
}
if (LoggedinUser.FreeMinutes <= 0)
{
LoggedinUser.FreeMinutes = 0;
if (!LoggedinUser.Subscribed && !LoggedinUser.Moderator && !LoggedinUser.Administrator)
{
dcLock = false;
Kick(Messages.KickReasonNoTime);
return;
}
}
// Those fun messages when u have been playing for awhile.
if (totalMinutesElapsed % (2 * 60) == 0)
{
string ptMessage = Messages.RngMessages[GameServer.RandomNumberGenerator.Next(0, Messages.RngMessages.Length)];
byte[] playTimeMessage = PacketBuilder.CreateChat(Messages.FormatPlaytimeMessage(totalMinutesElapsed / 60) + ptMessage, PacketBuilder.CHAT_BOTTOM_RIGHT);
SendPacket(playTimeMessage);
}
if (GameServer.RandomNumberGenerator.Next(0, 100) == 59) // RANDOM EVENT HAS OCCURED!
{
RandomEvent.ExecuteRandomEvent(LoggedinUser);
}
bool gotoPrision = false;
foreach(HorseInstance horse in LoggedinUser.HorseInventory.HorseList)
{
if (totalMinutesElapsed % 2 == 0)
{
horse.BasicStats.Thirst--;
horse.BasicStats.Hunger--;
if (horse.BasicStats.Thirst <= 0 && horse.BasicStats.Hunger <= 0)
{
horse.BasicStats.Health -= 5;
if(horse.BasicStats.Hunger <= 0)
{
gotoPrision = true; // Goto jail, go directly to jail, do not pass go, do not collect 200$
horse.BasicStats.Health = 10;
horse.BasicStats.Hunger = 500;
horse.BasicStats.Thirst = 500;
}
}
}
if(horse.Leaser > 0)
{
horse.LeaseTime--;
if (horse.LeaseTime <= 0)
{
int tpX = 0;
int tpY = 0;
if(horse.Breed.Type == "unicorn" || horse.Breed.Type == "pegasus")
{
foreach (World.SpecialTile tile in World.SpecialTiles)
{
if (tile.Code == null)
continue;
if (tile.Code.StartsWith("HORSELEASER-"))
{
int id = int.Parse(tile.Code.Split("-")[1]);
if (horse.Leaser == id)
{
string msg = Messages.FormatHorseReturnedToUniter(horse.Breed.Name);
if (horse.Breed.Type == "pegasus")
msg = Messages.HorseLeaserReturnedToUniterPegasus;
byte[] youWereTeleportedToUniter = PacketBuilder.CreateChat(msg, PacketBuilder.CHAT_BOTTOM_RIGHT);
SendPacket(youWereTeleportedToUniter);
tpX = tile.X;
tpY = tile.Y;
if(tile.ExitX != 0 && tile.ExitY != 0)
{
tpX = tile.ExitX;
tpY = tile.ExitY;
}
else
{
tpY++;
}
}
}
}
}
byte[] horseReturned = PacketBuilder.CreateChat(Messages.FormatHorseReturnedToOwner(horse.Name), PacketBuilder.CHAT_BOTTOM_RIGHT);
SendPacket(horseReturned);
if(tpX != 0 && tpY != 0)
LoggedinUser.Teleport(tpX, tpY);
if (LoggedinUser.CurrentlyRidingHorse != null)
{
if(LoggedinUser.CurrentlyRidingHorse.RandomId == horse.RandomId)
{
GameServer.StopRidingHorse(this);
}
}
if(LoggedinUser.LastViewedHorse != null)
{
if(LoggedinUser.LastViewedHorse.RandomId == horse.RandomId)
{
LoggedinUser.LastViewedHorse = null;
}
}
LoggedinUser.HorseInventory.DeleteHorse(horse);
}
}
}
if(gotoPrision)
{
byte[] sendToPrision = PacketBuilder.CreateChat(Messages.YouWereSentToPrisionIsle, PacketBuilder.CHAT_BOTTOM_RIGHT);
SendPacket(sendToPrision);
LoggedinUser.Teleport(45, 35);
}
if (totalMinutesElapsed % 5 == 0)
LoggedinUser.Thirst--;
if (totalMinutesElapsed % 15 == 0)
LoggedinUser.Hunger--;
if (totalMinutesElapsed % 15 == 0)
LoggedinUser.Tiredness--;
}
if (!isDisconnecting)
minuteTimer.Change(oneMinute, oneMinute);
dcLock = false;
}
private void keepAliveTimerTick(object state)
{
Logger.DebugPrint("Sending keep-alive packet to "+ LoggedinUser.Username);
byte[] updatePacket = PacketBuilder.CreateKeepAlive();
SendPacket(updatePacket);
}
private void warnTimerTick(object state)
{
Logger.DebugPrint("Sending inactivity warning to: " + RemoteIp);
byte[] chatPacket = PacketBuilder.CreateChat(Messages.FormatIdleWarningMessage(), PacketBuilder.CHAT_BOTTOM_RIGHT);
SendPacket(chatPacket);
if (LoggedIn)
LoggedinUser.Idle = true;
warnTimer.Dispose();
warnTimer = null;
}
private void kickTimerTick(object state)
{
Kick(Messages.FormatIdleKickMessage());
}
public void Login(int id)
{
// Check for duplicate
foreach(GameClient Client in GameServer.ConnectedClients)
{
if(Client.LoggedIn)
{
if (Client.LoggedinUser.Id == id)
Client.Kick(Messages.KickReasonDuplicateLogin);
}
}
LoggedinUser = new User(this,id);
LoggedIn = true;
Database.SetIpAddress(id, RemoteIp);
Database.SetLoginCount(id, Database.GetLoginCount(id) + 1);
inactivityTimer = new Timer(new TimerCallback(keepAliveTimerTick), null, keepAliveInterval, keepAliveInterval);
}
private bool receivePackets()
{
// HI1 Packets are terminates by 0x00 so we have to read until we receive that terminator
while(ClientSocket.Connected && !isDisconnecting)
{
if(isDisconnecting)
break;
try
{
using (MemoryStream ms = new MemoryStream())
{
if (ClientSocket.Available >= 1)
{
byte[] buffer = new byte[ClientSocket.Available];
ClientSocket.Receive(buffer);
foreach (Byte b in buffer)
{
if (isDisconnecting)
break;
ms.WriteByte(b);
if (b == 0x00)
{
ms.Seek(0x00, SeekOrigin.Begin);
byte[] fullPacket = ms.ToArray();
parsePackets(fullPacket);
ms.Seek(0x00, SeekOrigin.Begin);
ms.SetLength(0);
}
}
}
}
}
catch(SocketException)
{
Disconnect();
break;
}
}
while (dcLock) { }; // Refuse to shut down until dcLock is cleared. (prevents TOCTOU issues.)
// Stop Timers
if(inactivityTimer != null)
inactivityTimer.Dispose();
if(warnTimer != null)
warnTimer.Dispose();
if(kickTimer != null)
kickTimer.Dispose();
// Call OnDisconnect
GameServer.OnDisconnect(this);
LoggedIn = false;
// LoggedinUser = null;
// Close Sockets
ClientSocket.Close();
ClientSocket.Dispose();
return isDisconnecting; // Stop the thread.
}
private void parsePackets(byte[] Packet)
{
if (Packet.Length < 1)
{
Logger.ErrorPrint("Received an invalid packet (size: "+Packet.Length+")");
}
byte identifier = Packet[0];
// Reset timers
if (inactivityTimer != null && identifier != PacketBuilder.PACKET_KEEP_ALIVE)
{
if (LoggedIn)
LoggedinUser.Idle = false;
inactivityTimer.Change(keepAliveInterval, keepAliveInterval);
}
if (kickTimer != null && identifier != PacketBuilder.PACKET_KEEP_ALIVE)
kickTimer = new Timer(new TimerCallback(kickTimerTick), null, kickInterval, kickInterval);
if (warnTimer != null && identifier != PacketBuilder.PACKET_KEEP_ALIVE)
warnTimer = new Timer(new TimerCallback(warnTimerTick), null, warnInterval, warnInterval);
if (!LoggedIn) // Must be either login or policy-file-request
{
if (Encoding.UTF8.GetString(Packet).StartsWith("<policy-file-request/>")) // Policy File Request
{
GameServer.OnCrossdomainPolicyRequest(this);
}
switch (identifier)
{
case PacketBuilder.PACKET_LOGIN:
GameServer.OnLoginRequest(this, Packet);
break;
}
}
else
{
switch (identifier)
{
case PacketBuilder.PACKET_LOGIN:
GameServer.OnUserInfoRequest(this, Packet);
break;
case PacketBuilder.PACKET_MOVE:
GameServer.OnMovementPacket(this, Packet);
break;
case PacketBuilder.PACKET_PLAYERINFO:
GameServer.OnPlayerInfoPacket(this, Packet);
break;
case PacketBuilder.PACKET_PLAYER:
GameServer.OnProfilePacket(this, Packet);
break;
case PacketBuilder.PACKET_CHAT:
GameServer.OnChatPacket(this, Packet);
break;
case PacketBuilder.PACKET_CLICK:
GameServer.OnClickPacket(this, Packet);
break;
case PacketBuilder.PACKET_KEEP_ALIVE:
GameServer.OnKeepAlive(this, Packet);
break;
case PacketBuilder.PACKET_TRANSPORT:
GameServer.OnTransportUsed(this, Packet);
break;
case PacketBuilder.PACKET_INVENTORY:
GameServer.OnInventoryRequested(this, Packet);
break;
case PacketBuilder.PACKET_DYNAMIC_BUTTON:
GameServer.OnDynamicButtonPressed(this, Packet);
break;
case PacketBuilder.PACKET_DYNAMIC_INPUT:
GameServer.OnDynamicInputReceived(this, Packet);
break;
case PacketBuilder.PACKET_ITEM_INTERACTION:
GameServer.OnItemInteraction(this,Packet);
break;
case PacketBuilder.PACKET_ARENA_SCORE:
GameServer.OnArenaScored(this, Packet);
break;
case PacketBuilder.PACKET_QUIT:
GameServer.OnQuitPacket(this, Packet);
break;
case PacketBuilder.PACKET_NPC:
GameServer.OnNpcInteraction(this, Packet);
break;
case PacketBuilder.PACKET_BIRDMAP:
GameServer.OnBirdMapRequested(this, Packet);
break;
case PacketBuilder.PACKET_SWFMODULE:
GameServer.OnSwfModuleCommunication(this, Packet);
break;
case PacketBuilder.PACKET_HORSE:
GameServer.OnHorseInteraction(this, Packet);
break;
case PacketBuilder.PACKET_WISH:
GameServer.OnWish(this, Packet);
break;
case PacketBuilder.PACKET_RANCH:
GameServer.OnRanchPacket(this, Packet);
break;
case PacketBuilder.PACKET_AUCTION:
GameServer.OnAuctionPacket(this, Packet);
break;
case PacketBuilder.PACKET_PLAYER_INTERACTION:
GameServer.OnPlayerInteration(this, Packet);
break;
case PacketBuilder.PACKET_SOCIALS:
GameServer.OnSocialPacket(this, Packet);
break;
default:
Logger.ErrorPrint("Unimplemented Packet: " + BitConverter.ToString(Packet).Replace('-', ' '));
break;
}
}
}
public void Disconnect()
{
// Cant outright stop threads anymore in .NET core,
// Lets just let the thread stop gracefully.
this.isDisconnecting = true;
}
public void Kick(string Reason)
{
byte[] kickPacket = PacketBuilder.CreateKickMessage(Reason);
SendPacket(kickPacket);
Disconnect();
Logger.InfoPrint("CLIENT: "+RemoteIp+" KICKED for: "+Reason);
}
public void SendPacket(byte[] PacketData)
{
try
{
ClientSocket.Send(PacketData);
}
catch (Exception e)
{
if(!(e is SocketException))
Logger.ErrorPrint("Exception occured: " + e.Message);
Disconnect();
}
}
public GameClient(Socket clientSocket)
{
ClientSocket = clientSocket;
RemoteIp = clientSocket.RemoteEndPoint.ToString();
if(RemoteIp.Contains(":"))
RemoteIp = RemoteIp.Substring(0, RemoteIp.IndexOf(":"));
Logger.DebugPrint("Client connected @ " + RemoteIp);
kickTimer = new Timer(new TimerCallback(kickTimerTick), null, kickInterval, kickInterval);
warnTimer = new Timer(new TimerCallback(warnTimerTick), null, warnInterval, warnInterval);
minuteTimer = new Timer(new TimerCallback(minuteTimerTick), null, oneMinute, oneMinute);
recvPackets = new Thread(() =>
{
receivePackets();
});
recvPackets.Start();
}
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,32 @@
using System;
namespace HISP.Server
{
public class Logger
{
public static void HackerPrint(string text) // When someone is obviously cheating.
{
ConsoleColor prevColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[HACK] " + text);
Console.ForegroundColor = prevColor;
}
public static void DebugPrint(string text)
{
if (ConfigReader.Debug)
Console.WriteLine("[DEBUG] " + text);
}
public static void WarnPrint(string text)
{
Console.WriteLine("[WARN] " + text);
}
public static void ErrorPrint(string text)
{
Console.WriteLine("[ERROR] " + text);
}
public static void InfoPrint(string text)
{
Console.WriteLine("[INFO] " + text);
}
}
}

File diff suppressed because it is too large Load diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

View file

@ -0,0 +1,32 @@
## Written by SilicaAndPina,
## This Script is entered into the Public Domain!
## HISP v1.0 to v1.1 migration script...
# To use this script you must find/replace
# 'master' to your master db name
# and 'beta' to your game db name
CREATE DATABASE IF NOT EXISTS master;
CREATE TABLE IF NOT EXISTS master.Users(Id INT, Username TEXT(16),Email TEXT(128),Country TEXT(128),SecurityQuestion Text(128),SecurityAnswerHash TEXT(128),Age INT,PassHash TEXT(128), Salt TEXT(128),Gender TEXT(16), Admin TEXT(3), Moderator TEXT(3));
# Transfer user table to master db
USE beta;
INSERT INTO master.Users(SELECT Id,Username,Email,Country,SecurityQuestion,SecurityAnswerHash,Age,PassHash,Salt,Gender,Admin,Moderator FROM Users);
ALTER TABLE Users DROP COLUMN Email;
ALTER TABLE Users DROP COLUMN Country;
ALTER TABLE Users DROP COLUMN SecurityQuestion;
ALTER TABLE Users DROP COLUMN SecurityAnswerHash;
ALTER TABLE Users DROP COLUMN Age;
# Add new colums
ALTER TABLE UserExt ADD COLUMN TotalLogins INT;
UPDATE UserExt SET TotalLogins=0;
DROP TABLE OnlineUsers; # Server will re-generate the table when next started
# Change table sizes
ALTER TABLE UserExt CHANGE COLUMN ProfilePage ProfilePage TEXT(4000);
ALTER TABLE UserExt CHANGE COLUMN PrivateNotes PrivateNotes TEXT(65535);
ALTER TABLE MailBox CHANGE COLUMN Subject Subject TEXT(100);
ALTER TABLE MailBox CHANGE COLUMN Message Message TEXT(65535);
ALTER TABLE Horses CHANGE COLUMN description description TEXT(4000);
ALTER TABLE WildHorse CHANGE COLUMN description description TEXT(4000);
ALTER TABLE Ranches CHANGE COLUMN title title TEXT(50);
ALTER TABLE Ranches CHANGE COLUMN description description TEXT(250);

Binary file not shown.

File diff suppressed because it is too large Load diff

Some files were not shown because too many files have changed in this diff Show more