【发布时间】:2021-06-04 17:26:55
【问题描述】:
我最近开始玩monogame,为了了解它的工作原理,我想对排序算法进行可视化。
当我启动程序时,draw() 函数不会在当前状态下重绘列。
它显示第一个状态,在循环结束时只是跳转到排序状态。
我错过了什么吗?
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
if (Keyboard.GetState().IsKeyDown(Keys.Enter))
{
int temp;
for (int j = 0; j <= MainArray.Length - 2; j++)
{
for (int i = 0; i <= MainArray.Length - 2; i++)
{
if (MainArray[i] > MainArray[i + 1])
{
temp = MainArray[i + 1];
MainArray[i + 1] = MainArray[i];
MainArray[i] = temp;
Draw(gameTime);
Thread.Sleep(300);
}
}
}
}
// TODO: Add your update logic here
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
spriteBatch.Begin();
for (int i = 0; i < MainArray.Length; i++)
{
sprite.Draw(new Vector2(i * 40 + 20, -10), spriteBatch, new Rectangle(i * 40 + 30, 0, 30, MainArray[i] * 8));
}
spriteBatch.End();
// TODO: Add your drawing code here
base.Draw(gameTime);
}
【问题讨论】:
-
没有必要在
Update()方法中调用Draw(gameTime),因为Draw()方法已经自己调用了。也不鼓励使用Thread.Sleep(),因为这会迫使程序等待并且在其间什么也不做。 -
for (int j = 0; j <= MainArray.Length - 2; j++)行中存在错误。它应该是:for (int j = 0; j < MainArray.Length; j++)以确保它涵盖所有可能性。冒泡排序需要 N*N 次比较才能解决最坏的情况。