Rainbow is a simple program that shows a colorful rainbow traveling back and forth across the screen. The program makes use of the fact that when new lines of text appear, the existing text scrolls up, causing it to look like it’s moving. This program is good for beginners, and it’s similar to Project 15, “Deep Cave.”
The Program in Action
Figure 58-1 shows what the output will look like when you run rainbow.py.
How It Works
This program continuously prints the same rainbow pattern. What changes is the number of space characters printed to the left of it. Increasing this number moves the rainbow to the right, and decreasing it moves the rainbow to the left. The indent variable keeps track of the number of spaces. The indentIncreasing variable is set to True to note that indent should increase until it reaches 60, at which point it changes to False. The rest of the code decreases the number of spaces. Once it reaches 0, it changes back to True again to repeat the zigzag of the rainbow.
1. """Rainbow, by Al Sweigart [email protected]
2. Shows a simple rainbow animation. Press Ctrl-C to stop.
3. View this code at https://nostarch.com/big-book-small-python-projects
4. Tags: tiny, artistic, bext, beginner, scrolling"""
6. import time, sys
9. import bext
10. except ImportError:
11. print('This program requires the bext module, which you')
12. print('can install by following the instructions at')
16. print('Rainbow, by Al Sweigart [email protected]')
17. print('Press Ctrl-C to stop.')
20. indent = 0 # How many spaces to indent.
21. indentIncreasing = True # Whether the indentation is increasing or not.
24. while True: # Main program loop.
25. print(' ' * indent, end='')
27. print('##', end='')
29. print('##', end='')
31. print('##', end='')
33. print('##', end='')
35. print('##', end='')
39. if indentIncreasing:
40. # Increase the number of spaces:
41. indent = indent + 1
42. if indent == 60: # (!) Change this to 10 or 30.
43. # Change direction:
44. indentIncreasing = False
46. # Decrease the number of spaces:
47. indent = indent - 1
48. if indent == 0:
49. # Change direction:
50. indentIncreasing = True
52. time.sleep(0.02) # Add a slight pause.
53. except KeyboardInterrupt:
54. sys.exit() # When Ctrl-C is pressed, end the program.
Exploring the Program
Try to find the answers to the following questions. Experiment with some modifications to the code and rerun the program to see what effect the changes have.
What happens if you change False on line 44 to True?
What happens if you change the argument to all bext.fg() calls to 'random'?