Snake.cs 9.9 KB

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