from byubit import Bit
@Bit.run_from_empty(5, 3)
def go(bit):
while bit.front_clear():
bit.move()
bit.paint('green')
go_green.py
¶NOTES
Look at the go_green.py
file and learn about how we can define our own functions.
go
, we use bit
to refer to Bitgo_green
we could use cosmo
or jousting_dogs
to refer to whatever was passed to itNOTES
go
and the scope of go_green
bit
points to something on the heap (a bit world)go_green
is called, cosmo
now points to that same thing on the heapbit
in go_green
is different than bit
in go
bit
is good, cosmo
not so much, thing
even worse, color
worse still.Try running the code:
go_green
go_green()
What happens?
NOTES
Didn't invoke the function: missing parentheses
NOTES
Missing positional argument. The name the error gives you is the name of the parameter in the function you tried to call.
How can we figure out where the problem was? For example, was it the first or second call to go_green
?
In coming weeks, we'll talk about other tools that make this easier in complex programs.
For now, you can use bit.snapshot
to put breadcrumbs in the program to figure out where the problem is happening.
When naming a function:
_
(next to the zero key + shift) to break up compound namesgo_green
instead of gogreen
or goGreen
go
instead of Go
or GO
go
is different from Go
!from byubit import Bit
def go_green(bit):
"""
Bit moves in the direction it is already facing
and goes until it is blocked in front
Bit paints each square green,
except for the starting square
"""
while bit.front_clear():
bit.move()
bit.paint('green')
@Bit.run_from_empty(4, 3)
def go(bit):
go_green(bit)
bit.left()
go_green(bit)
"""
allow us to include multiple lines in the same string.The concept of creating and naming new ideas is called abstraction
Bit gives us move
, paint
, etc.
What new verbs would make this job even easier?
NOTES
We've done problems like this before (nested while, etc.), but this is the first time we are using functions to define the pieces. The emphasis of this exercise is on the decomposition and abstraction of the parts, and then putting those parts together.
Several strategies to consider:
Which seems easiest? Why?
NOTES
go
using fill_row_with_blue(bit)
(even though it isn't defined yet)Then define and implement fill_row_with_blue
What are the boundary conditions of fill_row_with_blue
?
NOTES
The event stream pattern works well: the event is running into a jumpable wall (left clear). The event loop runs until Bit cannot jump anymore.
if/else
as opposed to a single "jump hurdle" eventThe mosaic pattern could work: move to the base of the first hurdle, then jump hurdles (which includes advancing to the next) until left is not clear.
Approach this using the event-stream pattern, instead of the mosaic pattern used by Stanford
Note that "up" and "over" are similar, vs "down"
def