Snake.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using Terminal.Gui;
  8. namespace UICatalog.Scenarios;
  9. [ScenarioMetadata ("Snake", "The game of apple eating.")]
  10. [ScenarioCategory ("Colors")]
  11. [ScenarioCategory ("Drawing")]
  12. public class Snake : Scenario
  13. {
  14. private bool isDisposed;
  15. public override void Setup ()
  16. {
  17. base.Setup ();
  18. var state = new SnakeState ();
  19. state.Reset (60, 20);
  20. var snakeView = new SnakeView (state) { Width = state.Width, Height = state.Height };
  21. Win.Add (snakeView);
  22. var sw = new Stopwatch ();
  23. Task.Run (
  24. () =>
  25. {
  26. while (!isDisposed)
  27. {
  28. sw.Restart ();
  29. if (state.AdvanceState ())
  30. {
  31. // When updating from a Thread/Task always use Invoke
  32. Application.Invoke (() => { snakeView.SetNeedsDisplay (); });
  33. }
  34. long wait = state.SleepAfterAdvancingState - sw.ElapsedMilliseconds;
  35. if (wait > 0)
  36. {
  37. Task.Delay ((int)wait).Wait ();
  38. }
  39. }
  40. }
  41. );
  42. }
  43. protected override void Dispose (bool disposing)
  44. {
  45. isDisposed = true;
  46. base.Dispose (disposing);
  47. }
  48. private enum Direction
  49. {
  50. Up,
  51. Down,
  52. Left,
  53. Right
  54. }
  55. private class SnakeState
  56. {
  57. public const int AppleGrowRate = 5;
  58. public const int MaxSpeed = 20;
  59. public const int StartingLength = 10;
  60. public const int StartingSpeed = 50;
  61. private int step;
  62. /// <summary>Current position of the Apple that the snake has to eat.</summary>
  63. public Point Apple { get; private set; }
  64. public Direction CurrentDirection { get; private set; }
  65. /// <summary>Position of the snakes head</summary>
  66. public Point Head => Snake.Last ();
  67. public int Height { get; private set; }
  68. public Direction PlannedDirection { get; set; }
  69. public int SleepAfterAdvancingState { get; private set; } = StartingSpeed;
  70. public List<Point> Snake { get; private set; }
  71. public int Width { get; private set; }
  72. public void GrowSnake ()
  73. {
  74. Point tail = Snake.First ();
  75. Snake.Insert (0, tail);
  76. }
  77. public void GrowSnake (int amount)
  78. {
  79. for (var i = 0; i < amount; i++)
  80. {
  81. GrowSnake ();
  82. }
  83. }
  84. internal bool AdvanceState ()
  85. {
  86. step++;
  87. if (step < GetStepVelocity ())
  88. {
  89. return false;
  90. }
  91. step = 0;
  92. UpdateDirection ();
  93. Point newHead = GetNewHeadPoint ();
  94. Snake.RemoveAt (0);
  95. Snake.Add (newHead);
  96. if (IsDeath (newHead))
  97. {
  98. GameOver ();
  99. }
  100. if (newHead == Apple)
  101. {
  102. GrowSnake (AppleGrowRate);
  103. Apple = GetNewRandomApplePoint ();
  104. var delta = 5;
  105. if (SleepAfterAdvancingState < 40)
  106. {
  107. delta = 3;
  108. }
  109. if (SleepAfterAdvancingState < 30)
  110. {
  111. delta = 2;
  112. }
  113. SleepAfterAdvancingState = Math.Max (MaxSpeed, SleepAfterAdvancingState - delta);
  114. }
  115. return true;
  116. }
  117. /// <summary>Restarts the game with the given canvas size</summary>
  118. /// <param name="width"></param>
  119. /// <param name="height"></param>
  120. internal void Reset (int width, int height)
  121. {
  122. if (width < 5 || height < 5)
  123. {
  124. return;
  125. }
  126. Width = width;
  127. Height = height;
  128. var middle = new Point (width / 2, height / 2);
  129. // Start snake with a length of 2
  130. Snake = new List<Point> { middle, middle };
  131. Apple = GetNewRandomApplePoint ();
  132. SleepAfterAdvancingState = StartingSpeed;
  133. GrowSnake (StartingLength);
  134. }
  135. private bool AreOpposites (Direction a, Direction b)
  136. {
  137. switch (a)
  138. {
  139. case Direction.Left: return b == Direction.Right;
  140. case Direction.Right: return b == Direction.Left;
  141. case Direction.Up: return b == Direction.Down;
  142. case Direction.Down: return b == Direction.Up;
  143. }
  144. return false;
  145. }
  146. private void GameOver () { Reset (Width, Height); }
  147. private Point GetNewHeadPoint ()
  148. {
  149. switch (CurrentDirection)
  150. {
  151. case Direction.Left:
  152. return new Point (Head.X - 1, Head.Y);
  153. case Direction.Right:
  154. return new Point (Head.X + 1, Head.Y);
  155. case Direction.Up:
  156. return new Point (Head.X, Head.Y - 1);
  157. case Direction.Down:
  158. return new Point (Head.X, Head.Y + 1);
  159. }
  160. throw new Exception ("Unknown direction");
  161. }
  162. private Point GetNewRandomApplePoint ()
  163. {
  164. var r = new Random ();
  165. for (var i = 0; i < 1000; i++)
  166. {
  167. int x = r.Next (0, Width);
  168. int y = r.Next (0, Height);
  169. var p = new Point (x, y);
  170. if (p == Head)
  171. {
  172. continue;
  173. }
  174. if (IsDeath (p))
  175. {
  176. continue;
  177. }
  178. return p;
  179. }
  180. // Game is won or we are unable to generate a valid apple
  181. // point after 1000 attempts. Maybe screen size is very small
  182. // or something. Either way restart the game.
  183. Reset (Width, Height);
  184. return Apple;
  185. }
  186. private int GetStepVelocity ()
  187. {
  188. if (CurrentDirection == Direction.Left || CurrentDirection == Direction.Right)
  189. {
  190. return 1;
  191. }
  192. return 2;
  193. }
  194. private bool IsDeath (Point p)
  195. {
  196. if (p.X <= 0 || p.X >= Width - 1)
  197. {
  198. return true;
  199. }
  200. if (p.Y <= 0 || p.Y >= Height - 1)
  201. {
  202. return true;
  203. }
  204. if (Snake.Take (Snake.Count - 1).Contains (p))
  205. {
  206. return true;
  207. }
  208. return false;
  209. }
  210. private void UpdateDirection ()
  211. {
  212. if (!AreOpposites (CurrentDirection, PlannedDirection))
  213. {
  214. CurrentDirection = PlannedDirection;
  215. }
  216. }
  217. }
  218. private class SnakeView : View
  219. {
  220. private readonly Rune _appleRune;
  221. private readonly Attribute red = new (Color.Red, Color.Black);
  222. private readonly Attribute white = new (Color.White, Color.Black);
  223. public SnakeView (SnakeState state)
  224. {
  225. _appleRune = CM.Glyphs.Apple;
  226. if (!Driver.IsRuneSupported (_appleRune))
  227. {
  228. _appleRune = CM.Glyphs.AppleBMP;
  229. }
  230. State = state;
  231. CanFocus = true;
  232. ColorScheme = new ColorScheme
  233. {
  234. Normal = white,
  235. Focus = white,
  236. HotNormal = white,
  237. HotFocus = white,
  238. Disabled = white
  239. };
  240. }
  241. public SnakeState State { get; }
  242. public override void OnDrawContent (Rectangle viewport)
  243. {
  244. base.OnDrawContent (viewport);
  245. Driver.SetAttribute (white);
  246. Clear (viewport);
  247. var canvas = new LineCanvas ();
  248. canvas.AddLine (Point.Empty, State.Width, Orientation.Horizontal, LineStyle.Double);
  249. canvas.AddLine (Point.Empty, State.Height, Orientation.Vertical, LineStyle.Double);
  250. canvas.AddLine (new Point (0, State.Height - 1), State.Width, Orientation.Horizontal, LineStyle.Double);
  251. canvas.AddLine (new Point (State.Width - 1, 0), State.Height, Orientation.Vertical, LineStyle.Double);
  252. for (var i = 1; i < State.Snake.Count; i++)
  253. {
  254. Point pt1 = State.Snake [i - 1];
  255. Point pt2 = State.Snake [i];
  256. Orientation orientation = pt1.X == pt2.X ? Orientation.Vertical : Orientation.Horizontal;
  257. int length = orientation == Orientation.Horizontal ? pt1.X > pt2.X ? 2 : -2 :
  258. pt1.Y > pt2.Y ? 2 : -2;
  259. canvas.AddLine (
  260. pt2,
  261. length,
  262. orientation,
  263. LineStyle.Single
  264. );
  265. }
  266. foreach (KeyValuePair<Point, Rune> p in canvas.GetMap (Viewport))
  267. {
  268. AddRune (p.Key.X, p.Key.Y, p.Value);
  269. }
  270. Driver.SetAttribute (red);
  271. AddRune (State.Apple.X, State.Apple.Y, _appleRune);
  272. Driver.SetAttribute (white);
  273. }
  274. // BUGBUG: Should (can) this use key bindings instead.
  275. public override bool OnKeyDown (Key keyEvent)
  276. {
  277. if (keyEvent.KeyCode == KeyCode.CursorUp)
  278. {
  279. State.PlannedDirection = Direction.Up;
  280. return true;
  281. }
  282. if (keyEvent.KeyCode == KeyCode.CursorDown)
  283. {
  284. State.PlannedDirection = Direction.Down;
  285. return true;
  286. }
  287. if (keyEvent.KeyCode == KeyCode.CursorLeft)
  288. {
  289. State.PlannedDirection = Direction.Left;
  290. return true;
  291. }
  292. if (keyEvent.KeyCode == KeyCode.CursorRight)
  293. {
  294. State.PlannedDirection = Direction.Right;
  295. return true;
  296. }
  297. return false;
  298. }
  299. }
  300. }