Snake.cs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. using System.Diagnostics;
  2. using System.Text;
  3. namespace UICatalog.Scenarios;
  4. [ScenarioMetadata ("Snake", "The game of apple eating.")]
  5. [ScenarioCategory ("Colors")]
  6. [ScenarioCategory ("Drawing")]
  7. [ScenarioCategory ("Games")]
  8. public class Snake : Scenario
  9. {
  10. private bool _isDisposed;
  11. public override void Main ()
  12. {
  13. Application.Init ();
  14. var win = new Window { Title = GetQuitKeyAndName () };
  15. var state = new SnakeState ();
  16. state.Reset (60, 20);
  17. var snakeView = new SnakeView (state) { Width = state.Width, Height = state.Height };
  18. win.Add (snakeView);
  19. var sw = new Stopwatch ();
  20. Task.Run (
  21. () =>
  22. {
  23. while (!_isDisposed)
  24. {
  25. sw.Restart ();
  26. if (state.AdvanceState ())
  27. {
  28. // When updating from a Thread/Task always use Invoke
  29. Application.Invoke (() => { snakeView.SetNeedsDraw (); });
  30. }
  31. long wait = state.SleepAfterAdvancingState - sw.ElapsedMilliseconds;
  32. if (wait > 0)
  33. {
  34. Task.Delay ((int)wait).Wait ();
  35. }
  36. }
  37. }
  38. );
  39. Application.Run (win);
  40. win.Dispose ();
  41. Application.Shutdown ();
  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 () { 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 (Head.X - 1, Head.Y);
  153. case Direction.Right:
  154. return new (Head.X + 1, Head.Y);
  155. case Direction.Up:
  156. return new (Head.X, Head.Y - 1);
  157. case Direction.Down:
  158. return new (Head.X, Head.Y + 1);
  159. }
  160. throw new ("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 = Glyphs.Apple;
  226. if (!Application.Driver!.IsRuneSupported (_appleRune))
  227. {
  228. _appleRune = Glyphs.AppleBMP;
  229. }
  230. State = state;
  231. CanFocus = true;
  232. base.SetScheme (new (white));
  233. KeyBindings.Add (Key.CursorLeft, Command.Left);
  234. KeyBindings.Add (Key.CursorRight, Command.Right);
  235. KeyBindings.Add (Key.CursorUp, Command.Up);
  236. KeyBindings.Add (Key.CursorDown, Command.Down);
  237. AddCommand (Command.Left, () => SetDirection (Direction.Left));
  238. AddCommand (Command.Right, () => SetDirection (Direction.Right));
  239. AddCommand (Command.Up, () => SetDirection (Direction.Up));
  240. AddCommand (Command.Down, () => SetDirection (Direction.Down));
  241. return;
  242. bool? SetDirection (Direction direction)
  243. {
  244. State.PlannedDirection = direction;
  245. return true;
  246. }
  247. }
  248. private SnakeState State { get; }
  249. protected override bool OnDrawingContent (DrawContext context)
  250. {
  251. SetAttribute (white);
  252. ClearViewport ();
  253. var canvas = new LineCanvas ();
  254. canvas.AddLine (Point.Empty, State.Width, Orientation.Horizontal, LineStyle.Double);
  255. canvas.AddLine (Point.Empty, State.Height, Orientation.Vertical, LineStyle.Double);
  256. canvas.AddLine (new (0, State.Height - 1), State.Width, Orientation.Horizontal, LineStyle.Double);
  257. canvas.AddLine (new (State.Width - 1, 0), State.Height, Orientation.Vertical, LineStyle.Double);
  258. for (var i = 1; i < State.Snake.Count; i++)
  259. {
  260. Point pt1 = State.Snake [i - 1];
  261. Point pt2 = State.Snake [i];
  262. Orientation orientation = pt1.X == pt2.X ? Orientation.Vertical : Orientation.Horizontal;
  263. int length = orientation == Orientation.Horizontal ? pt1.X > pt2.X ? 2 : -2 :
  264. pt1.Y > pt2.Y ? 2 : -2;
  265. canvas.AddLine (
  266. pt2,
  267. length,
  268. orientation,
  269. LineStyle.Single
  270. );
  271. }
  272. foreach (KeyValuePair<Point, Rune> p in canvas.GetMap (Viewport))
  273. {
  274. AddRune (p.Key.X, p.Key.Y, p.Value);
  275. }
  276. SetAttribute (red);
  277. AddRune (State.Apple.X, State.Apple.Y, _appleRune);
  278. SetAttribute (white);
  279. return true;
  280. }
  281. }
  282. }