view API/Factories/Requirement/UnitRequiresAtLeastNUnitsRequirementFactory.cs @ 379:04f4c2fea356

Re #351: Add extensible requirement handling method * Extract common IRequirementFactory interface * Drop back to just returning IRequirement from factory to simplify generics * Add initial registration of requirement factories
author IBBoard <dev@ibboard.co.uk>
date Sat, 23 Jul 2011 19:53:42 +0000
parents c3b0b28bad48
children 3882b533d99d
line source
1 // This file (UnitRequiresAtLeastNUnitsRequirementFactory.cs) is a part of the IBBoard.WarFoundry.API project and is copyright 2011 IBBoard
2 //
3 // The file and the library/program it is in are licensed and distributed, without warranty, under the GNU Affero GPL license, either version 3 of the License or (at your option) any later version. Please see COPYING for more information and the full license.
4 using System;
5 using IBBoard.WarFoundry.API.Objects;
6 using IBBoard.WarFoundry.API.Objects.Requirement;
8 namespace IBBoard.WarFoundry.API.Factories.Requirement
9 {
10 public class UnitRequiresAtLeastNUnitsRequirementFactory : IRequirementFactory
11 {
12 public UnitRequiresAtLeastNUnitsRequirementFactory()
13 {
14 //Do nothing special
15 }
17 public string AppliesToID {
18 get {
19 return "RequiresAtLeastNUnits";
20 }
21 }
23 public IRequirement CreateRequirement<SOURCE_FILE_TYPE, ENTRY_TYPE>(UnitType type, string data, IRaceFactory<SOURCE_FILE_TYPE, ENTRY_TYPE> raceFactory)
24 {
25 UnitRequiresAtLeastNUnitsRequirement req = new UnitRequiresAtLeastNUnitsRequirement(type);
26 Race race = type.Race;
27 AddRequirements(req, race, data, raceFactory);
28 return req;
29 }
31 private void AddRequirements<SOURCE_FILE_TYPE, ENTRY_TYPE>(UnitRequiresAtLeastNUnitsRequirement req, Race race, string data, IRaceFactory<SOURCE_FILE_TYPE, ENTRY_TYPE> raceFactory)
32 {
33 foreach (string requirement in data.Split('|'))
34 {
35 string[] requirementParts = requirement.Split(':');
36 string unitID = requirementParts[0];
37 UnitType unitType = raceFactory.GetUnitType(unitID, race);
39 if (unitType == null)
40 {
41 throw new InvalidRequirementException(String.Format("Invalid unit type '{0}' for 'Requires at least N units' requirement", unitID));
42 }
44 if (requirementParts.Length == 2)
45 {
46 string amount = requirementParts[1];
48 try
49 {
50 req.AddUnitTypeRequirement(unitType, Int32.Parse(amount));
51 }
52 catch (FormatException)
53 {
54 throw new InvalidRequirementException(String.Format("Invalid amount '{0}' for unit type '{1}' for 'Requires at least N units' requirement", amount, unitID));
55 }
56 }
57 else
58 {
59 req.AddUnitTypeRequirement(unitType);
60 }
61 }
62 }
63 }
64 }