def damage(self, top): if not self.dmg: arr = PixelArray(self.image) self.set_damage(arr, top) self.dmg = True else: self.kill()
def generate(self, width, height): """ Generate a pyame Surface with pixels following a circular striped pattern from the center of the parent entity :param width: the width of the generated surface :param height: the height of the generated surface :return: the pygame Surface """ surface = Surface((width, height), SRCALPHA) pxarray = PixelArray(surface) x = width / 2 y = height / 2 for i in range(width): for j in range(height): if i != x: a = np.arctan((j - y) / (i - x)) else: a = np.sign(j - y) * np.pi / 2 r = a % (2 * np.pi / self.iterations) for mode, d, in enumerate(np.cumsum(self.ratios)): if r < 2 * np.pi * d / self.iterations: pxarray[i, j] = self.colors[mode] break return surface
def generate(self, width, height): """ Generate a pygame Surface with pixels following a normal density of diagonal covariance matrix. :param width: the width of the generated Surface :param height: the height of the generated Surface :return: the pygame Surface """ surface = Surface((width, height), SRCALPHA) pxarray = PixelArray(surface) m = np.array(self.m) d = np.array(self.d) t = np.zeros((width, height, 3)) for c in range(3): a, b = (0 - m[c]) / d[c], (255 - m[c]) / d[c] tc = truncnorm.rvs(a, b, size=width * height) t[:, :, c] = tc.reshape(width, height) for i in range(width): for j in range(height): pxarray[i, j] = tuple((d * t[i, j] + m).astype(int)) return surface
def generateCar(color): c = mainCar.copy() pixels = PixelArray(c) pixels.replace(Color(0,255,0, 255), color,0) surf = pixels.make_surface() del pixels surf = pygame.transform.smoothscale(surf,(30,30)) return surf
def test_rectangular_snipper_blocks(self): for x in range(20): w, h = self.surf.get_width(), self.surf.get_height() #pixel #dimmensions parser = PixelParser.green bw, bh = randint(1, w), randint(1, h) #block dimmensions rs = RectangularSnipper(self.surf, bw, bh, parser) parr = PixelArray(self.surf) pixarr = [[parser(parr[x, y]) for x in range(w)] for y in range(h)] self.assertEqual(len(pixarr), h) self.assertEqual(sum(len(x) for x in pixarr), h * w) self.assertEqual(len(rs), (h // bh) * (w // bw)) self.assertSequenceEqual(rs.shape, (len(pixarr[0]) // bw, len(pixarr) // bh)) self.assertSequenceEqual(rs.pxarray, pixarr) lw, lh = w // bw, h // bh #shape of the surface in blocks (maximum #width, maximum height) last_index = len(rs) - 1 #last block self.assertEqual(last_index, lw * lh - 1) self.assertSequenceEqual( rs[last_index], #last block reduce(add, [ pixarr[y][(lw - 1) * bw:lw * bw] for y in range((lh - 1) * bh, lh * bh) ])) self.assertSequenceEqual( rs[last_index], #last block rs.get_item((lw - 1), (lh - 1))) #last block self.assertRaises(ValueError, rs.get_item, lw, lh - 1) #out of range self.assertRaises(ValueError, rs.get_item, lw - 1, lh) #out of range self.assertRaises(IndexError, rs.__getitem__, len(rs)) rnd_index = randint(0, last_index) x_index, y_index = rnd_index % lw, rnd_index // lw self.assertSequenceEqual( rs.__getitem__(rnd_index), reduce(add, (pixarr[y][bw * x_index:bw * x_index + bw] for y in range(bh * y_index, bh * y_index + bh)), [])) rnd_slice = slice(randint(0, last_index), randint(0, last_index)) w, h = rs.shape result = [ reduce(add, (pixarr[y][bw * w:bw * (w + 1)] for y in range(bh * h, bh * (h + 1))), []) for (w, h) in map(lambda x: (x % lw, x // lw), range(*rnd_slice.indices(len(rs)))) ] self.assertSequenceEqual(rs[rnd_slice], result) #select all
def damage(self, top): if not self.tookDamage: pix = PixelArray(self.image) if top: for i in range(self.height * 3): pix[randrange(0, self.width - 1), randrange(0, self.height // 2)] = (0, 0, 0, 0) # get rid of pixel by making it invisiable else: for i in range(self.height * 3): pix[randrange(0, self.width - 1), randrange(self.height // 2, self.height - 1)] = (0, 0, 0, 0) # get rid of pixel by making it invisible self.tookDamage = True else: self.kill()
def __init__(self, level_file, color_mapping): self.color_mapping = color_mapping # Load image from file and store dimensions pixmap = image.load(level_file) self.width, self.height = pixmap.get_size() # Convert pixels to colors def index_to_color(i): color = pixmap.unmap_rgb(i) return (color.r, color.g, color.b) self.color_array = list(map( lambda index: list(map( index_to_color, index)), PixelArray(pixmap)))
def damage(self, top): """handle when bunk get hit by beam""" if not self.hit: px_array = PixelArray(self.image) if top: for i in range(int(self.height * 3)): px_array[randrange(0, self.width - 1), randrange(0, self.height // 2)] = (0, 0, 0, 0) else: for i in range(self.height * 3): px_array[randrange(0, self.width - 1), randrange(self.height // 2, self.height - 1)] = (0, 0, 0, 0) self.hit = True else: self.kill()
def bunker_hit(self, top): if not self.hit: px_array = PixelArray(self.image) if top: for i in range(self.height * 3): px_array[randrange(0, self.width - 1), randrange(0, self.height // 2)] = (0, 0, 0, 0) else: for i in range(self.height * 3): px_array[randrange(0, self.width - 1), randrange(self.height // 2, self.height - 1)] = (0, 0, 0, 0) self.hit = True else: self.kill()
def damage(self, top): if not self.dmg: px_array = PixelArray(self.image) if top: for i in range(self.height * 3): px_array[randrange(0, self.width - 1), randrange(0, self.height // 2)] = ( 0, 0, 0, 0) # transparent pixel else: for i in range(self.height * 3): px_array[randrange(0, self.width - 1), randrange(self.height // 2, self.height - 1)] = ( 0, 0, 0, 0) # transparent pixel self.dmg = True else: self.kill()
def atmo(vol, rect): y = interpolacion_lineal(vol) pxarray = PixelArray(graph) p, d = 0, 0 for j in range(0, rect.bottom - 80): # noinspection PyUnresolvedReferences rgba = graph.unmap_rgb(pxarray[y, j]) if rgba == (0, 217, 184, 255): if p == 0: p = j d = j else: p += 1 elif p != 0: break del pxarray return d, p
def update(self): self.pixels = PixelArray(self.image) if self.hitCount == 1: for i in range(25): for j in range(34): self.pixels[i, j] = (0, 0, 0) elif self.hitCount == 2: for i in range(50, 100): for j in range(30, 70): self.pixels[i, j] = (0, 0, 0) elif self.hitCount == 3: for i in range(50, 100): for j in range(70): self.pixels[i, j] = (0, 0, 0) elif self.hitCount == 4: for i in range(25, 50): for j in range(70): self.pixels[i, j] = (0, 0, 0) self.pixels.close()
def generate(self, width, height): """ Generate a pygame Surface with pixels following a uniform density :param width: the width of the generated Surface :param height: the height of the generated Surface :return: the pygame Surface """ surface = Surface((width, height)) pxarray = PixelArray(surface) a = np.array(self.a) b = np.array(self.b) t = rand.rand(width, height, 3) for i in range(width): for j in range(height): pxarray[i, j] = tuple((a + t[i, j] * (b - a)).astype(int)) return surface
def damage(self, top): """If the block is not already damaged, make random pixels (limited to direction the damage is coming from) transparent to show damage. If the block is already damaged, kill it so that projectiles can pass through later.""" if not self.dmg: px_array = PixelArray(self.image) if top: for i in range(self.height * 3): px_array[randrange(0, self.width - 1), randrange(0, self.height // 2)] = ( 0, 0, 0, 0) # transparent pixel else: for i in range(self.height * 3): px_array[randrange(0, self.width - 1), randrange(self.height // 2, self.height - 1)] = ( 0, 0, 0, 0) # transparent pixel self.dmg = True else: self.kill()
def __init__(self, surface, bwidth, bheight, pix_parser=lambda x: x): """ I.__init__(surface, width, height) -> ImageSniper """ if not isinstance(surface, Surface): raise TypeError("The specified surface source does not " "implement pygame.Surface") bwidth, bheight = int(bwidth), int(bheight) if bwidth < 1 or bheight < 1: raise ValueError("The size of the block must be more " "than one pixel, ({}, {}) specified.".format( bwidth, bheight)) if surface.get_width() < bwidth or surface.get_height() < bheight: raise ValueError("Snippet dimmensions are out of range. " "Image size:{} < Block size:{}".format( surface.get_size(), (bwidth, bheight))) self.__bwidth, self.__bheight = bwidth, bheight pxarr = PixelArray(surface) shape = pxarr.shape self.__pxarray = [[pix_parser(pxarr[x, y]) for x in range(shape[0])] for y in range(shape[1])]
def colourise(surface: Surface, rgb: tuple) -> Surface: """ Returns the same surface with an rgb value added to all the pixels on it. """ validate(colourise, locals()) r, g, b = rgb pixels = PixelArray(surface) for x in range(surface.get_width()): for y in range(surface.get_height()): px_colour = surface.unmap_rgb(pixels[x][y]) new_r = clamp(px_colour.r + r, 0, 255) new_g = clamp(px_colour.g + g, 0, 255) new_b = clamp(px_colour.b + b, 0, 255) pixels[x][y] = (new_r, new_g, new_b) return pixels.surface
def generate(self, width, height): """ Generate a pygame Surface with pixels following a striped pattern. :param width: the width of the generated surface :param height: the height of the generated surface :return: the pygame Surface """ surface = Surface((width, height), SRCALPHA) pxarray = PixelArray(surface) for i in range(width): for j in range(height): l = np.sqrt(i**2 + j**2) * np.cos( np.arctan((j + 1) / (i + 1)) - self.angle) r = l % sum(self.lengths) for mode, d in enumerate(np.cumsum(self.lengths)): if r < d: pxarray[i, j] = self.colors[mode] break return surface
def main(): rect = Rect((0, 0), SCREEN_SIZE) surface = Surface(SCREEN_SIZE) pxarray = PixelArray(surface) P = [(0, 100), (100, 0), (200, 0), (300, 100), (400, 200), (500, 200), (600, 100), (400, 400), (700, 50), (800, 200)] n = len(P) - 1 # n = len(P) - 1; (P[0], ... P[n]) k = 3 # degree of curve m = n + k + 1 # property of b-splines: m = n + k + 1 _t = 1 / (m - k * 2) # t between clamped ends will be evenly spaced # clamp ends and get the t between them t = k * [0] + [t_ * _t for t_ in xrange(m - (k * 2) + 1)] + [1] * k S = Bspline(P, t, k) # insert a knot (just to demonstrate the algorithm is working) S.insert(0.9) step_size = 1 / STEP_N for i in xrange(STEP_N): t_ = i * step_size try: x, y = S(t_) # if curve not defined here (t_ is out of domain): skip except AssertionError: continue x, y = int(x), int(y) pxarray[x][y] = (255, 0, 0) del pxarray for p in zip(S.X, S.Y): draw.circle(surface, (0, 255, 0), p, 3, 0) SCREEN.blit(surface, (0, 0)) while 1: for ev in event.get(): if ev.type == KEYDOWN: if ev.key == K_q: exit() display.update()
def as_pixel_array(self): return PixelArray(self._image)
def replaceColor(self, color, dist=0, replace=(0, 0, 0, 0)): "Change a color to transparent or an alternative color" img = self.convert(True) if self.bits < 32 else self.clone() PixelArray(img.surface).replace(color, replace, dist) return img
for char in range(len( char_list)): # convert all chars into 3-piece strings to be injected while len(char_list[char]) != largest_char: char_list[char] = '0' + char_list[char] char_list.insert(0, str(len(char_list))) char_list.insert( 0, str(len(str(len(char_list)))) ) # adds the number of digits, so the revealer can know how much we're looking at char_list.insert(0, str(largest_char)) print('Digits:', len(str(len(char_list)))) char_list = [c for char in char_list for c in char] arr = PixelArray( image.load(img)) # load the specified image as an integer array width = len(arr) height = len(arr[0]) if width * height < len(char_list): print('The image is not large enough') sys.exit() x = 0 y = 0 for char in char_list: str_pix = str(arr[x][y]) str_pix = str_pix[:-1] + char if int(str_pix) > 16777215:
def animate(self, direction, position, repeat, special_render_item, render_single_frame=None, finished=False): if not self.finished and not finished: if special_render_item and 'sound' in special_render_item: if self.sound_playing != sound_cache[ special_render_item['sound']]: self.sound_play_start = 9999999999 self.sound_playing = sound_cache[special_render_item['sound']] self.play_animation_sound( sound_cache[special_render_item['sound']]) else: if self.sound_playing != self.sound: self.sound_play_start = 9999999999 self.sound_playing = self.sound self.play_animation_sound(self.sound) self.cycletime += config.clock animation_size = len(self.image_list[direction]) if animation_size > 0: if self.cycletime > self.interval[self.render_idx]: self.cycletime = 0 if self.render_idx + 1 == animation_size: if repeat == -1: self.render_idx = (self.render_idx + 1) % animation_size elif self.repeat + 1 < repeat: self.render_idx = (self.render_idx + 1) % animation_size self.repeat += 1 elif self.repeat + 1 == repeat: self.repeat = 0 self.finish() else: self.render_idx = (self.render_idx + 1) % animation_size render_image = None if render_single_frame is not None: self.render_idx = render_single_frame if self.image_list[direction][self.render_idx] is not None: render_image = self.image_list[direction][ self.render_idx].copy() if finished: tmp = image.load("image/mask/finished.bmp").convert() render_image.blit(tmp, (0, 0), None, BLEND_RGBA_MULT) if special_render_item and 'mask' in special_render_item: pixel_array = PixelArray( map_image_cache[special_render_item['mask']]) render_image_pixel_array = PixelArray(render_image) for i in range(len(render_image_pixel_array)): for j in range(len(render_image_pixel_array[0])): if pixel_array[i][j] != map_image_cache[ special_render_item['mask']].map_rgb( 247, 0, 255): render_image_pixel_array[i][j] = Color( 247, 0, 255, 0) render_image = render_image.convert_alpha() render_image.set_colorkey(self.color_key) render_queue.append((0, render_image, position))
import computer WIDTH = 800 HEIGHT = 800 GRID_SIZE = 4 # pixel size of one little square in the game grid # convert pixel coordinates to grid coords def screen_to_grid(x, y): return round(x / GRID_SIZE), round(y / GRID_SIZE) trails = PixelArray(Surface(screen_to_grid(WIDTH, HEIGHT))) bike1 = Actor('bike1') bike2 = Actor('bike2') bike1.colour = (252, 186, 3) # yellow / orange bike2.colour = (0, 255, 255) # cyan bike1.is_computer = False # <-- human or AI bike2.is_computer = True # <-- human or AI # maps a direction to (angle, velocity, reverse) tuple directions = { 'right': (0, (GRID_SIZE, 0), 'left'), 'up': (90, (0, -GRID_SIZE), 'down'), 'left': (180, (-GRID_SIZE, 0), 'right'), 'down': (270, (0, GRID_SIZE), 'up'),
from pygame import image, PixelArray import sys img = sys.argv[1] arr = PixelArray(image.load(img)) max_size = int(str(arr[0][0])[-1]) digits = int(str(arr[0][1])[-1]) print(digits) length = '' for i in range(2, digits + 2): length += str(arr[0][i])[-1:] length = int(length) print('Length:', length) height = len(arr[0]) word = '' x = 0 y = digits + 2 char_buffer = '' for i in range(length * max_size + 1): if len(char_buffer) == max_size: print('Decoding character:', char_buffer) word += chr(int(char_buffer)) char_buffer = '' char_buffer += str(arr[x][y])[-1:]