def RL_GRID_DOTS(board: Board, surface: Surface): """.""" if board.grid is None: return rect = board.get_rect() view_rect = board.get_view_rect() gx, gy = math2d.grid(view_rect.topleft, (board.grid, board.grid)) if gy < view_rect.top: gy += board.grid if gx < view_rect.left: gx += board.grid orig_gx = gx while gy < view_rect.bottom: _, gly = board.to_global((0, gy)) gly -= rect.y while gx < view_rect.right: glx, _ = board.to_global((gx, 0)) glx -= rect.x surface.set_at(math2d.v_int((glx, gly)), board.style["grid-color"]) gx += board.grid gx = orig_gx gy += board.grid
def render(self, surf: pygame.Surface): color = self.color n = len(self.points) - 1 i = 0 last_pos = None for t in range(self.reso): t /= self.reso tt = 1 - t end = V2(0, 0) for k, p in enumerate(self.points): end += comb(n, k) * p * t**k * tt**(n - k) if end.ti == last_pos: i += 1 continue else: last_pos = end.ti if callable(self.color): color = self.color(t) if self.line_width < 2: surf.set_at(end.ti, color) else: x, y = end.ti gfxdraw.aacircle(surf, x, y, round(self.line_width / 2), color) gfxdraw.filled_circle(surf, x, y, round(self.line_width / 2), color) print(i, self.reso, sep='/')
def _iter_flood_fill(self, surface: pygame.Surface, position: Tuple[int, int]) -> pygame.Surface: clock = pygame.time.Clock() color = self.options_context.line_color points = [position] while len(points) > 0: (x, y), *points = points print(len(points), x, y) surface.set_at((x, y), color) if self.is_valid(surface, (x + 1, y)): points.append((x + 1, y)) if self.is_valid(surface, (x - 1, y)): points.append((x - 1, y)) if self.is_valid(surface, (x, y + 1)): points.append((x, y + 1)) if self.is_valid(surface, (x, y - 1)): points.append((x, y - 1)) color_context = DrawContext(surface, (0, 0)) color_context.is_valid = False draw_to_surface(self.gui_context.screen, [color_context, *self.gui_context.draw_surfaces]) pygame.display.flip() clock.tick(100) return surface
def render(self, surface: pygame.Surface): for i, position in enumerate(self.body): if i == 0: surface.set_at(position, (0, 200, 0)) # make head slightly darker else: surface.set_at(position, (0, 255, 0))
def render_image(camera=None, objects=None, lights=None, depth=2, verbose=1, scene=None, pygame_mode=False): if None in [camera, objects, lights]: if scene is None: return else: camera = scene.camera objects = scene.objects lights = scene.lights if pygame_mode: img = Surface((camera.res_x, camera.res_y)) else: img = Image.new('RGB', (camera.res_x, camera.res_y)) for y in range(camera.res_y): if verbose: if y % (camera.res_y // 10) == 0: print(y / camera.res_y) for x in range(camera.res_x): ray = camera.get_ray(y, x) color = trace(ray, objects, lights, depth) if pygame_mode: img.set_at((x, y), get_color(color)) else: img.putpixel((x, y), get_color(color)) if verbose: print('1.0') return img
def bitwise_and(s1, s2): result = Surface(SIZE) for i in range(0, SIZE[0]): for j in range(0, SIZE[1]): c = s1.get_at((i, j))[0] & s2.get_at((i, j))[0] result.set_at((i, j), Color(c, c, c)) return result
def render(self, surface: pygame.Surface): for position in self.positions: x, y = position if (x + y) % 2 == 0: surface.set_at(position, (100, 100, 100)) else: surface.set_at(position, (120, 120, 120))
def absdiff(s1, s2, tl=(0, 0), br=SIZE): result = Surface((br[0] - tl[0], br[1] - tl[1])) for i in range(tl[0], br[0]): for j in range(tl[1], br[1]): result.set_at((i - tl[0], j - tl[1]), pixelDiff(s1.get_at((i - tl[0], j - tl[1])), s2.get_at((i - tl[0], j - tl[1])))) return result
def _generate_random_surface(width, height): surf = Surface((width, height)) for h in range(height): for w in range(width): surf.set_at((h, w), Color(randint(0, 255), randint(0, 255), randint(0, 255))) return surf
def region_color_fill(surface: pygame.Surface, regions, color_provider): """ :param color_provider: lambda region -> color """ for reg in regions: color = color_provider(reg) for r in reg: surface.set_at(r, add_alpha(color))
def draw(self, canvas: pygame.Surface): width, height = canvas.get_size() for y in range(height): for x in range(width): pos = x, y color = self.color_from_xy(x, y) canvas.set_at(pos, color)
def change_image_color(surface: pygame.Surface, color: tuple[int, int, int]) -> pygame.Surface: size = surface.get_size() for x in range(size[0]): for y in range(size[1]): px = surface.get_at((x, y)) if px[3] != 0: surface.set_at((x, y), color) return surface
def bitwise_and(s1, s2, tl=(0, 0), br=SIZE): result = Surface((br[0] - tl[0], br[1] - tl[1])) for i in range(tl[0], br[1]): for j in range(tl[1], br[1]): c = s1.get_at((i - tl[0], j - tl[1]))[0] & s2.get_at( (i - tl[0], j - tl[1]))[0] result.set_at((i - tl[0], j - tl[1]), Color(c, c, c)) return result
def generate_surface(iterations): surf = Surface((WIDTH, HEIGHT)) for _ in range(iterations): new_point = new_point_square() surf.set_at(convert2int(new_point), WHITE) return surf
def toGrayscale(screen): result = Surface(SIZE) for i in range(0, SIZE[0]): for j in range(0, SIZE[1]): pixel = screen.get_at((i,j)) grayValue = toGray(pixel) pixel = (grayValue, grayValue, grayValue) result.set_at((i,j), pixel) return screen
def toGrayscale(screen, tl=(0, 0), br=SIZE): result = Surface((br[0] - tl[0], br[1] - tl[1])) for i in range(tl[0], br[0]): for j in range(tl[1], br[1]): pixel = screen.get_at((i, j)) grayValue = toGray(pixel) pixel = (grayValue, grayValue, grayValue) result.set_at((i - tl[0], j - tl[1]), pixel) return result
def test_bottom(self): """ L{loadTerrainFromSurface} places a single C{GRASS} voxel for a zero-valued pixel in the image data. """ surface = Surface((1, 1)) surface.set_at((0, 0), (0, 0, 0)) terrain = loadTerrainFromSurface(surface) self.assertEquals(terrain.dict(), {(0, 0, 0): GRASS})
def render(self, surface: pygame.Surface): r, g, b = self.color for i, position in enumerate(self.body): if i == 0: surface.set_at(position, (int(0.8 * r), int( 0.8 * g), int(0.8 * b))) # make head slightly darker else: surface.set_at(position, (r, g, b))
def recolor_image( image: pygame.Surface, primary: (int, int, int)) -> pygame.Surface: for x in range(image.get_width()): for y in range(image.get_height()): color = image.get_at((x, y)) if color[3] == 255: percent = color[0] / 255 result = (primary[0] * percent, primary[1] * percent, primary[2] * percent) image.set_at((x, y), result) return image
def on_key_down(key): if key == keys.F12: s = Surface((PIXELSW, PIXELSH), depth=24) for i, p in enumerate(pixels): y, x = divmod(i, 64) if x >= PIXELSW: continue y = PIXELSH - y - 1 x = PIXELSW - x - 1 s.set_at((x, y), p) pygame.image.save(s, 'grab.png')
def getBlood(self, img: pg.Surface) -> pg.Surface: """Return bloody version of given surface.""" w, h = img.get_size() for y in range(h): for x in range(w): if img.get_at([x, y])[3] > 200: r = randint(192, 255) gb = randint(0, 96) img.set_at([x, y], [r, gb, gb, 255]) else: img.set_at([x, y], [0]*4) return img
def convert_to_grayscale(surf): """Convert a Surface to grayscale, pixel by pixel. Quite slow.""" # pylint: disable=E1121 gray = Surface(surf.get_size(), 0, 8) # pylint: enable=E1121 w, h = surf.get_size() for x in xrange(w): for y in xrange(h): red, green, blue, alpha = surf.get_at((x, y)) average = (red + green + blue) // 3 gs_color = (average, average, average, alpha) gray.set_at((x, y), gs_color) return gray
def find_colours(image: pygame.Surface) -> list: """This function is used to find all of the different colours in an image. It will output a list of colours.""" list_of_colours = [] for x in range(image.get_size()[0]): for y in range(image.get_size()[1]): pos = (x, y) pixel = image.get_at(pos) if pixel not in list_of_colours: list_of_colours.append(pixel) image.set_at(pos, pixel) return list_of_colours
def draw_point(point: Vector, color: Tuple[int, int, int], surf: pygame.Surface, radius: int, font: pygame.font, text: str, text_color: Tuple[int, int, int]) -> None: projected = Engine.get_projection([point])[0][:] if radius > 1: pygame.draw.circle(surf, color, (round(projected[0]), round(projected[1])), radius) else: surf.set_at((round(projected[0]), round(projected[1])), color) if text != '': surf.blit(font.render(str(text), True, text_color), (round(projected[0]), round(projected[1])))
def test_height(self): """ L{loadTerrainFromSurface} uses the red color component to determine how many voxels to stack. """ surface = Surface((1, 1)) surface.set_at((0, 0), (3, 0, 0)) terrain = loadTerrainFromSurface(surface) self.assertEquals( terrain.dict(), {(0, 0, 0): MOUNTAIN, (0, 1, 0): MOUNTAIN, (0, 2, 0): GRASS})
def change_colours(image: pygame.Surface, colour_to_change: pygame.Color, target_colour: pygame.Color, new_file_name: str) -> pygame.Surface: """Function will convert a colour in an image into a different colour. It will save the edited image to file in the asset folder, and return the image.""" for x in range(image.get_size()[0]): for y in range(image.get_size()[1]): pos = (x, y) pixel_col = image.get_at(pos) if pixel_col == colour_to_change: pixel_col = target_colour image.set_at(pos, pixel_col) pygame.image.save(image, f"assets/{new_file_name}_re-skin.png") return image
def test_varyingZ(self): """ L{loadTerrainFromSurface} varies the z coordinate of the loaded terrain with the y coordinate of the image data. """ surface = Surface((1, 2)) surface.set_at((0, 0), (3, 0, 0)) surface.set_at((0, 1), (2, 0, 0)) terrain = loadTerrainFromSurface(surface) self.assertEquals( terrain.dict(), {(0, 0, 0): MOUNTAIN, (0, 0, 1): MOUNTAIN, (0, 1, 0): MOUNTAIN, (0, 1, 1): GRASS, (0, 2, 0): GRASS})
def color_image(surface: pygame.Surface, color: color_t) -> pygame.Surface: if isinstance(color, str): color = hexa_color_to_rgb(color) alpha = (100 if len(color) == 3 else color[3]) / 255 size = surface.get_size() for x in range(size[0]): for y in range(size[1]): px = surface.get_at((x, y)) if px[3] != 0: al = (1 - alpha) f_px = (int(color[0] * alpha + px[0] * al), int(color[1] * alpha + px[1] * al), int(color[2] * alpha + px[2] * al)) surface.set_at((x, y), f_px) return surface
def render(screen: pygame.Surface, objects: Tuple[Geometry], lights: Tuple[Light]): screen.lock() for j in range(-int(SCREEN[1] / 2), int(SCREEN[1] / 2)): for i in range(-int(SCREEN[0] / 2), int(SCREEN[0] / 2)): x = (2 * (i + 0.5)) / (SCREEN[0] - 1) * math.tan(FOV / 2.0) * int( SCREEN[0]) / SCREEN[1] y = -(2 * (j + 0.5)) / (SCREEN[1] - 1) * math.tan(FOV / 2.0) direction = Vector(x, y, -1).normalize() screen.set_at((i + int(SCREEN[0] / 2), j + int(SCREEN[1] / 2)), cast_ray(Vector(0, 0, 0), direction, tuple(objects), tuple(lights))) pygame.display.flip() screen.unlock()
class PyGameCameraSensorArray(CameraSensorArray): def __init__(self, columns, rows): CameraSensorArray.__init__(self, columns, rows) self.sensorArray = Surface(self.dimensions.tupled()) def collect(self, column, row, intensities): self.sensorArray.set_at((int(column), int(row)), intensities) def capture(self): # Copy the sensor array data as a frame. frame = self.sensorArray.copy() # Clear the sensor array for the next frame. self.sensorArray.fill((0, 0, 0)) return frame
def func(size): if size == func.last_size: return func.last_surf.copy() surf = Surface(size, SRCALPHA) surf.fill(edge) if size[0] > 2 * thickness and size[1] > 2 * thickness: if fill[3] == 255: surf1 = Surface([a - (2 * thickness) for a in size], SRCALPHA) surf1.fill(fill) surf.blit(surf1, (thickness, thickness)) else: for y in range(thickness, size[1] - thickness): for x in range(thickness, size[0] - thickness): surf.set_at((x, y), fill) func.last_size = size func.last_surf = surf.copy() return surf
def prepare_font_image(image: pg.Surface, scale_factor: int) -> pg.Surface: try: image.lock() for y in range(image.get_height()): for x in range(image.get_width()): r, g, b, a = image.get_at((x, y)) if (r, g, b, a) == (0, 0, 0, 255): image.set_at((x, y), (255, 255, 255, 255)) else: image.set_at((x, y), (0, 0, 0, 0)) finally: image.unlock() old_width = image.get_width() old_height = image.get_height() new_width = old_width * scale_factor new_height = old_height * scale_factor return pg.transform.scale(image, (new_width, new_height))
def __init__(self, memory: Memory, caption: str): self._scaling = 4 self._caption = caption self._surface = None self._clock = None self._screen = None self._active = False self._sprites: List[Surface] = [] for sprite in memory.sprites: surface = Surface((16, 16)) for y in range(16): for x in range(16): intensity = sprite[x + y * 16] surface.set_at((x, y), (intensity, intensity, intensity)) self._sprites.append(surface) self._memory = memory self._status_area_width = 200 self._font = None
def test_loadImageTerrain(self): """ If the terrain option is specified as a file containing image-based terrain data, terrain data is loaded from it. """ temp = FilePath(self.mktemp()) temp.makedirs() terrain = temp.child("terrain.png") surface = Surface((2, 1)) surface.set_at((0, 0), (1, 0, 0)) surface.set_at((1, 0), (3, 0, 0)) save(surface, terrain.path) service = gam3plugin.makeService({ "port": 123, "log-directory": None, "terrain": terrain.path}) gam3 = service.getServiceNamed(GAM3_SERVICE_NAME) self.assertEquals( gam3.world.terrain.dict(), {(1, 0, 0): MOUNTAIN, (0, 0, 0): GRASS, (1, 1, 0): MOUNTAIN, (1, 2, 0): GRASS})
class Layer(Rect,object): def __init__(self,rect,alpha,delta): Rect.__init__(self,rect) self.surface = Surface(self.size,SRCALPHA) self.alpha = alpha self.delta = delta def render(self): scr.blit(self.surface,self) array = surfarray.pixels_alpha(self.surface) array[(self.alpha<array)&(array<self.alpha+self.delta)] = self.alpha array[array>self.alpha] = array[array>self.alpha]-self.delta def blit(self,*arg): self.surface.blit(*arg) def fill(self,*arg): self.surface.fill(*arg) def set_at(self,*arg): self.surface.set_at(*arg)
def scaleImageInFile(path): print "loading", path try: sourceImage = pygame.image.load(path) except: print 'An error occurred loading image \"%s\"' % path sys.exit(2) # copy the source image into the target image, though we're about to overwrite it we want its format targetImage = Surface((sourceImage.get_width() * 2, sourceImage.get_height() * 2), sourceImage.get_flags(), sourceImage) for x in range(0, sourceImage.get_width()): for y in range(0, sourceImage.get_height()): # determine neighboring pixels # TODO check diagonal edges #a = sourceImage.get_at((x - 1, y - 1)) if y > 0 and x > 0 else sourceImage.get_at((x, y)) b = sourceImage.get_at((x, y - 1)) if y > 0 else sourceImage.get_at((x, y)) #c = sourceImage.get_at((x + 1, y - 1)) if y > 0 and (x + 1) < sourceImage.get_width() else sourceImage.get_at((x, y)) d = sourceImage.get_at((x - 1, y)) if x > 0 else sourceImage.get_at((x, y)) e = sourceImage.get_at((x, y)) f = sourceImage.get_at((x + 1, y)) if (x + 1) < sourceImage.get_width() else sourceImage.get_at((x, y)) #g = sourceImage.get_at((x - 1, y + 1)) if (y + 1) < sourceImage.get_height() and x > 0 else sourceImage.get_at((x, y)) h = sourceImage.get_at((x, y + 1)) if (y + 1) < sourceImage.get_height() else sourceImage.get_at((x, y)) #i = sourceImage.get_at((x + 1, y + 1)) if (y + 1) < sourceImage.get_height() and (x + 1) < sourceImage.get_width() else sourceImage.get_at((x, y)) if b != h and d != f: e0 = d if d == b else e e1 = f if b == f else e e2 = d if d == h else e e3 = f if h == f else e else: e0 = e e1 = e e2 = e e3 = e # figure out target coordinates for e0, e1, e2, e3 targetImage.set_at((x * 2, y * 2), e0) targetImage.set_at((x * 2 + 1, y * 2), e1) targetImage.set_at((x * 2, y * 2 + 1), e2) targetImage.set_at((x * 2 + 1, y * 2 + 1), e3) # write image back to file filename, extension = os.path.splitext(path) newPath = filename + '.scaled2x' + extension pygame.image.save(targetImage, newPath) # print happy message print "Scaled up version is at", newPath
mdy = randint(-2048,2048) def spouses(x, y): global mdx global mdy m = noise.snoise2((x+mdx),(y+mdy),1,1) m = max(0, m) return int(4*m) + 1 shownoise = '-shownoise' in [a.lower() for a in argv] background = Surface(screen.get_size()) if shownoise: background.lock() for y in range(0, background.get_height()): for x in range(0, background.get_width()): background.set_at((x,y), grayvalue(noiseat(x,y))) background.unlock() else: background.fill((255,255,255)) screen.blit(background, (0,0)) sprites = Group() def personat(x,y): return noiseat(x*8,y*8) <= 0.95 for x in range(0, background.get_width(), 8): for y in range(0, background.get_height(), 8): present = personat(x/8, y/8) if shownoise and not present:
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