コード例 #1
1
        private static void HandleCollision(Snake snake, ConsoleRenderer renderer)
        {
            List<GameFieldCoords> snakeElements = new List<GameFieldCoords>();

            foreach (GameFieldCoords element in snake.GetPosition())
            {
                snakeElements.Add(element);
            }

            foreach (GameFieldCoords element in snakeElements)
            {
                if (element.Row >= renderer.GameFieldSize.Row || element.Row < 0
                    || element.Col >= renderer.GameFieldSize.Col || element.Col < 0)
                {
                    snake.IsDestroyed = true;
                }
            }

            for (int element = 0; element < snakeElements.Count - 1; element++)
            {
                if (snakeElements.Last().Row == snakeElements[element].Row
                    && snakeElements.Last().Col == snakeElements[element].Col)
                {
                    snake.IsDestroyed = true;
                }
            }
        }
コード例 #2
0
ファイル: Game1.cs プロジェクト: japotter4/Project-Games
        protected override void Initialize()
        {
            //Init the background grid
            backgroundGrid = new Grid(this, "backgroundFile.txt");
            //Init the background brick texture
            bgBrick = Content.Load<Texture2D>(@"Textures/GreyBlock");
            //Init the snake
            snake = new Snake(this, backgroundGrid);
            //Init the snake texture
            snakeTexture = Content.Load<Texture2D>(@"Textures/RedBlock");

            base.Initialize();
        }
コード例 #3
0
 private static void HandleEating(Snake snake, List<Food> foodList)
 {
     foreach (Food food in foodList)
     {
         foreach (GameFieldCoords snakeElementPosition in snake.GetPosition())
         {
             if (food.GetPosition()[0].Row == snakeElementPosition.Row
                 && food.GetPosition()[0].Col == snakeElementPosition.Col)
             {
                 snake.GetBigger();
                 food.RespondToEating();
             }
         }
     }
 }
コード例 #4
0
ファイル: GameEngine.cs プロジェクト: titaniummick/SnakeGame
        /// <summary>
        /// จุดเริ่มต้นของ Game
        /// </summary>
        public static void Main()
        {
            Console.CursorVisible = false;
            grassField = new GrassField();
            snake = new Snake(grassField);
            food = new Food(grassField);
            snake.Food = food;
            scoreBoard = new ScoreBoard(grassField);

            grassField.Render();
            snake.Render();
            food.Render();
            scoreBoard.Render();

            Loop();
        }
コード例 #5
0
        public Engine(ConsoleRenderer renderer, IUserController controller, int snakeLength, int foodAmount)
        {
            this.userName = this.usersManager.RequestUserName(renderer);

            this.renderer = renderer;
            this.controller = controller;
            this.snakeLength = snakeLength;
            this.foodAmount = foodAmount;

            this.foodList = new List<Food>(foodAmount);
            this.snake = new Snake(snakeLength);

            for (int counter = 0; counter < foodAmount; counter++)
            {
                this.AddFood();
            }
        }
コード例 #6
0
        // 먹이를 먹었나 판단
        public void IsEatFood()
        {
            if (map[sn[0].PointX, sn[0].PointY] == 3 && Count < 21)
            {
                Count++;
                sn[Count] = new Snake(sn[Count - 1].PointX, sn[Count - 1].PointY);
                MakeFood();

                timer1.Interval = (int)(timer1.Interval * 0.93);
                SpeedX = SpeedX + 22;
            }
            else if (map[sn[0].PointX, sn[0].PointY] == 3)
            {
                Count++;
                sn[Count] = new Snake(sn[Count - 1].PointX, sn[Count - 1].PointY);
                MakeFood();
            }
        }
コード例 #7
0
        public void SnakeShouldDieCollidingWithHerself()
        {
            var game  = new Game(map2);
            var snake = new SnakeGame.Snake(new Point(1, 1), Direction.Down, "");

            game.aliveCreatures.Add(snake);
            for (var i = 2; i < game.MapHeight; i++)
            {
                game.map[1, i] = new Food(new Point(1, i), "food");
                game.GameIteration();
            }
            game.KeyPressed(Keys.Right);
            game.GameIteration();
            game.KeyPressed(Keys.Up);
            game.GameIteration();
            game.KeyPressed(Keys.Left);
            game.GameIteration();
            Assert.AreEqual(true, game.isOver);
            Assert.AreEqual(false, snake.IsAlive());
        }
コード例 #8
0
        public void InitSnake()
        {
            //게임시작전 지렁이 위치 세팅 (21 * 21맵)
            Random random = new Random();
            int x = random.Next(10, 22); // 벽에 너무 붙어서 지렁이가 생성되지 않도록 범위지정
            int y = random.Next(10, 22); // 위와 동일

            while (true)
            {
                if ((13 > x || x > 18) && (y < 21 || y > 18))
                    break;
                else
                {
                    x = random.Next(10, 22); // 벽에 너무 붙어서 지렁이가 생성되지 않도록 범위지정
                    y = random.Next(10, 22); // 위와 동일
                }
            }
            PointX = x;
            PointY = y;
            sn[0] = new Snake(PointX, PointY);
            sn[1] = new Snake(PointX, PointY);        // 여기들도 쫌 문제가 있음
            sn[2] = new Snake(PointX, PointY);
        }
コード例 #9
0
ファイル: MainFrm.cs プロジェクト: jpalmisano/SnakeGame
 //method just to make a restart of the game
 public void restart()
 {
     timer1.Enabled = false;
     MessageBox.Show("Game Over");
     writeToDatabase(score);
     snakeScoreLabel.Text = "0";
     score = 0;
     spaceBarLabel.Text = "Press Space Bar to Begin";
     snake = new Snake();
     //by assigning snake to the new data type of the snake class the
     //whole program is like new and restarts.
 }
コード例 #10
0
 public void MoveLeft(Snake snake)
 {
     Console.SetCursorPosition(snake.headX, snake.headY);
     Console.Write("*");
 }
コード例 #11
0
 public Food(Snake snake, Obstacles obstacles)
 {
     this.snake     = snake;
     this.obstacles = obstacles;
 }
コード例 #12
0
 public Make(Map map, Snake snake)
 {
     this.map = map;
     this.snake = snake;
 }
コード例 #13
0
 public static void HandleCollisions(Snake snake, List<Food> foodList, ConsoleRenderer renderer)
 {
     HandleEating(snake, foodList);
     HandleCollision(snake, renderer);
 }
コード例 #14
0
 public void SetupNewGame()
 {
     snake = getCenter();
     GetNewApple();
 }
コード例 #15
0
        void time_Tick(object sender, EventArgs e)
        {
            if (direction != 0)
            {
                for (int i = snakebody.Count - 1; i > 0; i--)
                {
                    snakebody[i] = snakebody[i - 1];
                }
            }


            if (direction == up)
            {
                y -= 10;
            }
            if (direction == down)
            {
                y += 10;
            }
            if (direction == left)
            {
                x -= 10;
            }
            if (direction == right)
            {
                x += 10;
            }


            if (snakebody[0].x == food[0].x && snakebody[0].y == food[0].y)
            {
                snakebody.Add(new Snake(food[0].x, food[0].y));
                food[0] = new Food(rd.Next(0, 37) * 10, rd.Next(0, 35) * 10);
                mycanvas.Children.RemoveAt(0);
                addfoodincanvas();
                score++;
                txtbScore.Text = score.ToString();
            }


            snakebody[0] = new Snake(x, y);

            if (snakebody[0].x > 370 || snakebody[0].y > 350 || snakebody[0].x < 0 || snakebody[0].y < 0)
            {
                this.Close();
            }


            for (int i = 1; i < snakebody.Count; i++)
            {
                if (snakebody[0].x == snakebody[i].x && snakebody[0].y == snakebody[i].y)
                {
                    this.Close();
                }
            }


            for (int i = 0; i < mycanvas.Children.Count; i++)
            {
                if (mycanvas.Children[i] is Rectangle)
                {
                    count++;
                }
            }
            mycanvas.Children.RemoveRange(1, count);
            count = 0;
            addsnakeincanvas();
        }
コード例 #16
0
 public InputController(Snake _snake)
 {
     snake = _snake;
 }
コード例 #17
0
 private void Restart()
 {
     _isSnakeDead = false;
     _snake       = CreateSnake();
 }
コード例 #18
0
        private static void Start()
        {
            Walls walls = new Walls(Width, Height);

            walls.Draw();

            Point p     = new Point(4, 5, '@');
            Snake snake = new Snake(p, 4, Direction.RIGHT);

            snake.Draw();

            FoodCreator foodCreator = new FoodCreator(Width, Height, '$');
            Point       food        = foodCreator.CreateFood(snake);

            food.Draw();
            int[,] s = new int[Width, Height];

            while (true)
            {
                if (walls.IsHit(snake) || snake.IsHitTail())
                {
                    break;
                }
                if (snake.Eat(food))
                {
                    do
                    {
                        food = foodCreator.CreateFood(snake);
                    } while (IsColision(snake, food));

                    food.Draw();
                }
                else
                {
                    for (int i = 0; i < Width; i++)
                    {
                        for (int j = 0; j < Height; j++)
                        {
                            s[i, j] = (int)Figures.EmptySpace;
                        }
                    }

                    foreach (var item in walls.Points)
                    {
                        s[item.x, item.y] = (int)Figures.Barrier;
                    }

                    s[food.x, food.y] = (int)Figures.Destination;

                    foreach (var item in snake.Points)
                    {
                        var first = snake.Points.Last();
                        if (item == first)
                        {
                            s[item.x, item.y] = (int)Figures.StartPosition;
                        }
                        else
                        {
                            s[item.x, item.y] = (int)Figures.Barrier;
                        }
                    }
                    var li = new LeeAlgorithm(s);
                    System.Drawing.Point head = new System.Drawing.Point(0, 0);
                    System.Drawing.Point nextstep;
                    if (!li.PathFound)
                    {
                        food = foodCreator.CreateFood(snake);
                    }
                    else
                    {
                        foreach (var item in li.Path)
                        {
                            if (item == li.Path.Last())
                            {
                                s[item.Item1, item.Item2] = (int)Figures.StartPosition;
                                head = new System.Drawing.Point(item.Item1, item.Item2);
                            }
                            else if (item == li.Path.First())
                            {
                                s[item.Item1, item.Item2] = (int)Figures.Destination;
                            }
                            else
                            {
                                s[item.Item1, item.Item2] = (int)Figures.Path;
                            }
                        }

                        nextstep = new System.Drawing.Point(li.Path[li.Path.Count - 2].Item1, li.Path[li.Path.Count - 2].Item2);



                        var dir = GetDirection(head, nextstep);

                        switch (dir)
                        {
                        case Direction.LEFT:
                            snake.HandleKey(ConsoleKey.LeftArrow);
                            break;

                        case Direction.RIGHT:
                            snake.HandleKey(ConsoleKey.RightArrow);
                            break;

                        case Direction.UP:
                            snake.HandleKey(ConsoleKey.UpArrow);
                            break;

                        case Direction.DOWN:
                            snake.HandleKey(ConsoleKey.DownArrow);
                            break;
                        }
                    }
                    int speed = 1;
                    snake.Move();
                    Thread.Sleep(speed);
                }
            }
            WriteGameOver();
            Console.ReadLine();
        }
コード例 #19
0
        /**
         * Gama main logic.
         */
        private Snake Logic(Snake snake)
        {
            var preX = snake.TailX[0];
            var preY = snake.TailY[0];

            // Move snake.
            if (snake.Direction != "STOP")
            {
                snake.TailX[0] = snake.HeadX;
                snake.TailY[0] = snake.HeadY;

                for (var i = 1; i < snake.NTail; i++)
                {
                    var tempX = snake.TailX[i];
                    var tempY = snake.TailY[i];
                    snake.TailX[i] = preX;
                    snake.TailY[i] = preY;

                    preX = tempX;
                    preY = tempY;
                }
            }

            if (snake.Direction == "RIGHT")
            {
                // Move right.
                snake.HeadX++;
            }
            else if (snake.Direction == "LEFT")
            {
                // Move left.
                snake.HeadX--;
            }
            else if (snake.Direction == "UP")
            {
                // Move forvard.
                snake.HeadY--;
            }
            else if (snake.Direction == "DOWN")
            {
                // Move back.
                snake.HeadY++;
            }
            else if (snake.Direction == "STOP")
            {
                while (true)
                {
                    Console.Clear();

                    Console.CursorLeft = Width / 2 - 6;

                    Console.WriteLine("GAME PAUSED");
                    Console.WriteLine();
                    Console.WriteLine();
                    Console.WriteLine("    - Press S to resume the game");
                    Console.WriteLine("    - Press R to reset the game");
                    Console.Write("    - Press ESC to quit the game");

                    _keypress = Console.ReadKey(true);
                    if (_keypress.Key == ConsoleKey.Escape)
                    {
                        // Close game.
                        Environment.Exit(0);
                    }
                    else if (_keypress.Key == ConsoleKey.R)
                    {
                        // Reset game.
                        _reset = true;
                        break;
                    }
                    else if (_keypress.Key == ConsoleKey.S)
                    {
                        // Resume game.
                        break;
                    }
                }

                snake.Direction = snake.PreDirection;
            }

            // Ff the snake collided with borders.
            if (snake.HeadX <= 0 || snake.HeadX >= Width - 1 || snake.HeadY <= 0 ||
                snake.HeadY >= Height - 1)
            {
                _gameOver = true;
            }
            else
            {
                _gameOver = false;
            }

            if (snake.HeadX == Fruit.X && snake.HeadY == Fruit.Y)
            {
                // Ate fruit.
                _score += Fruits[Fruit.Id].Weight;
                snake.NTail++;
                Fruit.X  = Rand.Next(1, Width - 1);
                Fruit.Y  = Rand.Next(1, Height - 1);
                Fruit.Id = Rand.Next(0, Fruits.Count - 1);
            }

            for (var i = 1; i < snake.NTail; i++)
            {
                // if the snake collided with itself.
                if (snake.TailX[i] == snake.HeadX && snake.TailY[i] == snake.HeadY)
                {
                    if (snake.IsHorizontal() || snake.IsVertical())
                    {
                        _gameOver = false;
                    }
                    else
                    {
                        _gameOver = true;
                    }
                }

                if (snake.TailX[i] != Fruit.X || snake.TailY[i] != Fruit.Y)
                {
                    continue;
                }

                Fruit.X  = Rand.Next(1, Width - 1);
                Fruit.Y  = Rand.Next(1, Height - 1);
                Fruit.Id = Rand.Next(0, Fruits.Count - 1);
            }

            return(snake);
        }
コード例 #20
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SnakeGame.GameplayController"/> class.
        /// </summary>
        /// <param name="difficulty">The difficulty level to play at.</param>
        public GameplayController(Difficulty difficulty)
        {
            _score              = new Score(difficulty);
            _playArea           = new Grid(32, 32);
            _player             = new Snake(_playArea, _playArea[16, 16], 5, Direction.Right);
            _objective          = new Fruit(_playArea, _player.OccupiedCells, 3);
            _handler            = new FruitEatenHandler(_objective, _player, _score);
            _mover              = new SnakeMovementControlHandler(_player, (int)difficulty);
            _mover.OutOfBounds += (object sender, EventArgs e) =>
            {
                string       finalScore   = "Final score: " + _score.Value;
                Color        textColor    = CellDrawing.GetColor("#e00707");
                EventHandler gameOverText = delegate(object sender2, EventArgs e2)
                {
                    SwinGame.DrawText("GAME OVER", textColor, 96, 128);
                    SwinGame.DrawText(finalScore, textColor, 96, 140);
                };
                var gameOverTimeout = new System.Timers.Timer(2048);
                gameOverTimeout.Elapsed += (object sender2, System.Timers.ElapsedEventArgs e2) =>
                {
                    gameOverTimeout.Stop();
                    gameOverTimeout.Dispose();
                    RenderEvents.RenderTick -= gameOverText;
                    OnDone(new ScoreInputController(_score));
                };
                gameOverTimeout.Start();
                RenderEvents.RenderTick += gameOverText;
            };
            _mover.AfterMove += (object sender, EventArgs e) =>
            {
                _handler.EvaluateState();
            };

            _up = new BooleanControlsFlag(delegate()
            {
                return(SwinGame.KeyDown(KeyCode.vk_w) || SwinGame.KeyDown(KeyCode.vk_UP));
            });
            _up.StateSetTrue += (object sender, EventArgs e) =>
            {
                _mover.Enqueue(Direction.Up);
            };
            _left = new BooleanControlsFlag(delegate()
            {
                return(SwinGame.KeyDown(KeyCode.vk_a) || SwinGame.KeyDown(KeyCode.vk_LEFT));
            });
            _left.StateSetTrue += (object sender, EventArgs e) =>
            {
                _mover.Enqueue(Direction.Left);
            };
            _down = new BooleanControlsFlag(delegate()
            {
                return(SwinGame.KeyDown(KeyCode.vk_s) || SwinGame.KeyDown(KeyCode.vk_DOWN));
            });
            _down.StateSetTrue += (object sender, EventArgs e) =>
            {
                _mover.Enqueue(Direction.Down);
            };
            _right = new BooleanControlsFlag(delegate()
            {
                return(SwinGame.KeyDown(KeyCode.vk_d) || SwinGame.KeyDown(KeyCode.vk_RIGHT));
            });
            _right.StateSetTrue += (object sender, EventArgs e) =>
            {
                _mover.Enqueue(Direction.Right);
            };

            Color scoreColor = CellDrawing.GetColor("#008282");

            _renderer = delegate(object sender, EventArgs e)
            {
                int offset = 1;
                int x;
                int y;
                for (y = -1, x = -1; x <= _playArea.Width; x++)
                {
                    CellDrawing.Draw(offset, offset, new Cell(_playArea, x, y));
                    CellDrawing.Draw(offset, offset, new Cell(_playArea, x, _playArea.Height));
                }
                for (y = 0, x = -1; y < _playArea.Height; y++)
                {
                    CellDrawing.Draw(offset, offset, new Cell(_playArea, x, y));
                    CellDrawing.Draw(offset, offset, new Cell(_playArea, _playArea.Width, y));
                }
                foreach (MovementNode node in _player)
                {
                    CellDrawing.Draw(offset, offset, node.Cell);
                }
                CellDrawing.Draw(offset, offset, _objective.OccupiedCell);
                SwinGame.DrawText("Score: " + _score.Value, scoreColor, 12, 2);
            };
            RenderEvents.RenderTick += _renderer;
        }
コード例 #21
0
        static void Main(string[] args)
        {
            // Number of foods eaten and length of body
            int score = 4;

            // Size of game board
            int width  = Console.WindowWidth;
            int height = Console.WindowHeight;

            // Positioning snake in the middle of the game field
            int x = width / 2;
            int y = height / 2;

            // Starting game speed
            decimal gameSpeed = 150m;

            // Removes the marker that appears in front of the snake
            Console.CursorVisible = false;

            bool gameIsPlaying = true;
            bool wallIsHit;
            bool bodyIsHit;
            bool foodIsEaten;

            // Show current score on screen
            var currentScore = new Score(score);

            currentScore.ShowScore(score, width);

            // Draw game board
            var gameBoard = new GameBoard(width, height);

            gameBoard.Draw();

            // Place snake on game board
            var snake = new Snake(x, y, score);

            snake.DrawSnake();

            // Create food
            var food = new Food(width, height);

            food.DrawFood();

            // Read which key is pressed
            ConsoleKey direction = Console.ReadKey().Key;

            // Game loop
            while (gameIsPlaying)
            {
                // Detect if snake hits wall
                wallIsHit = snake.SnakeCollidedWithWall(snake.SnakeX, snake.SnakeY, height, width);

                if (wallIsHit)
                {
                    gameIsPlaying = false;
                    Console.SetCursorPosition(width / 2 - 16, height / 2 - 1);
                    Console.ForegroundColor = ConsoleColor.DarkRed;
                    Console.WriteLine("GAME OVER! The snake hit the wall :(");
                }

                // Detect if snake hits itself
                bodyIsHit = snake.SnakeCollidedWithItself(snake.SnakeX, snake.SnakeY);

                if (bodyIsHit)
                {
                    gameIsPlaying = false;
                    Console.SetCursorPosition(width / 2 - 16, height / 2 - 1);
                    Console.ForegroundColor = ConsoleColor.DarkRed;
                    Console.WriteLine("GAME OVER! The snake hit itself :(");
                }

                // Detect if apple was eaten
                foodIsEaten = food.FoodWasEaten(snake.SnakeX, snake.SnakeY, food.X, food.Y);

                if (foodIsEaten)
                {
                    // Keep track of how many foods were eaten + make snake longer
                    score++;

                    // Update score that is displayed on the screen
                    currentScore = new Score(score);
                    currentScore.ShowScore(score, width);

                    // Create new food item and draw it on the game board
                    food = new Food(width, height);
                    food.DrawFood();

                    // Make snake faster
                    gameSpeed *= 0.925m;
                }

                snake.DrawSnake();

                snake.MoveSnakeBody(foodIsEaten);

                // Change direction of snake
                switch (direction)
                {
                case ConsoleKey.LeftArrow:
                case ConsoleKey.UpArrow:
                case ConsoleKey.RightArrow:
                case ConsoleKey.DownArrow:
                    snake.Movement(direction);
                    break;
                }


                if (Console.KeyAvailable)
                {
                    direction = Console.ReadKey().Key;
                }

                // Slow down the game
                Thread.Sleep(Convert.ToInt32(gameSpeed));
            }
        } // end of Main()