One of my students asked: "Can Python write Python?"
Mr Kershaw: "Um... yeah, I guess. A Python file is really just a text file, and Python can read and write text files, so there's no reason Python can't generate Python."
For this task you have to recycle the code from 'Dec 13 - Forest' to create a new program 'star.py' which draws a star.
You'll use file read/write and string.replace(old, new)
Copy the multi-line string 'forest_lines' into an empty Python program.
Copy the 'changes' list into your program
Create an empty list called 'star_lines'.
Iterate over the items in the list of 'changes':
grab the indicated line from 'forest_lines'
use line.replace to switch 'old_text' to 'new_text'
append the modified line to star_lines (don't strip its trailing \n).
Write the contents of star_lines to a text file called star.py
Today's puzzle solution is the total length of the created file.
NOTE: Since the Python code for creating a turtle called 't' is different for every implementation of the turtle module (there are several) you'll need to add whatever turtle creating code your setup requires to star.py before running it.
forest_lines = '''def draw_tree(x, y, w, h):
wth = w / 8
hth = h / 8
# t.fillcolor('white')
# draw_rect(x, y, w, h) # bounding box
t.fillcolor('brown')
draw_rect(x + wth * 3, y, wth * 2, hth * 2) # trunk
t.fillcolor('green')
draw_triangle(x + wth * 0, y + hth * 2, wth * 8, hth * 4) # base
draw_triangle(x + wth * 1, y + hth * 4, wth * 6, hth * 3) # middle
draw_triangle(x + wth * 2, y + hth * 6, wth * 4, hth * 2) # top
def draw_rect(x, y, w, h): # x,y is bottom left corner
t.penup()
t.goto(x, y)
t.pendown()
t.begin_fill()
t.goto(x + w, y)
t.goto(x + w, y + h)
t.goto(x, y + h)
t.goto(x, y)
t.end_fill()
def draw_triangle(x, y, w, h): # x,y is bottom left corner
t.penup()
t.goto(x, y)
t.pendown()
t.begin_fill()
t.goto(x + w, y)
t.goto(x + w/2, y+h)
t.goto(x, y)
t.end_fill()
# ADD CODE TO DRAW THE PRESENT RECTANGLES
# red present (100's digit)
# blue present (10's digit)
# yellow present (1's digit)
for i, tree in enumerate(trees):
x,y,w,h = tree
draw_tree(x, y, w, h)
t.hideturtle()
turtle.update()
'''
changes = [ # line_number, old_text, new_text
[13, '_rect', '_star'],
[6, 'brown', 'yellow'],
[42, 'tree', 'triangle'],
[9, ' + wth * 0, y + hth * 2, wth * 8, hth * 4', ', y+h*3/4, w, -h'],
[23, '', ''],
[24, '', ''],
[25, '', ''],
[26, '', ''],
[27, '', ''],
[28, '', ''],
[29, '', ''],
[30, '', ''],
[31, '', ''],
[32, '', ''],
[23, '', ''],
[44, 't.hideturtle()', 'draw_star(-50, 50, 100, 100)'],
]