这是一个简单的蛇的游戏,但我有一个问题与蛇的食物。我用generateSnakeFood();
刷出一个新的食物,这很好,但是当我尝试创建多个蛇食时,它只是在不同的位置重新绘制一个新的蛇食,这是因为只有一个蛇食,所以刷在另一个区域绘制一个新的蛇食。如果是这样,我该如何修复它,这样我就可以有多个相同的蛇食?
private Square SnakeFood = new Square();
private void generateSnakeFood()
{
int maxXPosition = pictureBox1.Size.Width / GameSetting.Width;
int maxYPosition = pictureBox1.Size.Height / GameSetting.Height;
SnakeFood = new Square { X = random.Next(0, maxXPosition), Y = random.Next(0, maxYPosition) };
}
private void UpdateGame(object sender, PaintEventArgs e)
{
Graphics canvas = e.Graphics
canvas.FillRectangle(Brushes.Red,
new Rectangle(
SnakeFood.X * GameSetting2.Width2,
SnakeFood.Y * GameSetting2.Width2,
GameSetting2.Width2, GameSetting2.Height2
));
}
这是因为只能有一个SnakeFood所以刷在另一个区域画一个新的
是的。即使你做了一个new Square
你仍然重新激活了相同的变量。代码的绘制部分只是读取1个变量并绘制1个Square
。您将需要使用某种类型的集合,以便您可以有不同的计数。这也意味着你需要改变你的代码,你检测碰撞和你吃食物的地方,并删除它。
有很多方法可以实现这一点,可以使用List
并像这样更改代码
private List<Square> SnakeFoods = new List<Square>();
private void generateSnakeFood()
{
// create new random food using the new method
// doesn't mean it's valid yet
Square newFood = GenerateRandomFood();
// you need to make sure there is not another food at that same location
// in the collection or else you have a duplicate.
// if there is a duplicate you need to generate a new one until it's unique.
// Here I use linq, a feature available on List to check if
// you already have a food at that location in order to prevent doubles
// While it find ANY item in the collection that has the same X and Y it regenerate a new random food.
while(SnakeFoods.Any(snakeFood => snakeFood.X == newFood.X && snakeFood.Y == newFood.Y))
{
newFood = GenerateRandomFood();
}
// when the code get's here the loop above had taken care that
// newFood is not a duplicate so we can add it
SnakeFoods.Add(newFood);
}
// this will just return a new random food without storing it as we dont know if it's good
private Square GenerateRandomFood()
{
int maxXPosition = pictureBox1.Size.Width / GameSetting.Width;
int maxYPosition = pictureBox1.Size.Height / GameSetting.Height;
// just return new random food
return new Square { X = random.Next(0, maxXPosition), Y = random.Next(0, maxYPosition) };
}
绘图部分需要稍微改变一下,以便在集合上循环并绘制其中的所有食物。
private void UpdateGame(object sender, PaintEventArgs e)
{
Graphics canvas = e.Graphics
// one minor change is to loop to draw all foods (squares)
foreach(Square SnakeFood in SnakeFoods)
{
canvas.FillRectangle(Brushes.Red,
new Rectangle(
SnakeFood.X * GameSetting2.Width2,
SnakeFood.Y * GameSetting2.Width2,
GameSetting2.Width2, GameSetting2.Height2));
}
}
尽管所有这些变化显示了多种食物来源的工作代码,但您仍然需要编写代码,检查您是否吃过一个以及如何将其从列表中删除。我把它省略了,所以你还有工作要做,还有东西要学。