コード例 #1
1
ファイル: _shadow.py プロジェクト: YannThorimbert/ThorPy-1.0
 def _get_raw_shadow(self):
     target_img = self.target.get_image(self.capture_state)
     r = target_img.get_rect()
     #the shadow will be larger in order to make free space for fadeout.
     r.inflate_ip(2*self.shadow_radius, 2*self.shadow_radius)
     img = Surface(r.size)
     img.fill((255, 255, 255, 255))
     img.blit(target_img, (self.shadow_radius, self.shadow_radius))
     if self.sun_angle <= 0.:
         raise Exception("Sun angle must be greater than zero.")
     elif self.sun_angle != 45. and self.vertical:
         w, h = img.get_size()
         new_h = h / tan(self.sun_angle * pi / 180.)
         screen_size = functions.get_screen().get_size()
         new_h = abs(int(min(new_h, max(screen_size))))
         img = scale(img, (w, new_h))
     if self.angle_mode == "flip":
         img = flip(img, self.mode_value[0], self.mode_value[1])
     elif self.angle_mode == "rotate":
         img = rotate(img, self.mode_value)
     else:
         raise Exception("angle_mode not available: " + str(self.angle_mode))
     shadow = pilgraphics.get_shadow(img,
                                     radius=self.shadow_radius,
                                     black=self.black,
                                     alpha_factor=self.alpha_factor,
                                     decay_mode=self.decay_mode,
                                     color=self.color)
     return shadow
コード例 #2
0
ファイル: player.py プロジェクト: jlevey3/CS112-Spring2012
class Player(Sprite):
    color = 255,25,69
    size = 20,20

    def __init__(self, loc, bounds):
        Sprite.__init__(self) #makes player a sprite object

        self.image = Surface(self.size)
        self.rect = self.image.get_rect() 

        self.rect.center = loc
        self.bounds = bounds

        self.image.fill(self.color)
        self.bullets = Group()

    def update(self):
        self.rect.center = pygame.mouse.get_pos() #player moves/stays with mouse
        self.rect.clamp_ip(self.bounds) #cant leave screen bounds

    def shoot(self):
        if not self.alive():
            return #stop doing anything in this function
        bullet = Bullet(self.bounds)
        bullet.rect.midbottom = self.rect.midtop 
        self.bullets.add(bullet)
コード例 #3
0
ファイル: client_main.py プロジェクト: apsmi/PyTanks
def window_init(width, height, color, caption):
    display = (width, height)                   # Группируем ширину и высоту в одну переменную
    screen = pygame.display.set_mode(display)   # Создаем окошко
    pygame.display.set_caption(caption)         # Пишем в шапку
    bg = Surface((width,height))                # Создание видимой поверхности, будем использовать как фон
    bg.fill(Color(color))                       # Заливаем поверхность сплошным цветом
    return bg, screen
コード例 #4
0
ファイル: matris.py プロジェクト: noiron/NotingImportant
    def block(self, color, shadow = False):
        colors = {'blue':   (27, 34, 224),
                  'yellow': (225, 242, 41),
                  'pink':   (242, 41, 195),
                  'green':  (22, 181, 64),
                  'red':    (204, 22, 22),
                  'orange': (245, 144, 12),
                  'cyan':   (10, 255, 226)}

        if shadow:
            end = [40]  # end is the alpha value
        else:
            end = []    # Adding this to the end will not change the array, thus no alpha value

        border = Surface((self.blocksize, self.blocksize), pygame.SRCALPHA, 32)
        border.fill(map(lambda c: c*0.5, colors[color]) + end)

        borderwidth = 2

        box = Surface((self.blocksize-borderwidth*2, self.blocksize-borderwidth*2),
                        pygame.SRCALPHA, 32)
        boxarr = pygame.PixelArray(box)
        for x in range(len(boxarr)):
            for y in range(len(boxarr)):
                boxarr[x][y] = tuple(map(lambda c: min(255, int(c*random.uniform(0.8, 1.2))),
                                    colors[color]) + end)

        del boxarr # deleting boxarr or else the box surface will be 'locked' or something like that and won't blit
        border.blit(box, Rect(borderwidth, borderwidth, 0, 0))

        return border
コード例 #5
0
ファイル: __init__.py プロジェクト: chriskoerner/PyTagCloud
def create_tag_image(
        tags, 
        file, 
        size=(800, 600), 
        background=(255, 255, 255), 
        layout=LAYOUT_MIX, 
        crop=True, 
        fontname=DEFAULT_FONT,
        palette=DEFAULT_PALETTE, 
        fontzoom=2, 
        rectangular=False):
    """
    Create a png tag cloud image
    """
    image_surface = Surface(size, SRCALPHA, 32)
    image_surface.fill(background)
    tag_store = _draw_cloud(tags, image_surface, layout, fontname=fontname, palette=palette, fontzoom=fontzoom, rectangular=rectangular)

    if crop:
        boundingRect = _get_group_bounding(tag_store, size)
        crop_surface = Surface((boundingRect.width, boundingRect.height), pygame.SRCALPHA, 32)
        crop_surface.blit(image_surface, (0, 0), area=boundingRect)
        pygame.image.save(crop_surface, file)
    else:
        pygame.image.save(image_surface, file)
コード例 #6
0
ファイル: Common.py プロジェクト: bashkirtsevich/Port-Tales
def reset_screen(img_file=None, color=BACKGROUND_COLOR):
    # Test display
    if not pyg.display.get_init():
        pyg.init()
    # Init screen
    flag = pyg.FULLSCREEN #| pyg.DOUBLEBUF | pyg.HWSURFACE
    flag *=  Constants.FULLSCREEN
    flag |= pyg.NOFRAME * NOFRAME
    screen = pyg.display.set_mode(WINDOW_SIZE, flag)
    ico = load_image(ICON_FILE).convert_alpha()
    pyg.display.set_icon(ico)
    pyg.display.set_caption(WINDOW_TITLE)
    # Build background
    background = Surface(WINDOW_SIZE)
    background.fill(color)
    # Get background
    if isinstance(img_file, basestring):
        image = load_image(img_file).convert_alpha()
        width = int(WINDOW_WIDTH * REDUCE_FACTOR)
        height = int(WINDOW_HEIGHT *REDUCE_FACTOR)
        image = pyg.transform.smoothscale(image, (width,height))
        center = WINDOW_WIDTH/2, WINDOW_HEIGHT/2
        background.blit(image, image.get_rect(center=center))
    # Apply background
    screen.blit(background, background.get_rect())
    pyg.display.flip()
    # Return screen
    return screen, background
コード例 #7
0
ファイル: join_images.py プロジェクト: Eronarn/libRPG
def join_files(target, sources, images_per_line):
    lines = len(sources) / images_per_line
    if len(sources) % images_per_line != 0:
        lines += 1
    first = pygame.image.load(sources[0])
    w, h = first.get_width(), first.get_height()

    result = Surface((w * images_per_line, h * lines)).convert_alpha()
    result.fill((255, 255, 255, 0))

    for i, source in enumerate(sources):
        im = pygame.image.load(source)
        im.convert_alpha()
        if im.get_width() != w or im.get_height() != h:
            print 'Image %s is not of the same size as the first'
            exit()

        x = w * (i % images_per_line)
        y = h * (i / images_per_line)
        result.blit(im, (x, y))
    # bg = Surface((640, 480), depth=32)
    # bg.convert_alpha()
    # bg.fill((255, 0, 0))
    # bg.blit(result, (0, 0))
    # d.blit(bg, (0, 0))
    # pygame.display.flip()
    # raw_input()
    pygame.image.save(result, target)
コード例 #8
0
class MortarTower(Tower):
    def __init__(self, pos):
        Tower.__init__(self, pos)
        self.name = "Mortar Tower"
        self.image = Surface((40, 40)).convert()
        self.image.fill((0, 0, 255))
        self.projectile = Surface((15, 15)).convert()
        self.projectile.fill((255, 150, 0))
        self.projectile_speed = 3

        self.radius = 300
        self.fire_rate = 3
        self.damage = 15
        self.description = "A long-range tower that fires mortars which " \
                           "explode on impact, dealing damage to all nearby enemies."
        self.cost = 75

        self.frame = TowerFrame(self)

    def update_info(self):
        self.frame = TowerFrame(self)

    def upgrade(self):
        if self.level < 5:
            self.damage += 5
            self.radius += 10
            self.projectile_speed += 0.25
            self.level += 1
            self.update_info()
            return True
        return False
コード例 #9
0
class RoboImages(Sprite):
    color = 0,0,0
    size = 60,60
    def __init__(self, parent):
        Sprite.__init__(self)
        self.parent = parent
        self.name = parent.name
        if parent.name == "baby":
            self.size = 40,40
        self.color = parent.color
        self.image = Surface(self.size)
        self.rect = self.image.get_rect()
        self.rect.centerx = self.parent.rect.centerx
        self.rect.centery = self.parent.rect.centery
        self.dir = dir
        
    

        try:
            self.image = load_image(self.name+'bot')
            print "found family sprite"
        except:
            self.image.fill(self.color)
            print "failed to load family image"
        
        
        self.image = pygame.transform.scale(self.image, self.size)
        self.image.set_colorkey((255,255,255))
        
   
    def update(self):
        self.rect.center = self.parent.rect.center
        if not self.parent.alive():
            self.kill()
コード例 #10
0
ファイル: player.py プロジェクト: sgoodspeed/samKeenanGame
class Player(Sprite):

    def __init__(self, bounds):
        Sprite.__init__(self)

        self.bounds = bounds

        self.image = Surface((80, 80))
        self.rect = self.image.get_rect()

        self.image.fill((0,0,0))
        self.image.fill(PLAYER_COLOR, self.rect.inflate(-4,-4))

        self.x, self.y = bounds.center
        self.vx = PLAYER_SPEED
        self.vy = PLAYER_SPEED

    def update(self, dt):
        dt = dt / 1000.0
        keys = pygame.key.get_pressed()
        if keys[K_UP]:
            self.y -= self.vy * dt
        if keys[K_DOWN]:
            self.y += self.vy * dt
        if keys[K_LEFT]:
            self.x -= self.vx * dt
        if keys[K_RIGHT]:
            self.x += self.vx * dt

        # update player 
        self.rect = self.image.get_rect()
        self.rect.center = int(self.x), int(self.y)
        self.rect.clamp_ip(self.bounds)
コード例 #11
0
class Impact(Meteor):
    size = (100,100)
    COLOR = 0,140,0
    duration = 5
    def __init__(self,loc, bounds, duration, kind):
        
        #print "explosion!"
        
        # Ice should have moving impacts
        Sprite.__init__(self)
        self.image = Surface(self.size)
        self.rect = self.image.get_rect()
        self.rect.center = loc
        self.image.fill(self.COLOR)
        self.bounds = bounds
        self.duration = duration
        self.kind = kind
        if kind == "rock":
            self.duration = 10
    def update(self):
        self.duration -= 1
        if self.duration <= 0:
            self.coord_x, self.coord_y = self.rect.center
            self.kill()
            
    #def collision(self, robot):
        
        
    def kill (self):
        Sprite.kill(self)
コード例 #12
0
ファイル: LemonadeGui.py プロジェクト: FOSSRIT/lemonade-stand
    def _blit_to_block(self, text_array, text_color=(255, 255, 255),
                       block_color=(0, 0, 0)):
        """
        Takes an array of strings with optional text and background colors,
        creates a Surface to house them, blits the text and returns the
        Surface.
        """

        rendered_text = []
        font_width = []
        font_height = []

        for text in text_array:
            ren = self.__font.render(text, True, text_color)
            rendered_text.append(ren)
            fw, fh = ren.get_size()
            font_width.append(fw)
            font_height.append(fh)

        block = Surface((max(font_width) + 20, sum(font_height) + 20))
        block.fill(block_color)

        h = 10
        for text in rendered_text:
            block.blit(text, (10, h))
            h += font_height[0]

        return block
コード例 #13
0
ファイル: __init__.py プロジェクト: Xpitfire/wordcloud
def create_tag_image(
        tags, 
        output, 
        size=(500,500), 
        background=(255, 255, 255), 
        layout=LAYOUT_MIX, 
        fontname=DEFAULT_FONT,
        rectangular=False):
    """
    Create a png tag cloud image
    """
    
    if not len(tags):
        return
    
    sizeRect, tag_store = _draw_cloud(tags,
                                      layout,
                                      size=size, 
                                      fontname=fontname,
                                      rectangular=rectangular)
    
    image_surface = Surface((sizeRect.w, sizeRect.h), SRCALPHA, 32)
    image_surface.fill(background)
    for tag in tag_store:
        image_surface.blit(tag.image, tag.rect)
    pygame.image.save(image_surface, output)
コード例 #14
0
class Bomb(Sprite):
    width = 10
    height = 10
    color = 0,200,255
    fuse = 3000

    def __init__(self, pos):
        self.image = Surface((self.width, self.height))
        self.image.fill(self.color)

        self.rect = Rect(0,0,self.width, self.height)
        self.rect.center = pos

        self.time = fuse

    def update(self, dt):
        self.time -= dt
        step = self.time / 500

        if step % 2 == 0:
            color = 255,255,0
        else:
            color = 255,0,0

        self.image.fill(color, self.rect.inflate(-self.width/2, self.height/2))
コード例 #15
0
class Shield(Sprite):
    color = 255,255,255
    transparent = 0,0,0
    size = 120,120
    kind = "null"
    
    def __init__(self, parent, kind):
        self.parent=parent
        Sprite.__init__(self)
        self.kind = kind
        self.hiss_sfx = load_sfx("hiss")
        if kind == "baseball":
            self.color = 0,90,90
        elif kind == "cigar":
            self.color = 255,100,0
        elif kind == "health":
            self.color = 180, 200, 180
        self.image = Surface(self.size)
        self.rect = self.image.get_rect()
        self.rect.center = self.parent.rect.center
        self.image.fill(self.transparent)
        self.image.set_colorkey(self.transparent)
        pygame.draw.ellipse(self.image, (self.color), self.image.get_rect())
        pygame.draw.ellipse(self.image, self.transparent, self.image.get_rect().inflate(-10, -10))
        #pygame.draw.ellispe(self.image, (30,255,30), self.rect.center, ((self.rect.width)/2))
            
    def update(self):
        
        if not self.parent.alive():
            self.kill()
        
        self.rect.center = self.parent.rect.center
コード例 #16
0
ファイル: player.py プロジェクト: AKilgore/CS112-Spring2012
class Player(Sprite):
    color = 255, 255, 0
    size = 20, 20
    
    def __init__(self, loc, bounds):
        Sprite.__init__(self)

        self.image = Surface(self.size)
        self.rect = self.image.get_rect()

        self.rect.center = loc
        self.bounds = bounds

        self.image.fill(self.color)
        self.bullets = Group()

    def update(self):
        self.rect.center = pygame.mouse.get_pos()
        self.rect.clamp_ip(self.bounds)

    def shoot(self):
        if not self.alive():
            return

        bullet = Bullet(self.bounds)
        bullet.rect.midbottom = self.rect.midtop
        self.bullets.add(bullet)
コード例 #17
0
ファイル: enemy.py プロジェクト: nigelgant/CS112-Spring2012
class Enemy(Sprite):
    size = width,height = 50,50
    color = 255,0,0
    vx, vy = 6,6

    def __init__(self,loc,bounds):
        Sprite.__init__(self)
        self.image = Surface(self.size)
        self.rect = self.image.get_rect()
        self.bounds = bounds


        self.image.fill(self.color)
        self.rect.bottomleft = loc

        self.vx = randrange(4,8)
        direction = 2 * randrange(2)- 1
        self.vx *= direction

    def update(self):
        self.rect.x += self.vx
        self.rect.y += self.vy

        if self.rect.left < self.bounds.left or self.rect.right > self.bounds.right:
            self.rect.x -= 2 * self.vx
            self.vx = -self.vx

        if self.rect.top > self.bounds.bottom:
            self.kill()
コード例 #18
0
ファイル: gameobject.py プロジェクト: theihor/cytadels
    def highlight(self):
        if not self.highlighted:
            (x, y) = self.pos()
            (w, h) = self.rect.size
            (lw, lh) = (round(w * 1.5), round(h * 1.5))

            img = Surface((lw, lh), pygame.SRCALPHA)
            img.fill(COLOR_WHITE)
            a = surfa.pixels_alpha(img)
            d = max(lw, lh) / 2
            (cx, cy) = (lw // 2, lh // 2)

            for i in range(len(a)):
                for j in range(len(a[i])):
                    k = math.sqrt(sqr(100.0 * (i - cx) / cx) + sqr(100.0 * (j - cy) / cy))
                    if k > 100: a[i][j] = 0
                    else: a[i][j] = 255 - round(k / 100.0 * 255.0)

            a = None

            img.blit(self.image, ((lw - w) // 2, (lh - h) // 2))
            self.image = img

            self.set_pos(x - (lw - w) // 2, y - (lh - h) // 2)
            self.highlighted = True
コード例 #19
0
ファイル: Player.py プロジェクト: LoganStalker/second_season
class Player(Sprite):
    def __init__(self, x, y):
        Sprite.__init__(self)
        self.image = Surface((22, 32))
        self.image.fill((150, 150, 150))
        self.xvel = 0
        self.yvel = 0
        self.x = x
        self.y = y
        self.onGroung = False

    def update(self, left, right):
        if left:
            self.xvel = -MOVE_SPEED
        if right:
            self.xvel = MOVE_SPEED
        if not(left or right):
            self.xvel = 0

        if not self.onGroung:
            self.yvel += GRAVITY

        self.x += self.xvel
        self.y += self.yvel

    def draw(self, surf):
        surf.blit(self.image, (self.x, self.y))
コード例 #20
0
ファイル: game.py プロジェクト: sgoodspeed/CS112-Spring2012
class Enemy(Sprite):
    width = 40
    height = 40
    
    y = -40
    
    def __init__(self):
        self.x = randrange(0,scrWidth-self.width)
        Sprite.__init__(self)

        #Self.rect and self.image
        self.rect = Rect((self.x,self.y),(self.width,self.height))
        self.image = Surface(self.rect.size)
        self.image.fill((0,0,0))
        self.image.set_colorkey((0,0,0))

        #Draw stuff
        pygame.draw.ellipse(self.image,red,self.image.get_rect())
        pygame.draw.ellipse(self.image,blue2,self.image.get_rect(),15)

        #Randomly picking trajectory
        self.down = randrange(1,5)
        self.side = randrange(-6,6,4)
    def update(self):
        "Movement behavior"
        
        self.rect.y += self.down
        self.rect.x += self.side
        
        if self.rect.right > scrWidth or self.rect.left < 0:
            self.side *=-1
        if self.rect.top > scrHeight:
            self.kill()
コード例 #21
0
ファイル: tower.py プロジェクト: brandr/Tower_Defense
	def rotated_bolt_image(self, angle):
		image = Surface((32, 32))
		image.set_colorkey(DEFAULT_COLORKEY)
		image.fill(DEFAULT_COLORKEY)
		image.blit(self.projectile_image, (0, 0))
		image = pygame.transform.rotate(image, angle)
		return image
コード例 #22
0
ファイル: tower.py プロジェクト: brandr/Tower_Defense
	def load_transparent_image(self):
		image = Surface((32, 32))
		image.fill(DEFAULT_COLORKEY)
		image.set_colorkey(DEFAULT_COLORKEY)
		image.blit(self.image, (0, 0))
		image.set_alpha(120)
		self.transparent_image = image
コード例 #23
0
ファイル: recolor.py プロジェクト: roSievers/Orbital4
def compileSVASheet(sheet, color):
    color = tuple([255-c for c in color])
    
    width = sheet.get_width()
    height = sheet.get_height() / 3
    
    colorSurf = Surface((width, height))
    colorSurf.fill(color)
    
    colorSurf.blit(sheet, (0, 0), None, BLEND_MULT)
    
    # Now create a white surface so we can invert the Saturation map
    result = Surface((width, height), SRCALPHA)
    result.fill((255, 255, 255))
    
    result.blit(colorSurf, (0, 0), None, BLEND_RGB_SUB)
    
    # Multiply this with the Value Map
    result.blit(sheet, (0, -height), None, BLEND_MULT)
    
    # copy the alpha mask from the spritesheet
    alpha = Surface((width, height))
    alpha.blit(sheet, (0, -2 * height))
    
    #convert the (nearly done) Surface to per pixel alpha
    result.convert_alpha()
    
    # Use Numpy here
    numWhite = surfarray.pixels_alpha( result )
    
    numAlpha = surfarray.pixels3d( alpha )
    
    numWhite[ :, : ] = numAlpha[ :, :, 0 ]
    
    return result.copy()
コード例 #24
0
ファイル: matris.py プロジェクト: noiron/NotingImportant
    def main(self, screen):
        clock = pygame.time.Clock()
        background = Surface(screen.get_size())

        background.blit(construct_nightmare(background.get_size()), (0, 0))

        self.matris = Matris()
        matris_border = Surface((MATRIX_WIDTH * BLOCKSIZE + BORDERWIDTH * 2,
                                VISIBLE_MATRIX_HEIGHT * BLOCKSIZE + BORDERWIDTH * 2))
        matris_border.fill(BORDERCOLOR)

        while 1:
            dt = clock.tick(45)
            self.matris.update((dt / 1000.) if not self.matris.paused else 0)
            if self.matris.gameover:
                return

            tricky_centerx =  WIDTH - (WIDTH - (MATRIS_OFFSET + BLOCKSIZE *
                            MATRIX_WIDTH + BORDERWIDTH * 2)) / 2

            background.blit(matris_border, (MATRIS_OFFSET, MATRIS_OFFSET))
            background.blit(self.matris.surface, (MATRIS_OFFSET + BORDERWIDTH, 
                            MATRIS_OFFSET + BORDERWIDTH))

            nextts = self.next_tetromino_surf(self.matris.surface_of_next_tetromino)
            background.blit(nextts, nextts.get_rect(top = MATRIS_OFFSET, 
                                centerx = tricky_centerx))

            infos = self.info_surf()
            background.blit(infos, infos.get_rect(bottom = HEIGHT - MATRIS_OFFSET,
                                centerx = tricky_centerx))

            screen.blit(background, (0, 0))
            pygame.display.flip()
コード例 #25
0
ファイル: ships.py プロジェクト: sambwhit/CS112-Spring2012
class Ship(Sprite):
    width = 20
    height = 20

    def __init__(self, x, y, vx, vy, bounds, color):
        Sprite.__init__(self)

        self.vx = vx
        self.vy = vy
        self.bounds = bounds
        self.color = color

        self.rect = Rect(x, y, self.width, self.height)
        self.image = Surface(self.rect.size)
        self.draw_image()
        
    def draw_image(self):
        self.image.fill(self.color)

    def update(self, dt):
        dt /= 1000.0
        dx = int(self.vx * dt)
        dy = int(self.vy * dt)
        self.rect.x += dx
        self.rect.y += dy
コード例 #26
0
ファイル: desc.py プロジェクト: tps12/Dorftris
    def _makebackground(self, size):
        self._renderer = TextRenderer(self._font, size[0])

        bg = Surface(size, flags=SRCALPHA)
        bg.fill((0,0,0))

        dy = 0
        bg, dy = self._addline(bg,
                           self._creature.physical(),
                           (255,255,255),
                           dy)
        appetites = self._creature.appetitereport()
        if appetites:
            bg, dy = self._addline(bg,
                               appetites,
                               (255,255,255),
                               dy)
        inventory = self._creature.inventoryreport()
        if inventory:
            bg, dy = self._addline(bg,
                               inventory,
                               (255,255,255),
                               dy)

        self._background = Surface(size, flags = bg.get_flags())
        
        self._scroll.draw(self._background, bg)
コード例 #27
0
ファイル: neighborhood.py プロジェクト: tps12/Dorftris
    def makebackground(self, surface):
        surface.fill((0,0,0))
        
        template = Surface(2*(min(self.zoom.width, self.zoom.height),))
        template.fill((0,0,0,255))
        width,height = template.get_size()

        ylim = surface.get_height()/height
        xlim = surface.get_width()/width

        data = self._data
        noise = [[pnoise2(self._selected[1][0]+x,
                          self._selected[0][0]+y,
                          4, 0.85) * 50
                  for x in range(xlim)]
                 for y in range(ylim)]

        hmin = hmax = 0
        for y in range(ylim):
            for x in range(xlim):
                yd = len(data)*float(y)/ylim
                xd = len(data[0])*float(x)/xlim

                h = self._height(data, yd, xd)
                n = noise[y][x]
                if h < 0:
                    h += -n if n > 0 else n
                else:
                    h += n if n > 0 else -n
                if h < hmin:
                    hmin = h
                if h > hmax:
                    hmax = h

        self.rects = []
        for y in range(ylim):
            for x in range(xlim):
                block = template.copy()
                yd = len(data)*float(y)/ylim
                xd = len(data[0])*float(x)/xlim

                h = self._height(data, yd, xd)
                n = noise[y][x]
                if h < 0:
                    h += -n if n > 0 else n
                else:
                    h += n if n > 0 else -n
                if h < 0:
                    color = 0, 0, int(255 * (1 - h/hmin))
                else:
                    color = 0, int(255 * h/hmax), 0
                block.fill(color)
                if self.selection:
                    if self.selection[0][0] <= yd <= self.selection[0][1]:
                        if self.selection[1][0] <= xd <= self.selection[1][1]:
                            block.fill((255,0,0,32),
                                       special_flags = BLEND_ADD)
                rect = Rect(x*width, y*height, width, height)
                surface.blit(block, rect.topleft)
                self.rects.append((rect, (yd, xd)))
コード例 #28
0
ファイル: LemonadeGui.py プロジェクト: FOSSRIT/lemonade-stand
    def ingredient_count(self, items, money):
        # sides are at 650 and 675
        #            /1200    /900
        #            13/24   27/36
        ingredient_block = Surface((self.game_engine.width * 11/24,
                                    self.game_engine.height * 9/36))
        ingredient_block.fill((255, 255, 255))
        
        icon_size = int(ingredient_block.get_width() / (len(items) * 1.5))
        icon_width = ingredient_block.get_width() / len(items)
        j = icon_size / 3
        render_top = 15 + icon_size
        for name, count in items.items():
            icon = image.load("images/icon-%s.gif" % name).convert()
            icon = transform.scale(icon, (icon_size, icon_size))
            ingredient_block.blit(icon, (j, 10))

            # Put an item count under the icon.
            ren = self.__font.render(str(count), True, (0, 0, 0))
            fw, fh = ren.get_size()
            render_left = j + (icon_size / 2) - (fw / 2)
            ingredient_block.blit(ren, (render_left, render_top))
            j += icon_width

        ren = self.__font.render("Funds: %s" % format_money(money), True, (0, 0, 0))
        fw, fh = ren.get_size()
        render_left = ingredient_block.get_width() / 2 - fw / 2
        render_top = (ingredient_block.get_height() - render_top) / 2 + render_top
        ingredient_block.blit(ren, (render_left, render_top))

        return ingredient_block
コード例 #29
0
ファイル: view.py プロジェクト: YoannQDQ/pyweek-dojo
 def get_image(self):
     """Draw the rectange on a transparent surface."""
     img = Surface(self.rect.size).convert_alpha()
     img.fill((0, 0, 0, 0), special_flags=pg.BLEND_RGBA_MULT)
     draw.rect(img, self.model.color, img.get_rect(), 1)
     img.fill((255, 255, 255, 128), special_flags=pg.BLEND_RGBA_MULT)
     return img
コード例 #30
0
class Impact(Meteor):
    size = (100,100)
    COLOR = 0,140,0
    duration = 5
    dir = 0
    damage = 10
    
    def __init__(self,loc, bounds, duration, kind, dir = 0):
        
        #print "explosion!"
        self.dir = dir
        # Ice should have moving impacts
        Sprite.__init__(self)
        self.image = Surface(self.size)
        self.rect = self.image.get_rect()
        self.rect.center = loc
        self.image.fill(self.COLOR)
        self.bounds = bounds
        self.duration = duration
        self.kind = kind
        self.get_sprite()
        self.get_sound()
        self.impact_sfx.stop()

        self.impact_sfx.play()
    def get_sprite(self):
        #return

        #-----------This will attempt to load an image, and fill if it fails.
        try:
            self.image = load_image('explosion_'+self.kind)
            print "impact explosion yay"
        except:
            self.image.fill(self.COLOR)
            print "failed to find explosion"
        #Scale the image to the proper size and add random rotation
        #if randint(0,2) == 0:
        #    self.image = pygame.transform.flip(self.image, True, False)
        #self.image = pygame.transform.rotate(self.image, randint(-360,360))
        
        self.image = pygame.transform.scale(self.image, self.size) #temp
        #Anything that's pure white will be transparent
        self.image.set_colorkey((255,255,255))
        #-------
        
    def get_sound(self):
         self.impact_sfx = load_sfx("stockmeteorhit")
        
        
    def update(self):
        self.duration -= 1
        if self.duration <= 0:
            self.coord_x, self.coord_y = self.rect.center
            self.kill()
            
    #def collision(self, robot):
        
        
    def kill (self):
        Sprite.kill(self)
コード例 #31
0
    def main(self, screen):
        """
        Main loop for game
        Redraws scores and next tetromino each time the loop is passed through
        """
        clock = pygame.time.Clock()
        self.matris = Matris()

        screen.blit(construct_nightmare(screen.get_size()), (0, 0))

        matris_border = Surface(
            (MATRIX_WIDTH * BLOCKSIZE + BORDERWIDTH * 2,
             VISIBLE_MATRIX_HEIGHT * BLOCKSIZE + BORDERWIDTH * 2))
        matris_border.fill(BORDERCOLOR)
        screen.blit(matris_border, (MATRIS_OFFSET, MATRIS_OFFSET))

        self.redraw()

        while True:
            try:
                timepassed = clock.tick(50)
                if self.matris.update((
                        timepassed / 1000.) if not self.matris.paused else 0):
                    try:
                        self.redraw()
                    except:
                        print(
                            "Error when placing agent tetromino. Starting a new game."
                        )
                        for line in range(
                                0, len(self.matris.agent.agent_tetromino[0])):
                            print(
                                str(self.matris.agent.agent_tetromino[0]
                                    [line]))
                        self.matris.gameover()
            except GameOver:
                return
コード例 #32
0
class IntroScreen():
    def __init__(self):
        self.size = pygame.display.get_surface().get_size()
        self.bg = Color(69, 139, 116)

        #Homework-specific code
        self.surf_size = (50, 50)
        self.surf = Surface(self.surf_size, pygame.SRCALPHA)
        #We're hard-coding the colour because it will be used only once
        self.surf.fill(Color(0, 0, 0, 0))
        self.rect = self.surf.get_rect()
        #creating arbitrary colour
        t = Color(186, 116, 139)
        pygame.draw.circle(self.surf, t, self.rect.center, int(self.surf_size[0]/2))
        self.rect.center = (int(self.size[0]/2), int(self.size[1]/2))

    def update(self):
        pass

    def render(self):
        temp_surf = pygame.display.get_surface()
        temp_surf.fill(self.bg)
        temp_surf.blit(self.surf, self.rect)

    def resize(self, new_size):
        self.size = new_size

        #CHALLENGE CODE
        self.surf_size = (int(new_size[0]/9), int(new_size[0]/9))
        self.surf = Surface(self.surf_size, pygame.SRCALPHA)
        #We're hard-coding the colour because it will be used only once
        self.surf.fill(Color(0, 0, 0, 0))
        self.rect = self.surf.get_rect()
        #creating arbitrary colour
        t = Color(186, 116, 139)
        pygame.draw.circle(self.surf, t, self.rect.center, int(self.surf_size[0]/2))
        self.rect.center = (int(self.size[0]/2), int(self.size[1]/2))
コード例 #33
0
class Animator(object):
    def __init__(self, file_path, size=Vector2()):
        self.size = size
        self.file_path = file_path
        self.surface = Surface(self.size.get_t, SRCALPHA)

        self.spritesheet = load_img(file_path)
        self.surface.fill((0, 0, 0, 0))
        self.flipx = False
        self.frames_rows = {}
        self.current_frames_row = None
        self.current_frame_name = None

    def add_frames_row(self, name, frames_row):
        if isinstance(frames_row, FrameRow):
            self.frames_rows[name] = frames_row
        else:
            raise TypeError('Must be FrameRow type')

    def set_row(self, row):
        if row in self.frames_rows:
            self.current_frame_name = row
            self.current_frames_row = self.frames_rows[row]
            self.current_frames_row.current_frame = 0
            self.current_frames_row.last_frame_time = 0
        else:
            raise TypeError('Must be FrameRow type')

    def draw(self):
        self.surface.fill((0, 0, 0, 0))

        self.surface.blit(self.spritesheet, (0, 0),
                          self.current_frames_row.frame)
        self.surface = flip(self.surface, self.flipx, False)

    def update_frame(self, time):
        self.current_frames_row.calculate_frame(time)
コード例 #34
0
class BunkerBlock(sprite.Sprite):
    """Represents a portion of bunker block"""
    def __init__(self, ai_settings, screen, row, col):
        super().__init__()
        self.screen = screen
        self.height = ai_settings.bunker_block_size
        self.width = ai_settings.bunker_block_size
        self.color = ai_settings.bunker_color
        self.image = Surface((self.width, self.height))
        self.image.fill(self.color)
        self.rect = self.image.get_rect()
        self.row = row
        self.col = col
        self.dmg = False

    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 update(self):
        self.screen.blit(self.image, self.rect)
コード例 #35
0
ファイル: animated_grid.py プロジェクト: graynoah/Battleships
    def _generate_animation_frames(self) -> None:
        """Create the animated grid's animation frames."""
        self._animation_frames = []
        self._square_w = self._rect.w // self._horizontal_tile_count
        self._square_h = self._rect.h // self._vertical_tile_count

        tint_surface = Surface(self._rect.size).convert_alpha()
        tint_surface.set_colorkey(None)

        if(self._style.primary_color is not None):
            tint_surface.fill(self._style.primary_color)

        if(self._style.primary_color is None and
            len(self._tiles) == 0 and
            (self._style.border_width == 0 or
             self._style.secondary_color is None)):
            return

        self._scaled_frames = []
        for i in range(len(self._raw_frames)):
            animation_frame = tint_surface.copy()
            self._scaled_frames.append(transform.smoothscale(
                self._raw_frames[i], (self._square_w, self._square_h)))

            # Draw outlines
            if(self._style.border_width > 0 and
               self._style.secondary_color is not None):

                for y in range(self._vertical_tile_count):
                    for x in range(self._horizontal_tile_count):
                        rect = Rect(self._square_w * x, self._square_h *
                                    y, self._square_w, self._square_h)
                        self._draw_outline(animation_frame, rect,
                                           self._style.secondary_color,
                                           self._style.border_width)

            self._animation_frames.append(animation_frame)
コード例 #36
0
def create_tag_image(tags,
                     output,
                     size=(1024, 768),
                     background=(255, 255, 255),
                     layout=LAYOUT_MIX,
                     fontname=DEFAULT_FONT,
                     rectangular=False):
    """
    Create a png tag cloud image
    """

    if not len(tags):
        return

    pygame.init()

    sizeRect, tag_store = _draw_cloud(tags,
                                      layout,
                                      size=size,
                                      fontname=fontname,
                                      rectangular=rectangular)

    tag_surface = Surface((sizeRect.w, sizeRect.h), SRCALPHA, 32)
    tag_surface.fill(background)
    for tag in tag_store:
        tag_surface.blit(tag.image, tag.rect)
    tag_surface = pygame.transform.scale(
        tag_surface, (int(sizeRect.w * 0.9), int(sizeRect.h * 0.9)))

    xo = int(sizeRect.w * 0.05)
    yo = int(sizeRect.h * 0.05)
    output_surface = Surface((sizeRect.w, sizeRect.h), SRCALPHA, 32)
    output_surface.fill(background)
    output_surface.blit(tag_surface, (xo, yo))
    pygame.image.save(output_surface, output)

    pygame.quit()
コード例 #37
0
    def block(self, color, shadow=False):
        colors = {
            'blue': (47, 64, 224),
            'yellow': (225, 242, 41),
            'pink': (242, 41, 195),
            'green': (22, 181, 64),
            'red': (204, 22, 22),
            'orange': (245, 144, 12),
            'cyan': (10, 255, 226)
        }

        if shadow:
            end = [40]  # end is the alpha value
        else:
            end = [
            ]  # Adding this to the end will not change the array, thus no alpha value

        border = Surface((self.blocksize, self.blocksize), pygame.SRCALPHA, 32)
        border.fill(list(map(lambda c: c * 0.5, colors[color])) + end)

        borderwidth = 2

        box = Surface((self.blocksize - borderwidth * 2,
                       self.blocksize - borderwidth * 2), pygame.SRCALPHA, 32)
        boxarr = pygame.PixelArray(box)
        for x in range(len(boxarr)):
            for y in range(len(boxarr)):
                boxarr[x][y] = tuple(
                    list(
                        map(
                            lambda c: min(255, int(c * random.uniform(
                                0.8, 1.2))), colors[color])) + end)

        del boxarr  # deleting boxarr or else the box surface will be 'locked' or something like that and won't blit.
        border.blit(box, Rect(borderwidth, borderwidth, 0, 0))

        return border
コード例 #38
0
		def handsurf(pid, bare=False):
			handlen = len(hands[pid])
			if handlen <= 0:
				return
			padding = UNO_WIDTH // 4
			surf = Surface(
				(UNO_WIDTH * handlen + UNO_WIDTH + padding, UNO_HEIGHT),
				SRCALPHA, 32
			)
			assert surf.get_width() > 0
			surf.fill((0, 0, 0, 0))
			color = UnoCard.COLORS[discard[0].suit]
			surf.fill(color, rect=(
				UNO_WIDTH - padding // 2, 0,
				padding * 2, UNO_HEIGHT
			))
			for i, j in enumerate(hands[pid]):
				surf.blit(j.image, (UNO_WIDTH + padding + UNO_WIDTH * i, 0))
			surf.blit(discard[0].image, (0, 0))
			background(sendsurf(
				players[pid].send, surf, 'uno', 'hand.png',
				embed=embed(players[pid],
					title=('uno/hand-title',),
					description=('uno/hand', points[pid]),
					fields=((
						('uno/card-numbers-title',),
						('uno/card-numbers',),
						False
					),) if not bare else None,
					footer=(
						('uno/waiting-for-card',)
						if can_turn(pid)
						else ('uno/cannot-turn',)
					) if not bare else None,
					color=discord.Color.from_rgb(*color)
				).set_image(url='attachment://hand.png')
			))
コード例 #39
0
    def _draw(self, screen: pygame.Surface,
              changes: List[pygame.Rect]) -> None:
        """Draw the textbox's visuals to the screen. <change> is a list of
        rectangles that represent the changed areas of the screen.
        """
        Component._draw(self, screen, changes)

        text_rect = self._text_image.get_rect()
        text_rect.center = self._rect.center

        # Draw Selection Background
        if (self._has_multi_char_selection()):
            start = self._style.font.size(self.get_text()[:self._cursor_pos])
            end = self._style.font.size(
                self.get_text()[:self._selection_end_pos])

            start_x = min(start[0], end[0])
            end_x = max(start[0], end[0])

            background_rect = pygame.Rect(text_rect.x + start_x, text_rect.y,
                                          end_x - start_x, text_rect.height)
            changes.append(screen.fill((0, 0, 255), background_rect))
            Label._draw_text(self, screen, changes)
            return

        # Draw text
        Label._draw_text(self, screen, changes)

        # Draw Blinker
        if (self._is_blinker_on):
            size = self._style.font.size(self.get_text()[:self._cursor_pos])
            cursor_rect = pygame.Rect(text_rect.x + size[0], text_rect.y, 2,
                                      text_rect.height)

            if (self._rect.x < cursor_rect.x < self._rect.right):
                changes.append(
                    screen.fill(self._style.primary_color, cursor_rect))
コード例 #40
0
ファイル: extension.py プロジェクト: annie60/Xilarius
def createWarning(screen,message):

    def close():
        nonlocal tmpFrame
        tmpFrame.kill()

    # Creation
    tmpFont = font.SysFont("Arial",34)
    tmpText = tmpFont.render("!",1,(0,0,0))
    tmpFrame = Frame(screen,htitle="Warning",width=300,height=100)
    t = TypableSurface((160,90),text=message)
    tmpSurface = Surface((42,36))
    tmpButton = Button(tmpFrame,width=50,height=20,text="Ok",target=close)
    # Assembly
    tmpSurface.fill((255,255,255))
    draw.polygon(tmpSurface,(255,255,0),[(20,0),(0,35),(40,35)])
    draw.polygon(tmpSurface,(0,0,0),[(20,0),(0,35),(40,35)],3)
    tmpSurface.blit(tmpText,(16,0))
    tmpFrame.blit(tmpSurface,(2,10))
    tmpFrame.blit(t,(50,10))
    tmpButton.place((122,74))
    tmpFrame.place((screen.get_width()//2-150,screen.get_height()//2-50))

    return tmpFrame
コード例 #41
0
class Player(Sprite):
    def __init__(self, x, y):
        # чтобы связать класс игрок с классом спрайт
        Sprite.__init__(self)
        self.image = Surface((22, 22))
        self.image.fill((150, 150, 150))
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

    def update(self, left, right, up, down, boxes):
        if left:
            self.rect.x -= speed
        if right:
            self.rect.x += speed
        if up:
            self.rect.y -= speed
        if down:
            self.rect.y += speed

        self.collide(right, left, up, down, boxes)

#    def draw(self, surf):
#        surf.blit(self.image, (self.rect.x, self.rect.y))

    def collide(self, right, left, up, down, boxes):
        for bx in boxes:
            if self.rect.colliderect(bx.rect):
                if right:
                    self.rect.right = bx.rect.left
                if left:
                    self.rect.left = bx.rect.right
                if down:
                    self.rect.bottom = bx.rect.top
                if up:
                    self.rect.top = bx.rect.bottom
コード例 #42
0
    def draw(self, win: pygame.Surface) -> None:
        win.fill(MID_BLACK)

        index = self.background_index // 10
        win.blit(self.backgrounds[index], (0, 0))

        
        # win.blit(self.base, (0, 0))
        self.bird.move()
        self.bird.draw(self.win)

        for i in range(len(self.pipes) - 1, -1, -1):
            pipe = self.pipes[i]
            pipe.move()
            if pipe.isOnScreen():
                pipe.draw(win)
            else:
                self.pipes.remove(pipe)
                del pipe

        self.draw_base(self.win)
        self.draw_title(self.win)
        
        pygame.display.update()
コード例 #43
0
 def get_imgs():
     """Load an return the images used as file and folder icons."""
     print "*** MCEDIT DEBUG: file_dialog:", __file__
     print "*** MCEDIT DEBUG: directory:", os.path.dirname(__file__)
     print "*** MCEDIT DEBUG: current directory:", os.getcwd()
     try:
         file_image = get_image('file.png', prefix='')
         folder_image = get_image('folder.png', prefix='')
     except Exception as e:
         print "MCEDIT DEBUG: Could not load file dialog images."
         print e
         from pygame import draw, Surface
         from pygame.locals import SRCALPHA
         from math import pi
         file_image = Surface((16, 16), SRCALPHA)
         file_image.fill((0,0,0,0))
         draw.lines(file_image, (255, 255, 255, 255), False, [[3, 15], [3, 1], [13, 1]], 2)
         draw.line(file_image, (255, 255, 255, 255), [3, 7], [10, 7], 2)
         folder_image = Surface((16, 16), SRCALPHA)
         folder_image.fill((0,0,0,0))
         draw.line(folder_image, (255, 255, 255, 255), [3, 15], [3, 1], 2)
         draw.arc(folder_image, (255, 255, 255, 255), [0, 1, 13, 15], 0, pi/1.9, 2)
         draw.arc(folder_image, (255, 255, 255, 255), [0, 1, 13, 15], 3*pi/2, 2*pi, 2)
     return file_image, folder_image
コード例 #44
0
ファイル: animated_grid.py プロジェクト: graynoah/Battleships
    def _draw(self, screen: Surface, changes: List[Rect]) -> None:
        """Draw the animated grid's visuals to the screen. <change> is a list
        of rectangles that represent the changed areas of the screen.
        """
        AnimatedImage._draw(self, screen, changes)

        if(self.is_hovered()):
            rect = Rect(self._square_w * self._hover_pos[0] + self._rect.x,
                        self._square_h *
                        self._hover_pos[1] + self._rect.y,
                        self._square_w, self._square_h)

            changes.append(screen.fill(self._style.hover_color,
                                       rect,
                                       BLEND_RGB_MULT))
コード例 #45
0
ファイル: matris.py プロジェクト: jakehwang99/TetrisAI
    def main(self, screen, age):
        """
		Main loop for game
		Redraws scores and next tetromino each time the loop is passed through
		"""
        clock = pygame.time.Clock()
        self.matris = Matris()

        screen.blit(construct_nightmare(screen.get_size()), (0, 0))

        matris_border = Surface(
            (MATRIX_WIDTH * BLOCKSIZE + BORDERWIDTH * 2,
             VISIBLE_MATRIX_HEIGHT * BLOCKSIZE + BORDERWIDTH * 2))
        matris_border.fill(BORDERCOLOR)
        screen.blit(matris_border, (MATRIS_OFFSET, MATRIS_OFFSET))

        timewait = 0
        print("session:" + str(age))
        if age % 100 == 0:
            timewait = 0.5
        else:
            timewait = 0.0001

        learn = learner.Learner(self.matris, self, timewait)
コード例 #46
0
    def get_sprite(self):
        # if state is name of sprite, return it
        if self.state in self.sprites:
            if self.direction == 1:
                return self.sprites[self.state]
            elif self.direction == -1:
                return flip(self.sprites[self.state], 1, 0)
        # otherwise, find the most recent animation frame
        f = self.frame
        while f >= 0:
            name = self.state + ":" + str(f)
            if name in self.sprites:
                if self.direction == 1:
                    return self.sprites[name]
                elif self.direction == -1:
                    return flip(self.sprites[name], 1, 0)
            f -= 1

        # if no sprite was found, return a placeholder
        draft = Surface((self.w, self.h))
        draft.fill((0, 255, 0))
        draft.blit(HEL16.render(self.state, 0, (0, 0, 0)), (0, 0))

        return draft
コード例 #47
0
class Cell(sprite.Sprite):
    def __init__(self, x, y, r=BG[0], g=BG[1], b=BG[2], a=BG[3]):
        sprite.Sprite.__init__(self)

        self.posx = x
        self.posy = y
        self.color = (r, g, b, a)
        self.image = None
        self.rect = None

    def set(self, w, h):
        self.image = Surface([w, h])
        self.image.convert_alpha()
        self.rect = self.image.get_rect()
        self.rect.topleft = (self.posx, self.posy)

    def fill(self, r, g, b, a, color=(-1, -1, -1)):
        if color != (-1, -1, -1):
            self.color = (r, g, b, a)
        else:
            self.color = color

    def update(self):
        self.image.fill(self.color)
コード例 #48
0
def update_screen(ai_settings: Settings, screen: pygame.Surface,
                  stats: GameStats, sb: ScoreBoard, ship: Ship,
                  aliens: pygame.sprite.Group, bullets: pygame.sprite.Group,
                  play_button: Button) -> NoReturn:
    """更新屏幕上的图像,并切换到新屏幕"""

    # 每次循环时都重绘屏幕
    screen.fill(ai_settings.bg_color)

    # 在飞船和外星人后面重绘所有子弹
    for bullet in bullets.sprites():
        bullet.draw_bullet()
    ship.blitme()
    aliens.draw(screen)

    # 显示得分
    sb.show_score()

    # 如果游戏处于非活动状态,就绘制Play按钮
    if not stats.game_active:
        play_button.draw_button()

    # 让最近绘制的屏幕可见
    pygame.display.flip()
コード例 #49
0
def drawn_rule(rule):
    surf = Surface((PW * 4 * 8, PW * 2))
    surf.fill((255, 255, 255))
    binary = tobin8(rule)
    for i, b in enumerate(binary):
        cell = tobin3(i)
        pygame.draw.rect(surf, (0, 0, 0), Rect((i * (PW * 4), 0), (PW, PW)))
        pygame.draw.rect(surf, col[int(cell[2])],
                         Rect((i * (PW * 4) + 1, 1), (PW - 2, PW - 2)))
        pygame.draw.rect(surf, (0, 0, 0),
                         Rect(((i * (PW * 4)) + PW, 0), (PW, PW)))
        pygame.draw.rect(surf, col[int(cell[1])],
                         Rect(((i * (PW * 4)) + PW + 1, 1), (PW - 2, PW - 2)))
        pygame.draw.rect(surf, (0, 0, 0),
                         Rect(((i * (PW * 4)) + (PW * 2), 0), (PW, PW)))
        pygame.draw.rect(
            surf, col[int(cell[0])],
            Rect(((i * (PW * 4)) + (PW * 2) + 1, 1), (PW - 2, PW - 2)))
        pygame.draw.rect(surf, (0, 0, 0),
                         Rect(((i * (PW * 4)) + PW, PW), (PW, PW)))
        pygame.draw.rect(
            surf, col[int(b)],
            Rect(((i * (PW * 4)) + PW + 1, PW + 1), (PW - 2, PW - 2)))
    return surf
コード例 #50
0
ファイル: Draw.py プロジェクト: illume/eyestabs
def draw_rect(width, height, color=None):
    """draw_rect (...) -> Surface

    Creates a rectangle surface.
    
    Creates a pygame.Surface with the size of 'width' and 'height' and
    fills it with the given background color 'color', which needs to
    match the pygame color style. If no color is provided, the surface
    will be left unfilled.

    The following example creates a red square surface:

    draw_rect (10, 10, (255, 0, 0))

    Note: This method calls pygame.Surface() to create the surface, but
    does not provide any values for the flags, depth or masks, which can
    be applied in the pygame.Surface() call. It uses the default values
    given by pygame. If this is not wanted, it is recommended to
    override this function, where necessary.
    """
    surface = Surface((width, height))
    if color:
        surface.fill(color)
    return surface
コード例 #51
0
ファイル: main.py プロジェクト: N-A-D/Arcade-games
def game_loop(screen: pygame.Surface):
    snake = Snake()
    apple = make_apple()

    clock = pygame.time.Clock()
    play = True
    game_over = False
    while play:
        clock.tick(10)

        # events
        for event in pygame.event.get():
            if event.type == QUIT:
                play = False

        # logic
        if apple_collides_with_snake_head(apple, snake):
            apple = make_apple()
            while apple_collides_with_snake_body(apple, snake):
                apple = make_apple()
            snake.add_segment()

        snake.update()

        if snake_out_of_bounds(snake) or snake.collides_with_itself():
            play = False
            game_over = True

        # rendering
        screen.fill(BACKGROUND_COLOR)
        draw_apple(apple, screen)
        snake.draw(screen)
        draw_grid(screen)
        pygame.display.flip()
    if game_over:
        game_over_loop(screen)
コード例 #52
0
ファイル: pokedex.py プロジェクト: Kyrokx/PygaMone
    def render(self, display: pygame.Surface) -> NoReturn:
        display.fill("#ecdcdf")
        pygame.draw.polygon(display, "#f4523b", PokeDex.poly_1)
        pygame.draw.polygon(display, "#fa7248", PokeDex.poly_2)
        pygame.draw.polygon(display, "#333333", PokeDex.poly_3)
        pygame.draw.polygon(display, "#cedae0", PokeDex.poly_4)

        utils.draw_button_info(display, **self.keys)

        nb = game.FONT_24.render(game.get_game_instance().get_message("number"), True, (255, 255, 255))
        nb_s = nb.get_size()

        # 839 = (1060 - x(40)) // 2 + x(40)
        display.blit(nb, (839 - (nb_s[0] // 2), 40 - (nb_s[1] // 2)))
        nb = game.FONT_24.render(game.get_game_instance().get_message("pokedex"), True, (0, 0, 0))
        display.blit(nb, (10, 40 - (nb_s[1] // 2)))
        x_1 = 20 + nb.get_size()[0]

        pygame.draw.rect(display, "#595959", (x_1, 22, 100, 34), border_radius=10)
        display.blit(f := game.FONT_20.render(str(self.nb_caught), True, (255, 255, 255)),
                     (x_1 + 50, 40 - (f.get_size()[1] // 2)))
        display.blit(utils.RED_POKEBALL, (x_1 + 10, 23))
        pygame.draw.rect(display, "#595959", (x_1 + 110, 22, 100, 34), border_radius=10)
        display.blit(f := game.FONT_20.render(str(self.nb_saw), True, (255, 255, 255)),
                     (x_1 + 160, 40 - (f.get_size()[1] // 2)))
        display.blit(utils.POINT_POKEBALL, (x_1 + 120, 23))

        range_ = self.get_range()

        y = 90

        for id_ in range(*range_):
            self.draw_pokemon(display, id_, y)
            if self.selected == id_:
                display.blit(self.arrow, (625, y + 10))
            y += 50
コード例 #53
0
def draw_ellipse(rot_angle):
    img = Surface((400, 400))
    img.fill(Color('white'))
    rect = img.get_rect()

    draw.line(img, Color('grey'), rect.midleft, rect.midright, 1)
    draw.line(img, Color('grey'), rect.midtop, rect.midbottom, 1)

    r = radians(rot_angle)
    cos_r, sin_r = cos(r), sin(r)
    cx = c * cos_r
    cy = c * sin_r
    for angle in range(0, 361):
        ang = radians(angle)
        cos_a, sin_a = cos(ang), sin(ang)

        #   offsets, foci,  ellipse,  rotation...
        x = offset_x + cx + a * cos_a * cos_r - b * sin_a * sin_r
        y = offset_y + cy + b * sin_a * cos_r + a * cos_a * sin_r
        img.set_at((int(x), int(y)), Color('black'))

    draw.circle(img, Color('yellow'), (c1, c2), 7)

    return img
コード例 #54
0
ファイル: SbMenus.py プロジェクト: MihailRis/Python-Zendes25
class State_Panel():
    def __init__(self, path):
        self.sise = (600, 100)
        self.image = Surface(self.sise, pygame.SRCALPHA)
        #		self.hp_text = font.Font(path+"/resources/FreeSansBold.ttf", 13)
        self.state_icons = []
        for x in xrange(1, 20):
            self.state_icons.append(State_icon(x, path, "heart"))
        self.state_icons2 = []
        for x in xrange(1, 20):
            self.state_icons2.append(State_icon(x, path, "air"))
        self.state_icons3 = []
        for x in xrange(1, 20):
            self.state_icons3.append(State_icon(x, path, "hunger"))
#		self.state_icons2.append(State_icon(10,path,"air"))

    def update(self, player):
        x = 0
        x2 = 0
        x3 = 0
        self.image.fill((0, 0, 0, 0))
        #		self.image.set_colorkey(PINK)
        for icon in self.state_icons:
            icon.update(20, player.hp)
            self.image.blit(icon.texture, (x, 0))
            x += 25
        if player.air < 20:
            for icon in self.state_icons2:
                icon.update(20, player.air)
                self.image.blit(icon.texture, (x2, 50))
                x2 += 25

        for icon in self.state_icons3:
            icon.update(20, int(player.hunger))
            self.image.blit(icon.texture, (x3, 25))
            x3 += 25
コード例 #55
0
class TowerShopTab():
    def __init__(self, tower, pos):
        self.pos = pos
        self.tower = tower
        self.name = self.tower.name
        self.description = self.tower.description
        self.surface_inside = Surface((123, 38)).convert()
        self.surface_inside.fill((100, 100, 100))
        self.image = tower.image
        self.cost = tower.cost
        self.surface = Surface((125, 40)).convert()
        self.rect = Rect(self.pos, self.surface.get_size())
        self.font = font.Font(None, 15)
        self.info_tab = tower.frame.image

        self.surface_inside.blit(transform.scale(self.tower.image, (20, 20)),
                                 (5, 10))
        self.surface_inside.blit(
            self.font.render(self.tower.name, 1, (0, 0, 0)),
            (30, 25 - self.font.get_height()))
        self.surface.blit(self.surface_inside, (1, 1))

    def get_surface(self):
        return self.surface
コード例 #56
0
    def get_surface(self):
        """
		Returns a Surface to use as this element's background, decorated with whichever effect function
		is set on this widget having been applied.
		"""
        surface = Surface(self.rect.size)
        surface.fill(self.current_background_color())

        color = Color(*self.current_background_color())
        highlight = color.correct_gamma(2)
        shadow = color.correct_gamma(0.5)
        arc(surface, shadow, self._circle_rect, RADIANS_TOPRIGHT,
            RADIANS_BOTTOM_LEFT, self.bevel_depth)
        arc(surface, highlight, self._circle_rect, RADIANS_BOTTOM_LEFT,
            RADIANS_TOPRIGHT, self.bevel_depth)

        if self.selected:
            circle(surface, self.dot_color, self._circle_rect.center,
                   self.dot_radius)

        for att in ["disabled", "focused", "hovering"]:
            setattr(self._label, att, getattr(self, att))
        surface.blit(self._label.get_surface(), self._label_rect.topleft)
        return surface
コード例 #57
0
    def __init__(self, title: str, content: str, duration: float):
        banner_background_surface = Surface((1024, 150), flags=SRCALPHA)
        banner_background_surface.fill((111, 111, 111, 200))

        font = pyfont.Font(GlobalSettings.FONT, 33)
        text_surface: Surface = InformationBanner.render_font(
            font, title.upper())
        banner_background_surface.blit(
            text_surface,
            InformationBanner.title_text_placer(banner_background_surface,
                                                text_surface))

        font = pyfont.Font(GlobalSettings.FONT, 19)
        text_surface: Surface = InformationBanner.render_font(
            font, content.upper())
        banner_background_surface.blit(
            text_surface,
            InformationBanner.content_text_placer(banner_background_surface,
                                                  text_surface))

        GameObject.__init__(self, banner_background_surface)

        self._duration = duration
        self._death_time = 0
コード例 #58
0
ファイル: matris.py プロジェクト: jeongukjae/MaTris-Python-3
    def info_surf(self):

        textcolor = (255, 255, 255)
        font = pygame.font.Font(None, 30)
        width = (WIDTH-(MATRIS_OFFSET+BLOCKSIZE*MATRIX_WIDTH+BORDERWIDTH*2)) - MATRIS_OFFSET*2

        def renderpair(text, val):
            text = font.render(text, True, textcolor)
            val = font.render(str(val), True, textcolor)

            surf = Surface((width, text.get_rect().height + BORDERWIDTH*2), pygame.SRCALPHA, 32)

            surf.blit(text, text.get_rect(top=BORDERWIDTH+10, left=BORDERWIDTH+10))
            surf.blit(val, val.get_rect(top=BORDERWIDTH+10, right=width-(BORDERWIDTH+10)))
            return surf

        scoresurf = renderpair("Score", self.matris.score)
        levelsurf = renderpair("Level", self.matris.level)
        linessurf = renderpair("Lines", self.matris.lines)
        combosurf = renderpair("Combo", "x{}".format(self.matris.combo))

        height = 20 + (levelsurf.get_rect().height + 
                       scoresurf.get_rect().height +
                       linessurf.get_rect().height + 
                       combosurf.get_rect().height )

        area = Surface((width, height))
        area.fill(BORDERCOLOR)
        area.fill(BGCOLOR, Rect(BORDERWIDTH, BORDERWIDTH, width-BORDERWIDTH*2, height-BORDERWIDTH*2))

        area.blit(levelsurf, (0,0))
        area.blit(scoresurf, (0, levelsurf.get_rect().height))
        area.blit(linessurf, (0, levelsurf.get_rect().height + scoresurf.get_rect().height))
        area.blit(combosurf, (0, levelsurf.get_rect().height + scoresurf.get_rect().height + linessurf.get_rect().height))

        return area
コード例 #59
0
class Monster(sprite.Sprite):
    def __init__(self, x, y, textus):
        sprite.Sprite.__init__(self)
        #self.image=image.load(filename)
        #self.image.set_colorkey ((255,255,255))
        self.image = Surface((45, 45))
        self.image.fill((120, 30, 200))
        self.a = "Я злобный монстр!"
        self.rect = Rect(0, 0, 45, 45)
        self.rect.x = x
        self.rect.y = y
        self.name = "monster"
        self.textus = text
        self.n = 0
        self.s = 1
        self.tree = text.zombi1

    #def conversation (self):
    #hero.conversation (text.zombi1)

    def interaction(self):
        #screens.information_screen.blit(fonts.font1.render ((self.a), True, (250,250,250)),(0,0))
        #self.conversation ()
        pass
コード例 #60
0
ファイル: gui.py プロジェクト: 15Andrew43/Proga2019-2020
def draw_board(screen: Surface, pos_x: int, pos_y: int, elem_size: int,
               board: BoardState):
    screen.fill(color)
    dark = (0, 0, 0)
    white = (255, 255, 255)
    line_color = (182, 93, 37)
    # pygame.font.SysFont('arial', 56)
    # pygame.font.Font('Verdana.ttf', 24)
    screen.blit(InputBox.FONT.render('GOMOKU', True, dark),
                (0.7 * screen.get_size()[0], 0.1 * screen.get_size()[1]))
    if abs(board.current_player) == 2:
        winner = board.current_player
        screen.blit(
            InputBox.FONT.render(
                ('black' if winner == -2 else 'white') + ' player won!!!',
                True, dark),
            (0.7 * screen.get_size()[0], 0.2 * screen.get_size()[1]))

    for y, x in product(range(14), range(14)):
        position = pos_x + x * elem_size, pos_y + y * elem_size, elem_size, elem_size
        pygame.draw.rect(screen, line_color, position, 2)

    for y, x in product(range(15), range(15)):
        figure = board.board[y, x]

        if figure == 0:
            continue

        if figure > 0:
            figure_color = dark
        else:
            figure_color = white
        r = elem_size * 3 // 8

        pygame.draw.circle(screen, figure_color,
                           ((x + 1) * elem_size, (y + 1) * elem_size), r)