public void createAtRandomPos(Board board, Snake snake) { Random random = new Random(); List <BoardElement> emptyPlaces = new List <BoardElement>(); for (int i = 1; i < board.width - 1; i++) { for (int j = 1; j < board.height - 1; j++) { if (!snake.hitItself(i, j) && !board.checkWallHit(i, j)) { emptyPlaces.Add(new BoardElement(i, j)); } } } int index = random.Next(emptyPlaces.Count); x = emptyPlaces[index].x; y = emptyPlaces[index].y; if (level < Constants.MAX_FOOD_LVL) { level++; } Console.SetCursorPosition(x, y); Console.Write(level); }
public void start() { while (true) { if (state == GameStates.Menu) { Console.Clear(); openMenu(); } else if (state == GameStates.Starting) { Console.Clear(); board.draw(level); direction = Directions.RIGHT; snake = new Snake(board.width / 2, board.height / 2, Constants.SNAKE_SIZE); state = GameStates.Started; food.level = 0; food.createAtRandomPos(board, snake); Console.CursorVisible = false; } else // game started { int x = snake.getX(); int y = snake.getY(); checkKeyInput(); switch (direction) { case Directions.UP: y--; break; case Directions.RIGHT: x++; break; case Directions.DOWN: y++; break; case Directions.LEFT: x--; break; } int foodCollected = 0; if (snake.hitItself(x, y) || board.checkWallHit(x, y)) { over(); } else if (x == food.x && y == food.y) { foodCollected = food.level; food.createAtRandomPos(board, snake); if (food.level == Constants.FOOD_COUNT_FOR_LVLUP && level < Constants.MAX_LVL) { level++; snake = new Snake(board.width / 2, board.height / 2, Constants.SNAKE_SIZE); state = GameStates.Starting; } } snake.expandSnake(x, y); x = snake.body[0].x; y = snake.body[0].y; if (foodCollected == 0) { snake.removeLastPart(); Console.SetCursorPosition(x, y); Console.Write(" "); } else { foodCollected--; } snake.draw(); int speed = 100 - level * Constants.SPEED; if (speed > 0) { Thread.Sleep(speed); } } } }