micromissiles-unity/Assets/Scripts/Assignment/RoundRobinAssignment.cs

39 lines
1.4 KiB
C#
Raw Normal View History

2024-09-12 00:17:21 -07:00
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
// The round-robin assignment class assigns missiles to the targets in a
// round-robin order.
2024-09-13 22:45:25 -07:00
public class RoundRobinAssignment : IAssignment {
// Previous target index that was assigned.
private int prevTargetIndex = -1;
2024-09-12 00:17:21 -07:00
2024-09-24 19:59:25 -07:00
// Assign a target to each interceptor that has not been assigned a target yet.
2024-09-13 22:45:25 -07:00
public IEnumerable<IAssignment.AssignmentItem> Assign(List<Agent> missiles, List<Agent> targets) {
List<IAssignment.AssignmentItem> assignments = new List<IAssignment.AssignmentItem>();
2024-09-24 19:59:25 -07:00
List<int> assignableInterceptorIndices = IAssignment.GetAssignableInterceptorIndices(missiles);
if (assignableInterceptorIndices.Count == 0) {
2024-09-13 22:45:25 -07:00
return assignments;
}
2024-09-12 00:17:21 -07:00
2024-09-24 19:24:50 -07:00
List<int> activeThreatIndices = IAssignment.GetActiveThreatIndices(targets);
if (activeThreatIndices.Count == 0) {
2024-09-13 22:45:25 -07:00
return assignments;
}
2024-09-12 00:17:21 -07:00
2024-09-24 19:59:25 -07:00
foreach (int missileIndex in assignableInterceptorIndices) {
2024-09-24 19:24:50 -07:00
int nextActiveTargetIndex = activeThreatIndices.FindIndex(index => index > prevTargetIndex);
2024-09-12 00:17:21 -07:00
2024-09-13 22:45:25 -07:00
if (nextActiveTargetIndex == -1) {
nextActiveTargetIndex = 0;
}
2024-09-12 15:44:55 -07:00
2024-09-24 19:24:50 -07:00
int nextTargetIndex = activeThreatIndices[nextActiveTargetIndex];
2024-09-13 22:45:25 -07:00
assignments.Add(new IAssignment.AssignmentItem(missileIndex, nextTargetIndex));
prevTargetIndex = nextTargetIndex;
2024-09-12 00:17:21 -07:00
}
2024-09-13 22:45:25 -07:00
return assignments;
}
2024-09-12 00:17:21 -07:00
}