snapshotting some instructional scaffolding...

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

snapshotting some instructional scaffolding...

Kirby Urner-6
"""
OST Skunkworks:  Freakish Tractor

generator that moves forward to a boundary reading
current character, writing current marker.  Fuel
might run out.  send protocol may be employed to
tank up, redirect, change the marker.  Farm is an
n x m array, presumably smallish, for interactive
console experiments.

  -- Python track, O'Reilly School of Technology

Also:
"""


class Farm:

    def __init__(self, rows=8, columns=8, facing="N", bg="*"):
        self.h = rows
        self.w = columns
        self.facing = facing
        self.bg = bg  # background character
        self.tractors = []  # like Snake or Dog stomach
        self.field = [list(bg*self.w) for x in range(self.h)]  # model
        self.framenumber = 0
        self.trace = []

    def add(self, tractor):
        self.tractors.append(tractor)
        
    def ticktock(self):  # controller
        """tick tock o' the clock
        time marches on!
        Advance each tractor in the direction it's facing,
        ignoring stuck tractors already at a fence (some
        types of Tractor are smarter than others about fences).
        """
        for tractor in self.tractors:
            try:
               next(tractor) # state changer
            except StopIteration:
               pass  # harmless stuck tractor signal
            
        self.framenumber += 1
        return self.framenumber

    def render(self):
        display=""
        for line in self.field:
            display += "".join(line)+"\n"            
        return display  # view

    __str__ = render
    
    def __repr__(self):
        return "Farm({},{}) @ {}".format(self.w, self.h, id(self))


def tractor(thefarm , pos = [0,0], facing="N", marker="O", fuel=10):
    "pos is mutable = current position"
    while True:
        y,x = pos
        
        if fuel > 0:
            
            if facing   == "N":
                if y > 0:
                    y -= 1
                else:
                    raise StopIteration

            elif facing == "S": 
                if y < thefarm.h - 1:
                    y += 1
                else:
                    raise StopIteration
                
            elif facing == "W": 
                if x > 0:
                    x -= 1
                else:
                    raise StopIteration
                
            elif facing == "E": 
                if x < thefarm.w - 1:
                    x += 1
                else:
                    raise StopIteration
                    
            fuel -= 1            
            pos = (y,x)

        else:
            raise StopIteration

        changes = yield (thefarm.field[y][x], pos, fuel)
        thefarm.field[y][x] = marker
            
        if changes:
            facing = changes.get('facing',facing)
            marker = changes.get('marker',marker)
            fuel   = changes.get('fuel',fuel)
            pos    = changes.get('pos',pos)

def _test(n):
    # Agile Programming:  TDD is your friend
    thefarm = Farm(20,20, bg = ".")
    print("Empty field, all is peaceful", thefarm, sep="\n\n")  # frame of film
    t1 = tractor(thefarm, pos=[10,10], marker="O", facing="N")
    t2 = tractor(thefarm, pos=[10,11], marker="X", facing="S")
    thefarm.add(t1)
    thefarm.add(t2)
    print("Showing the tractors in a list: ", thefarm.tractors, "===", sep="\n")
    print("A busy day begins...", thefarm, sep="\n\n")  # frame of film

    for arrow_of_time in range(n):
        thefarm.ticktock()  # much physics involved in terms of what's a realistic throughput
        
    print("After {} ticks of the clock, the tractors have moved...".format(n),
          thefarm, sep="\n\n")  # frame of film

if __name__ == "__main__":
    _test(10)
    

_______________________________________________
Edu-sig mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/edu-sig
Reply | Threaded
Open this post in threaded view
|

Re: snapshotting some instructional scaffolding...

Kirby Urner-6
On Tue, May 3, 2011 at 10:07 PM, Kirby Urner <[hidden email]> wrote:
> """
> OST Skunkworks:  Freakish Tractor
> generator that moves forward to a boundary reading
> current character, writing current marker.  Fuel
> might run out.  send protocol may be employed to
> tank up, redirect, change the marker.  Farm is an
> n x m array, presumably smallish, for interactive
> console experiments.
>   -- Python track, O'Reilly School of Technology
>   http://www.facebook.com/oreillyschool
> Also:
http://mybizmo.blogspot.com/2011/05/lesson-planning.html
> """

As CS teachers know, it's often instructive to start not
with a blank canvas but some discrete unit of working
code that may be set back to zero (back to factory)
at any point.  

One then develops forward by adding features, by various 
deltas, these being the student projects.  

Many curricula focus on game frameworks and branching 
along those.  

Laura and I have done stuff with playing cards in this archive, 
and that remains a focus in many a Combinatorics course.

In the case of the above, we're pushing the boundaries of 
what generators are good for.  Adding a "run out of
fuel" feature has potential is many times we'd like to
iterate over a generator up to a certain point.  itertools
has islice for that.  

Here we inject a finite energy budget into the generator 
upon initialization.  It could terminate for no other reason 
that "running out of gas".  In a next iteration, the Tractor 
becomes a class with a __next__ and an __iter__ method.  

Student projects begin from there, again adding features, 
or simply making use of as is, as means to other ends.

A subclass of Tractor called a CropCircle participates in 
mowing the Mandelbrot Set (or 48 of them do -- I shared 
demo in the faculty lounge).


Kirby


_______________________________________________
Edu-sig mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/edu-sig