public void Game() { Snake snake = new Snake(gameFieldWidth, gameFieldHeight); FruitsInGame fruits = new FruitsInGame(gameFieldWidth, gameFieldHeight); while (snake.Alive) { Console.BackgroundColor = ConsoleColor.Gray; Console.Clear(); Console.CursorVisible = false; snake.Draw(); fruits.Draw(); snake.NextStep(fruits); fruits.Add(snake); Thread.Sleep(200); if (Console.KeyAvailable) { ConsoleKeyInfo klavesa = Console.ReadKey(); if (klavesa.Key == ConsoleKey.RightArrow) { snake.Direction = 0; } if (klavesa.Key == ConsoleKey.LeftArrow) { snake.Direction = 180; } if (klavesa.Key == ConsoleKey.DownArrow) { snake.Direction = 270; } if (klavesa.Key == ConsoleKey.UpArrow) { snake.Direction = 90; } if (klavesa.Key == ConsoleKey.P) { Console.ReadKey(); } } } Console.SetCursorPosition(0, 20); GameOver(); }
/// <summary> /// Next step - movement of snake, solving situation like: snake is out of game field, snake eats itself, snake eats fruit /// </summary> /// <param name="fruits">list of fruit, which can snake eats</param> public void NextStep(FruitsInGame fruits) { Part head = snakeParts[snakeParts.Count - 1]; int x = head.X; int y = head.Y; switch (Direction) { case 0: // Right x++; break; case 90: // Up y--; break; case 180: // Left x--; break; case 270: // Down y++; break; } // Snake is or is not out of game field if (x >= (width / 2) | x < 0 | y >= height | y < 0) { Alive = false; } // Snake eats itself for (int j = 0; j < snakeParts.Count; j++) { int snake_x = snakeParts[j].X; int snake_y = snakeParts[j].Y; if (snake_x == x && snake_y == y) { Alive = false; } } Part newHead = new Part(x, y); snakeParts.Add(newHead); // Snake eats fruit bool snakeAteFruit = false; for (int i = 0; i < fruits.fruitsCoordinates.Count; i++) { int fruit_x = fruits.fruitsCoordinates[i].X; int fruit_y = fruits.fruitsCoordinates[i].Y; if (fruit_x == x && fruit_y == y) { fruits.fruitsCoordinates.RemoveAt(i); snakeAteFruit = true; break; } } // Snake didnt eat fruit if (!snakeAteFruit) { snakeParts.RemoveAt(0); } }