gpt4 book ai didi

c# - 检查列表中的下一个最高/最低值并选择该项目

转载 作者:太空宇宙 更新时间:2023-11-03 23:35:49 25 4
gpt4 key购买 nike

更新:我应该更清楚。我正在尝试按升序对列表进行排序,然后获得比当前选择的武器具有更大值(value)的第一个武器。

此时我的 NextWeapon() 函数没有做任何事情(它只是用来展示我已经尝试过的东西),但在过去我只是简单地迭代到列表中的下一个项目,但是一个项目可能不在那里。

枚举 F3DFXType 是我的角色可能拿起的武器,但如果它们实际上不在 list 中,则循环遍历这些武器是没有意义的。因此,我尝试创建一个 int 类型的列表,并循环遍历它。当角色拿起新武器时,它会作为一个整数添加到列表中,然后当我切换到那个整数时,我会在 F3DFXType 枚举中检查相同的整数。

例如,在皮卡中我会检查碰撞事件,然后使用:weaponList.Add(5);认为它会将整数 5 添加到我的库存中。 F3DFXType 中的第 5 项是“Seeker”。当我尝试遍历我的 list 时,它实际上不会添加第 5 个 F3DFXType,它只会在 F3DFXType 中添加 NEXT 项目。 (例如:我已经有 Vulcan,这将简单地添加 SoloGun,这是枚举中的第二项)


我正在尝试遍历列表中的项目。

我遇到的问题是,如果 Ito 迭代到列表中的下一个项目,则该项目实际上可能不存在。那么我如何前进到列表中确实存在的下一个项目?

我不一定要使用下面的代码寻找答案,我只是想提供一些上下文,以便您可以了解我当前的方法。

// Possible weapon types
public enum F3DFXType
{
Vulcan = 1,
SoloGun,
Sniper,
ShotGun,
Seeker,
RailGun,
PlasmaGun,
PlasmaBeam,
PlasmaBeamHeavy,
LightningGun,
FlameRed,
LaserImpulse
}


// List of weapons currently avaialable
public List<int> weaponList;
public int currentIndex = 1;


void NextWeapon()
{
// Keep within bounds of list
if (currentIndex < weaponList.Count)
{
currentIndex++;

// Check if a higher value exists
var higherVal = weaponList.Any(item => item < currentIndex);

// create a new list to store current weapons in inventory
var newWeapList = new List<int>();
foreach (var weap in weaponList)
{
newWeapList.Add(weap);
}
weaponList = newWeapList;

// If a higher value exists....
if (higherVal)
{
// currentIndex = SOMEHIGHERVALUE
}
}
}



void PrevWeapon()
{
if (currentIndex > 1)
{
currentIndex--;
}
}



// Fire turret weapon
public void Fire()
{
switch (currentIndex)
{
case 1:
// Fire vulcan at specified rate until canceled
timerID = F3DTime.time.AddTimer(0.05f, Vulcan);
Vulcan();
break;
case 2:
timerID = F3DTime.time.AddTimer(0.2f, SoloGun);
SoloGun();
break;
case 3:
timerID = F3DTime.time.AddTimer(0.3f, Sniper);
Sniper();
break;
case 4:
ShotGun();
break;
case 5:
timerID = F3DTime.time.AddTimer(0.2f, Seeker);
Seeker();
break
default:
break;
}
}

最佳答案

如果我对问题的理解正确,我认为您可以简单地通过按升序对列表进行排序,然后获得比当前选择的武器具有更大值(value)的第一个武器来做到这一点。

例如:

void Next()
{
var nextWeapon = weaponList
.OrderBy(w => w) // Sort the weapon list
.FirstOrDefault(w => w > currentIndex); // Get the next highest weapon

// If nextWeapon is 0, there was no higher weapon found
currentIndex = nextWeapon > 0 ? nextWeapon : currentIndex;
}

编辑:

你也可以反过来得到之前的武器:

void PrevWeapon()
{
if (currentIndex > 1)
{
var previousWeapon = weaponList
.OrderByDescending(w => w) // Sort the weapon list
.FirstOrDefault(w => w < currentIndex); // Get the next lowest weapon

// If previousWeapon is 0, there is no next lowest weapon
currentIndex = previousWeapon > 0 ? previousWeapon : currentIndex;
}
}

关于c# - 检查列表中的下一个最高/最低值并选择该项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30632920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com