你能帮我在 C# 中创建 4 个从 1 到 10 的唯一数字吗?

Can you help me to create 4 unique numbers from 1-10 in C#?

我的游戏脚本有问题。目前我的游戏中有 6 个车道和 4 个敌人。如果敌人到达车道尽头,他会在新车道重生。我希望任何敌人都不会像上面那样走同一条路。

我是这样做的

Randomlane = rnd.Next(1, 7);
Enemy1_Lane = Randomlane;

if (Enemy1_Lane == Enemy2_Lane)
{
    if (Enemy1_Lane == 6)
    {
        Enemy1_Lane -= 1;
    }
    else
    {
        Enemy1_Lane += 1;
    }
}


But this only works with 2 Enemies. Now I have 4. Maybe you can help me.

你需要为每个敌人保存车道:

var lane_per_enemy = new List<int>();

如果敌人到达车道的尽头,将下一条车道与列表中的条目进行比较。

你可以做到

// Creates an enumeration from 1 to 10
// orders it randomly
// then picks 4 items
var enemyLanes = Enumerable.Range(1, 10).OrderBy(c => rnd.Next()).Take(4).ToArray();

这将 return 一个具有 4 个元素的 int[],这些元素是 110 之间的唯一随机值。


但进一步听起来您还希望在下一次迭代中它不会再次选择与以前相同的车道,这样您就可以记住您之前使用过的车道并过滤掉这些车道并执行例如

private int[] currentEnemyLanes;

...

// Except additionally removes all the elects of currentEnemyLanes from the options
// and keeps only these that are not currently occupied
var nextEnemyLanes = var enemyLanes = Enumerable.Range(1, 10).Except(currentEnemyLanes).OrderBy(c => rnd.Next()).Take(4).ToArray();

currentEnemyLanes = nextEnemyLanes;

总的来说,如果敌人存储他们当前的车道并在选择下一个车道时再次释放它,在我看来它甚至会更加优化,例如

private int currentLane;

private static HashSet<int> availableLanes = new HashSet<int>() { 1,2,3,4,5,6,7,8,9,10 };

void PickNextLane()
{
    // pick a random entry from all available lanes
    var newLane = availableLanes.OrderBy(l => rnd.Next()).First();

    // remove this from the options so another instance won't pick the same one
    availableLanes.Remove(newLane);

    // if you had a valid lane already
    if(currentLane > 0)
    {
        // Now give it free so another one can pick it again
        availableLanes.Add(currentLane);
    }

    // finally store the new value
    currentLane = newLane;
}