Exemple #1
0
    def UpdateDisplay(self, data):
        val = iter(data)
        for x, y, item in zip(val, val, val):
            if (x == -1 and y == 0):
                if (self._started == True):
                    print(f"Score will be set to {item}")
                    if (item > 0):
                        self._scores.append(item)
                pygame.display.set_caption('Score: ' + str(item))
            else:
                if (self._started == True):
                    if (item == 0 and (x, y) in self._positions.keys()
                            and self._positions[(x, y)] == 2):
                        print(f"Block at {x},{y} erased.")
                self._positions[(x, y)] = item
                if (item == 3):
                    self._paddle = (x, y)
                if (item == 4):
                    currentBall = self._ball
                    self._ball = (x, y)
                    if (self._started):
                        direction = 1 if self._ball[0] - currentBall[
                            0] > 0 else 0 if self._ball[0] - currentBall[
                                0] == 0 else -1
                        relationToPaddle = 1 if self._paddle[0] - self._ball[
                            0] > 0 else 0 if self._paddle[0] - self._ball[
                                0] == 0 else -1
                        if (direction != relationToPaddle
                                and relationToPaddle != 0):
                            self._joyStick = direction
                        else:
                            self._joyStick = 0
                self.SetBlockToScreen(x, y, item)

        surfarray.blit_array(self._surface, self._pixels)
Exemple #2
0
def make_surface (array):
    """pygame.numpyarray.make_surface (array): return Surface

    copy an array to a new surface

    Create a new Surface that best resembles the data and format on the
    array. The array can be 2D or 3D with any sized integer values.
    """
    # Taken from from Alex Holkner's pygame-ctypes package. Thanks a
    # lot.
    bpp = 0
    r = g = b = 0
    shape = array.shape
    if len (shape) == 2:
        # 2D array
        bpp = 8
        r = 0xFF >> 6 << 5
        g = 0xFF >> 5 << 2
        b = 0xFF >> 6
    elif len (shape) == 3 and shape[2] == 3:
        bpp = 32
        r = 0xff << 16
        g = 0xff << 8
        b = 0xff
    else:
        raise ValueError("must be a valid 2d or 3d array")

    surface = pygame.Surface ((shape[0], shape[1]), 0, bpp, (r, g, b, 0))
    blit_array (surface, array)
    return surface
    def draw(self, surface, model):

        # draw rectangles to display canvas
        for x, y in np.ndindex(model.world.shape):
            rect_x = x * self.scale
            rect_xa = rect_x - (self.scale - 1)
            rect_y = y * self.scale
            rect_ya = rect_y - (self.scale - 1)
            rect_shape = [rect_xa, rect_ya, rect_x, rect_y]
            if model.world[x, y] > 0:
                pygame.draw.rect(surface, (21, 128, 0), rect_shape)
            else:
                pygame.draw.rect(surface, (0, 0, 0), rect_shape)

        # apply post processing to display canvas
        rgbarray = surfarray.array3d(surface)
        factor = np.array((8,), np.int32)
        soften = np.array(rgbarray, np.int32)
        soften[1:, :] += rgbarray[:-1, :] * factor
        soften[:-1, :] += rgbarray[1:, :] * factor
        soften[:, 1:] += rgbarray[:, :-1] * factor
        soften[:, :-1] += rgbarray[:, 1:] * factor
        soften //= 16
        screen = pygame.display.set_mode(soften.
                                         shape[:2], 0, 32)
        surfarray.blit_array(screen, soften)
Exemple #4
0
def show_stimulus(stimulus, name='toto', resizable=True, exit=True, wait=0.0):
    """
    stimulus is a 4 dimension numpy array: [height, weight, frame, RGB]
    """
    from time import sleep

    h = stimulus.shape[0]
    w = stimulus.shape[1]
    f = stimulus.shape[2]
    surfarray.use_arraytype('numpy')
    pygame.init()
    pygame.display.set_caption(name)
    if (resizable == True): screen = pygame.display.set_mode((h, w), RESIZABLE)
    else: screen = pygame.display.set_mode((h, w))
    surface = pygame.Surface((h, w))
    looping = True
    i = 0
    while looping:
        if (i == f): i = 0
        surfarray.blit_array(surface, stimulus[:, :, i, :])
        screen.blit(surface, (0, 0))
        pygame.display.flip()
        event = pygame.event.poll()
        looping = quit(event, exit=exit)
        i += 1
        sleep(wait)
Exemple #5
0
    def render(self, text, antialias, forecolor, backcolor=(0, 0, 0, 255)):
        size = self.size(text)
        img = NSImage.alloc().initWithSize_(size)
        img.lockFocus()

        NSString.drawAtPoint_withAttributes_(
            text, (0.0, 0.0), {
                NSFontAttributeName:
                self._font,
                NSUnderlineStyleAttributeName:
                self._isUnderline and 1.0 or None,
                NSBackgroundColorAttributeName:
                backcolor and _getColor(backcolor) or None,
                NSForegroundColorAttributeName:
                _getColor(forecolor),
            })

        rep = NSBitmapImageRep.alloc().initWithFocusedViewRect_(
            ((0.0, 0.0), size))
        img.unlockFocus()
        if rep.samplesPerPixel() == 4:
            s = Surface(size, SRCALPHA | SWSURFACE, 32,
                        [-1 << 24, 0xff << 16, 0xff << 8, 0xff])

            a = Numeric.reshape(
                Numeric.fromstring(rep.bitmapData(), typecode=Numeric.Int32),
                (size[1], size[0]))
            blit_array(s, Numeric.swapaxes(a, 0, 1))
            return s.convert_alpha()
def main():
    import pygame
    from pygame import surfarray,transform
    screen_size = (DIM[0]*4,DIM[1]*4)
    screen = pygame.display.set_mode(screen_size)
    pygame.display.init()
    pygame.init()
    board = create_board(*DIM)
    board = initialize_board(
        board,
        [[5,5],[5,6]],
    )
    rate = .25
    next = time.time() -1
    small = pygame.Surface( DIM )
    blitter = pygame.Surface( screen_size )
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                raise SystemExit(0)
        if time.time() > next:
            next = time.time() + rate 
            board = cycle(board)
            surfarray.blit_array(small,board)
            transform.scale( small, screen_size, blitter )
        screen.blit( blitter, (0,0) )
        #surfarray.blit_array(screen,board)
        pygame.display.flip()
Exemple #7
0
def main(x, y, scale):
    global s
    pygame.init()
    win = pygame.display.set_mode((1000, 1000))
    t = time.time()
    pic = mandelbrot(0, 0, 0.5, 1000)
    print(time.time() - t)
    surfarray.blit_array(win, pic)
    pygame.display.update()
    while True:
        for ev in pygame.event.get():
            if ev.type == pygame.MOUSEBUTTONUP:
                maxiter = (s // 10 + 1) * 1000
                x0, y0 = ev.pos
                s += 1
                x += (x0 - 100) / scale
                y += (y0 - 250) / scale
                scale *= 2
                t = time.time()
                pic = mandelbrot(x, y, scale, maxiter)
                print(f'{time.time() - t}\n{x, y, scale, maxiter}\n')
                surfarray.blit_array(win, pic)
                pygame.display.update()
            if ev.type == pygame.KEYUP and ev.key == pygame.K_SPACE:
                draw(x, y, scale, maxiter)
Exemple #8
0
    def UpdateDisplay(self,result):
        if (self._direction == 1):
            y = self._robot[0] - Game.blockSize
            x = self._robot[1]
        elif (self._direction == 2):
            y = self._robot[0] + Game.blockSize
            x = self._robot[1]
        elif (self._direction == 3):
            y = self._robot[0]
            x = self._robot[1] - Game.blockSize
        elif (self._direction == 4):
            y = self._robot[0]
            x = self._robot[1] + Game.blockSize


        if (result == -1):
            self.SetBlockToScreen(self._robot,BT.Paddle)
        if (result == 0):
            self.SetBlockToScreen((y,x),BT.Wall)
        if (result == 1):
            if (self._origin == self._robot):
                blockType = BT.Paddle
            else:
                blockType = BT.Empty
            self.SetBlockToScreen(self._robot,blockType)
            blockType = BT.Ball
            self.SetBlockToScreen((y,x),blockType)
            self._robot = (y,x)
        if (result == 2):
            self.SetBlockToScreen(self._robot,BT.Empty)
            self.SetBlockToScreen((y,x),BT.Block)
            self._robot = (y,x)

        surfarray.blit_array(self._surface, self._pixels)
def graphics(state):
    state = np.transpose(state)
    largeState = np.kron(state * 255, np.ones((SCALE, SCALE)))
    screen = pygame.display.set_mode(largeState.shape[:2], 0, 8)
    surfarray.blit_array(screen, largeState)
    pygame.display.update()
    return
Exemple #10
0
def set_grid(surface, surfSize=(1, 1), interval=50):
    ss = (surfSize[0], surfSize[1], 3)
    striped = N.zeros(ss)
    striped[:] = (255, 255, 255)
    striped[::interval, :] = (220, 220, 220)
    striped[:, ::interval] = (220, 220, 220)
    surfarray.blit_array(surface, striped)
Exemple #11
0
    def render(self):
        """
		Renders based on world data
		"""

        #Build pixel array
        pixelarray = pygame.PixelArray(self.application.surface)

        #Copy tiledata to pixel array
        for x in range(self.application.screensize[0]):
            for y in range(self.application.screensize[1]):

                id = self.gamescene.world.tiledata[x][y]

                pixelarray[x][y] = self.gamescene.world.tiletypes[id].color(
                    x, y, self.gamescene.world.tiledata)

        surfarray.blit_array(self.application.surface, pixelarray)

        #Be sure to delete pixelarray, unlocking the surface
        del pixelarray

        #Apply scaled surface
        self.application.apply_surface()

        #Blit info text AFTER scale
        self.application.screen.blit(self.infosurf_keys, (20, 0))
        self.application.screen.blit(self.infosurf_shiftkeys, (20, 25))

        #Finalize render
        self.application.complete_render()
Exemple #12
0
def surfdemo_show(array_img, name):
    "displays a surface, waits for user to continue"
    screen = pg.display.set_mode(array_img.shape[:2], 0, 32)
    surfarray.blit_array(screen, array_img)
    pg.display.flip()
    pg.display.set_caption(name)
    while 1:
        e = pg.event.wait()
        if e.type == pg.MOUSEBUTTONDOWN:
            break
        elif e.type == pg.KEYDOWN and e.key == pg.K_s:
            # pg.image.save(screen, name+'.bmp')
            # s = pg.Surface(screen.get_size(), 0, 32)
            # s = s.convert_alpha()
            # s.fill((0,0,0,255))
            # s.blit(screen, (0,0))
            # s.fill((222,0,0,50), (0,0,40,40))
            # pg.image.save_extended(s, name+'.png')
            # pg.image.save(s, name+'.png')
            # pg.image.save(screen, name+'_screen.png')
            # pg.image.save(s, name+'.tga')
            pg.image.save(screen, name + ".png")
        elif e.type == pg.QUIT:
            pg.quit()
            raise SystemExit()
Exemple #13
0
 def propagateselection(self):
     for i in range(len(self.images)):
         blit_array(
             self._display_surf.subsurface(self.getXY(i) + self.img_size),
             self.images[self.selected[-1]])
         #self._display_surf.blit(s0,(0,0))
     pygame.display.flip()
Exemple #14
0
    def refresh(self):
        if "enable_ui_recording" in self.env.config:
            screen_to_dump = cv2.cvtColor(self.screen_arr.transpose(1, 0, 2), cv2.COLOR_BGR2RGB)
            cv2.imshow("Recording", screen_to_dump)
            cmd=cv2.waitKey(5)%256
            if cmd == ord('r'):
                self.start_record()
            if cmd == ord('q'):
                self.end_record()

            if self.is_recording:
                #self.curr_output.write(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
                #from IPython import embed; embed()
                cv2.imwrite(os.path.join(self.output_dir, "frame%06d.png" % self.record_nframe), screen_to_dump)
                self.record_nframe += 1
                #self.curr_output.write(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
        
        #with Profiler("Refreshing"):
        if self.use_pygame:
            pygame.display.flip()
            surfarray.blit_array(self.screen, self.screen_arr)
        #print(self.screen_arr.shape)
        screen_to_dump = cv2.cvtColor(self.screen_arr.transpose(1,0,2), cv2.COLOR_BGR2RGB)
        screen = pickle.dumps(cv2.imencode('.jpg', screen_to_dump), protocol=0)

        self.socket.send(b"ui" + screen)
Exemple #15
0
def main():
    import pygame
    from pygame import surfarray, transform
    screen_size = (DIM[0] * 4, DIM[1] * 4)
    screen = pygame.display.set_mode(screen_size)
    pygame.display.init()
    pygame.init()
    board = create_board(*DIM)
    board = initialize_board(
        board,
        [[5, 5], [5, 6]],
    )
    rate = .25
    next = time.time() - 1
    small = pygame.Surface(DIM)
    blitter = pygame.Surface(screen_size)
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                raise SystemExit(0)
        if time.time() > next:
            next = time.time() + rate
            board = cycle(board)
            surfarray.blit_array(small, board)
            transform.scale(small, screen_size, blitter)
        screen.blit(blitter, (0, 0))
        #surfarray.blit_array(screen,board)
        pygame.display.flip()
Exemple #16
0
def main(size, zoom, init_p):
    """Entry point."""
    # pylint:disable=no-member
    pg.init()

    random = np.random.rand(size, size)
    off = np.zeros((size, size), dtype=int)
    active = np.zeros((size, size), dtype=int)
    cooldown = np.zeros((size, size), dtype=int)
    active[random < init_p] = 1

    off[active == 0] = 1

    colors = np.zeros((size, size, 3), dtype=float)

    screen = pg.display.set_mode((size * zoom, size * zoom), 0, 24)
    # pylint:disable=too-many-function-args
    surface = pg.Surface((size, size))
    while True:
        loop_start_ms = pg.time.get_ticks()
        evt = pg.event.poll()
        if evt.type == lcls.QUIT:
            pg.image.save(screen, "out.png")
            raise SystemExit()
        _update(off, active, cooldown, colors)

        sf.blit_array(surface, colors)
        pg.transform.scale(surface, (size * zoom, size * zoom), screen)
        loop_end_ms = pg.time.get_ticks()
        if loop_end_ms > loop_start_ms + DELAY_MS:
            print("WARNING: too slow for desired framerate")
        else:
            pg.time.delay(loop_start_ms + DELAY_MS - loop_end_ms)
        pg.display.flip()
Exemple #17
0
def main():
    args = parse_args()
    
    env = make_atari(args.env)
    env = wrap_deepmind(env)
    
    # setup the model to process actions for one environment and one step at a time
    model = acktr_disc.Model(policies.CnnPolicy, env.observation_space, env.action_space, 1, 1)
    # load the trainable parameters from our trained file
    model.load(args.model_path)
    # keep track of the last 4 frames of observations
    env_width = env.observation_space.shape[0]
    env_height = env.observation_space.shape[1]
    obs_history = np.zeros((1, env_width, env_height, 4), dtype=np.uint8)

    # if we're supposed to show how the model sees the game
    if args.show_observation:
        obs = env.reset()
        import pygame
        from pygame import surfarray
        # the default size is too small, scale it up
        scale_factor = args.scale_factor
        screen = pygame.display.set_mode((env_width*scale_factor, env_height*scale_factor), 0, 8)
        # setup a gray palette
        pygame.display.set_palette(tuple([(i, i, i) for i in range(256)]))
        
    # if we're supposed to record video
    video_path = args.video_path
    if video_path is not None:
        video_recorder = VideoRecorder(
        env, base_path=video_path, enabled=video_path is not None)
        
    while True:
        obs, done = env.reset(), False
        episode_rew = 0
        while not done:
            env.render()
            if args.show_observation:
                # use the Kronecker product to scale the array up for display, and also transpose x/y axes because pygame
                # displays as column/row instead of gym's row/column
                transposed = obs_history[0,:,:,-1].transpose((1,0))
                scaled_array = np.uint8(np.kron(transposed, np.ones((scale_factor, scale_factor))))
                surfarray.blit_array(screen, scaled_array)
                pygame.display.flip()
            if video_path is not None:
                video_recorder.capture_frame()
            # add the current observation onto our history list
            obs_history = np.roll(obs_history, shift=-1, axis=3)
            obs_history[:, :, :, -1] = obs[None][:, :, :, 0]
            # get the suggested action for the current observation history
            action, v, _ = model.step(obs_history)
            
            obs, rew, done, info = env.step(action)
            episode_rew += rew
        print("Episode reward", episode_rew)
        # if we're taking video, stop it now and clear video path so no more frames are added if we're out of lives or there are no lives in this game
        if video_path is not None and ('ale.lives' not in info or info['ale.lives'] == 0):
            video_path = None
            video_recorder.close()
def surfdemo_show(array_img, zbuffer, name):
    "displays a surface, waits for user to continue"
    screen = pygame.display.set_mode(array_img.shape[:2], 0, 32)
    surfarray.blit_array(screen, array_img)
    array_img[:, :] = 0
    pygame.display.flip()
    pygame.display.set_caption(name)
    zbuffer[:, :] = ninf
Exemple #19
0
def surfdemo_show(screen, array_img, zbuffer, name, index=None):
    "displays a surface, waits for user to continue"
    surfarray.blit_array(screen, array_img)
    if index is not None:
        pygame.image.save(screen, str(index) + ".png")
    array_img[:, :] = 0
    pygame.display.flip()
    pygame.display.set_caption(name)
    zbuffer[:, :] = ninf
Exemple #20
0
    def draw(self, surface):
        blit_array(self.surface, create_background(self.scent_map, self.scale))

        for resource in self.resources:
            resource.draw(self.surface)

        for hive in self.hives:
            hive.draw(self.surface)

        surface.blit(self.surface, self.scaled_rect)
Exemple #21
0
def main():
    clock = pg.time.Clock()

    pg.init()
    screen = pg.display.set_mode(WINSIZE)

    pg.display.set_caption("GOL")

    array1 = np.full((SIZE, SIZE), 0)
    array2 = np.full((SIZE, SIZE), 0)
    arrays = [array1, array2]

    canvas = pg.Surface(CANSIZE)

    done = 0
    n = 1
    x = 0
    init(array1)
    init(array2)

    surfarray.blit_array(canvas, array1)
    pg.transform.scale(canvas, screen.get_size(), screen)

    pg.display.update()
    cells = first_update(array1, array2, SIZE)
    pg.display.update()
    now = datetime.datetime.now()
    while not done:

        x += 1
        cells = update(arrays[n], arrays[(-n) + 1], SIZE, cells)
        #array3 = colorer(arrays[(-n)+1])
        surfarray.blit_array(canvas, arrays[(-n) + 1])
        n = (-n) + 1
        pg.transform.scale(canvas, screen.get_size(), screen)
        pg.display.update()
        for e in pg.event.get():
            if e.type == pg.QUIT or (e.type == pg.KEYUP
                                     and e.key == pg.K_ESCAPE):
                done = 1
                break
            if e.type == pg.MOUSEBUTTONDOWN:
                pos = pg.mouse.get_pos()
                print(pos)
                f = WINSIZE[0] / SIZE
                pos = (int(pos[0] / f), int(pos[1] / f))
                addcell(cells, pos[0], pos[1], SIZE)
                arrays[n][pos[0]][pos[1]] = ALIVE

        if x % 100 == 0:
            then = now
            now = datetime.datetime.now()
            print(now - then)
        clock.tick()
    pg.quit()
Exemple #22
0
	def genChunk(self, x, y):
		pixels = numpy.zeros((self.CHUNK_SIZE, self.CHUNK_SIZE), numpy.int32)
		for i in range(self.PIXELS):
			for j in range(self.PIXELS):
				colorInt = self.getPixel(x, y, i, j)
				for xOffset in range(self.PIXEL_SIZE):
					for yOffset in range(self.PIXEL_SIZE):
						pixels[i * self.PIXEL_SIZE + xOffset, j * self.PIXEL_SIZE + yOffset] = int(colorInt)
		surface = pygame.Surface((128, 128))
		surfarray.blit_array(surface, pixels)
		return surface
Exemple #23
0
def makecircle(radius, color):
    surf = pg.Surface((radius*2, radius*2), 0, 8)
    surf.set_palette(((0, 0, 0), color))

    axis = abs(numpy.arange(radius*2)-(radius-0.5)).astype(int)**2
    mask = numpy.sqrt(axis[numpy.newaxis,:] + axis[:,numpy.newaxis])
    mask = numpy.less(mask, radius).astype(int)**2

    surfarray.blit_array(surf, mask)
    surf.set_colorkey(0, RLEACCEL)

    return surf.convert()
Exemple #24
0
def makecircle(radius, color):
    surf = pygame.Surface((radius*2, radius*2), 0, 8)
    surf.set_palette(((0, 0, 0), color))

    axis = abs(numpy.arange(radius*2)-(radius-0.5)).astype(int)**2
    mask = numpy.sqrt(axis[numpy.newaxis,:] + axis[:,numpy.newaxis])
    mask = numpy.less(mask, radius).astype(int)**2

    surfarray.blit_array(surf, mask)
    surf.set_colorkey(0, RLEACCEL)

    return surf.convert()
Exemple #25
0
def winblit(img, win, info):
    from pygame import transform
    from pygame import surfarray

    surface = pygame.Surface(img.shape[:2])
    surfarray.blit_array(surface, img)
    surface = transform.scale(surface, (info[N_X], info[N_Y]))
    x = (info[screen_width] - info[N_X]) / 2
    y = (info[screen_height] - info[N_Y]) / 2
    win.screen.blit(surface, (x, y))
    pygame.display.flip()
    time.sleep(info[duration_image])
Exemple #26
0
def main(size, border, zoom):
    """Entry point."""
    # pylint:disable=no-member
    pg.init()

    font = ft.Font("iosevka-regular.ttf")

    field = np.zeros((size, size), dtype=int)
    colors = np.zeros((size, size, 3), dtype=int)
    screen = pg.display.set_mode((size * zoom, size * zoom), 0, 24)
    # pylint:disable=too-many-function-args
    surface = pg.Surface((size, size))
    idx = 1
    frame = 1
    grains = 0
    while True:
        evt = pg.event.poll()
        # pylint:disable=no-member
        if evt.type == lcls.KEYDOWN and evt.key == lcls.K_SPACE:
            pg.image.save(surface,
                          os.path.join("out", "out-{:09d}.png").format(frame))
        # pylint:disable=no-member
        if evt.type == lcls.QUIT:
            raise SystemExit()
        if _update(field, border, colors):
            grains += 1
        idx += 1
        if idx % 1000 == 0:
            size2 = size * size
            filled = np.count_nonzero(colors) * 100 / size2
            red = np.count_nonzero(colors[:, :, 0]) * 100 / size2
            green = np.count_nonzero(colors[:, :, 1]) * 100 / size2
            blue = np.count_nonzero(colors[:, :, 2]) * 100 / size2
            print("{} ({}): {:.2f}% -> "
                  "{:.2f}% / {:.2f}% / {:.2f}%".format(idx, grains, filled,
                                                       red, blue, green))
        if _interesting(grains):
            sf.blit_array(surface, colors)
            if SHOW_NUMBER:
                font.render_to(surface, (10, 10),
                               "{}".format(grains),
                               fgcolor=(0, 255, 255),
                               size=12)
            if SAVE:
                pg.image.save(
                    surface,
                    os.path.join("out", "out-{:09d}.png").format(frame))
            frame += 1
            pg.transform.smoothscale(surface, (size * zoom, size * zoom),
                                     screen)
            # pg.transform.scale(surface, (size * zoom, size * zoom), screen)
            pg.display.flip()
Exemple #27
0
    def drawPlayerPieces(self):
        self.piecebox.fill((255, 255, 255))
        pieceImg = image.load(join("sprites", "piecesmall.jpg"))

        pieceArrays = {
            "r": surfarray.array3d(pieceImg),
            "g": surfarray.array3d(pieceImg),
            "b": surfarray.array3d(pieceImg),
            "y": surfarray.array3d(pieceImg)
        }
        pieceArrays["r"][:, :, 1:] = 0
        pieceArrays["g"][:, :, [0, 2]] = 0
        pieceArrays["b"][:, :, :2] = 0
        pieceArrays["y"][:, :, 2] = 0

        bpos = n.array((0, 0))
        for player in o.players.players:
            surfarray.blit_array(pieceImg, pieceArrays[player.c])
            for size in player.pieces.keys():
                for p in player.pieces[size]:
                    if len(p.m) < len(p.m[0]):
                        isTaller = True
                        h = len(p.m)
                        psize = (9 * len(p.m[0]), 9 * len(p.m))
                    else:
                        isTaller = False
                        h = len(p.m[0])
                        psize = (9 * len(p.m), 9 * len(p.m[0]))
                    pieceImg.set_alpha(100)
                    if player is o.players.cur:
                        pieceRect = self.piecebox.subsurface(Rect(bpos, psize))
                        o.players.pieces.append((pieceRect, size, p))
                        if p is player.curPiece:
                            pieceImg.set_alpha(255)
                    for r in range(len(p.m)):
                        for c in range(len(p.m[0])):
                            if isTaller:
                                x = c
                                y = r
                            else:
                                x = r
                                y = c
                            if p.m[r][c] == 1:
                                pos = n.array((x * 9, y * 9))
                                if player.c == o.players.cur.c:
                                    pieceRect.blit(pieceImg, pos)
                                else:
                                    self.piecebox.blit(pieceImg, bpos + pos)
                    bpos[1] += h * 9 + 1
            bpos[0] += 50
            bpos[1] = 0
Exemple #28
0
    def on_render(self):
        self._display_surf.fill(self.cfg.app.surface.screen_color)

        # Render the image and all information on this frame
        surfarray.blit_array(self._display_surf, self.image_sensor.last_image)

        self.show_text(
            'FPS image: %.1f ' % self.image_sensor.average_framerate, 0, 0)
        self.show_text(
            ' distance: %.1f ' %
            self.forward_distance_sensor.average_framerate, 140, 0)

        self.show_text('forward: {:06.2f} cm '.format(
            self.forward_distance_sensor.last_value),
                       0,
                       15,
                       background_color=self.cfg.text.data.background_color)
        self.show_text('backward: {:06.2f} cm'.format(
            self.backward_distance_sensor.last_value),
                       170,
                       15,
                       background_color=self.cfg.text.data.background_color)

        # Show all control values
        control_y = self._display_surf.get_height() - 15
        # Need to abbreviate on smaller displays
        #        def show_signal((index, (name, channel))):
        #            self.show_text('{}: {}'.format(name, channel.signal), index*110, control_y)
        #        map(show_signal, enumerate(reversed(sorted(self.controller.channels.items()))))
        self.show_text(
            '{}: {} '.format("trtl",
                             self.controller.channels['throttle'].signal), 0,
            control_y)
        self.show_text(
            '{}: {} '.format("steer",
                             self.controller.channels['steering'].signal), 100,
            control_y)
        self.show_text(
            '{}: {} '.format("shift",
                             self.controller.channels['shift'].signal), 210,
            control_y)
        self.show_text(
            '{}: {}'.format("leg", self.controller.channels['leg'].signal),
            320, control_y)

        # Update the surface after we have applied all drawing operations
        pygame.display.flip()
        # Fixed fps rate for the application
        self.clock.tick(self.cfg.app.clock_rate)
Exemple #29
0
def main():
    pygame.init()
    size = (640, 480)
    area = (-2.0, 0.5, -1.25, 1.25)
    matrix = np.zeros(size + (3, ))
    matrix = mandelbrot_set(area[0], area[1], area[2], area[3], size[0],
                            size[1], 10000, matrix)[2]
    yuzey = pygame.display.set_mode(size, pygame.FULLSCREEN)
    while True:
        ev = pygame.event.poll()
        if ev.type == pygame.QUIT or ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE:
            break
        surfarray.blit_array(yuzey, matrix)
        pygame.display.flip()
    pygame.quit()
Exemple #30
0
def pygame_loop(conway: Conway,
                screen_size: tuple = (1600, 800),
                fps: int = 30):
    """
    Function to display the evolution of Conway's Game of Life or any other
    simulation with a 2D output.

    Parameters
    ----------
    conway : Conway
        Any class providing the attributes
         * shape
         * is_empty
        and the methods
         * show_field() -> numpy.ndarray
         * update_field()
         * reset_field()
    screen_size : Tuple(int, int), optional
        Size of the Screen to be displayed. The default is (1600, 800).
    fps : int, optional
        Frames per second goal to achieve. The default is 30.
    """
    pygame.init()
    screen = pygame.display.set_mode(screen_size, HWSURFACE | DOUBLEBUF)
    running = True
    clock = pygame.time.Clock()
    while running:
        pygame.display.update()
        conway.update_field()  #
        arr = conway.show_field(
        )  #Bild im Format: BreitexHöhexFarbe -> Farbe RGB
        surf = pygame.Surface(conway.shape)
        surfarray.blit_array(surf, arr)
        surf = pygame.transform.scale(surf, screen_size)
        screen.blit(surf, (0, 0))
        clock.tick(fps)
        pygame.display.set_caption(
            f"Conway's Game of Life | fps: {clock.get_fps():.3}")
        for event in pygame.event.get():
            if event.type == KEYDOWN:
                if event.key == K_BACKSPACE:
                    running = False
            elif event.type == QUIT:
                running = False
                pygame.quit()
        if conway.is_empty:
            sleep(0.05)
            conway.reset_field()
Exemple #31
0
 def get_image(self,surface=None,*argv,**argd):
     """
     Since we are using opencv there are some differences here.
     This function will return a cvmat by default (the quickest route from camera to your code)
     Or if pygame was specified a 3dpixel array
       - this can be blitted directly to a pygame surface
       - or can be converted to a surface array and returned to your pygame code.
     
     """
     if self.imageType == "pygame":
         try:
             surfarray.blit_array(surface,conversionUtils.cv2SurfArray(hg.cvQueryFrame(self.capture)))
             return surface
         except:
             return surfarray.make_surface(conversionUtils.cv2SurfArray(hg.cvQueryFrame(self.capture))).convert()
     return hg.cvQueryFrame(self.capture)
Exemple #32
0
    def loop(self):
        cornerless_x = slice(0, self.width - 1)
        cornerless_y = slice(0, self.height - 1)
        while self._continue_flag is True:
            if (self.buffer_2.min() > -0.2 and self.buffer_2.max() < 0.2):
                self.buffer_1.fill(0)
                self.buffer_2.fill(0)
            self.sums[cornerless_x, cornerless_y] = self.buffer_1[self.rows, self.cols] \
                                                    .sum(axis=1, keepdims=True) \
                                                    .reshape((self.width - 1,
                                                              self.height - 1))
            self.buffer_2 = (self.sums / 2 - self.buffer_2) * self.dampening
            surfarray.blit_array(self.canvas, self.buffer_2)
            self.swap_buffers()
            pygame.display.flip()
            # print(self.clock.get_fps())
            self.clock.tick(30)
            for event in pygame.event.get():
                # Quit the program if the use close the windows
                if (event.type == pygame.QUIT):
                    pygame.quit()
                    self._continue_flag = False
                # Or press ESCAPE
                if (event.type == pygame.KEYDOWN):
                    if (event.key == pygame.K_ESCAPE):
                        pygame.quit()
                        self._continue_flag = False

                if (event.type == pygame.MOUSEBUTTONDOWN):
                    self.mouse_down = True
                    mouse_x = event.pos[0]
                    mouse_y = event.pos[1]
                    x_slice = slice(mouse_x - 4, mouse_x + 4)
                    y_slice = slice(mouse_y - 4, mouse_y + 4)
                    self.buffer_1[mouse_x, mouse_y] = 500
                    self.buffer_2[x_slice, y_slice] = 500

                elif (event.type == pygame.MOUSEMOTION
                      and self.mouse_down is True):
                    mouse_x = event.pos[0]
                    mouse_y = event.pos[1]
                    x_slice = slice(mouse_x - 4, mouse_x + 4)
                    y_slice = slice(mouse_y - 4, mouse_y + 4)
                    self.buffer_2[x_slice, y_slice] = 500

                elif (event.type == pygame.MOUSEBUTTONUP):
                    self.mouse_down = False
Exemple #33
0
def main():
    DIMENSION = 600

    WIDTH = HEIGHT = DIMENSION

    pygame.init()
    screen = pygame.display.set_mode([WIDTH, HEIGHT])
    clock = pygame.time.Clock()
    font = pygame.font.Font(None, 30)

    fluid = Fluid(WIDTH, 0.05, 0.0000001, 0.0000001)

    prev_x, prev_y = pygame.mouse.get_pos()
    running = True
    while running:
        # Did the user click the window close button?
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

            if event.type == pygame.MOUSEMOTION:
                x, y = pygame.mouse.get_pos()
                change_x = x - prev_x
                change_y = y - prev_y
                for i in range(-1, 2):
                    for j in range(-1, 2):
                        fluid.add_density(x + i, y + j,
                                          random.randint(100, 200))
                        fluid.add_velocity(x, y, change_x * 2, change_y * 2)

                prev_x, prev_y = x, y

        fluid.density[fluid.density > 0] -= 0.5

        fluid.step()
        density = fluid.density.reshape(WIDTH, HEIGHT).copy()
        surfarray.blit_array(screen, density)

        fps = font.render(str(int(clock.get_fps())), True,
                          pygame.Color('White'))
        screen.blit(fps, (50, 50))

        # Flip the display
        pygame.display.flip()
        clock.tick(144)

    pygame.quit()
Exemple #34
0
    def refresh(self):
        if self.env.config["enable_ui_recording"]:
            screen_to_dump = cv2.cvtColor(self.screen_arr.transpose(1, 0, 2),
                                          cv2.COLOR_BGR2RGB)
            cv2.imshow("Recording", screen_to_dump)
            cmd = cv2.waitKey(5) % 256
            if cmd == ord('r'):
                self.start_record()
            if cmd == ord('q'):
                self.end_record()

            if self.is_recording:
                #self.curr_output.write(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
                #from IPython import embed; embed()
                cv2.imwrite(
                    os.path.join(self.output_dir,
                                 "frame%06d.png" % self.record_nframe),
                    screen_to_dump)
                self.record_nframe += 1
                #self.curr_output.write(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))

        #with Profiler("Refreshing"):
        if self.use_pygame:
            pygame.display.flip()
            surfarray.blit_array(self.screen, self.screen_arr)
        #print(self.screen_arr.shape)
        screen_to_dump = cv2.cvtColor(self.screen_arr.transpose(1, 0, 2),
                                      cv2.COLOR_BGR2RGB)
        screen = pickle.dumps(cv2.imencode('.jpg', screen_to_dump), protocol=0)

        self.socket.send(b"ui" + screen)

        debug = 0
        if debug:
            path = os.path.join(
                os.path.expanduser("~"),
                "PycharmProjects/Gibson_Exercise/gibson/utils/user_int")
            try:
                os.mkdir(path)
            except OSError:
                pass

            cv2.imwrite(
                os.path.join(path, 'Frame_UI_%i.jpg') % (self.nframe),
                screen_to_dump)
Exemple #35
0
    def __init__(self, master=None, surface=None, **surf_kwargs):
        self.children = []

        if not surface:
            self._build_surface(**surf_kwargs)
        else:
            surf_rect = surface.get_rect()
            Surface.__init__(surf_rect.size,
                             masks=pygame.mask.from_surface(surface))
            array = surfarray.array2d(surface)
            surfarray.blit_array(self, array)

        if not master:
            self.master = pygame.display.get_surface()
        else:
            self.master = master

        Events.__init__(self)
Exemple #36
0
    def __generate(self):
        print(f'Generating Terrain {self.width}x{self.height}')
        a, b, c = 0.78, 1.4, 1.25
        self.topology = np.ndarray((self.width, self.height, 1))
        pixel_array = np.ndarray(
            (self.topology.shape[0], self.topology.shape[1], 3))
        background_surface = Surface(
            (self.topology.shape[0], self.topology.shape[1]))

        # this code needs to be vectorized
        for x in range(len(self.topology)):
            for y in range(len(self.topology[0])):
                self.topology[x][y] = self.noise(x, y)
                self.topology[x][y] += self.__islandify(x, y, a, b, c)
                pixel_array[x][y] = self.height_to_color(self.topology[x][y])

        surfarray.blit_array(background_surface, pixel_array)
        print('Finished Proc Gen')
        return background_surface
    def render(self, text, antialias, forecolor, backcolor=(0,0,0,255)):
        size = self.size(text)
        img = NSImage.alloc().initWithSize_(size)
        img.lockFocus()

        NSString.drawAtPoint_withAttributes_(text, (0.0, 0.0), {
            NSFontAttributeName: self._font,
            NSUnderlineStyleAttributeName: self._isUnderline and 1.0 or None,
            NSBackgroundColorAttributeName: backcolor and _getColor(backcolor) or None,
            NSForegroundColorAttributeName: _getColor(forecolor),
        })

        rep = NSBitmapImageRep.alloc().initWithFocusedViewRect_(((0.0, 0.0), size))
        img.unlockFocus()
        if rep.samplesPerPixel() == 4:
            s = Surface(size, SRCALPHA|SWSURFACE, 32, [-1<<24,0xff<<16,0xff<<8,0xff])
            
            a = Numeric.reshape(Numeric.fromstring(rep.bitmapData(), typecode=Numeric.Int32), (size[1], size[0]))
            blit_array(s, Numeric.swapaxes(a,0,1))
            return s.convert_alpha()
Exemple #38
0
    def draw8(self, ylines, regX, regY):
        collision = 0
        yline = 0
        for byte in ylines:
            byte = ylines[yline]
            for xline in range(8):
                if (byte & (0x80>>xline)) != 0:
                    x = (regX + xline) % 64
                    y = (regY + yline) % 32
                    if self.pixel_data[x][y] == 1:
                        self.pixel_data[x][y] = 0
                        collision = 1
                    else:
                        self.pixel_data[x][y] = 1
            yline = yline + 1

        surfarray.blit_array( self.scale_screen, self.pixel_data )
        temp = pygame.transform.scale(self.scale_screen, self.screen.get_size())
        self.screen.blit(temp, (0,0))
        pygame.display.update()
        return collision
    def output(self, state):
        outdir = '/tmp/out/'
        imgpath = os.path.join(outdir, 'step_%s.tif' % self.step)
        print imgpath
        print state
  
        if self.draw:
            size = np.array(state.shape)*2
            scaleup = np.zeros(size,dtype=np.int32)
            scaleup[::2,::2] = state
            scaleup[1::2,::2] = state
            scaleup[:,1::2] = scaleup[:,::2]
            screen = pygame.display.set_mode(scaleup.shape[:2], 0, 32)
            surfarray.blit_array(screen, scaleup)
            pygame.display.flip()
            pygame.display.set_caption("Step %s" % self.step)
         
        if self.save:
            imgformat = "GTiff"
            driver = gdal.GetDriverByName( imgformat )
            gdt = get_GDT_from_dtype(state.dtype)
            dst_ds = driver.Create( imgpath, state.shape[1], state.shape[0], 1, gdt)
            dst_ds.SetGeoTransform( self.geotrans )
            dst_band = dst_ds.GetRasterBand(1)
            dst_band.WriteArray( state )
            dst_band.SetNoDataValue(0.0)

            if str(state.dtype).lower() in ['byte','uint16'] and imgformat == 'GTiff':
                print "Apply color ramp..."
                min_val, max_val = dst_band.ComputeRasterMinMax()
                start_color = (0,0,255,255)
                end_color = (255,0,0,255)
                ct = gdal.ColorTable()
                ct.CreateColorRamp(int(min_val),start_color,int(max_val),end_color)
                dst_band.SetColorTable(ct)

            dst_band = None
            dst_ds = None
            driver = None
Exemple #40
0
 def surfdemo_show(array_img, name):
     "displays a surface, waits for user to continue"
     screen = pygame.display.set_mode(array_img.shape[:2], 0, 32)
     surfarray.blit_array(screen, array_img)
     pygame.display.flip()
     pygame.display.set_caption(name)
     while 1:
         e = pygame.event.wait()
         if e.type == MOUSEBUTTONDOWN: break
         elif e.type == KEYDOWN and e.key == K_s:
             #pygame.image.save(screen, name+'.bmp')
             #s = pygame.Surface(screen.get_size(), 0, 32)
             #s = s.convert_alpha()
             #s.fill((0,0,0,255))
             #s.blit(screen, (0,0))
             #s.fill((222,0,0,50), (0,0,40,40))
             #pygame.image.save_extended(s, name+'.png')
             #pygame.image.save(s, name+'.png')
             #pygame.image.save(screen, name+'_screen.png')
             #pygame.image.save(s, name+'.tga')
             pygame.image.save(screen, name+'.png')
         elif e.type == QUIT:
             raise SystemExit()
Exemple #41
0
 def on_init(self):
     pygame.init()
     self._display_surf = pygame.display.set_mode(self.size)
     self._running = True
     blit_array(self._display_surf, self.img)
     pygame.display.flip()
Exemple #42
0
def run_detector():
    # import os
    # os.environ['SDL_VIDEODRIVER'] = 'windib'
    # os.environ['SDL_VIDEODRIVER'] = 'directx'


    parser = OptionParser(usage="""\
    Detect SnapMyinfo QRcodes in a live video stream

    Usage: %prog [options] camera_index
    """)

    parser.add_option('-f','--fs','--fullscreen',
                      dest="fullscreen", default=False,
                      action='store_true',
                      help="""Run the Live Decoder full screen.""")

    parser.add_option('--hw','--hw_accel',
                    dest="hw_accel", default=False,
                    action='store_true',
                    help="""Runs pygame with the directx hw driver (if avail). Automatically assumes fullscreen.""")

    parser.add_option('-s','--scale',
                    dest="scale", default=4.0,
                    action='store', type="float",
                    help="""Sets the precision of code tracking. Valid values are >1.0 and less than 8.0. Lower values represent more accurate tracking, but consume more CPU.""")

    parser.add_option('--flip',
                    dest="flip", default=False,
                    action='store_true',
                    help="""Flip the video image horizontally before processing.""")

    parser.add_option('-m','--max_cards',
                    dest="tracker_count", default=3, type="int",
                    action="store",
                    help="""The number of simultaneous snap codes that can be tracked in the video stream.""")


    parser.add_option('--nv','--no_video',
                    dest="no_video", default=False, 
                    action="store_true",
                    help="""A debugging option, turns off the video stream from the web cam.""")

    parser.add_option('-d','--debug',
                    dest="debug", default=False, 
                    action="store_true",
                    help="""Debugging option, turns on fps display and additional tracking data on the display.""")


    opts, args = parser.parse_args()

    import os
    os.environ['SDL_VIDEODRIVER'] = 'windib'
    if opts.hw_accel:
        os.environ['SDL_VIDEODRIVER'] = 'directx'
        opts.fullscreen = True

    # initialize pygame
    pygame.init()

    display_size = (800,600)
    video_size = (1280,720)
    
    # scale is roughly equivalent to tracking precision
    # the higher the scale, the less precise, but faster, the gross
    # tracking will be scale of 1 means 1:1 tracking, but can be slow
    # recommend 2-4 as a good scale/precision factor. higher res images
    # usually benefit from higher scale
    scale = opts.scale
    
    
    # this can be used to throttle the max framerate processed. 0 means no throttle
    max_frame_rate = 30
    
    names =  [args[0]]
    name = names[0]

    if not opts.no_video:
        # connect to web camera and set the webcam options
        capture = cvCreateCameraCapture( int(name) )
        cvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_WIDTH, video_size[0] )
        cvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_HEIGHT, video_size[1] )
    
        # query the camera once to get the camera properties
        # the frame is just a throwaway
        cvQueryFrame( capture )

        # get the camera properties
        (o_width,o_height) = [cvGetCaptureProperty(capture, prop) for prop in [CV_CAP_PROP_FRAME_WIDTH,CV_CAP_PROP_FRAME_HEIGHT]]
        video_size = (int(o_width),int(o_height))
    else:
        blank = cvCreateImage(video_size,8,3)
        cvZero(blank)

    # create the pygame display
    flags = 0
    if opts.fullscreen:
        flags = pygame.FULLSCREEN
    if opts.hw_accel:
        flags = flags|pygame.HWSURFACE|pygame.DOUBLEBUF

    display_layer = pygame.display.set_mode( display_size,  flags ) 

    video = pygame.Surface(video_size).convert()

    # set the window name
    pygame.display.set_caption('Live Detector') 

    # some debug information
    # print the current driver being used
    print 'Driver %s\nVideo Input Resolution: %s\nDisplay Resolution: %s\n' % (pygame.display.get_driver(), video_size, display_size)

    # for convert to work, pygame video mode has to be set
    image_buffer = ImageBuffer(video_size,display_size,scale)
    if opts.no_video:
        image_buffer.frame_buffer = cvCreateImage(video_size,8,3)
        # blank = cvCreateImage(video_size,8,3)
        # cvZero(blank)
    worker = GrossTracker(image_buffer) 
    
    # pool of tracker objects
    pool = TrackerPool(image_buffer, opts.tracker_count)
    thread_objects.append(pool)


    status = Status()
    
    connector = Connector(pool,status)
    connector.start()
    thread_objects.append(connector)
    
    # for i in range(4):
    #     win_name = "thread-%d" % i
    #     cvNamedWindow(win_name, CV_WINDOW_AUTOSIZE)
    
    pyg_clock = pygame.time.Clock()
    update_count = 0
    last_rects = []
    last_fills = []
    hud_last_fills = []

    if opts.debug:
        dbg = DebugDisplay()

    snap_logo = pygame.image.load('./images/snap_logo.png').convert_alpha()
    
    still = False
    running = True
    fps = 0.0
    while running:
        pyg_clock.tick(max_frame_rate)
        if update_count > 20:
            fps = pyg_clock.get_fps()
            update_count = 0
        update_count += 1

        # get the pygame events
        events = pygame.event.get()
        for e in events:
            # 'quit' event key
            if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE):
                running = False
            elif e.type == KEYDOWN and e.unicode == u't':
                still = True
            
            
        # take a frame from the web camera
        if opts.no_video:
            cvCopy(blank,image_buffer.frame_buffer)
        else:
            image_buffer.frame_buffer = cvQueryFrame( capture )

        if opts.flip:
            cvFlip(image_buffer.frame_buffer,image_buffer.frame_buffer,1)
            
        # update the image buffer with the latest frame
        image_buffer.update()

        # analyze the small frame to find collapsed candidates
        squares = worker.analyze_frame()        

        # check squares and assign a tracker if new
        pool.check(squares)
        # update all trackers
        pool.update()

        status.update()
        
        # clear the paint buffer
        for rect in last_rects:
            pygame.gfxdraw.rectangle(image_buffer.paint_buffer, rect, Color(0,0,0))
        last_rects = []
        
        for blank in last_fills:
            image_buffer.paint_buffer.fill((0,0,0),blank)
        last_fills = []


        for blank in hud_last_fills:
            image_buffer.hud_buffer.fill((0,0,0,0),blank)
        hud_last_fills = []



        # draw the sprite and tracker boundaries
        # boundaries will be replaced (or turned off)
        pool.sort_active()
        for t_id in pool.active_trackers:
            #rect = pool.trackers[t_id].get_bound_rect()
            center = pool.trackers[t_id].get_avg_center(2)

            frame_color = Color(128,255,128)
            if pool.trackers[t_id].sprite:
                # print str(dir(pool.trackers[t_id].sprite))
                sprite_size = pool.trackers[t_id].sprite.get_size()
                # print str(sprite_size)
                x_diff = sprite_size[0] / 2.0
                y_diff = sprite_size[1] / 2.0
                
                # frame_color = Color(250,250,255)
                
                rect = pygame.Rect(center.x * image_buffer.display_scale[0] - x_diff, center.y * image_buffer.display_scale[1] - y_diff, sprite_size[0],sprite_size[1])
                # pygame.gfxdraw.rectangle(image_buffer.paint_buffer, rect, pool.trackers[t_id].color)
                # last_rects.append(rect)
                #if pool.trackers[t_id].user_id:
                image_buffer.paint_buffer.blit(pool.trackers[t_id].sprite,(rect.x ,rect.y ))
                last_fills.append(rect) #pygame.Rect(rect.x ,rect.y ,closer_img.size[0],closer_img.size[1]))
            else:
                # rect = pygame.Rect(center.x * scale - 100, center.y * scale - 100, 200,200)
                # 
                # 
                # pygame.gfxdraw.rectangle(image_buffer.paint_buffer, rect, frame_color)
                # last_rects.append(rect)

                #c = pygame.Color(164,229,135,150)
                #c1 = pygame.Color(164,229,135,255)
                c = pygame.Color(229,229,135,200)
                # c1 = pygame.Color(229,229,135,255)

                pygame.gfxdraw.filled_polygon(image_buffer.hud_buffer, pool.trackers[t_id].get_bounding_points(),c)
                # pygame.gfxdraw.polygon(image_buffer.hud_buffer, pool.trackers[t_id].get_bounding_points(),c1)
                # pygame.gfxdraw.rectangle(image_buffer.hud_buffer, rect, frame_color)
                # pygame.gfxdraw.filled_polygon(image_buffer.hud_buffer, pool.trackers[t_id].get_bounding_points(),c)
                hud_last_fills.append(pool.trackers[t_id].get_bound_rect())
                


        # draw the orphans and frame rate display
        # debug for now, lets me know when it's trying to lock onto something
        if opts.debug:
            fps_sprite = dbg.gen_sprite('''%.2f fps''' % fps)
            image_buffer.hud_buffer.blit(fps_sprite,(image_buffer.display_size[0]-100,10))
            fps_rect = pygame.Rect(video_size[0]-100,10, dbg.size[0], dbg.size[1])
            hud_last_fills.append(fps_rect)
            
            for orphans in pool.orphan_frames:
                for orphan in orphans:
                    orphan = pygame.Rect(orphan.x * image_buffer.display_scale[0], orphan.y * image_buffer.display_scale[1], orphan.width * image_buffer.display_scale[0], orphan.height * image_buffer.display_scale[1])
                    pygame.gfxdraw.rectangle(image_buffer.paint_buffer, orphan, Color(190,255,190))
                    last_rects.append(orphan)

        # no data in the frame buffer means we're done
        if not image_buffer.frame_buffer:
            break

        # Surf_dat array is not oriented the same way as the pyame display so
        # first it's transposed. Then the
        # the surface RGB values are not the same as the cameras
        # this means that two of the channels have to be swapped in the numpy
        # array before being blit'ted onto the array
        surf_dat = image_buffer.frame_buffer.as_numpy_array().transpose(1,0,2)[...,...,::-1]
        
        # blit_array zaps anything on the surface and completely replaces it with the array, much
        # faster than converting the bufer to a surface and bliting it
        # replaces video with the data in surf_dat
        surfarray.blit_array(video,surf_dat)
        
        # this resizes the video surface and stores it in display_layer. Completely
        # overwrites whatever is in display_layer
        pygame.transform.scale(video, image_buffer.display_size, display_layer)
        
        # blit the paint buffer onto the surface. Paint buffer has a chromakey so all black values will show through
        display_layer.blit(image_buffer.paint_buffer,(0,0))

        # the "HUD" is added next. 
        display_layer.blit(image_buffer.hud_buffer,(0,0))

        # Write out the status sprite to the display_layer
        if status.sprite:
            display_layer.blit(status.sprite,(10,image_buffer.display_size[1] - status.height - 10 ))


        # finally watermark the screen with the company logo and name of the product
        # putting it here means it always shows above the other layers
        logo_size = snap_logo.get_size()
        display_layer.blit(snap_logo,(image_buffer.display_size[0]-logo_size[0]-10 , image_buffer.display_size[1]-logo_size[1]-10))


        if still == True:
            pygame.image.save(display_layer, 'test.jpg')
            still = False

        # flip() actually displays the surface
        pygame.display.flip()

    # we've left the loop
    # exit
    print 'exiting...'
    def render(self, text, antialias = True, 
               forecolor=(255, 255, 255, 255), 
               backcolor=(255, 255, 255, 0)):
        size = self.size(text)
        img = NSImage.alloc().initWithSize_(size)
        img.lockFocus()

        NSString.drawAtPoint_withAttributes_(text, (0.0, 0.0), {
            NSFontAttributeName: self._font,
            NSUnderlineStyleAttributeName: self._isUnderline and 1.0 or 0,
            NSBackgroundColorAttributeName: _getColor(backcolor),# or None,
            NSForegroundColorAttributeName: _getColor(forecolor),
        })

        rep = NSBitmapImageRep.alloc().initWithFocusedViewRect_(((0.0, 0.0), size))
        img.unlockFocus()
        if rep.samplesPerPixel() == 4:
            s = Surface(size, SRCALPHA|SWSURFACE, 32, [-1<<24,0xff<<16,0xff<<8,0xff])
            
            a = Numeric.reshape(Numeric.fromstring(rep.bitmapData(), typecode=Numeric.Int32), (size[1], size[0]))
            blit_array(s, Numeric.swapaxes(a, 0, 1))
            #print "surface size is ", size

            filter_size = self.shadow_filter_size()
            border = self.border_size()
            
            result = []
            result_size = (size[0] + border*2, size[1] + border*2)
            #print "result size is ", result_size
            for y in range(result_size[1]):
                result.append([(0, 0, 0, 0)] * result_size[0])
            
            # Filter the character appropriately.
            s.lock()
            for y in range(size[1]):
                for x in range(size[0]):
                    color = s.get_at((x, y))
                    s.set_at((x, y), (255, 255, 255, color[3]))

            if filter_size == 3:
                factors = [[1, 2, 1],
                           [2, 4, 2],
                           [1, 2, 1]]
            elif filter_size == 5:
                factors = [[1,  4,  6,  4,  1],
                           [4,  16, 24, 16, 4],
                           [6,  24, 36, 24, 6],
                           [4,  16, 24, 16, 4],
                           [1,  4,  6,  4,  1]]
            elif filter_size == 7:
                factors = [[1,  6,   15,  20,  15,  6,   1],
                           [6,  36,  90,  120, 90,  36,  6],
                           [15, 90,  225, 300, 225, 90,  15],
                           [20, 120, 300, 400, 300, 120, 20],
                           [15, 90,  225, 300, 225, 90,  15],
                           [6,  36,  90,  120, 90,  36,  6],
                           [1,  6,   15,  20,  15,  6,   1]]
            else:
                print "factors for filter size", filter_size, "not defined!"
                factors = 0

            # Filter a shadow.
            for ry in range(result_size[1]):
                for rx in range(result_size[0]):
                    inpos = (rx - int(border), ry - int(border))
                    count = 0
                    colorsum = 0
                    u = 0
                    v = 0
                    for a in filter_range(filter_size):
                        v = 0
                        for b in filter_range(filter_size):
                            x, y = (inpos[0] + a, inpos[1] + b)
                            factor = factors[u][v]
                            if x >= 0 and y >= 0 and x < size[0] and y < size[1]:
                                colorsum += factor * s.get_at((x, y))[3]
                            count += factor
                            v += 1
                        u += 1
                    if count > 0:
                        result_color = (int(colorsum) + count/2) / count
                    else:
                        result_color = 0
                    result[ry][rx] = (0, 0, 0, min(255, result_color*1.4))

            # Blend the glyph itself to the result.
            for y in range(size[1]):
                for x in range(size[0]):
                    color = s.get_at((x, y))
                    result[border + y][border + x] = \
                        alpha_blend(color, result[border + y][border + x])
                    result[border + y][border + x] = \
                        alpha_blend(color, result[border + y][border + x])
                    #result[border + y][border + x] = \
                    #    alpha_blend(color, result[border + y][border + x])

            s.unlock()
                    
            glyph_rgba = Numeric.array(result, typecode=Numeric.UnsignedInt8)
            return glyph_rgba, result_size
Exemple #44
0
 def draw(self, surface, x, y):
     surfarray.blit_array(self.surface, self.array)
     surface.blit(self.surface, (x, y))
def main():

    # Initialize pygame/SDL
    pygame.init()

    modes = pygame.display.list_modes()
    width, height = modes[0]

    # Check options to set the size
    opts, args = getopt.getopt(sys.argv[1:], "w:h:", ["width=", "height="])

    for o, a in opts:
        if o in ("-w", "--width"):
            width = int(a)
        elif o in ("-h", "--height"):
            height = int(a)
   
    # Load the rule set
    rule = int(args[0])

    try:
        rules = parseRule(rule) 
    except RuleError as e:
        print "An exception occurred parsing rule", e.value
        exit(1)


    size = width, height
    white = 255, 255, 255
    black = 0, 0, 0

    # Output information to console.
    print "Rule:", rule
    print "Display size:", width,"x",height


    screen = pygame.display.set_mode(size)
    pygame.display.set_caption("elementary.py Rule " + str(rule))

    tick = 0

    # Generate the initial generation
    world = numpy.zeros((width,height,1), dtype=int)
    render = numpy.zeros((width,height,3), dtype=int)


    render[round(width/2),tick] = (0,0,0)
    world[round(width/2),tick] = 1

    # Generate the initial world

    while 1:
        for event in pygame.event.get():
            if event.type == pygame.QUIT: sys.exit()
        
        # Evaluate the current array
        life = 0
        for index in range(0,width-1):
            pre = index - 1
            suc = index + 1
            if pre < 0:
                pre = width-1
            if suc >= width:
                suc = 0

            pattern = 0
            if world[pre,tick] == 1:
                pattern += 100
            if world[index,tick] == 1:
                pattern += 10
            if world[suc,tick] == 1:
                pattern += 1

            if tick + 1 == height:
                new_tick = 1
            else:
                new_tick = tick+1

            if pattern in rules:
                render[index,new_tick] = (0,0,0)
                world[index,new_tick] = 1
                life += 1
            else:
                render[index,new_tick] = (255,255,255)
                world[index,new_tick] = 0
           
        
        # Render
        surfarray.blit_array(screen,render)
        updateRect = pygame.Rect((0,tick-1),(width-1,tick))
        pygame.display.update(updateRect)
        tick += 1
        if life == 0:
            sys.exit()
            
        if tick == height:
            tick = 1
	def read(self, surface):
		surfarray.blit_array(surface, self.get())
Exemple #47
0
 def blit_images(self):
     for i in range(len(self.images)):
         blit_array(self.surfaces[i], self.images[i])
     pygame.display.flip()
Exemple #48
0
 def propagateselection(self):
     for i in range(len(self.images)):
         blit_array(self._display_surf.subsurface(
             self.getXY(i)+self.img_size), self.images[self.selected[-1]])
         #self._display_surf.blit(s0,(0,0))
     pygame.display.flip()
Exemple #49
0
def drawfield( screen, scale_surface, pixels ):
    surfarray.blit_array( scale_surface, pixels )
    temp = pygame.transform.scale(scale_surface, screen.get_size())
    screen.blit(temp, (0,0))
    return
Exemple #50
0
def surfdemo_show(array_img, name):
    screen = pygame.display.set_mode(array_img.shape[:2], 0, 32)
    surfarray.blit_array(screen, array_img)
    pygame.display.flip()