Programmed Graphics - Runpython-IntroProgramming/Course-Syllabus GitHub Wiki
Return to the tutorial repository that you created in the
first graphics tutorial. Add a new
source file called tutorial2.py
and open it in
runpython.org.
Copy the following code into your editor:
from ggame import App, Color, LineStyle, Sprite
from ggame import CircleAsset
red = Color(0xff0000, 1.0)
green = Color(0x00ff00, 1.0)
blue = Color(0x0000ff, 1.0)
black = Color(0x000000, 1.0)
myapp = App()
myapp.run()
This is a "skeleton" for creating a graphics program with ggame. It should look familiar to you.
In the lists and sequences tutorial, you
learned about the Python list comprehension. For example, if you use the Python range
function to make a list of numbers (in the runpython console:
>>> list(range(0, 360, 10))
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140,
150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260, 270,
280, 290, 300, 310, 320, 330, 340, 350]
Then you could generate a new list consisting of those numbers, divided by 5:
>>> [x//5 for x in range(0, 360, 10)]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32,
34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64,
66, 68, 70]
You can also do other things while creating a list comprehension. In our case, we'll use it to generate sprites!
Paste the following example code into your tutorial2.py
program, between the colors and
the myapp = App()
line:
thinline = LineStyle(1, black)
mycircle = CircleAsset(5, thinline, blue)
xcoordinates = range(100, 600, 10)
# Generate a list of sprites that form a line!
sprites = [Sprite(mycircle, (x, x*0.5 + 100)) for x in xcoordinates]
You may notice that in the first list comprehension example above, the range
function
was used inside the list comprehension. In the example immediately above, the range
function
was used to create and initialize the xcoordinates
variable first, then xcoordinates
was used inside the list comprehension. Both styles work the same way. There are many cases where
there is more than one way to accomplish something in Python. You are free to choose the method
that makes the most sense to you, or which leads to the most readable code.
- Try changing the way the
xcoordinates
variable is created. - Can you change the program to generate both a blue and red series of circles along different lines?
If you understand this program, you may be ready to attempt the Sine and Cosine challenge.