Skip to content

Instantly share code, notes, and snippets.

@Minikloon
Created June 7, 2016 08:14
Show Gist options
  • Save Minikloon/6db15c11689d11b6c359f8c7d8a0e954 to your computer and use it in GitHub Desktop.
Save Minikloon/6db15c11689d11b6c359f8c7d8a0e954 to your computer and use it in GitHub Desktop.
public static class ActionBlock
{
private static readonly Dictionary<string, List<Action<Level, Player>>> Hooks = new Dictionary<string, List<Action<Level, Player>>>();
private static readonly ReaderWriterLockSlim RwLock = new ReaderWriterLockSlim();
// returns true if an interaction took place
public static bool InteractHook(this Block block, Level level, Player player, BlockFace face)
{
string hash = GetHash(level, block);
List<Action<Level, Player>> hooks;
RwLock.EnterReadLock();
try
{
if (!Hooks.TryGetValue(hash, out hooks) || !hooks.Any())
return false;
}
finally
{
RwLock.ExitReadLock();
}
foreach (var hook in hooks)
hook(level, player);
return true;
}
public static void RegisterHook(this Block block, Level level, Action<Level, Player> callback)
{
string hash = GetHash(level, block);
RwLock.EnterWriteLock();
List<Action<Level, Player>> hooks;
if (!Hooks.TryGetValue(hash, out hooks))
{
hooks = new List<Action<Level, Player>>();
Hooks[hash] = hooks;
}
hooks.Add(callback);
RwLock.ExitWriteLock();
}
public static void UnregisterAllHooks(this Block block, Level level)
{
string hash = GetHash(level, block);
RwLock.EnterWriteLock();
Hooks.Remove(hash);
RwLock.ExitWriteLock();
}
// returns what uniquely identifies a block registration, in this case its location
private static string GetHash(Level level, Block block)
{
var coords = block.Coordinates;
return level.LevelId + $"({coords.X},{coords.Y},{coords.Z})";
}
}
if (message.face <= 5)
{
var coords = message.blockcoordinates;
var face = (BlockFace) message.face;
Block target = Level.GetBlock(coords);
if (target.InteractHook(Level, this, face))
return;
Level.Interact(Level, this, message.item.Id, coords, message.item.Metadata, face, message.facecoordinates);
} else {
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment