PageRenderTime 55ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/SDK/api/CSharp/ClassLibrary1/SkyportConnection.cs

https://bitbucket.org/ehvattum/draugr_contrib
C# | 269 lines | 246 code | 20 blank | 3 comment | 11 complexity | fc5600b2be7b60fce46724b4738537c3 MD5 | raw file
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net.Sockets;
  5. namespace Skyport
  6. {
  7. public class SkyportConnection
  8. {
  9. private readonly string host;
  10. private readonly SkyportObserver observer;
  11. private readonly int port;
  12. private TcpClient client;
  13. private StreamReader reader;
  14. private StreamWriter writer;
  15. public SkyportConnection(string HostName, int PortNumber, SkyportObserver ObserverArg)
  16. {
  17. observer = ObserverArg;
  18. host = HostName;
  19. port = PortNumber;
  20. }
  21. private void Send(object obj)
  22. {
  23. string str = fastJSON.JSON.Instance.ToJSON(obj,
  24. new fastJSON.JSONParameters {EnableAnonymousTypes = true});
  25. writer.WriteLine(str);
  26. }
  27. private string ReadDataFromSocket()
  28. {
  29. string line = reader.ReadLine();
  30. return line;
  31. }
  32. private void Parse(Dictionary<string, object> obj)
  33. {
  34. object messageType;
  35. if (obj.TryGetValue("error", out messageType))
  36. {
  37. observer.OnError((string) messageType);
  38. return;
  39. }
  40. if (!obj.TryGetValue("message", out messageType))
  41. {
  42. Console.WriteLine("Error: JSON packet has no 'message' key");
  43. return;
  44. }
  45. Console.WriteLine("got: " + (string) messageType);
  46. switch ((string) messageType)
  47. {
  48. case "connect":
  49. observer.OnHandshakeSuccessful();
  50. break;
  51. case "gamestate":
  52. ParseGamestate(obj);
  53. break;
  54. case "action":
  55. ParseAction(obj);
  56. break;
  57. case "endturn":
  58. observer.OnEndturn();
  59. break;
  60. default:
  61. Console.WriteLine("Got unknown message: " + messageType);
  62. break;
  63. }
  64. }
  65. private void ParseGamestate(Dictionary<string, object> obj)
  66. {
  67. object turnNumber;
  68. object map;
  69. object players;
  70. obj.TryGetValue("turn", out turnNumber);
  71. obj.TryGetValue("map", out map);
  72. obj.TryGetValue("players", out players);
  73. if ((long) turnNumber == 0)
  74. {
  75. observer.OnGamestart(new Map(map));
  76. }
  77. else
  78. {
  79. List<object> playerArr = (List<object>) players;
  80. PlayerData[] playerDataList = new PlayerData[playerArr.Count];
  81. for (int i = 0; i < playerArr.Count; i++)
  82. {
  83. playerDataList[i] = new PlayerData(playerArr[i]);
  84. }
  85. observer.OnGamestate((long) turnNumber, new Map(map), playerDataList);
  86. }
  87. }
  88. private void ParseAction(Dictionary<string, object> obj)
  89. {
  90. object player;
  91. object action;
  92. object type;
  93. obj.TryGetValue("from", out player);
  94. obj.TryGetValue("type", out type);
  95. obj.Remove("message");
  96. obj.Remove("from");
  97. obj.Remove("type");
  98. Dictionary<string, string> parameters = new Dictionary<string, string>();
  99. observer.OnAction((string) player, (string) type, obj);
  100. }
  101. /**
  102. * Public API
  103. */
  104. public void Run()
  105. {
  106. try
  107. {
  108. client = new TcpClient(host, port);
  109. Stream s = client.GetStream();
  110. reader = new StreamReader(s);
  111. writer = new StreamWriter(s);
  112. writer.AutoFlush = true;
  113. observer.OnConnectionEstablished(this);
  114. }
  115. catch (Exception e)
  116. {
  117. Console.WriteLine("Error establishing connection: " + e.Message);
  118. }
  119. while (true)
  120. {
  121. string data = ReadDataFromSocket();
  122. if (data == null)
  123. {
  124. break;
  125. }
  126. data.TrimEnd('\r', '\n');
  127. object newobj;
  128. try
  129. {
  130. newobj = fastJSON.JSON.Instance.Parse(data);
  131. }
  132. catch (Exception e)
  133. {
  134. Console.WriteLine("Warning: Invalid JSON packet received: '" + data + "':" + e.Message);
  135. return;
  136. }
  137. Dictionary<string, object> newdict = (Dictionary<string, object>) newobj;
  138. Parse(newdict);
  139. }
  140. }
  141. public void SendHandshake(string AIName)
  142. {
  143. Send(new {message = "connect", revision = 1, name = AIName});
  144. }
  145. public void SendLoadout(string PrimaryWeapon, string SecondaryWeapon)
  146. {
  147. Dictionary<string, string> newdict = new Dictionary<string, string>();
  148. newdict.Add("message", "loadout");
  149. newdict.Add("primary-weapon", PrimaryWeapon);
  150. newdict.Add("secondary-weapon", SecondaryWeapon);
  151. Send(newdict);
  152. }
  153. public void SendMove(string whereto)
  154. {
  155. Send(new {message = "action", type = "move", direction = whereto});
  156. }
  157. public void AttackLaser(string whereto)
  158. {
  159. Send(new {message = "action", type = "laser", direction = whereto});
  160. }
  161. public void AttackMortar(long j, long k)
  162. {
  163. Send(new {message = "action", type = "mortar", direction = j + "," + k});
  164. }
  165. public void AttackDroid(string[] CommandSequence)
  166. {
  167. Send(new {message = "action", type = "droid", sequence = CommandSequence});
  168. }
  169. public void Mine()
  170. {
  171. Send(new {message = "action", type = "mine"});
  172. }
  173. public void Upgrade(string WeaponToUpgrade)
  174. {
  175. Send(new {message = "action", type = "upgrade", weapon = WeaponToUpgrade});
  176. }
  177. }
  178. public class PlayerData
  179. {
  180. public string PrimaryWeapon;
  181. public long PrimaryWeaponLevel;
  182. public string SecondaryWeapon;
  183. public long SecondaryWeaponLevel;
  184. public long health;
  185. public long j;
  186. public long k;
  187. public string name;
  188. public long score;
  189. public PlayerData(object obj)
  190. {
  191. Dictionary<string, object> newdict = (Dictionary<string, object>) obj;
  192. object primaryObj,
  193. secondaryObj,
  194. primaryStringObj,
  195. secondaryStringObj,
  196. primaryLevelObj,
  197. secondaryLevelObj,
  198. positionStringObj,
  199. nameStringObj,
  200. scoreObj,
  201. healthObj;
  202. newdict.TryGetValue("primary-weapon", out primaryObj);
  203. newdict.TryGetValue("secondary-weapon", out secondaryObj);
  204. Dictionary<string, object> primaryDict = (Dictionary<string, object>) primaryObj;
  205. Dictionary<string, object> secondaryDict = (Dictionary<string, object>) secondaryObj;
  206. primaryDict.TryGetValue("name", out primaryStringObj);
  207. primaryDict.TryGetValue("level", out primaryLevelObj);
  208. secondaryDict.TryGetValue("name", out secondaryStringObj);
  209. secondaryDict.TryGetValue("level", out secondaryLevelObj);
  210. newdict.TryGetValue("name", out nameStringObj);
  211. newdict.TryGetValue("health", out healthObj);
  212. newdict.TryGetValue("score", out scoreObj);
  213. newdict.TryGetValue("position", out positionStringObj);
  214. string coordString = (string) positionStringObj;
  215. string[] coords = coordString.Split(',');
  216. j = Int64.Parse(coords[0]);
  217. k = Int64.Parse(coords[1]);
  218. name = (string) nameStringObj;
  219. score = (long) scoreObj;
  220. health = (long) healthObj;
  221. PrimaryWeapon = (string) primaryStringObj;
  222. SecondaryWeapon = (string) secondaryStringObj;
  223. PrimaryWeaponLevel = (long) primaryLevelObj;
  224. SecondaryWeaponLevel = (long) secondaryLevelObj;
  225. }
  226. }
  227. public class Map
  228. {
  229. public Map(object obj)
  230. {
  231. Dictionary<string, object> map = (Dictionary<string, object>) obj;
  232. object jLength, kLength, data;
  233. map.TryGetValue("j-length", out jLength);
  234. map.TryGetValue("k-length", out kLength);
  235. map.TryGetValue("data", out data);
  236. string[,] mapArray = new string[(long) jLength,(long) kLength];
  237. List<object> outer = (List<object>) data;
  238. for (int j = 0; j < outer.Count; j++)
  239. {
  240. List<object> inner = (List<object>) (outer[j]);
  241. for (int k = 0; k < inner.Count; k++)
  242. {
  243. Console.Write(inner[k] + ", ");
  244. }
  245. Console.WriteLine("");
  246. }
  247. }
  248. }
  249. }