Pixel Art in Python

smiley pixel art

Learning Objectives


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.

List?


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[0]?
Or daysOfTheWeek[3] ?

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:

Multi-dimensional Lists?


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:
e.g.:

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[2][4] #This would return the value of the 5th of the 3rd line!

Let’s apply this to our pixel art project


Challenge #1:


Change this code to create the pixel art of a space invader:
spaceInvader

Challenge #2:


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:
Applepix

Did you like this challenge?

Click on a star to rate it!

Average rating 2.8 / 5. Vote count: 33

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!