This short program produces a tessellated image of a hexagonal grid, similar to chicken wire. It shows that you don’t need a lot of code to make something interesting. A slightly more complicated variation of this program is Project 65, “Shining Carpet.”
Note that this program uses raw strings, which prefix the opening quote with a lowercase r
so that the backslashes in the string aren’t interpreted as escape characters.
Figure 35-1 shows what the output will look like when you run hexgrid.py.
The power behind programming is that it can make a computer carry out repetitive instructions quickly and without mistakes. This is how a dozen lines of code can create hundreds, thousands, or millions of hexagons on the screen.
In the Command Prompt or Terminal window, you can redirect a program’s output from the screen to a text file. On Windows, run py hexgrid.py > hextiles.txt
to create a text file that contains the hexagons. On Linux and macOS, run python3 hexgrid.py > hextiles.txt
. Without the size of the screen as a limit, you can increase the X_REPEAT
and Y_REPEAT
constants and save the contents to a file. From there, it’s easy to print the file on paper, send it in an email, or post it to social media. This applies to any computer-generated artwork you create.
1. """Hex Grid, by Al Sweigart [email protected]
2. Displays a simple tessellation of a hexagon grid.
3. This code is available at https://nostarch.com/big-book-small-python-programming
4. Tags: tiny, beginner, artistic"""
5.
6. # Set up the constants:
7. # (!) Try changing these values to other numbers:
8. X_REPEAT = 19 # How many times to tessellate horizontally.
9. Y_REPEAT = 12 # How many times to tessellate vertically.
10.
11. for y in range(Y_REPEAT):
12. # Display the top half of the hexagon:
13. for x in range(X_REPEAT):
14. print(r'/ \_', end='')
15. print()
16.
17. # Display the bottom half of the hexagon:
18. for x in range(X_REPEAT):
19. print(r'\_/ ', end='')
20. print()
After entering the source code and running it a few times, try making experimental changes to it. The comments marked with (!)
have suggestions for small changes you can make. On your own, you can also try to figure out how to do the following:
For practice, try re-creating this program with larger hexagon grids, such as the following patterns:
/ \ / \ / \ / \ / \ / \ / \
/ \___/ \___/ \___/ \___/ \___/ \___/ \
\ / \ / \ / \ / \ / \ / \ /
\___/ \___/ \___/ \___/ \___/ \___/ \___/
/ \ / \ / \ / \ / \ / \ / \
/ \___/ \___/ \___/ \___/ \___/ \___/ \
/ \ / \ / \ / \
/ \ / \ / \ / \
/ \_____/ \_____/ \_____/ \_____
\ / \ / \ / \ /
\ / \ / \ / \ /
\_____/ \_____/ \_____/ \_____/
/ \ / \ / \ / \
/ \ / \ / \ / \
/ \_____/ \_____/ \_____/ \_____
This is a base program, so there aren’t many options to customize it. Instead, consider how you could similarly program patterns of other shapes.