""" 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 """ 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 Edu-sig@python.org http://mail.python.org/mailman/listinfo/edu-sig