C# 俄罗斯方 block 游戏性能缓慢

标签 c# performance picturebox lag tetris

我正在为我的 C# 学校项目编写一个俄罗斯方 block 克隆程序。我正在使用 Microsoft Visual Studio 2012。游戏本身是作为二维 block 数组( block 列表列表)实现的,每个 block 都有自己的纹理(bmp 图像)。我将整个数组绘制到 PictureBox 控件上,这就是问题开始的地方。更新 PictureBox 上的图像(移动/旋转事件形状)时,游戏会稍微滞后。我尝试在面板控件上绘图,但结果是相同的。我大概知道什么可能会导致延迟,但我不知道如何消除它。

这是游戏“网格”的绘制方法:

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”是一个私有(private)Bitmap变量,我在类构造函数中只创建一次(以减少(不成功)延迟)。

只要游戏状态发生变化(例如移动/旋转事件的四格骨牌和每个“重力”刻度),就会调用 GameDraw 方法

最佳答案

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

Double buffering uses a memory buffer to address the flicker problems associated with multiple paint operations. When double buffering is enabled, all paint operations are first rendered to a memory buffer instead of the drawing surface on the screen

您可以使用 Control.DoubleBuffered 启用它属性(property)

关于C# 俄罗斯方 block 游戏性能缓慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16541905/

相关文章:

c# - Dropdownlist onselectedindexchanged 问题

c# - 在 ASP.NET 中从 SQL Server 读取 XML 文件

javascript - 等待一项发布完成后再开始另一项发布

c# - 移动图片框元素

c# - 如何修复从删除条件注释中删除 HTML 注释的正则表达式?

c# - 从 C# 中的 BinaryReader 读取字符串不读取第一个字节

Python 2 列出比较优化

c++ - 在 C++ 中优化 MySQL 插入

c# - 当我重新运行应用程序时,图片框不显示最后上传的图像

c# - 如何在 Microsoft 报告中显示来自字节数组的图像