Hello All,
I am trying my hand at making an invaders clone. there are 30 aliens arranged in a 5x 6 matrix on screen. I need to give the bottom most alien the ability to fire a shot. I am using LINQ to group the aliens into 5 groups based on Location.X and then sort the groups descending.I then need to choose one of the groups ( that gives me 5 groups) and select the First alien in the group and use it;s coordinate to fire a shot.
My code below ,well ,works , but aliens in ANY row are merrily firing shots- not just the bottom most. Pl look at my code below and tell me whats wrong. (r = an instance of the Random class, all aliens are in a list called invaders).
{
var query = (from inv in invaders
group inv by inv.Location.X
into invgroup
orderby invgroup.Key descending
select invgroup).ToList();
var invfirst = query[r.Next(query.Count)].First();
invaderShots.Add(new Shot(
new Point(invfirst.Area.X + invfirst.Area.Width / 2, invfirst.Area.Y + invfirst.Area.Height + 5),
displayrect, Shot.Direction.Down));
}
EDIT:
Solved.Now it works as required after David B pushed me in the right direction.
Final code below. May definitely need some improvements in light of the large number of grouping/sorting going on. If anyone has something constructive to say on this I am all ears ( or eyes , in this case). Thanks to all who helped.
List<Invader> firstinvader = invaders.GroupBy(inv => inv.Location.X)
.Select(g => g.OrderByDescending(inv => inv.Location.Y)).ElementAt(r.Next(5)).ToList();
firstinvader.Sort(comparerByLocation);
Invader item = firstinvader[firstinvader.Count -1];
if(invaderShots.Count < 2)
{
invaderShots.Add(new Shot(
new Point(item.Area.X + item.Area.Width / 2, item.Area.Y + item.Area.Height / 2),
displayrect, Shot.Direction.Down));
}
else
{
return;
}