In this blog post we are going to investigate how to use lists and list of lists with Python to create some 2D pixel art graphics.
In Python, a list is used to save collection of values. For instance, to save all the different days of the week we could declare a variable called “daysOfTheWeek” and assign a list as follows:
daysOfTheWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
Based on this what do you think len(daysOfTheWeek) would return?
What’s about daysOfTheWeek?
Or daysOfTheWeek ?
Now look at this program used to display all the days of the week:
When using lists you can use a range of methods to add or remove values in the list. For instance:
Sometimes you need more than on dimension to a list. In Python you can achieve this by creating a list of lists!
For instance for our pixel art project we want to store each pixel on a line within a list:
line1=[1,0,1,0,1,0] line2=[0,1,0,1,0,1] line3=[1,0,1,0,1,0]
We can then store all these lines into a list. Let’s call this list “grid”
grid=[line1, line2, line3]
A quicker way to do this is to do it all in one line as follows:
grid = [[1,0,1,0,1,0],[0,1,0,1,0,1],[1,0,1,0,1,0]]
We can then access any cell within this grid using the following command:
print grid #This would return the value of the 5th of the 3rd line!
Let’s apply this to our pixel art project
Change this code to create the pixel art of a space invader:
Tweak this code to allow colours to be used in your pixel art.
To do so you will first create a new list called colourPalette to store a collection of colours of your choice: e.g.
colourPalette = ["#FF0000#", "#00FF00", "#0000FF", "#000000", "#FFFFFF"]
More changes will be required for you to be able to recreate this pixel art: