Chances are that our programs won't have just one thing to draw, but many. We could have a hundred characters moving around, and we don't want to write code for each and every one of them. It would be boring and time-consuming.
Fortunately, we can make "lists" of things. When we have lists, we can write code to deal with everything on the list, regardless of whether the list has one item or a thousand.
Start a new program from scratch. Type it as follows:
many_things = [2, 4, 6]
print(many_things)
for thing in many_things:
print(thing)
The words for
and in
above are special. They create a loop, similar to the ones we have already seen. We use this construct to loop over lists. We could do it with while
too, but it's easier this way.
You can use variables when creating a list:
some_number = 4
many_things = [2, some_number, 6]
print(many_things)
for thing in many_things:
print(thing)
You can even have lists of lists:
some_number = 4
first_list = [2, some_number, 6]
second_list = [first_list, 4, 5]
print(second_list)
for thing in second_list:
print(thing)
Now we are going to use two concepts we just learned:
Let's try again to build a Pygame program from scratch. Start with a blank Python file and write code for each of the following, one at a time:
So far, it's all stuff we have done before. Next let's apply some of what we saw in the chapter about objects:
Actor
.actor1
.x
and the y
coordinates for the actor. Use any numbers you like.actor2
, with the same image, but different coordinates.actor_list
that has both actor1
and actor2
.OK so far? Here comes the interesting part. After the code above, write code for the following:
actor_list
, do the following:
y
coordinate.Come on, get typing. I'll wait.
OK, how did it go? If you are having trouble, remember to address one thing at a time. Don't try to write all at once. Review the previous lessons if you need.