简体   繁体   中英

Static vs Dynamic programming

I know that in order to clean up your code you use loops. ie instead of saying

myItem = myArray[0]
my2ndItem = myArray[1]

up to element 100 or so will take 100 lines of your code and will be ugly. It can be slimmed down and look nice / be more efficient using a loop.

Let's say you're creating a game and you have 100 non player controlled enemies that spawn in an EXACT position, each position differing.

How on earth would you spawn every single one without using 100 lines of code? I can understand if, say for example, you wanted them all 25 yards apart, you could just use a loop and increment by 25.

So that said, programming statically in this case is the only way I can see a possible outcome, yet I know programming dynamically is the way to go.

How do people do this? And if you could provide other similar examples that would be great.

var spawnLocs = new SpawnLocation[10];
if (RandomPosition)
{
    for (int i = 0; i < spawnLocs.Length; i++)
    {
        spawnLocs[i] = // auto define using algorithm / logic
    }
}
else
{
    spawnLocs[0] = // manually define spawn location
    spawnLocs[1] = 
    ...
    ...
    spawnLocs[9] = 
}

Spawn new enemy:

void SpawnEnemy(int spawnedCount)
{
    if (EnemyOnMap < 10 && spawnedCount < 100)
    {
        var rd = new Random();
        Enemy e = new Enemy();
        SpawnLocation spawnLoc = new SpawnLocation();
        bool locationOk = false;
        while(!locationOk)
        {
            spawnLoc = spawnLocs[rd.Next(0, spawnLoc.Length)];
            if (!spawnLoc.IsOccupied)
            {
                locationOk = true; 
            }
        }
        e.SpawnLocation = spawnLoc;

        this.Map.AddNewEnemy(e);
    }
}

Just specify the positions as an array or list or whatever data-format suits the purpose, then implement a 3 line loop that reads from that input for each enemy, and finds and sets the corresponding position.

Most languages will have some kind of "shorthand" format for providing the data for an array or list directly, as in C# for instance:

var myList = new List<EnemyPosition>{
                          new EnemyPosition{ x = 0, y = 1 },
                          new EnemyPosition{ x = 45, y = 31 },
                          new EnemyPosition{ x = 12, y = 9 },
                          (...)
                };

You could naturally put the same data in an XML file, or a database, or your grandmothers cupboard for that matter, just as long you have some interface to retrieve it when needed.

Then you can set it up with a loop, just as in your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM