Add Feature pt1

This commit is contained in:
Silica 2022-03-07 07:08:47 -05:00
parent a184e4d735
commit 092534e331
131 changed files with 3113 additions and 1418 deletions

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,431 @@
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
{
private static List<Arena> arenas = new List<Arena>();
private List<ArenaEntry> entries;
private Timer arenaTimeout;
public static int[] ExpRewards;
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 static Arena[] Arenas
{
get
{
return arenas.ToArray();
}
}
public ArenaEntry[] Entries
{
get
{
return entries.ToArray();
}
}
public class ArenaEntry
{
public User EnteredUser;
public HorseInstance EnteredHorse;
public int SubmitScore = 0;
public bool Done = false;
}
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 bool HaveAllPlayersCompleted()
{
int playersCompleted = 0;
foreach(ArenaEntry entry in Entries)
{
if (entry.Done)
playersCompleted++;
}
if (playersCompleted >= Entries.Length)
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.Length <= 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 "CONFORMATION":
entry.EnteredHorse.BasicStats.Mood -= 300;
entry.EnteredHorse.BasicStats.Tiredness -= 200;
message = Messages.ArenaConformationStartup;
break;
default:
message = "<B>Arena Type not recognized.</B><BR>Why dont you stop asking questions and get to fucking beating the competition.";
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 place = 0;
ArenaEntry[] winners = Entries.OrderByDescending(o => o.SubmitScore).ToArray();
int[] expRewards = new int[winners.Length];
Array.Copy(ExpRewards, expRewards, winners.Length);
expRewards = expRewards.Reverse().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.Length;
entry.EnteredUser.AddMoney(prize);
byte[] youWinMessage = PacketBuilder.CreateChat(Messages.FormatArenaYouWinMessage(prize, expReward), PacketBuilder.CHAT_BOTTOM_RIGHT);
entry.EnteredUser.LoggedinClient.SendPacket(youWinMessage);
// Awards:
if (Entries.Length >= 2 && Type == "JUMPING")
entry.EnteredUser.Awards.AddAward(Award.GetAwardById(5)); // Good Jumper
if (Entries.Length >= 4 && Type == "JUMPING")
entry.EnteredUser.Awards.AddAward(Award.GetAwardById(6)); // Great Jumper
if (Entries.Length >= 2 && Type == "RACING")
entry.EnteredUser.Awards.AddAward(Award.GetAwardById(7)); // Good Racer
if (Entries.Length >= 4 && Type == "RACING")
entry.EnteredUser.Awards.AddAward(Award.GetAwardById(8)); // Great Racer
if (Entries.Length >= 2 && Type == "DRESSAGE")
entry.EnteredUser.Awards.AddAward(Award.GetAwardById(9)); // Good Dressage
if (Entries.Length >= 4 && Type == "DRESSAGE")
entry.EnteredUser.Awards.AddAward(Award.GetAwardById(10)); // Great Dressage
if (Entries.Length >= 2 && Type == "DRAFT")
entry.EnteredUser.Awards.AddAward(Award.GetAwardById(38)); // Strong Horse Award
if (Entries.Length >= 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 (Entries.Length + 1 > Slots)
{
if (Entries.Length + 1 > Slots)
{
byte[] enterFailed = PacketBuilder.CreateChat(Messages.ArenaFullErrorMessage, PacketBuilder.CHAT_BOTTOM_RIGHT);
user.LoggedinClient.SendPacket(enterFailed);
GameServer.UpdateArea(user.LoggedinClient);
return;
}
}
if(!UserHasHorseEntered(user))
{
ArenaEntry arenaEntry = new ArenaEntry();
arenaEntry.EnteredUser = user;
arenaEntry.EnteredHorse = horse;
entries.Add(arenaEntry);
}
user.TakeMoney(EntryCost);
byte[] enteredIntoCompetition = PacketBuilder.CreateChat(Messages.ArenaEnteredInto, PacketBuilder.CHAT_BOTTOM_RIGHT);
user.LoggedinClient.SendPacket(enteredIntoCompetition);
GameServer.UpdateAreaForAll(user.X, user.Y, true);
return;
}
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) == 1)
{
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.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,634 @@
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;
private static List<Filter> filteredWords = new List<Filter>();
private static List<Correction> correctedWords = new List<Correction>();
private static List<Reason> reasons = new List<Reason>();
public static void AddFilter(Filter filter)
{
filteredWords.Add(filter);
}
public static void AddCorrection(Correction correction)
{
correctedWords.Add(correction);
}
public static void AddReason(Reason reason)
{
reasons.Add(reason);
}
public static Filter[] FilteredWords
{
get
{
return filteredWords.ToArray();
}
}
public static Correction[] CorrectedWords
{
get
{
return correctedWords.ToArray();
}
}
public static Reason[] Reasons
{
get
{
return reasons.ToArray();
}
}
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("%SWF"))
return Command.Swf(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("%PRISON"))
return Command.Prison(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("%MODHORSE"))
return Command.ModHorse(message, args, user);
if (message.ToUpper().StartsWith("%DELITEM"))
return Command.DelItem(message, args, user);
if (message.ToUpper().StartsWith("%SHUTDOWN"))
return Command.Shutdown(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")) // some stupid handling on this one.
{
string placeName = message.Substring("!WARP".Length);
placeName = placeName.Trim();
return Command.Warp(message, placeName.Split(' '), user);
}
else if (message.ToUpper().StartsWith("!DANCE"))
return Command.Dance(message, args, user);
else if (message.ToUpper().StartsWith("!VERSION"))
return Command.Version(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 GameClient.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 GameClient.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 GameClient.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 GameClient.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 GameClient.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 && to != "")
{
List<GameClient> recipiants = new List<GameClient>();
foreach (GameClient client in GameClient.ConnectedClients)
{
if (client.LoggedIn)
{
if (!client.LoggedinUser.MutePrivateMessage && !client.LoggedinUser.MuteAll)
{
if (client.LoggedinUser.Username.ToLower().StartsWith(to.ToLower()))
{
recipiants.Add(client);
break;
}
}
}
}
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.");
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,78 @@
using System.Collections.Generic;
namespace HISP.Game.Chat
{
public class SocialType
{
public SocialType(string type)
{
socials = new List<Social>();
Type = type;
socialTypes.Add(this);
}
private static List<SocialType> socialTypes = new List<SocialType>();
public string Type;
private List<Social> socials;
public void AddSocial(Social social)
{
socials.Add(social);
}
public static SocialType[] SocialTypes
{
get
{
return socialTypes.ToArray();
}
}
public Social[] Socials
{
get
{
return socials.ToArray();
}
}
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.AddSocial(social);
return;
}
}
SocialType sType = new SocialType(type);
social.BaseSocialType = sType;
sType.AddSocial(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 GameClient.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 GameClient.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.Length;
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,159 @@
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 void AddThrownAt(User user)
{
thrownAt.Add(user);
}
public User Thrower;
private List<User> thrownAt;
public User[] ThrownAt
{
get
{
return thrownAt.ToArray();
}
}
}
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 = 50; // Thanks MayDay!
// Give Splatterballs
int[] allUsers = Database.GetModeratorUsers();
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 GameClient.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 GameClient.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.AddThrownAt(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,264 @@
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 GameClient.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 GameClient.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 GameClient.ConnectedClients)
if(client.LoggedIn)
client.SendPacket(eventEndMessage);
stopEvent();
}
private void stopEvent()
{
foreach(Participent participent in Participents)
{
if (participent == null)
continue;
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();
quizTimer.Dispose();
Active = false;
GameServer.QuizEvent = null;
}
private void quizTimesUp(object state)
{
EndEvent();
}
}
}

View file

@ -0,0 +1,125 @@
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 GameClient.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))
{
byte[] alreadyWonRiddleMessage = PacketBuilder.CreateChat(Messages.EventAlreadySovledRealTimeRiddle, PacketBuilder.CHAT_BOTTOM_RIGHT);
winner.LoggedinClient.SendPacket(alreadyWonRiddleMessage);
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 GameClient.ConnectedClients)
{
if (client.LoggedIn)
if (client.LoggedinUser.Id != winner.Id)
client.SendPacket(riddleWonMessage);
else
client.SendPacket(riddleYouWonMessage);
}
EndEvent();
}
public void EndEvent()
{
if(Active)
{
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 GameClient.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,155 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using HISP.Game.Services;
using HISP.Server;
using HISP.Game.Horse;
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 GameClient.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.Length);
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 GameClient.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, true, true);
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 GameClient.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 GameClient.ConnectedClients)
if (client.LoggedIn)
client.SendPacket(eventEndedMessage);
}
}
}
}

View file

@ -0,0 +1,166 @@
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;
}
private List<ThrownCounter> thrownWaterBalloonMemory;
public bool Active;
private Timer gameTimeout;
private const int WATER_BALLOON_GAME_TIMEOUT = 5;
public ThrownCounter[] ThrownWaterBalloonMemory
{
get
{
return thrownWaterBalloonMemory.ToArray();
}
}
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 GameClient.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 GameClient.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;
List<ThrownCounter> winningCounter = new List<ThrownCounter>();
// Find the highest throw count
foreach (ThrownCounter throwMemory in ThrownWaterBalloonMemory)
{
if (throwMemory == null)
continue;
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 == null)
continue;
if (throwMemory.NumThrown == maxThrown)
{
winningCounter.Add(throwMemory);
}
}
return winningCounter.ToArray();
}
public void LeaveEvent(User userToLeave)
{
foreach (ThrownCounter thrownMemory in ThrownWaterBalloonMemory)
{
if (thrownMemory == null)
continue;
if (thrownMemory.UserHit.Id == userToLeave.Id)
thrownWaterBalloonMemory.Remove(thrownMemory);
}
}
private ThrownCounter getThrownCounter(User userToGet)
{
foreach(ThrownCounter thrownMemory in ThrownWaterBalloonMemory)
{
if (thrownMemory == null)
continue;
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,659 @@
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 * 2) - baseHorse.Breed.BaseStats.Speed);
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;
private static List<Category> horseCategories = new List<Category>();
private static List<Breed> breeds = new List<Breed>();
public static void AddBreed(Breed breed)
{
breeds.Add(breed);
}
public static void AddHorseCategory(Category category)
{
horseCategories.Add(category);
}
public static Category[] HorseCategories
{
get
{
return horseCategories.ToArray();
}
}
public static Breed[] Breeds
{
get
{
return breeds.ToArray();
}
}
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,129 @@
using HISP.Game.Items;
using System.Collections.Generic;
namespace HISP.Game.Horse
{
public class Leaser
{
private static List<Leaser> horseLeasers = new List<Leaser>();
public static void AddHorseLeaser(Leaser leaser)
{
horseLeasers.Add(leaser);
}
public static Leaser[] HorseLeasers
{
get
{
return horseLeasers.ToArray();
}
}
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.Length)];
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,109 @@
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, bool ignoreFull=false)
{
if (HorseList.Length + 1 > baseUser.MaxHorses && !ignoreFull)
throw new InventoryFullException();
horse.Owner = baseUser.Id;
if(addToDb)
Database.AddHorse(horse);
horsesList.Add(horse);
}
public void DeleteHorseId(int id, bool removeFromDb = true)
{
foreach(HorseInstance horse in HorseList)
{
if(horse.RandomId == id)
{
if (removeFromDb)
Database.RemoveHorse(horse.RandomId);
horsesList.Remove(horse);
}
}
}
public void DeleteHorse(HorseInstance horse, bool removeFromDb=true)
{
DeleteHorseId(horse.RandomId, removeFromDb);
}
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,36 @@
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;
private List<ItemInstance> itemInstances;
public void RemoveItem(ItemInstance itm)
{
itemInstances.Remove(itm);
}
public void AddItem(ItemInstance itm)
{
itemInstances.Add(itm);
}
public ItemInstance[] ItemInstances
{
get
{
return itemInstances.ToArray();
}
}
}
}

View file

@ -0,0 +1,181 @@
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.AddItem(item);
return;
}
}
InventoryItem inventoryItem = new InventoryItem();
inventoryItem.ItemId = item.ItemId;
inventoryItem.AddItem(item);
inventoryItems.Add(inventoryItem);
}
public InventoryItem[] GetItemList()
{
return inventoryItems.OrderBy(o => Item.GetItemById(o.ItemId).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.RemoveItem(instance);
if (inventoryItem.ItemInstances.Length <= 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.Length >= Item.MAX_STACK)
{
throw new InventoryMaxStackException();
}
}
else if (Count >= BaseUser.MaxItems)
{
throw new InventoryFullException();
}
addItem(item, true);
}
}
}

View file

@ -0,0 +1,191 @@
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;
inventoryItems = new List<InventoryItem>();
}
private void addItem(ItemInstance item, bool addToDatabase)
{
foreach (InventoryItem invetoryItem in inventoryItems)
{
if (invetoryItem.ItemId == item.ItemId)
{
if (invetoryItem.Infinite)
{
addToDatabase = false;
goto retrn;
}
// no need to add +1, theres allready infinite quanity.
invetoryItem.AddItem(item);
goto retrn;
}
}
InventoryItem inventoryItem = new InventoryItem();
inventoryItem.ItemId = item.ItemId;
inventoryItem.Infinite = false;
inventoryItem.AddItem(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.AddItem(new ItemInstance(inventoryItem.ItemId));
inventoryItems.Add(inventoryItem);
}
public void Add(ItemInstance item, bool addToDb)
{
addItem(item, addToDb);
}
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 int GetSortPos(InventoryItem item)
{
if (item == null)
return 0;
int bias = 1000;
int sortBy = Item.GetItemById(item.ItemId).SortBy;
if (item.Infinite)
sortBy -= bias;
return sortBy;
}
public InventoryItem[] GetItemList()
{
return inventoryItems.OrderBy(o => GetSortPos(o)).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.RemoveItem(instance);
if (inventoryItem.ItemInstances.Length <= 0)
inventoryItems.Remove(inventoryItem);
if (!inventoryItem.Infinite) // no need to bug the database.
Database.RemoveItemFromShopInventory(baseShop.Id, item);
else
inventoryItem.AddItem(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,344 @@
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!!!
for (int i = 0; i < droppedItemsList.Count; 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]);
}
}
}
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()
{
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 (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 (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();
}
}
}

View file

@ -0,0 +1,276 @@
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 const int MAX_STACK = 50;
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 (no < 0)
return 0;
if (no >= MiscFlags.Length)
return 0;
else
return MiscFlags[no];
}
}
public struct ThrowableItem
{
public int Id;
public string HitMessage;
public string ThrowMessage;
public string HitYourselfMessage;
}
private static List<ItemInformation> items = new List<ItemInformation>();
private static List<ThrowableItem> throwableItems = new List<ThrowableItem>();
public static void AddItemInfo(ItemInformation itm)
{
items.Add(itm);
}
public static void AddThrowableItem(ThrowableItem throwableItem)
{
throwableItems.Add(throwableItem);
}
public static ItemInformation[] Items
{
get
{
return items.ToArray();
}
}
public static ThrowableItem[] ThrowableItems
{
get
{
return throwableItems.ToArray();
}
}
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 Ruby;
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 ItemInformation GetRandomItem()
{
while (true)
{
Item.ItemInformation itm = Items[GameServer.RandomNumberGenerator.Next(0, Items.Length)];
if (itm.Type == "QUEST" || itm.Type == "CONCEPTUAL" || itm.Type == "TEXT")
continue;
return itm;
}
}
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.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(Util.CapitalizeFirstLetter(itemInfo.EmbedSwf));
set.Add(itemInfo);
}
catch(KeyNotFoundException)
{
TackSet tackSet = new TackSet();
tackSet.SetName = Util.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,138 @@
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 PrisonIsleX;
public static int PrisonIsleY;
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,108 @@
using HISP.Player;
using HISP.Server;
using System.Collections.Generic;
using System.Linq;
namespace HISP.Game
{
public class Multiroom
{
private static List<Multiroom> multirooms = new List<Multiroom>();
private List<User> joinedUsers = new List<User>();
public int x;
public int y;
public User[] JoinedUsers
{
get
{
return joinedUsers.ToArray();
}
}
public static Multiroom[] Multirooms
{
get
{
return multirooms.ToArray();
}
}
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 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.MajorPriority)
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.MajorPriority)
GameServer.UpdateArea(joinedUser.LoggedinClient);
}
}
}
}

View file

@ -0,0 +1,339 @@
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;
}
private static List<NpcEntry> npcList = new List<NpcEntry>();
public static void AddNpc(NpcEntry npc)
{
npcList.Add(npc);
}
public static NpcEntry[] NpcList
{
get
{
return npcList.ToArray();
}
}
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,395 @@
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;
}
private static List<QuestEntry> questList = new List<QuestEntry>();
public static void AddQuestEntry(QuestEntry quest)
{
questList.Add(quest);
}
private static QuestEntry[] QuestList
{
get
{
return questList.ToArray();
}
}
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.Length >= 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,488 @@
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 Convert.ToInt32(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 Convert.ToInt32(Math.Round((double)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)
{
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 = Util.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)
{
if (buildingId < 0)
return null;
if (buildingId >= buildings.Length)
return null;
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,373 @@
using HISP.Game.Horse;
using HISP.Player;
using HISP.Security;
using HISP.Server;
using System.Collections.Generic;
namespace HISP.Game.Services
{
public class Auction
{
private static List<Auction> auctionRooms = new List<Auction>();
public static Auction[] AuctionRooms
{
get
{
return auctionRooms.ToArray();
}
}
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;
private List<AuctionBid> bidders = new List<AuctionBid>();
public AuctionBid[] Bidders
{
get
{
return bidders.ToArray();
}
}
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.RemoveBid(bid);
}
bidders.Clear();
}
}
public void AddBid(AuctionBid bid)
{
bidders.Add(bid);
}
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.AddBid(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()
{
World.SpecialTile[] tiles = World.GetSpecialTilesByName("AUCTION-" + this.RoomId.ToString());
foreach (World.SpecialTile tile in tiles)
{
GameServer.UpdateAreaForAll(tile.X, tile.Y, true);
}
}
public void DeleteEntry(AuctionEntry entry)
{
Database.DeleteAuctionRoom(entry.RandomId);
auctionEntries.Remove(entry);
}
public void AddExistingEntry(AuctionEntry entry)
{
auctionEntries.Add(entry);
}
public void AddEntry(AuctionEntry entry)
{
entry.auctionRoomPlacedIn = this;
Database.AddAuctionRoom(entry, this.RoomId);
auctionEntries.Add(entry);
}
private List<AuctionEntry> auctionEntries;
public int RoomId;
public AuctionEntry[] AuctionEntries
{
get
{
return auctionEntries.ToArray();
}
}
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.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,44 @@
using System;
using System.Collections.Generic;
namespace HISP.Game.Services
{
public class Groomer
{
private static List<Groomer> groomers = new List<Groomer>();
public static Groomer[] Groomers
{
get
{
return groomers.ToArray();
}
}
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.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 Convert.ToInt32(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,68 @@
using HISP.Game.Horse;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace HISP.Game.Services
{
public class Pawneer
{
public Pawneer(int breedId, int basePrice)
{
BreedId = breedId;
BasePrice = basePrice;
}
private static List<Pawneer> pawneerPriceModels = new List<Pawneer>();
private static Pawneer[] PawneerPriceModels
{
get
{
return pawneerPriceModels.ToArray();
}
}
public static void AddPawneerPriceModel(Pawneer pawneerPrice)
{
pawneerPriceModels.Add(pawneerPrice);
}
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,72 @@
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, int id)
{
this.Inventory = new ShopInventory(this);
this.Id = id;
foreach (int stock in infiniteStocks)
{
if (Item.ItemIdExist(stock))
this.Inventory.AddInfinity(Item.GetItemById(stock));
else
Logger.WarnPrint("Item ID: " + stock + " Does not exist.");
}
ItemInstance[] instances = Database.GetShopInventory(this.Id);
foreach (ItemInstance instance in instances)
{
this.Inventory.Add(instance, false);
}
Shop.ShopList.Add(this);
}
public UInt64 CalculateBuyCost(Item.ItemInformation item)
{
return Convert.ToUInt64(Math.Round((double)item.SellPrice * (100.0 / (double)BuyPricePercentage)));
}
public UInt64 CalculateSellCost(Item.ItemInformation item)
{
return Convert.ToUInt64(Math.Round((double)item.SellPrice * (100.0 / (double)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,27 @@
using System.Collections.Generic;
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.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,107 @@
using System;
using System.Collections.Generic;
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;
private List<RequiredItem> requiredItems;
public void AddRequiredItem(RequiredItem item)
{
requiredItems.Add(item);
}
public RequiredItem[] RequiredItems
{
get
{
return requiredItems.ToArray();
}
}
}
public int X;
public int Y;
private List<CraftableItem> craftableItems;
private static List<Workshop> workshops = new List<Workshop>();
public void AddCraftableItem(CraftableItem craftItem)
{
craftableItems.Add(craftItem);
}
public static void AddWorkshop(Workshop wkShop)
{
workshops.Add(wkShop);
}
public CraftableItem[] CraftableItems
{
get
{
return craftableItems.ToArray();
}
}
public static Workshop[] Workshops
{
get
{
return workshops.ToArray();
}
}
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,168 @@
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;
}
private static List<PoetryEntry> poetList = new List<PoetryEntry>();
private static List<PoetryPeice[]> poetryRooms = new List<PoetryPeice[]>();
public static void AddPoetEntry(PoetryEntry poetEntry)
{
poetList.Add(poetEntry);
}
public static PoetryEntry[] PoetList
{
get
{
return poetList.ToArray();
}
}
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)
{
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.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,129 @@
using HISP.Server;
using System.Collections.Generic;
namespace HISP.Game.SwfModules
{
public class Dressup
{
private static List<DressupRoom> dressupRooms = new List<DressupRoom>();
public static DressupRoom[] DressupRooms
{
get
{
return dressupRooms.ToArray();
}
}
public class DressupRoom
{
public int RoomId;
private List<DressupPeice> dressupPeices;
public DressupPeice[] DressupPeices
{
get
{
return dressupPeices.ToArray();
}
}
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 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,235 @@
using HISP.Player;
using HISP.Security;
using HISP.Server;
using System.Collections.Generic;
using System.Threading;
namespace HISP.Game
{
public class TwoPlayer
{
private static List<TwoPlayer> twoPlayerGames = new List<TwoPlayer>();
public static TwoPlayer[] TwoPlayerGames
{
get
{
return twoPlayerGames.ToArray();
}
}
public static void TwoPlayerRemove(User user)
{
foreach(TwoPlayer twoPlayerGame in TwoPlayerGames)
{
if((twoPlayerGame.Invitee.Id == user.Id))
{
twoPlayerGame.CloseGame(user, true);
}
}
}
public static bool IsPlayerInvitingPlayer(User sender, User checkInvites)
{
foreach (TwoPlayer twoPlayerGame in TwoPlayerGames)
{
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)
{
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)
{
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)
{
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.MajorPriority = false;
Inviting.MajorPriority = 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)
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.MajorPriority = false;
Inviting.MajorPriority = false;
if (!closeSilently)
UpdateAll();
else
updateOthers();
twoPlayerGames.Remove(this);
}
}
}
}

View file

@ -0,0 +1,398 @@
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)
{
foreach (SpecialTile specialTile in SpecialTiles)
{
if (specialTile.X == x && specialTile.Y == y)
{
return true;
}
}
return false;
}
public static bool InIsle(int x, int y)
{
foreach (Isle isle in Isles)
{
if (isle.StartX <= x && isle.EndX >= x && isle.StartY <= y && isle.EndY >= y)
{
return true;
}
}
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[] GetSpecialTilesByCode(string code)
{
List<SpecialTile> tiles = new List<SpecialTile>();
foreach (SpecialTile tile in SpecialTiles)
{
if (tile.Code == code)
{
tiles.Add(tile);
}
}
return tiles.ToArray();
}
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;
}
}
}