Snake.cs 7.6 KB

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