NetworkSerializationExtensions.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. using Microsoft.Xna.Framework.Net;
  2. using CardsFramework;
  3. namespace Blackjack.Networking
  4. {
  5. public static class NetworkSerializationExtensions
  6. {
  7. public static void Write(this PacketWriter writer, TraditionalCard card)
  8. {
  9. writer.Write((byte)card.Type); // Suit (fits in byte - max 0x08)
  10. writer.Write((ushort)card.Value); // Value (needs ushort - max 0x4000)
  11. }
  12. public static TraditionalCard ReadCard(this PacketReader reader)
  13. {
  14. var suit = (CardSuit)reader.ReadByte();
  15. var value = (CardValue)reader.ReadUInt16();
  16. return TraditionalCard.Create(suit, value);
  17. }
  18. public static void Write(this PacketWriter writer, Hand hand)
  19. {
  20. writer.Write(hand.Count);
  21. for (int i = 0; i < hand.Count; i++)
  22. {
  23. writer.Write(hand[i]);
  24. }
  25. }
  26. public static Hand ReadHand(this PacketReader reader)
  27. {
  28. var hand = new Hand();
  29. int count = reader.ReadInt32();
  30. for (int i = 0; i < count; i++)
  31. {
  32. // Add is internal, so this may need to be called from within the same assembly
  33. var card = reader.ReadCard();
  34. hand.GetType().GetMethod("Add", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)
  35. .Invoke(hand, new object[] { card });
  36. }
  37. return hand;
  38. }
  39. }
  40. }