0

好的,所以我正在用 c# 创建一个 pacman 游戏,我已经把 pacman 搞定了。现在我正试图让我的怪物进入游戏。

我创建了一个带有移动方法和所有内容的类。现在的问题是我在不同的图形对象上绘制怪物和吃豆人。它们都是我面板的大小,当我运行代码时,只有 pacman 出现,怪物正在工作,但它位于 pacman 正在移动的图形对象下方。

这是绘制怪物和吃豆人的代码:

private void timMove_Tick(object sender, EventArgs e)
    {
        Bitmap bitmap = new Bitmap(panBox.Width, panBox.Height);
        Graphics g = Graphics.FromImage(bitmap);
        foreach (Monster mon in monsters)
        {
            mon.move(g);
        }
        foreach (Pacman pac in characters)
        {
           pac.move(g);
        }
        Graphics g2 = panBox.CreateGraphics();
        g2.DrawImage(bitmap, 0, 0);            
    }

我的问题是:如何让它们在同一个图形对象上绘图,或者它们都只显示而不是现在只显示 pacman?

4

1 回答 1

1

我认为您应该总体上考虑您的班级结构。我建议使用这样的东西作为起点:

abstract class GameObject
{
    public abstract void Move();
    public abstract void Draw(Graphics g);
}

class Pacman : GameObject
{
    public override void Move()
    {
        //Update the Position of Pacman, check for collisions, ...
    }

    public override void Draw(Graphics g)
    {
        //Draw Pacman at his x and y coordinates
    }
}

class Monster : GameObject
{
    public override void Move()
    {
        //Update the Position of the Monster, ...   
    }

    public override void Draw(Graphics g)
    {
        //Draw the Monster at his current position
    }
}

class GameClass
{
    private Pacman _pacman;
    private Monster _monster;
    private List<GameObject> _gameobjects = new List<GameObject>();

    public GameClass()
    {
        _pacman = new Pacman();
        _monster = new Monster();
        _gameobjects.Add(_pacman);
        _gameobjects.Add(_monster);
    }


    private void TimerTick()
    {
        //update all GameObjects
        foreach (var gameobject in _gameobjects)
        {
            gameobject.Move();
        }
        //Draw every single GameObject to the Bitmap
        Bitmap bitmap = new Bitmap(panBox.Width, panBox.Height);
        using (Graphics g = Graphics.FromImage(bitmap))
        {
            foreach (var gameobject in _gameobjects)
            {
                gameobject.Draw(g);
            }
        }
        //Draw the Bitmap to the screen
        using (Graphics g = panBox.CreateGraphics())
        {
            g.DrawImage(bitmap, 0, 0);
        }
    }

您应该看一下一般的继承/多态性和类。多态性: https : //docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/polymorphism 类: https ://docs.microsoft.com/en-us/dotnet/csharp /programming-guide/classes-and-structs/classes

于 2017-10-19T17:21:03.173 回答