Ejemplo n.º 1
0
 def _evHandle(self):
     "Handle events in the pygame event queue"
     for ev in pygame.event.get():
         try:
             if ev.type != pygame.VIDEORESIZE:
                 self.evMgr.dispatch(ev)
             elif ev.size != self.size:
                 self.resize(ev.size)
                 if hasattr(self, "onresize"): self.onresize(ev)
         except: logError()
Ejemplo n.º 2
0
 def run(self):
     r = self.robot
     args = r, id(self)
     if self.log:
         print('{} is running in thread {}.'.format(*args), file=stderr)
     try:
         while r._startup: r.sleep()
         r._startTime = time()
         r.brain()
         if hasattr(r, "shutdown"): r.shutdown()
     except: logError()
     if self.log:
         print('{} is shutting down in thread {}.'.format(*args), file=stderr)
Ejemplo n.º 3
0
 def draw(self, srf=None):
     "Draw all sprites and call their update method"
     if not srf: srf = pygame.display.get_surface()
     for s in self: s.draw(srf)
     if self.run:
         self._toRemove = set()
         self._lock = True
         for s in self:
             if s.status:
                 try: s.update()
                 except: logError()
         self._lock = False
         if len(self._toRemove):
             self.remove(self._toRemove)
         del self._toRemove
Ejemplo n.º 4
0
 def _evHandle(self):
     "Handle events in the pygame event queue"
     for ev in pygame.event.get():
         try:
             if ev.type != pygame.VIDEORESIZE:
                 self.evMgr.dispatch(ev)
             elif ev.size != self.size:
                 setattr(ev, "originalSize", self.size)
                 self._resize_ev = ev
                 s = hasattr(self, "_scrollSize")
                 if s: self.scrollTo()
                 self.resize(ev.size)
                 if s: self.resizeCoords(ev)
         except:
             logError()
Ejemplo n.º 5
0
 def run(self):
     r = self.robot
     args = r, id(self)
     if self.log:
         print('{} is running in thread {}.'.format(*args), file=stderr)
     try:
         while r._startup:
             r.sleep()
         r._startTime = time()
         r.brain()
         if hasattr(r, "shutdown"): r.shutdown()
     except:
         logError()
     if self.log:
         print('{} is shutting down in thread {}.'.format(*args),
               file=stderr)
Ejemplo n.º 6
0
    def ondraw(self):
        "Update robot sprite each frame"

        if not self.active: raise InactiveError()

        # Target wheel speed...
        sk = self.sketch
        v = self.maxSpeed * sk.width
        v1, v2 = self._motors
        v1 *= v
        v2 *= v

        # Angular speed and turning radius...
        w = (v1 - v2) / (2 * self.radius)
        self.spin = w / DEG
        if w:
            R = (v1 + v2) / (2 * w)
            v = w * R
        else:
            v = v1

        # Acceleration...
        v = vec2d(v, self.angle)
        a = delta(v, self.vel)
        if hypot(*a) > 0.05:
            self.acc = delta(a, mag=0.05)
        else:
            self.vel = v
            self.acc = 0, 0

        # Adjust wheel speed...
        p = self.power
        self.costumeTime = 0 if p == 0 else round(36 / (1 + 5 * p))

        # Update position and angle...
        super().ondraw()

        # Update sensors if requested...
        if self._updateSensors:
            try:
                self._checkDown()
                self._checkFront()
                self._drawLEDs()
                self._updateSensors = False
            except:
                logError()
        self._startup = False
Ejemplo n.º 7
0
    def ondraw(self):
        "Update robot sprite each frame"

        if not self.active: raise InactiveError()

        # Target wheel speed...
        sk = self.sketch
        v = self.maxSpeed * sk.width
        v1, v2 = self._motors
        v1 *= v
        v2 *= v

        # Angular speed and turning radius...
        w = (v1 - v2) / (2 * self.radius)
        self.spin = w / DEG
        if w:
            R = (v1 + v2) / (2 * w)
            v = w * R
        else: v = v1

        # Acceleration...
        v = vec2d(v, self.angle)
        a = delta(v, self.vel)
        if hypot(*a) > 0.05:
            self.acc = delta(a, mag=0.05)
        else:
            self.vel = v
            self.acc = 0, 0

        # Adjust wheel speed...
        p = self.power
        self.costumeTime = 0 if p == 0 else round(36 / (1 + 5 * p))

        # Update position and angle...
        super().ondraw()

        # Update sensors if requested...
        if self._updateSensors:
            try:
                self._checkDown()
                self._checkFront()
                self._drawLEDs()
                self._updateSensors = False
            except: logError()
        self._startup = False
Ejemplo n.º 8
0
 def onaction(self, ev):
     try: size = int(self["Size"].data)
     except: size = 384
     try: step = float(self["Step"].data)
     except: step = None
     try:
         lrbt = [float(x.strip()) for x in self["Grid"].data.split(",")]
         if step is None: step = (lrbt[1] - lrbt[0]) / 10
         opt = self["Options"]
         opt = dict(
             resultant = opt[0].selected,
             components = opt[1].selected,
             draggable = opt[2].selected
         )
         self.lastDiagram = self.diagram([PVector(v) for v in self.vectors], size, lrbt, step, bg="white", **opt)
     except:
         self.lastDiagram = None
         logError()
Ejemplo n.º 9
0
 def run(self):
     r = self.robot
     b = self.brain
     if self.log:
         args = "{}.{}".format(b.__module__, b.__name__), r.name, id(self)
         print('{} is controlling "{}" in thread {}.'.format(*args),
               file=stderr)
     try:
         while r._starting:  # Wait for sensors before starting brain
             r.sleep()
         r.startTime = r.sketch.time
         b(r)
     except:
         logError()
     r.shutdown()
     r.startTime = None
     if self.log:
         print('{} is shutting down in "{}".'.format(*args), file=stderr)
Ejemplo n.º 10
0
 def record(self):
     "Begin screen recording"
     self.rec = []
     self.recTime = datetime.now()
     self.frameTimes = []
     try:
         param = self["Param"].data.split(" ")
         param = [abs(int(c)) for c in param if c]
         if len(param) not in (0, 1, 3, 5):
             raise ValueError("Parameters not valid")
         self.frameRate = max(1, param[0]) if param else 15
         if len(param) == 5: r = param[3:] + param[1:3]
         elif len(param) == 3: r = [0, 0] + param[1:3]
         else: r = None
         self.grab = Grabber(r)
     except:  # Abort!
         blink(self, False)
         self.grab = None
         logError()
Ejemplo n.º 11
0
 def plot(self,
          pts,
          marker=None,
          fill=None,
          stroke=(0, 0, 0),
          strokeWeight=1,
          markerSize=(15, 15),
          closed=False):
     "Plot a sequence of points as markers or lines (but not both!)"
     if fill and marker is None:
         if type(pts) not in (list, tuple):
             pts = tuple(pts)
         Image.polygon(pts, closed, fill, stroke, strokeWeight,
                       self.size).blitTo(self)
     else:
         alpha = stroke and getAlpha(stroke) < 255 or fill and getAlpha(
             fill) < 255
         img = Image(self.size) if alpha else self
         if type(marker) is int:
             marker = self.renderMarker(marker, markerSize, fill, stroke,
                                        strokeWeight)
         if closed and marker is None:
             pts = close(pts)
         first = True
         pt0 = None
         for pt in pts:
             try:
                 if pt is not None:
                     pt = round(pt[0]), round(pt[1])
                     if marker:
                         marker.blitTo(img, pt, CENTER)
                     elif first:
                         first = False
                     elif pt0 is not None:
                         line(img.surface, stroke, pt0, pt, strokeWeight)
                 pt0 = pt
             except:
                 logError()
         if alpha: img.blitTo(self)
     return self
Ejemplo n.º 12
0
    def play(self, caption="sc8pr", icon=None, mode=True):
        "Initialize pygame and run the main drawing / event handling loop"

        # Initialize
        pygame.init()
        self._clock = pygame.time.Clock()
        pygame.key.set_repeat(400, 80)
        _pd.set_caption(caption)
        try:
            try: icon = pygame.image.load(icon)
            except: icon = Image.fromBytes(sc8prData("alien")).image 
            _pd.set_icon(icon)
        except: logError()
        w, h = self._size
        self._fixedAspect = w / h
        mode = self._pygameMode(mode)
        self._mode = mode
        self.image = _pd.set_mode(self._size, mode)
        self.key = None
        self.mouse = pygame.event.Event(pygame.USEREVENT,
            code=None, pos=(0,0), description="Sketch startup")

        # Run setup
        try:
            if hasattr(self, "setup"): self.setup()
            else:
                main = sys.modules["__main__"]
                if hasattr(main, "setup"): main.setup(self)
        except: logError()

        # Drawing/event loop
        while not self.quit:
            try:
                self.frameCount += 1
                br = self.dirtyRegions
                flip = br is None
                self.draw()
                if not flip:
                    br += self.dirtyRegions
                    flip = self._largeArea()
                self._clock.tick(self.frameRate)
                if flip: _pd.flip()
                else: _pd.update(br)
                if self.capture is not None: self.capture.capture(self)
                if self.ondraw: self.ondraw()
                self._evHandle()
            except: logError()

        pygame.quit()
        mod = sys.modules.get("sc8pr.text")
        if mod: mod.Font.dumpCache()
        return self
Ejemplo n.º 13
0
    def play(self, caption="sc8pr", icon=None, mode=True):
        "Initialize pygame and run the main drawing / event handling loop"

        # Initialize
        pygame.init()
        self._clock = pygame.time.Clock()
        pygame.key.set_repeat(400, 80)
        _pd.set_caption(caption)
        try:
            try:
                icon = pygame.image.load(icon)
            except:
                icon = Image.fromBytes(sc8prData("alien")).image
            _pd.set_icon(icon)
        except:
            logError()
        w, h = self._size
        self._fixedAspect = w / h
        mode = self._pygameMode(mode)
        self._mode = mode
        self.image = _pd.set_mode(self._size, mode)
        self.key = None
        self.mouse = pygame.event.Event(pygame.USEREVENT,
                                        code=None,
                                        pos=(0, 0),
                                        description="Sketch startup")

        # Run setup
        try:
            if hasattr(self, "_defer_coords"):
                self.setCoords(*self._defer_coords)
                del self._defer_coords
            if hasattr(self, "setup"): self.setup()
            else:
                main = sys.modules["__main__"]
                if hasattr(main, "setup"): main.setup(self)
        except:
            logError()

        # Drawing/event loop
        while not self.quit:
            try:
                self.frameCount += 1
                br = self.dirtyRegions
                flip = br is None
                self.ondrawList = []
                self.draw()
                if not flip:
                    br += self.dirtyRegions
                    flip = self._largeArea()
                self._clock.tick(self.frameRate)
                if flip: _pd.flip()
                else: _pd.update(br)
                if self.capture is not None: self.capture.capture(self)
                for gr in self.ondrawList:
                    try:
                        gr.ondraw()
                    except:
                        logError()
                if self.ondraw: self.ondraw()
                self._evHandle()
            except:
                logError()

        pygame.quit()
        mod = sys.modules.get("sc8pr.text")
        if mod: mod.Font.dumpCache()
        return self