コード例 #1
0
ファイル: SnakeGame.cs プロジェクト: Ket/PG3300-Innlevering1
        static void Main()
        {
            Console.CursorVisible = false;

            // Instanciate Snake with 3 bodyparts
            Snake snake = new Snake(3);
            // Take control of it.
            InputHandler.Instance.SetControl(snake);

            // Instanciate apple
            Apple apple = new Apple(Global.defaultAppleTexture);
            /* Tell the apple to monitor the snakes
            position so it can respawn "safely". */
            apple.AddSnakeMonitor(snake);
            /* Spawn the apple. */
            apple.Respawn(snake.body.GetOccupiedPositions());

            /* Start the game loop */

            Stopwatch intervalClock = new Stopwatch();
            intervalClock.Start();
            while(!Global.isGameFinished)
            {
                // Update input
                InputHandler.Instance.Update();

                // Enforce update interval
                if (intervalClock.ElapsedMilliseconds < Global.updateInterval)
                {
                    continue;
                }

                /* If game is paused, don't update
                 * the rest of the game. Just the input */
                if (Global.isGamePaused)
                {
                    continue;
                }

                // Update game objects
                snake.Update();
                apple.Update();

                // If Snake eats the apple...
                if (snake.position.Equals(apple.position)){

                    // Check if there is room for more apples on the gameboard.
                    if (snake.body.length == Global.maxApples)
                    {
                       Global.isGameFinished = true;
                       continue;
                    }

                    // Then grow the snake.
                    snake.body.Grow();

                    // Reincarnate the apple
                    apple.Respawn(snake.body.GetOccupiedPositions());
                }

                /* Check the status of the snake */
                if (!snake.alive)
                {
                    Global.isGameFinished = true;
                }

                // Check if the snake has moved out of bounds.
                if (snake.position.X < 0 || snake.position.Y < 0 ||
                    snake.position.X >= Global.windowWidth ||
                    snake.position.Y >= Global.windowHeight
                    )
                {
                    Global.isGameFinished = true;
                }

                // Check if the game is finished before drawing anything.
                if (Global.isGameFinished)
                {
                    continue;
                }

                // Draw apple and snake
                apple.Draw();
                snake.Draw();

                // Restart update interval-clock before next update.
                intervalClock.Restart();
            }
        }