Click here to Skip to main content
15,892,537 members
Articles / Artificial Intelligence

Writing a Multiplayer Game (in WPF)

Rate me:
Please Sign up or sign in to vote.
4.93/5 (131 votes)
16 Mar 2012CPOL25 min read 215.8K   17.1K   246  
This article will explain some concepts of game development and how to apply and adapt them for multiplayer development.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Pfz.Caching;
using Pfz.DynamicObjects;

namespace Pfz.Extensions
{
	/// <summary>
	/// This class adds two methods to the EventInfo class, making it possible
	/// to register into events in a "weak" manner. This means that the registered
	/// object can still be collected, also deregistering itself from the event.
	/// </summary>
	public static class PfzEventExtensions
	{
		private sealed class WeakProxy:
			WeakReference,
			IProxyDelegate
		{
			public WeakProxy(object target):
				base(target)
			{
			}

			internal Delegate _delegate;
			internal MethodInfo _methodInfo;
			public object Invoke(object[] parameters)
			{
				var target = Target;
				if (target != null)
					return _methodInfo.Invoke(target, parameters);

				return null;
			}
		}

		private static readonly object _registeredEventsLock = new object();
		private static Dictionary<EventInfo, Dictionary<MethodInfo, Dictionary<object, HashSet<WeakProxy>>>> _registeredEvents;

		[SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")]
		static PfzEventExtensions()
		{
			GCUtils.Collected += _Collected;
		}
		private static void _Collected()
		{
			lock(_registeredEventsLock)
			{
				var oldRegisteredEvents = _registeredEvents;
				if (oldRegisteredEvents == null)
					return;

				var newRegisteredEvents = new Dictionary<EventInfo, Dictionary<MethodInfo, Dictionary<object, HashSet<WeakProxy>>>>();
				foreach(var pair1 in oldRegisteredEvents)
				{
					var eventInfo = pair1.Key;
					var oldMethodDictionary = pair1.Value;
					var newMethodDictionary = new Dictionary<MethodInfo, Dictionary<object, HashSet<WeakProxy>>>();
					foreach(var pair2 in oldMethodDictionary)
					{
						var methodInfo = pair2.Key;
						var oldOwnerDictionary = pair2.Value;
						var newOwnerDictionary = new Dictionary<object, HashSet<WeakProxy>>();

						foreach(var pair3 in oldOwnerDictionary)
						{
							var owner = pair3.Key;
							var oldHashset = pair3.Value;
							var newHashset = new HashSet<WeakProxy>();

							foreach(var weakProxy in oldHashset)
								if (weakProxy.IsAlive)
									newHashset.Add(weakProxy);

							if (newHashset.Count > 0)
								newOwnerDictionary.Add(owner, newHashset);
						}

						if (newOwnerDictionary.Count > 0)
							newMethodDictionary.Add(methodInfo, newOwnerDictionary);
					}

					if (newMethodDictionary.Count > 0)
						newRegisteredEvents.Add(eventInfo, newMethodDictionary);
				}

				if (newRegisteredEvents.Count > 0)
					_registeredEvents = newRegisteredEvents;
				else
					_registeredEvents = null;
			}
		}

		/// <summary>
		/// Adds an event-handler to an event, but still allows the target object to
		/// be collected.
		/// </summary>
		public static void AddWeakEventHandler(this EventInfo eventInfo, object eventOwner, Delegate handler)
		{
			if (eventInfo == null)
				throw new ArgumentNullException("eventInfo");
			
			if (handler == null)
				throw new ArgumentNullException("handler");
				
			var target = handler.Target;
			if (target == null)
				throw new ArgumentException("The handler does not have a target. Do not use this method for static event-handlers.");
				
			if (eventInfo.GetAddMethod().IsStatic != (eventOwner == null))
				throw new ArgumentException("Invalid eventOwner.");
				
			Type handlerType = eventInfo.EventHandlerType;
			
			if (handler.GetType() != handlerType)
				throw new ArgumentException("Invalid handler for this eventInfo.");

			WeakProxy weakProxy = new WeakProxy(target);
			weakProxy._methodInfo = handler.Method;

			var newHandler = DelegateProxier.Proxy(weakProxy, handler.GetType());
			weakProxy._delegate = newHandler;
			eventInfo.AddEventHandler(eventOwner, newHandler);

			lock(_registeredEventsLock)
			{
				var registeredEvents = _registeredEvents;
				if (registeredEvents == null)
				{
					registeredEvents = new Dictionary<EventInfo, Dictionary<MethodInfo, Dictionary<object, HashSet<WeakProxy>>>>();
					_registeredEvents = registeredEvents;
				}

				Dictionary<MethodInfo, Dictionary<object, HashSet<WeakProxy>>> methodDictionary;
				if (!registeredEvents.TryGetValue(eventInfo, out methodDictionary))
				{
					methodDictionary = new Dictionary<MethodInfo, Dictionary<object, HashSet<WeakProxy>>>();
					registeredEvents.Add(eventInfo, methodDictionary);
				}

				MethodInfo methodInfo = handler.Method;
				Dictionary<object, HashSet<WeakProxy>> ownerDictionary;
				if (!methodDictionary.TryGetValue(methodInfo, out ownerDictionary))
				{
					ownerDictionary = new Dictionary<object, HashSet<WeakProxy>>();
					methodDictionary.Add(methodInfo, ownerDictionary);
				}

				var fakeOwner = eventOwner;
				if (eventOwner == null)
					fakeOwner = _registeredEventsLock;

				HashSet<WeakProxy> hashset;
				if (!ownerDictionary.TryGetValue(fakeOwner, out hashset))
				{
					hashset = new HashSet<WeakProxy>();
					ownerDictionary.Add(fakeOwner, hashset);
				}

				hashset.Add(weakProxy);
			}
		}
		
		/// <summary>
		/// Removes an event previously registered as weak.
		/// </summary>
		public static void RemoveWeakEventHandler(this EventInfo eventInfo, object eventOwner, Delegate handler)
		{
			if (eventInfo == null)
				throw new ArgumentNullException("eventInfo");
			
			if (handler == null)
				throw new ArgumentNullException("handler");

			var target = handler.Target;
			if (target == null)
				throw new ArgumentException("handler.Target is null.", "handler");
			
			lock(_registeredEventsLock)
			{
				var registeredEvents = _registeredEvents;
				if (registeredEvents == null)
					return;

				Dictionary<MethodInfo, Dictionary<object, HashSet<WeakProxy>>> methodDictionary;
				if (!registeredEvents.TryGetValue(eventInfo, out methodDictionary))
					return;

				Dictionary<object, HashSet<WeakProxy>> ownerDictionary;
				if (!methodDictionary.TryGetValue(handler.Method, out ownerDictionary))
					return;
				
				var fakeOwner = eventOwner;
				if (eventOwner == null)
					fakeOwner = _registeredEventsLock;

				HashSet<WeakProxy> hashset;
				if (!ownerDictionary.TryGetValue(fakeOwner, out hashset))
					return;

				foreach(var weakProxy in hashset)
				{
					if (weakProxy.Target == target)
					{
						eventInfo.RemoveEventHandler(target, weakProxy._delegate);
						hashset.Remove(weakProxy);
						break;
					}
				}
			}
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Microsoft
United States United States
I started to program computers when I was 11 years old, as a hobbyist, programming in AMOS Basic and Blitz Basic for Amiga.
At 12 I had my first try with assembler, but it was too difficult at the time. Then, in the same year, I learned C and, after learning C, I was finally able to learn assembler (for Motorola 680x0).
Not sure, but probably between 12 and 13, I started to learn C++. I always programmed "in an object oriented way", but using function pointers instead of virtual methods.

At 15 I started to learn Pascal at school and to use Delphi. At 16 I started my first internship (using Delphi). At 18 I started to work professionally using C++ and since then I've developed my programming skills as a professional developer in C++ and C#, generally creating libraries that help other developers do their work easier, faster and with less errors.

Want more info or simply want to contact me?
Take a look at: http://paulozemek.azurewebsites.net/
Or e-mail me at: paulozemek@outlook.com

Codeproject MVP 2012, 2015 & 2016
Microsoft MVP 2013-2014 (in October 2014 I started working at Microsoft, so I can't be a Microsoft MVP anymore).

Comments and Discussions