невозможно преобразовать из int в MsPacman.Ghost.Direction - PullRequest
0 голосов
/ 29 марта 2020

Я не использовал ничего из этого в классе, но это все еще является требованием для нашего проекта, и меня немного сжимают.

Подведем итог: Мне нужно сыграть в pacman в 2D с использованием расширения моногейма в Visual Studio язык C#, и возникает проблема, когда я пытаюсь переместить призраков , создавая автономное движение Я не могу обернуть голову вокруг решения, поэтому вот что я получил:

float dist = Vector2.Distance(position.ToVector2(), targetPosition.ToVector2());

if (dist <= 1)
{
    List<Direction> availableDirections = new List<Direction>();

    foreach (var dir in Surroundings)
        if (game1.Board.board[targetPosition.X / (Game1.outputTileSize) + dir.Value.X, targetPosition.Y / (Game1.outputTileSize) + dir.Value.Y] == ' ')
            availableDirections.Add(dir.Key);

    if (availableDirections.Count == 0) return;

    availableDirections = availableDirections.OrderBy(dir =>
    {
        float distP1 = Vector2.Distance(targetPosition.ToVector2() + Surroundings[dir].ToVector2() * Game1.outputTileSize, game1.Player.position.ToVector2());
        return distP1;
    }).ToList();

    direction = availableDirections[0];

    direction = Surroundings[availableDirections.Count - 1];


    targetPosition = targetPosition + availableDirections[direction].Game1.outputTileSize;
}
else
{
    //Position is not the same, move the guy
    Vector2 vec = targetPosition.ToVector2() - position.ToVector2();
    vec.Normalize();
    position = (position.ToVector2() + vec).ToPoint();
    //Incrementar frame
    if ((position.X + position.Y) % 4 == 0)
        frame++;
    if (frame > 1) frame = -1;

}

Я пытался создать другой тип списка, все еще используя словарь, но проблема в том, что он не распознает позиция в списке как целое число, и это конфликтует. Вот остаток кода, который важен для понимания того, как все соединяется:

namespace MsPacMan
{
    public class Ghost : DrawableGameComponent
    {
        //enumeradores
        enum Orientation { Horizontal, Vertical }

        enum Direction { Up, Down, Left, Right }

        #region variables

        private Texture2D texture;

        private SpriteBatch spriteBatch;

        private SoundEffect eatghostSound;

        private Game1 game1;

        private int ghostType;

        private Board board;

        private Orientation orientation;

        public Point position, targetPosition, origin;

        int enemyLives = 4;

        int patrolSize;

        int patrolPosition = 0;

        int direction = 1;

        int frame = 0;

        public static int ghostValue = 200;

        Dictionary<Direction, Vector2> ghostColor;

        Dictionary<Direction, Point> Surroundings;

        Direction gDirection = Direction.Up;

        #endregion

        #region Constructor
        public Ghost(Game1 game, int x, int y, int ghostType) : base(game)
        {
            orientation = Game1.rnd.Next(2) > 0 ? Orientation.Horizontal : Orientation.Vertical;

            texture = game.SpriteSheet;

            spriteBatch = game.SpriteBatch;

            this.ghostType = ghostType;

            position.Y = y;

            position.X = x;

            targetPosition = position;

            game1 = game;

            board = game1.Board;

            origin = targetPosition = position;

            patrolSize = 2 + Game1.rnd.Next(4);

            eatghostSound = game1.Content.Load<SoundEffect>("pacman_eatghost");

            Surroundings = new Dictionary<Direction, Point>
            {
                [Direction.Up] = new Point(0, -1),
                [Direction.Down] = new Point(0, 1),
                [Direction.Left] = new Point(-1, 0),
                [Direction.Right] = new Point(0, 1),
            };

            ghostColor = new Dictionary<Direction, Vector2>
            {
                [Direction.Right] = new Vector2(0, ghostType),
                [Direction.Left] = new Vector2(2, ghostType),
                [Direction.Up] = new Vector2(4, ghostType),
                [Direction.Down] = new Vector2(6, ghostType),
            };

        }


        #endregion

        #region Properties
        public Board Board => board;

        #endregion

        #region Methods


        public override void Update(GameTime gameTime)
        {
            Rectangle pRect = new Rectangle(game1.Player.position, new Point(Game1.outputTileSize));

            Rectangle EnemyArea = new Rectangle(((position.ToVector2()) * Game1.outputTileSize).ToPoint(), new Point(Game1.outputTileSize));

            ChasePattern(ghostType);

            if (EnemyArea.Intersects(pRect))
            {
                Pellet.GetPelletStatus();

                if (Pellet.powerPellet)
                {
                    this.Die();
                }

                else
                {
                    game1.Player.Die();
                }

            }
        }

        //Draws the different types of ghosts
        public override void Draw(GameTime gameTime)
        {
            Rectangle outRect = new Rectangle(position.X * Game1.outputTileSize, position.Y * Game1.outputTileSize, Game1.outputTileSize, Game1.outputTileSize);

            Rectangle sourceRec = new Rectangle(((ghostColor[gDirection] + Vector2.UnitX * frame) * 16).ToPoint(), new Point(15));

            Rectangle sourcePelletRec = new Rectangle(8 * 16, 0, 16, 15);

            spriteBatch.Begin();

            Pellet.GetPelletStatus();

            if (!Pellet.powerPellet)
            {
                spriteBatch.Draw(texture, outRect, sourceRec, Color.White);
            }
            else
            {
                spriteBatch.Draw(texture, outRect, sourcePelletRec, Color.White);
            }
            spriteBatch.End();
        }

        public void Die()
        {
            eatghostSound.Play();

            enemyLives--;

            int n = 4 - enemyLives;

            AssignGhostValue(n);

            game1.Ghosts.Remove(this);

            game1.Components.Remove(this);

            position = targetPosition = origin;

            game1.Ghosts.Add(this);

            game1.Components.Add(this);
        }

        public void AssignGhostValue(int n)
        {
            ghostValue = ghostValue * n;

            game1.Player.Score += ghostValue;
        }

        public void ChasePattern(int ghostType)
        {
            int ghosType = ghostType;

            int blinky = 0, pinky = 1, inky = 2, clyde = 3;

            if (ghosType == blinky)
            {
                ChaseAggressive();
            }
            else if (ghosType == pinky)
            {
                ChaseAmbush();
            }
            else if (ghosType == inky)
            {
                ChasePatrol();
            }
            else if (ghosType == clyde)
            {
                ChaseRandom();
            }
        }

        public void ChaseAggressive()
        {
            //Blinky the red ghost is very aggressive in its approach while chasing Pac - Man and will follow Pac-Man once located


            float dist = Vector2.Distance(position.ToVector2(), targetPosition.ToVector2());

            if (dist <= 1)
            {
                List<Direction> availableDirections = new List<Direction>();


                foreach (var dir in Surroundings)
                    if (game1.Board.board[targetPosition.X / (Game1.outputTileSize) + dir.Value.X, targetPosition.Y / (Game1.outputTileSize) + dir.Value.Y] == ' ')
                        availableDirections.Add(dir.Key);

                if (availableDirections.Count == 0) return;

                availableDirections = availableDirections.OrderBy(dir =>
                {
                    float distP1 = Vector2.Distance(targetPosition.ToVector2() + Surroundings[dir].ToVector2() * Game1.outputTileSize, game1.Player.position.ToVector2());
                    return distP1;
                }).ToList();

                direction = availableDirections[0];

                direction = Surroundings[availableDirections.Count - 1];


                targetPosition = targetPosition + availableDirections[direction]. Game1.outputTileSize;
            }
            else
            {
                //Position is not the same, move the guy
               Vector2 vec = targetPosition.ToVector2() - position.ToVector2();
                vec.Normalize();
                position = (position.ToVector2() + vec).ToPoint();
                //Incrementar frame
                if ((position.X + position.Y) % 4 == 0)
                    frame++;
                if (frame > 1) frame = -1;
            }
        }
    }
}
...