首页 > 解决方案 > My snake program won't show the objects I drew. How can I fix it?

问题描述

I'm following a snake tutorial right now and I wrote the exact thing as said, but it won't even show the rectangles of the snake and food.enter code here I'm using Windows Form Application. I made separate classes - Food; Snake; And the one for the form.

//Snake class
public Rectangle[] Body;
        private int x = 0, y = 0, width = 20, height = 20;

        public Snake()
        {
            Body = new Rectangle[1];
            Body[0] = new Rectangle(x, y, width, height);
        }
        public void Draw()
        {
            for (int i = Body.Length - 1; i < 0; i--)
                Body[i] = Body[i - 1];
        }

        public void Draw (Graphics graphics)
        {
            graphics.FillRectangles(Brushes.AliceBlue, Body);

        }

         public void Move (int direction)         
         {
            Draw();

//Food Class
public class Food
    {
        public Rectangle Piece;
        private int x, y, width = 20, height = 20;

        public Food(Random rand)
        {
            Generate(rand);
            Piece = new Rectangle(x, y, width, height);
        }

        public void Draw(Graphics graphics)
        {
            Piece.X = x;
            Piece.Y = y;
            graphics.FillRectangle(Brushes.Red, Piece);

标签: c#

解决方案


您没有从任何形式的可绘制上下文对象继承您的身体和食物类。因此,每当发生更改时,都需要显式调用“绘制”例程。您似乎试图模仿 WinForms UI 组件的结构,其中它有自己的内置 Draw() 方法,该方法在 UI 需要更新时被隐式调用。

此外,由于您在没有任何参数的情况下调用“Draw”,除非您在不需要参数的地方有重载,否则应该会引发错误。在这种情况下,将没有要绘制的图形上下文。

我不是游戏图形方面的专家,但我知道不断调用 UI 组件的重绘方法是非常低效的。Invalidate() 方法有一些覆盖,您可以在其中提供矩形以仅使整个组件的一小部分无效。这有助于提高重绘率。

我建议在屏幕上使用一个可渲染的 UI 组件链接到您的数据对象。并覆盖该组件的 draw() 方法,以便它根据存储在游戏对象中的数据绘制整个游戏板(或基于无效区域的部分游戏板)。


推荐阅读