我正在为我的 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/