c#俄罗斯方块游戏运行缓慢

本文关键字:运行 缓慢 游戏 方块 俄罗斯 | 更新日期: 2023-09-27 18:13:41

我正在为我的c#学校项目编程一个俄罗斯方块克隆。我使用的是Microsoft Visual Studio 2012。游戏本身被实现为一个二维的块数组(块列表的列表),每个块都有自己的纹理(bmp图像)。我将整个数组绘制到PictureBox控件上,这就是问题开始的地方。当在PictureBox上更新图像(移动/旋转活动形状)时,游戏会稍微滞后。我尝试在Panel控件上绘制,但结果是一样的。我有一个大概的想法是什么可能导致延迟,但我不知道确切的方法来摆脱它。

这是游戏"grid"的绘制方法:

public void Draw(Graphics g)
{
   Brush brush;
   Font font = new System.Drawing.Font( "Arial", 5);
   for (int i = 0; i < Width; i++)
     for (int j = 0; j < Height; j++)
     {
          brush = new TextureBrush(Blocks[i][j].Texture);
          if (Blocks[i][j].Occupied==true)
             g.FillRectangle(brush, i * 20, j * 20, i * 20 + Blocks[i][j].Texture.Width, j * 20 + Blocks[i][j].Texture.Height); 
     }
}

这是活性四重奏的绘制方法:

public void Draw(Graphics g)
{
    Brush brush = new TextureBrush(Blocks[0].Texture);
    foreach (FullBlock b in Blocks)
       g.FillRectangle(brush, b.x * 20, b.y * 20,b.Texture.Width, b.Texture.Height);
}

游戏本身会同时使用它们(双缓冲尝试):

public void GameDraw(PictureBox p)
{
    Graphics g = Graphics.FromImage(gb);
    gameGrid.Draw(g);
    PlayingShape.Draw(g);
    p.Image = gb;
    p.Refresh();
}

其中"gb"是私有Bitmap变量,我只在类构造函数中创建一次(以减少(不成功的)延迟)。

GameDraw方法在游戏状态改变时被调用(例如移动/旋转活动的tetromino和每个"重力"刻度)

c#俄罗斯方块游戏运行缓慢

您需要双缓冲,但您没有设置。引用MSDN:

双缓冲使用内存缓冲区来解决闪烁问题与多个油漆操作相关联。当双缓冲是启用后,所有绘制操作首先呈现到内存缓冲区而不是屏幕上的绘图面

您可以使用Control启用它。DoubleBuffered地产

不需要图片框,添加自己的控件:

using System.Drawing;
using System.Windows.Forms;
namespace TetrisGame
{
    public sealed class TetrisControl : Control
    {
        private TheBlockType[][] blocks = ...;
        protected override void OnPaint(PaintEventArgs e)
        {
            //draw your stuff here direct to the control, no buffers in the middle
            //if that causes flickering, turn on double buffering, but don't bother doing it yourself
            //this is your existing draw method:
            Draw(e.Graphics);
        }
    }
}

然后在每次滴答或移动时,执行而不是调用paint,只是使控件无效:

tetris.Invalidate();

还有,跳出思维定势…而不是做一个完整的网格扫描,你可以让你的每个形状的链接列表的一部分,并根据他们在网格中的位置重新绘制他们…在你的网格完全填满之前,你会做更少的扫描。

或者,考虑只重画你需要重画的部分,即一个块落在顶部附近,不需要完全重画整个网格。

优化是我们与动物的区别。除了鸭嘴兽,谁是最理想的生物。