如何随机生成一个级别?

时间:2012-04-09 21:44:47

标签: java android platform auto-generate

我目前正在编写10个不同的实例,如下面的代码,但是我想创建更多。我不知道是否有新级别的相同布局,我想知道是否还有为每个块生成一个随机X值(这将是它的水平有多远)。一个10万像素宽的水平就足够了,但如果有人知道一个系统让水平继续下去,我也想知道。这基本上就是我现在定义块的方式(删除了不相关的代码):

block = new Block(R.drawable.block, 400, platformheight);
block2 = new Block(R.drawable.block, 600, platformheight);
block3 = new Block(R.drawable.block, 750, platformheight);

400是X位置,我想在整个关卡中随机放置,platformheight变量定义我不想改变的Y位置。

1 个答案:

答案 0 :(得分:1)

考虑到每个块需要比前一个块更远,

List<Block> blocks = new LinkedList<Block>();
Random rnd = new Random(System.currentTimeMillis());

int x = 400;

while (youNeedMoreBlocks)
{
    int offset = rnd.nextInt(400) + 100; //500 is the maximum offset, this is a constant
    x += offset;                         //ofset will be between 100 and 400

    blocks.add(new Block(R.drawable.block, x, platformheight));

    //if you have enough blocks, set youNeedMoreBlocks to false
}

但这对我来说过于简单。要么我不明白你的问题,要么就是那么简单。

编辑:

对于这样的作业:

block.setY(three_quarters - 10); 
block2.setY(three_quarters - 10); 
block3.setY(three_quarters - 10);

您需要使用以下命令修改循环:

List<Block> blocks = new LinkedList<Block>();
Random rnd = new Random(System.currentTimeMillis());

int x = 400;

while (youNeedMoreBlocks)
{
    int offset = rnd.nextInt(400) + 100; //500 is the maximum offset, this is a constant
    x += offset;                         //ofset will be between 100 and 400

    Block tmp = new Block(R.drawable.block, x, platformheight);
    tmp.setY(three_quarters - 10);                 
            //do with tmp everything you need to apply to each block

    blocks.add(tmp);

    //if you have enough blocks, set youNeedMoreBlocks to false
}

另一个明智的想法是当玩家靠近地图边缘时按需生成块,这样你的加载时间就会更快。