public void RenderGame(ISnake snake) { Console.Clear(); Console.CursorVisible = false; for (int i = 1; i <= Console.BufferWidth - 1; i++) { Console.BackgroundColor = ConsoleColor.DarkGray; Console.SetCursorPosition(i, 2); Console.Write(" "); Console.SetCursorPosition(i, Console.BufferHeight - 1); Console.Write(" "); Console.BackgroundColor = ConsoleColor.Black; } for (int i = 1; i < Console.BufferHeight - 1; i++) { Console.BackgroundColor = ConsoleColor.DarkGray; Console.SetCursorPosition(0, i); Console.Write(" "); Console.SetCursorPosition(Console.BufferWidth - 1, i); Console.Write(" "); Console.BackgroundColor = ConsoleColor.Black; } foreach (var position in snake.Body) { Console.SetCursorPosition(position.Y, position.X); Console.Write(SnakeSymbol); } }
public Direction ChangeDirection(ISnake snake, ISpace space, IReadOnlyCollection <ISnake> snakes) { // Si no me choco adelante, sigo igual IPosition pos = snake.MoveNew(); if (pos.IsValid(space.TopX, space.TopY) && (space[pos.X, pos.Y] == 0)) { return(snake.Direction); } //Busco nueva dirección clockwise para no chocarme foreach (Direction dir in new[] { 0, 1, 2, 3 }) { pos = snake.MoveNew(dir); if (!pos.IsValid(space.TopX, space.TopY)) { continue; } if (space[pos.X, pos.Y] > 0) { continue; } return(dir); } return(snake.Direction); //TODO: no meterse en callejones }
public GameManager(ISnake snake, Food food, GameBoardSettings gameBoardSettings, Direction initSnakeDirection, ILogger logger) { if (logger is null) { throw new ArgumentNullException($"Объект {nameof(logger)} не может иметь значение null и должен быть определен"); } if (snake is null) { throw new ArgumentNullException($"Объект {nameof(snake)} не может иметь значение null и должен быть определен"); } if (food is null) { throw new ArgumentNullException($"Объект {nameof(food)} не может иметь значение null и должен быть определен"); } if (gameBoardSettings is null) { throw new ArgumentNullException($"Объект {nameof(gameBoardSettings)} не может иметь значение null и должен быть определен"); } this._snake = snake; this.Snake = snake.Points; this._food = food; this._gameBoardSettings = gameBoardSettings; this._snakeDirectionQueue = new Queue <Direction>(); this._snakeDirectionQueue.Enqueue(initSnakeDirection); this._logger = logger; }
public void Start(ISnake snake) { this.Snake = snake; this.SpawnApple(); this.ResetObstructions(); while (true) { if (Console.KeyAvailable) { ConsoleKey key = Console.ReadKey(true).Key; switch (key) { case ConsoleKey.LeftArrow: Snake.CurrentDirection = Direction.Left; break; case ConsoleKey.RightArrow: Snake.CurrentDirection = Direction.Right; break; case ConsoleKey.UpArrow: Snake.CurrentDirection = Direction.Up; break; case ConsoleKey.DownArrow: Snake.CurrentDirection = Direction.Down; break; case ConsoleKey.Spacebar: Pause(); break; } } Snake.Move(); if (Snake.Head.Equals(AppleLocation)) { SpawnApple(); AppleCounter++; Snake.Extend++; ResetObstructions(); } OutputWriter.Draw(this); if (Snake.Dead) { OutputWriter.DisplayDeathMessage(this); break; } Thread.Sleep(300); } }
public void GenerateSnakeTest() { int xPos = rand.Next(1000); int yPos = rand.Next(1000); int length = rand.Next(1000); ISnake snake = SnakeGenerator.GenerateSnake(xPos, yPos, length); Assert.AreEqual(length, snake.BodyParts.Count); for (int i = 0; i < snake.BodyParts.Count; ++i) { if (i == 0) { Assert.IsTrue(snake.BodyParts[i].IsSnakeHead); } else { Assert.IsFalse(snake.BodyParts[i].IsSnakeHead); } if (i == snake.BodyParts.Count - 1) { Assert.IsNull(snake.BodyParts[i].NextBodyPart); } else { Assert.AreEqual(snake.BodyParts[i + 1], snake.BodyParts[i].NextBodyPart); } } }
public void SetupGame(int gameWidth, int gameHeight, ISnake snake) { ExceptionHelper.ThrowArgumentOutOfRangeIfZeroOrLower(nameof(gameWidth), gameWidth); ExceptionHelper.ThrowArgumentOutOfRangeIfZeroOrLower(nameof(gameHeight), gameHeight); GameWidth = gameWidth; GameHeight = gameHeight; Snake = snake; }
public void CreateNewGame(ISkinFactory skinFactory) { IPosition startPosition = positionRandomizer.RandomizePosition(); SnakeBuilder builder = new SnakeBuilder(skinFactory, startPosition); this.map = map; this.snake = builder.Build(); this.foods = new List <AbstractFood>(); this.foodFactory = new FoodFactory(skinFactory); }
public void Initialize(IList <IPlayer> players, ISnake snake) { this.ValidatePlayers(players); for (int i = 1; i <= InitialSnakeLenght; i++) { var position = new Position(SnakeStartPointCol, i); snake.AddSegmentToSnake(position); } }
public GameScene(ISnake snake, IDrawManager drawManager, IFoodFactory foodFactory, IBorder border, IScoreBoard scoreBoard, IScene pauseScene, IScene gameOverScene) { this.snake = snake; this.drawManager = drawManager; this.foodFactory = foodFactory; this.border = border; this.scoreBoard = scoreBoard; this.pauseScene = pauseScene; this.gameOverScene = gameOverScene; this.spawnedFood = null; this.GameSpeed = GameMinSpeed; }
public void SetupGameSnakeParameterTest_NegativeWidth_ArgumentOutOfRangeException() { int width = -rand.Next(); int height = rand.Next(); int startingXPos = rand.Next(); int startingYPos = rand.Next(); int startingSnakeLength = rand.Next(1000); ISnake snake = SnakeGenerator.GenerateSnake(startingXPos, startingYPos, startingSnakeLength); SnakeGameHandler gameHandler = new SnakeGameHandler(); Assert.ThrowsException <ArgumentOutOfRangeException>(() => gameHandler.SetupGame(width, height, snake)); }
// --------------------------------------------------------------------------- private void Awake() { if (m_SnakeContainer != null) { var obj = Instantiate(m_SnakeContainer, transform); Snake = obj.GetComponent <ISnake>(); } else { Snake = FindObjectsOfType <MonoBehaviour>().OfType <ISnake>().FirstOrDefault(); } }
//this is for testing public Game( IInputProvider inputProvider, IOutputProvider outputProvider, ISnake snake, IBoard board ) { this.inputProvider = inputProvider; this.outputProvider = outputProvider; this.snake = snake != null ? snake : null; this.board = board; }
public StandardOnePlayerEngine(IInputProvider inputProvider, IOutputProvider outputProvider, IRenderer renderer, IData data) { this.players = new List <IPlayer>(); snake = new Snake(); this.inputProvider = inputProvider; this.outputProvider = outputProvider; this.direction = new Direction(); this.randomGenerator = new RandomGenerator(); this.RandomPosition = this.randomGenerator.GetRandomPosition(); this.sleepTime = 100; this.data = data; this.renderer = renderer; }
public void InitGame() { Console.CursorVisible = false; IMenu menu = new StartMenu(); OutputWriter.DisplayMenu(menu); IGame game = SelectGame(20, 20); ISnake selectedSnake = SelectSnake(game); game.Start(selectedSnake); }
public void SetupGameSnakeParameterTest() { int width = rand.Next(); int height = rand.Next(); int startingXPos = rand.Next(); int startingYPos = rand.Next(); int startingSnakeLength = rand.Next(1000); ISnake snake = SnakeGenerator.GenerateSnake(startingXPos, startingYPos, startingSnakeLength); SnakeGameHandler gameHandler = new SnakeGameHandler(); gameHandler.SetupGame(width, height, snake); Assert.AreEqual(width, gameHandler.GameWidth); Assert.AreEqual(height, gameHandler.GameHeight); Assert.AreEqual(snake, gameHandler.Snake); }
public static void ValidatePosition(ISnake snake, Position newSnakeHead) { if (newSnakeHead.X >= Console.WindowHeight - Constants.FrameworkBorderSideFour || newSnakeHead.X < Constants.FrameworkBorderSideThree || newSnakeHead.Y >= Console.WindowWidth - Constants.FrameworkBorderSideTwo || newSnakeHead.Y <= Constants.FrameworkBorderSideOne ) { throw new InvalidOperationException(Constants.GameOverMessage); } var isValid = snake.Body.Where(x => x.X == newSnakeHead.X && x.Y == newSnakeHead.Y).FirstOrDefault(); if (isValid != null) { throw new InvalidOperationException(Constants.GameOverMessage); } }
private GameObject SpawnWithTail(GameObject headPrototype, GameObject tailPrototype, int tailsCount, bool isNeedToUpdateUI = false) { GameObject head = Instantiate(headPrototype); head.transform.position = LevelManager.RandomFieldPosition; ISnake headController = head.GetComponent <ISnake>(); for (int i = 0; i < tailsCount; i++) { GameObject tail = Instantiate(tailPrototype); headController.AddTail(tail); if (isNeedToUpdateUI) { ReferenceContainer.UiManager.UpdateLengthText(headController.TailsLength + 1); } } return(head); }
public override bool CanWalkOnBy(IWorldItem itemCollision, ISnake item, Vector3 position) { if (itemCollision == null) { return(true); } var res = true; switch (itemCollision.WorldItemType) { case WorldItemType.Barrier: res = false; break; case WorldItemType.Snake: if (itemCollision.transform.GetInstanceID() == item.transform.GetInstanceID()) { res = false; } break; } return(res); }
private void InitializeSnake(ILevel currentLevel) { snake = new Snake(currentLevel.InitialSnakeLevelLength); }
public void StartGame(Snake snake, Board board) { // Customize Snake snake = CustomizeSnake(); // set the snake in the middle of the board snake.XPosition = board.Boardwidth / 2; snake.YPosition = board.Boardheight / 2; // set defaults //game is in play, no history of moves, snake length is 1 and game speed is 75 IsGameOver = false; DidHitWall = false; Eaten = new Dictionary <string, bool>(); int GameSpeed = 75; snake.Length = 1; //do not show the cursor and initialize a variable for key input Console.CursorVisible = false; ConsoleKeyInfo command; while (!IsGameOver) { // clear the console, set the title bar, and draw the board outputProvider.Clear(); outputProvider.CreateTitle(Message.Instructions); board.DrawBoard(); //clear move history, and add current position, then draw the snake Eaten.Clear(); Eaten.Add(snake.XPosition.ToString() + snake.YPosition.ToString(), true); snake.DrawSnake(); //wait for the player to move WaitForMove(); //set the speed by checking for keystrokes at the gamespeed in miliseconds DateTime nextCheck = DateTime.Now.AddMilliseconds(GameSpeed); while (!IsGameOver && !DidHitWall) { //Display the length at the top of the screen outputProvider.CreateTitle(Message.Score + snake.Length.ToString()); //wait for the next time you can check for keys while (nextCheck > DateTime.Now) { // see if the player has changed direction if (Console.KeyAvailable) { //read the key and map it to a direction command = Console.ReadKey(true); MapCommandToDirection(command); } } if (!IsGameOver) { ChangeDirection(snake, board); if (!DidHitWall) { //format the current positions to two rounded digits string positions = snake.XPosition.ToString("00") + snake.YPosition.ToString("00"); //if the snake hasn't been to the current positions, add the length and keep going if (!Eaten.ContainsKey(positions)) { snake.Length++; Eaten.Add(positions, true); snake.DrawSnake(); } //otherwise say they hit the wall else { DidHitWall = true; } } nextCheck = DateTime.Now.AddMilliseconds(GameSpeed); } } if (DidHitWall) { outputProvider.CreateTitle(Message.You_Died + snake.Length.ToString()); SetConsoleToDefault(); outputProvider.WriteLine(Message.SkullArt); JustWait(); IsGameOver = true; } } if (IsGameOver) { SetConsoleToDefault(); outputProvider.CreateTitle(Message.Youre_Done + snake.Length.ToString()); outputProvider.Write(Message.SnakeArt); JustWait(); } }
public void SetupGame(int gameWidth, int gameHeight, int snakeStartingXPos, int snakeStartingYPos, int snakeStartingLength) { ISnake snake = SnakeGenerator.GenerateSnake(snakeStartingXPos, snakeStartingYPos, snakeStartingLength); SetupGame(gameWidth, gameHeight, snake); }
public Form1() { InitializeComponent(); _snake = new Snake<Point, Direction2D>(new Coordinate2D(Direction2D.Up, new Point(25, 25)), 4, new SnakePartFactory<Point, Direction2D>()); }
public SnakeBodyAddableBehaviour(ISnake snake, SignalBus signalBus, SnakeSettings snakeSettings) { Snake = snake; this.snakeSettings = snakeSettings; this.signalBus = signalBus; }
// Set the title of the window public SnakeGame() { AppName = "SNAKE!"; snakeCharacter = new ExampleSnake(); }
/// <summary> /// Occurs when snake changed /// </summary> /// <param name="snake"></param> protected virtual void OnSnakeChanged(ISnake snake) { RestartSnakeEvents(); SnakeChanged?.Invoke(this, snake); }
/// <summary> /// Occurs before snake change /// </summary> /// <param name="snake"></param> protected virtual void OnSnakeBeforeChange(ISnake snake) { ResetSnakeEvents(); SnakeBeforeChanged?.Invoke(this, snake); }
public void SetSnake(ISnake snake) { this.snake = snake; }
private void DrawSnake() { snakeCanvas.Children.Clear(); ISnake snake = model.GetSnake(); SnakePart prev = null, next = null; SnakePart sp = snake.GetSnakeHead(); Image part1 = new Image(); Canvas.SetLeft(part1, sp.PositionOnX * viewCellSize); Canvas.SetTop(part1, sp.PositionOnY * viewCellSize); part1.Width = part1.Height = viewCellSize; part1.Source = new BitmapImage(new Uri("/SnakeGame;component/View/Resources/snake/cap2.png", UriKind.RelativeOrAbsolute)); switch (snake.Direction) { case SnakeDirection.Up: part1.RenderTransform = new RotateTransform(180, viewCellSize / 2, viewCellSize / 2); break; case SnakeDirection.Left: part1.RenderTransform = new RotateTransform(90, viewCellSize / 2, viewCellSize / 2); break; case SnakeDirection.Right: var transformGroup = new TransformGroup(); transformGroup.Children.Add(new RotateTransform(270, viewCellSize / 2, viewCellSize / 2)); transformGroup.Children.Add(new ScaleTransform(1, -1, viewCellSize / 2, viewCellSize / 2)); part1.RenderTransform = transformGroup; break; case SnakeDirection.Down: break; default: break; } snakeCanvas.Children.Add(part1); do { string type = "-"; prev = sp; sp = snake.GetNextPart(sp); next = snake.GetNextPart(sp); int partType = -1; Image part = new Image(); if (sp != null) { // e ultimul if (next == null) { if (coada) { part.Source = new BitmapImage(new Uri("/SnakeGame;component/View/Resources/snake/coada1.png", UriKind.RelativeOrAbsolute)); } else { part.Source = new BitmapImage(new Uri("/SnakeGame;component/View/Resources/snake/coada2.png", UriKind.RelativeOrAbsolute)); } coada = !coada; switch (GetCoadaDirection(prev, sp)) { case SnakeDirection.Up: break; case SnakeDirection.Left: var transformGroup = new TransformGroup(); transformGroup.Children.Add(new RotateTransform(90, viewCellSize / 2, viewCellSize / 2)); transformGroup.Children.Add(new ScaleTransform(-1, 1, viewCellSize / 2, viewCellSize / 2)); part.RenderTransform = transformGroup; break; case SnakeDirection.Right: transformGroup = new TransformGroup(); transformGroup.Children.Add(new RotateTransform(270, viewCellSize / 2, viewCellSize / 2)); transformGroup.Children.Add(new ScaleTransform(-1, 1, viewCellSize / 2, viewCellSize / 2)); part.RenderTransform = transformGroup; break; case SnakeDirection.Down: part.RenderTransform = new RotateTransform(180, viewCellSize / 2, viewCellSize / 2); break; default: break; } } else { partType = GetSnakePartType(prev, sp, next); } Canvas.SetLeft(part, sp.PositionOnX * viewCellSize); Canvas.SetTop(part, sp.PositionOnY * viewCellSize); part.Width = part.Height = viewCellSize; switch (partType) { case 1: part.Source = new BitmapImage(new Uri("/SnakeGame;component/View/Resources/snake/part1.png", UriKind.RelativeOrAbsolute)); break; case 2: part.Source = new BitmapImage(new Uri("/SnakeGame;component/View/Resources/snake/part2.png", UriKind.RelativeOrAbsolute)); break; case 3: part.Source = new BitmapImage(new Uri("/SnakeGame;component/View/Resources/snake/part3.png", UriKind.RelativeOrAbsolute)); break; case 4: part.Source = new BitmapImage(new Uri("/SnakeGame;component/View/Resources/snake/part4.png", UriKind.RelativeOrAbsolute)); break; case 5: part.Source = new BitmapImage(new Uri("/SnakeGame;component/View/Resources/snake/vertical2.png", UriKind.RelativeOrAbsolute)); break; case 6: part.Source = new BitmapImage(new Uri("/SnakeGame;component/View/Resources/snake/horizontal2.png", UriKind.RelativeOrAbsolute)); break; default: break; } snakeCanvas.Children.Add(part); } } while (sp != null); }
public void Start(ISnake snake) { this.Snake = snake; this.SpawnApple(); while (true) { if (Console.KeyAvailable) { ConsoleKey key = Console.ReadKey(true).Key; switch (key) { case ConsoleKey.LeftArrow: appleDirection = Direction.Left; break; case ConsoleKey.RightArrow: appleDirection = Direction.Right; break; case ConsoleKey.UpArrow: appleDirection = Direction.Up; break; case ConsoleKey.DownArrow: appleDirection = Direction.Down; break; case ConsoleKey.Spacebar: Pause(); break; } } if (random.Next(5) == 0) { int nextDirectionId = random.Next(2); if (nextDirectionId == 0) { if (Snake.CurrentDirection == Direction.Up) { Snake.CurrentDirection = Direction.Right; } else if (Snake.CurrentDirection == Direction.Right) { Snake.CurrentDirection = Direction.Down; } else if (Snake.CurrentDirection == Direction.Down) { Snake.CurrentDirection = Direction.Left; } else if (Snake.CurrentDirection == Direction.Left) { Snake.CurrentDirection = Direction.Up; } } else { if (Snake.CurrentDirection == Direction.Up) { Snake.CurrentDirection = Direction.Left; } else if (Snake.CurrentDirection == Direction.Right) { Snake.CurrentDirection = Direction.Up; } else if (Snake.CurrentDirection == Direction.Down) { Snake.CurrentDirection = Direction.Right; } else if (Snake.CurrentDirection == Direction.Left) { Snake.CurrentDirection = Direction.Down; } } } int currX = AppleLocation.X; int currY = AppleLocation.Y; int targetX; int targetY; switch (appleDirection) { case Direction.Up: targetX = currX; targetY = currY - 1; break; case Direction.Down: targetX = currX; targetY = currY + 1; break; case Direction.Left: targetX = currX - 1; targetY = currY; break; case Direction.Right: targetX = currX + 1; targetY = currY; break; default: throw new InvalidOperationException("Invalid direction"); } if (targetX < 0) { targetX = Width - 1; } else if (targetX == Width) { targetX = 0; } else if (targetY < 0) { targetY = Height - 1; } else if (targetY == Height) { targetY = 0; } AppleLocation = new Position(targetX, targetY); if (Snake.Head.Equals(AppleLocation)) { SpawnApple(); AppleCounter++; Snake.Extend++; } OutputWriter.Draw(this); if (!Snake.Head.Equals(AppleLocation) && Snake.Positions.Contains(AppleLocation)) { OutputWriter.DisplayDeathMessage(this); break; } if (random.Next(2) == 0) { Snake.Move(); } Thread.Sleep(300); } }
public SnakeMovementBehaviour(GameManager gameManager, ISnake snake, SnakeSettings snakeSettings) { Snake = snake; this.snakeSettings = snakeSettings; this.gameManager = gameManager; }
public void SetSnake(ISnake value) { _snake = value; }