Problem with winform redrawing itself
I am building a Space Invaders game. I have got a simple algorithm that removes an invader when it gets shot and adds a score.
The problem is in this bunch of statments:
if (removeInvaderBool)
{
// removeInvader is an Invader object which was hit, and to be removed.
Invaders.Score += removeInvader.addedScore; //Invader class has got a property with a specific score (e.g. score 50). Score is a static field in the Invaders class.
invaders.Remove(removeInvader);//invaders is a List<Invaders>
}
Now 80% of the time, the score is being upgraded and the invader is being removed. The other 20% of the time, the score goes up, and the invader isn't being removed...
Why is that..?
My game is on winforms, the Form1_Paint event handler draws all the graphics every 33 ms, and the game timer runs every 10 ms. (I use 2 timers, instead of threads.)
Why is it that 20% of the time the invader is not being removed while the score is being updated??
here is a bigger extract of my code as requested:
foreach (var invaderItem in hitInvaders)
{
// if the area of hte alien contains the shot remove the shot.
foreach (var player in playerShots)
{
if (isWeapon)
{
//Me: Will remove players shot.
if (invaderItem.Area.IntersectsWith(player.Area))
{
removeShot = true;
removePlayerShot = player;
removeInvaderBool = true;
}
}
else
{
//Me: Will remove players shot.
if (invaderItem.Area.Contains(player.Location))
{
removeShot = true;
removePlayerShot = player;
removeInvaderBool = true;
}
}
}
// remove the alien that contains 开发者_Python百科the shot
removeInvader = invaderItem;
}
if (removeShot)
{
Invaders.Score += removeInvader.addedScore;
playerShots.Remove(removePlayerShot);
}
if (removeInvaderBool)
{
invaders.Remove(removeInvader);
}
}
Debug your program. List<>.Remove() returns a bool. Make use of that:
Invaders.Score += removeInvader.addedScore;
bool ok = invaders.Remove(removeInvader);
System.Diagnostics.Debug.Assert(ok);
The debugger will break when the invader is not in the list. Consider that you may not have implemented its Equals() method correctly.
精彩评论