Tutorial: How to write games part 2

Go to page << 1 2 3 4 5 6 7 8 9 10 11 >>

Arrays and loops

Right! Now we can bring it all together and show exactly why arrays are very powerful for dealing with large amounts of data (like space alien positions :).
The technique involves using a for..next loop, and combining it with the using-a-variable-for-the-array-index we just saw above.
Now that sentence probably sounded like Mongolian Swahili to you, so we'll illustrate with another example:

Let's say we have an array of 10 numbers, and we want to set all the elements to the number 7. (Think of it like delivering a copy of 7 to all the mailboxes in the street).

One way would be to do this:

dim numbers(10)
numbers(1) = 7
numbers(2) = 7
numbers(3) = 7
numbers(4) = 7
numbers(5) = 7
numbers(6) = 7
numbers(7) = 7
numbers(8) = 7
numbers(9) = 7
numbers(10) = 7

That works fine.

Another way would be to do this:

dim numbers(10), i
i = 1
numbers(i) = 7
i = 2
numbers(i) = 7
i = 3
numbers(i) = 7
i = 4
numbers(i) = 7
i = 5
numbers(i) = 7
i = 6
numbers(i) = 7
i = 7
numbers(i) = 7
i = 8
numbers(i) = 7
i = 9
numbers(i) = 7
i = 10
numbers(i) = 7

This works fine too. But it's almost twice as long.
But! Here's the trick!
Notice that we are simply running the same instruction ten times:

numbers(i) = 7

Only we're putting an i = 1 infront of the first one then an i = 2 in front of the next one, then an i = 3, and so on...

If you remember back to the for..next loop, you may realise that this is exactly the same as saying:

for i = 1 to 10
    numbers (i) = 7
next

(Or here's the full program:)

dim numbers(10), i
for i = 1 to 10
    numbers(i) = 7
next

Now this does everything we needed it to do, and it's quite a bit shorter than the first program.

And it has other advantages.
Say you wanted to store an 8 in each array element (mailbox), it would be very easy to change the program to do this.
Or, if you decided you wanted to have 100 array elements (or 1000), it's still very easy to update the program to do this.

Go to page << 1 2 3 4 5 6 7 8 9 10 11 >>