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

46 lines
1.5 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-12 15:44:55 -07:00
public class RoundRobinAssignment : IAssignment
2024-09-12 00:17:21 -07:00
{
// Previous target index that was assigned.
private int prevTargetIndex = -1;
// Assign a target to each missile that has not been assigned a target yet.
2024-09-12 15:44:55 -07:00
public IEnumerable<IAssignment.AssignmentItem> Assign(List<Agent> missiles, List<Agent> targets)
2024-09-12 00:17:21 -07:00
{
2024-09-12 15:44:55 -07:00
List<IAssignment.AssignmentItem> assignments = new List<IAssignment.AssignmentItem>();
List<int> assignableMissileIndices = IAssignment.GetAssignableMissileIndices(missiles);
2024-09-12 00:17:21 -07:00
if (assignableMissileIndices.Count == 0)
{
2024-09-12 15:44:55 -07:00
return assignments;
2024-09-12 00:17:21 -07:00
}
2024-09-12 15:44:55 -07:00
List<int> activeTargetIndices = IAssignment.GetActiveTargetIndices(targets);
2024-09-12 00:17:21 -07:00
if (activeTargetIndices.Count == 0)
{
2024-09-12 15:44:55 -07:00
return assignments;
2024-09-12 00:17:21 -07:00
}
foreach (int missileIndex in assignableMissileIndices)
{
int nextActiveTargetIndex = activeTargetIndices
.FindIndex(index => index > prevTargetIndex);
if (nextActiveTargetIndex == -1)
{
nextActiveTargetIndex = 0;
}
int nextTargetIndex = activeTargetIndices[nextActiveTargetIndex];
2024-09-12 15:44:55 -07:00
assignments.Add(new IAssignment.AssignmentItem(missileIndex, nextTargetIndex));
2024-09-12 00:17:21 -07:00
prevTargetIndex = nextTargetIndex;
}
2024-09-12 15:44:55 -07:00
return assignments;
2024-09-12 00:17:21 -07:00
}
}