【发布时间】:2021-11-22 08:39:51
【问题描述】:
我需要帮助来删除我创建的块。当所有 200 万块都被删除时,我需要程序自行关闭。我已经尝试了几件事,但我的 RemoveAt 函数似乎从未按预期工作。我做错了什么?
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace projectblob_nivå1
{
class Block
{
public int X { get; set; } = 100;
public int Y { get; set; } = 100;
public Color Color { get; set; } = Color.Red;
public void Remove()
{
int i = 0;
block.RemoveAt(i);
i++;
}
public void Draw(SpriteBatch spriteBatch, Texture2D texture)
{
spriteBatch.Draw(texture, new Rectangle(X, Y, 30, 30), Color);
}
}
}
然后是 Game.cs
public class Game1 : Game
{
private GraphicsDeviceManager _graphics;
private SpriteBatch _spriteBatch;
Texture2D pixelTexture;
List<Block> blocks = new List<Block>();
public Game1()
{
_graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
IsMouseVisible = true;
}
protected override void Initialize()
{
Random rnd = new Random();
// TODO: Add your initialization logic here
for (int i = 0; i < 2000; i++)
{
var block = new Block();
block.X = rnd.Next(0, 600);
block.Y = rnd.Next(0, 400);
block.Color = new Color(rnd.Next(256), rnd.Next(256), rnd.Next(256));
blocks.Add(block);
}
base.Initialize();
}
protected override void LoadContent()
{
_spriteBatch = new SpriteBatch(GraphicsDevice);
pixelTexture = Content.Load<Texture2D>("pixel");
// TODO: use this.Content to load your game content here
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
foreach (Block block in blocks)
{
int i = 0;
block.RemoveAt(i);
i++;
if (i==2000)
{
Exit();
}
}
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
_spriteBatch.Begin();
foreach (Block block in blocks)
{
block.Draw(_spriteBatch, pixelTexture);
}
_spriteBatch.End();
base.Draw(gameTime);
}
}
感谢我能得到的所有帮助:)
【问题讨论】:
-
您过分简化了最低代码要求。正确版本的代码将具有删除条件,否则,空白项目将产生相同的输出(因为第一次调用 Update 将删除所有块)...所要求的答案是在
blocks.Clear();之前前锋;不是您想问的,所以请提供更多信息来澄清问题。