Percent Health
Below is the complete code for the Percent Health Try It Out! problem.
using System;
using System.Collections.Generic;
using System.Linq;
namespace QueryExpressions
{
public class GameObject
{
public int ID { get; set; }
public double X { get; set; }
public double Y { get; set; }
public double MaxHP { get; set; }
public double CurrentHP { get; set; }
public int PlayerID { get; set; }
}
public class Ship : GameObject { }
public class Player
{
public int ID { get; set; }
public string UserName { get; set; }
public string TeamColor { get; set; } // A Color class might be better than string here.
}
class Program
{
static void Main(string[] args)
{
List<GameObject> gameObjects = new List<GameObject>();
gameObjects.Add(new Ship { ID = 1, CurrentHP = 50, MaxHP = 100, PlayerID = 1 });
gameObjects.Add(new Ship { ID = 2, CurrentHP = 75, MaxHP = 100, PlayerID = 1 });
gameObjects.Add(new Ship { ID = 3, CurrentHP = 0, MaxHP = 100, PlayerID = 2 });
gameObjects.Add(new Ship { ID = 3, CurrentHP = 100, MaxHP = 100, PlayerID = 2 });
gameObjects.Add(new Ship { ID = 3, CurrentHP = 100, MaxHP = 200, PlayerID = 2 });
List<Player> players = new List<Player>();
players.Add(new Player { ID = 1, UserName = "Player 1", TeamColor = "Red" });
players.Add(new Player { ID = 2, UserName = "Player 2", TeamColor = "Blue" });
var results = from o in gameObjects
orderby o.CurrentHP / o.MaxHP
group o by o.PlayerID;
foreach(var group in results)
{
Console.WriteLine(group.Key);
foreach (var item in group)
Console.WriteLine(" " + item.CurrentHP + "/" + item.MaxHP +
" (" + (int)((item.CurrentHP / item.MaxHP) * 100) + "%)");
}
Console.ReadKey();
}
}
}