如何每个级别的位置只绘制一次并检查位置是否唯一?

时间:2012-01-29 21:41:51

标签: c# xna-4.0

就像在Title中一样,我希望从List<Vector2> positions = new List<Vector2>{/*here i got 9 vectors*/}获得位置,而我只希望获得其中的一些。

例如在第一级别我想要在第二级2位置中从该列表中随机选择1个位置,依此类推......

//making that in switch statement where i check which level user actually is
Random rnd = new Random();
List<Vector2> list = new List<Vector2>();
byte i = 0;
byte level; // number from 0 to 9 changing where level complited;
while(i < level){
      list.Add(positions[rnd.Next(0,10)]);
      i++;
 }

我遇到的问题是如何随机选择每个级别的这个位置现在我随机化这个但它一直在变化。我在绘制方法中制作它。

我应该在哪里抽签这个职位?在更新方法或其他地方?

修改 随机检查意味着我想从我的列表中只获得1个Vector2但是使用随机类随机化每个级别现在是否清楚?我不知道我能解释多么简单:(

EDIT1:

以及如何防止从列表中获取相同的位置我的意思是如何检查列表中的这个Vector2是否被绘制(是唯一的)。

感谢提前:)

1 个答案:

答案 0 :(得分:1)

加载关卡的方法中执行此操作。在while循环中添加i++

修改

好的,我明白你的意思了:一个是1级,2个是2级等。

你的代码没问题,并且会做你想要的,但是把它放在draw方法(或更新)中是错误的,因为这些方法经常执行。

您应该做的是使用一种特殊的方法来加载新级别。当您检测到某个级别已完成时,您可以调用此方法,它将执行的操作是清除上一级别的资源(如重置玩家位置,生命,弹药等)。然后你将构建新的等级 - 放置敌人等等,这包括你指定的代码。

我希望我有点清楚。

这是一个原型:

int _lives;
int _ammo;
List<Vector2> _positions;
Vector2 _playerPosition;
int _currentLevel;    

void LoadLevel(int level)
{
    _currentLevel = level;
    _playerPosition = Vector2.Zero;
    _lives = 3;
    _ammo = 100;
    List<Vector2> list = new List<Vector2>();
    Random rnd = new Random();
    int i = 0;
    while(i < level)
    {
      list.Add(_positions[rnd.Next(0,10)]);
      i++;
    }
    ...
}

然后在您的更新中:

protected void Update(GameTime gameTime)
{
    if(goToNextLevel) //here you put your condition that advances to next level;
    {
        LoadLevel(_currentLevel+1);
    }
}

EDIT2

要从列表中获取您之前没有的其他项目,您可以创建临时列表,然后从中删除项目,而不是仅选择它们。< / p>

我没有测试过这段代码,但它会是这样的:

    List<Vector2> list = new List<Vector2>();
    List<Vector2> tempList = new List<Vector2>(_positions);
    Random rnd = new Random();
    int i = 0;

    while(i < level)
    {
      int index = rnd.Next(tempList.Count); //random goes up to number of items
      list.Add(tempList[index]); //add the randomed item
      tempList.RemoveAt(index); //remove the randomed item from the temporary list.
      i++;
    }
    ...