Snake.cs 10 KB

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