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.
The Program in Action
Figure 35-1 shows what the output will look like when you run hexgrid.py.
How It Works
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. View this code at https://nostarch.com/big-book-small-python-projects
4. Tags: tiny, beginner, artistic"""
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.
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='')
17. # Display the bottom half of the hexagon:
18. for x in range(X_REPEAT):
19. print(r'\_/ ', end='')
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:
Create tiled hexagons of a larger size.
Create tiled rectangular bricks instead of hexagons.
For practice, try re-creating this program with larger hexagon grids, such as the following patterns: