comparison API/Factories/Requirement/UnitRequiresNUnitsForMUnitsRequirementFactory.cs @ 441:d2331ee59d74

Re #350: Add requirement to allow N of unit for specific other units * Add factory for requirement * Add extra method that assumes "allow N unit for every 1 unit" * Update/fix documentation
author IBBoard <dev@ibboard.co.uk>
date Sat, 03 Dec 2011 16:55:24 +0000
parents
children 5ac76de8ce62
comparison
equal deleted inserted replaced
440:baa34d91031f 441:d2331ee59d74
1 // This file (UnitRequiresNUnitsForMUnitsRequirementFactory.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;
7
8 namespace IBBoard.WarFoundry.API.Factories.Requirement
9 {
10 public class UnitRequiresNUnitsForMUnitsRequirementFactory : IRequirementFactory
11 {
12 public UnitRequiresNUnitsForMUnitsRequirementFactory()
13 {
14 //Do nothing special
15 }
16
17 public string AppliesToID
18 {
19 get
20 {
21 return RequiresNUnitsForMUnitsRequirement.REQUIREMENT_ID;
22 }
23 }
24
25 public IRequirement CreateRequirement<SOURCE_FILE_TYPE, ENTRY_TYPE>(UnitType type, string data, IRaceFactory<SOURCE_FILE_TYPE, ENTRY_TYPE> raceFactory)
26 {
27 RequiresNUnitsForMUnitsRequirement req = new RequiresNUnitsForMUnitsRequirement(type);
28 Race race = type.Race;
29 AddRequirements(req, race, data, raceFactory);
30 return req;
31 }
32
33 private void AddRequirements<SOURCE_FILE_TYPE, ENTRY_TYPE>(RequiresNUnitsForMUnitsRequirement req, Race race, string data, IRaceFactory<SOURCE_FILE_TYPE, ENTRY_TYPE> raceFactory)
34 {
35 foreach (string requirement in data.Split('|'))
36 {
37 string[] requirementParts = requirement.Split(':');
38 string unitID = requirementParts[0];
39 UnitType unitType = raceFactory.GetUnitType(unitID, race);
40
41 if (unitType == null)
42 {
43 throw new InvalidRequirementException(String.Format("Invalid unit type '{0}' for 'Requires N units for M units' requirement", unitID));
44 }
45
46 if (requirementParts.Length == 2)
47 {
48 string amount = requirementParts[1];
49
50 try
51 {
52 req.AddUnitTypeRequirement(unitType, 1, Int32.Parse(amount));
53 }
54 catch (FormatException)
55 {
56 throw new InvalidRequirementException(String.Format("Invalid amount '{0}' for unit type '{1}' for 'Requires N units for M units' requirement", amount, unitID));
57 }
58 }
59 else
60 {
61 req.AddUnitTypeRequirement(unitType);
62 }
63 }
64 }
65 }
66 }
67