Python pygame.Color() Examples

The following are 30 code examples of pygame.Color(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pygame , or try the search function .
Example #1
Source File: PlotPyGame.py    From Grid2Op with Mozilla Public License 2.0 7 votes vote down vote up
def _draw_topos_one_sub(self, fig, sub_id, buses_z, elements, bus_vect):
        colors = [pygame.Color(255, 127, 14), pygame.Color(31, 119, 180)]

        # I plot the buses
        for bus_id, z_bus in enumerate(buses_z):
            pygame.draw.circle(self.screen,
                               colors[bus_id],
                               [int(z_bus.real), int(z_bus.imag)],
                               int(self.bus_radius),
                               0)

        # i connect every element to the proper bus with the proper color
        for el_nm, dict_el in elements.items():
            this_el_bus = bus_vect[dict_el["sub_pos"]] -1
            if this_el_bus >= 0:
                pygame.draw.line(self.screen,
                                 colors[this_el_bus],
                                 [int(dict_el["z"].real), int(dict_el["z"].imag)],
                                 [int(buses_z[this_el_bus].real), int(buses_z[this_el_bus].imag)],
                                 2)
        return [] 
Example #2
Source File: playSnake.py    From You-are-Pythonista with GNU General Public License v3.0 6 votes vote down vote up
def main():
    global FPSCLOCK, DISPLAY, BASICFONT, BLACK, WHITE, RED, GREY

    # 初始化Pygame库
    pygame.init()
    # 初始化一个游戏界面窗口
    DISPLAY = pygame.display.set_mode((640, 480))
    # 设置游戏窗口的标题
    pygame.display.set_caption('人人都是Pythonista - Snake')
    # 定义一个变量来控制游戏速度
    FPSCLOCK = pygame.time.Clock()
    # 初始化游戏界面内使用的字体
    BASICFONT = pygame.font.SysFont("SIMYOU.TTF", 80)

    # 定义颜色变量
    BLACK = pygame.Color(0, 0, 0)
    WHITE = pygame.Color(255, 255, 255)
    RED = pygame.Color(255, 0, 0)
    GREY = pygame.Color(150, 150, 150)

    playGame()


# 开始游戏 
Example #3
Source File: task.py    From code-jam-5 with MIT License 6 votes vote down vote up
def _complete(self, successful: bool) -> None:
        """Called when task was completed."""
        if successful:
            Sound.task_completed.play()
        else:
            Sound.task_failed.play()

        # Set that task was closed
        game_vars.open_task = None
        # Add/reduce heat depending on results
        game_vars.current_heat += (
            self.heat_add_success if successful else self.heat_add_failure
        )

        # Screen notification to informa on task result
        game_vars.notification = Notification(
            self.biome.text_task_success if successful else self.biome.text_task_fail,
            Color.green if successful else Color.red,
        )

        self.is_done = True 
Example #4
Source File: creeps.py    From code-for-blog with The Unlicense 6 votes vote down vote up
def draw_walls(self):
        wallcolor = Color(140, 140, 140)
        
        for wall in self.walls:
            nrow, ncol = wall
            
            pos_x = self.field_rect.left + ncol * self.GRID_SIZE + self.GRID_SIZE / 2
            pos_y = self.field_rect.top + nrow * self.GRID_SIZE + self.GRID_SIZE / 2
            radius = 3
            
            pygame.draw.polygon(self.screen, wallcolor,
                [   (pos_x - radius, pos_y), (pos_x, pos_y + radius),
                    (pos_x + radius, pos_y), (pos_x, pos_y - radius)])
            
            if (nrow + 1, ncol) in self.walls:
                pygame.draw.line(self.screen, wallcolor,
                    (pos_x, pos_y), (pos_x, pos_y + self.GRID_SIZE), 3)
            if (nrow, ncol + 1) in self.walls:
                pygame.draw.line(self.screen, wallcolor,
                    (pos_x, pos_y), (pos_x + self.GRID_SIZE, pos_y), 3) 
Example #5
Source File: PlotPyGame.py    From Grid2Op with Mozilla Public License 2.0 6 votes vote down vote up
def _draw_topos_one_sub(self, fig, sub_id, buses_z, elements, bus_vect):
        colors = [pygame.Color(255, 127, 14), pygame.Color(31, 119, 180)]

        # I plot the buses
        for bus_id, z_bus in enumerate(buses_z):
            pygame.draw.circle(self.screen,
                               colors[bus_id],
                               [int(z_bus.real), int(z_bus.imag)],
                               int(self.bus_radius),
                               0)

        # i connect every element to the proper bus with the proper color
        for el_nm, dict_el in elements.items():
            this_el_bus = bus_vect[dict_el["sub_pos"]] -1
            if this_el_bus >= 0:
                pygame.draw.line(self.screen,
                                 colors[this_el_bus],
                                 [int(dict_el["z"].real), int(dict_el["z"].imag)],
                                 [int(buses_z[this_el_bus].real), int(buses_z[this_el_bus].imag)],
                                 2)
        return [] 
Example #6
Source File: viewfinder.py    From viewfinder with Apache License 2.0 6 votes vote down vote up
def DrawLabel(label, x, y, color, font, transparency, bold=False, border=False, left_justify=False):
  color = pygame.Color(*[int(i + transparency * (j - i)) for i, j in zip(color, backdrop_color)])
  offset = DimensionsToPixels([x, y])
  ts = bold_font.render(label, True, color) if bold else font.render(label, True, color)
  if y > iphone_dims[1] - ts.get_height():
    offset[1] -= (ts.get_height() + 2)
  else:
    offset[1] += 2
  if left_justify:
    offset[0] = min(iphone_dims[0], offset[0])
  else:
    offset[0] = max(0, offset[0] - ts.get_width())
  GetSurface().blit(ts, offset)
  if border:
    pygame.draw.rect(GetSurface(), color,
                     [offset[0]-2, offset[1]-2, ts.get_width() + 4, ts.get_height() + 4], 1) 
Example #7
Source File: css.py    From universalSmashSystem with GNU General Public License v3.0 6 votes vote down vote up
def recolorIcon(self,_reset=False):
        if _reset:
            self.icon.recolor(self.icon.image,
                                  self.icon_color,
                                  pygame.Color('#cccccc'))
            self.icon_color = pygame.Color('#cccccc')    
            
        else:
            display_color = self.wheel.fighterAt(0).palette_display
            new_color = display_color[self.current_color % len(display_color)]
            
            #If the icon matches the background, make it default to the icon color 
            if new_color == pygame.Color(self.fill_color):
                new_color = pygame.Color('#cccccc')
                
            self.icon.recolor(self.icon.image,
                              self.icon_color,
                              new_color)
            self.icon_color = new_color 
Example #8
Source File: period.py    From code-jam-5 with MIT License 6 votes vote down vote up
def draw_age(self) -> None:
        """Draw how long the earth lived."""
        if self.start_time is not None:
            # If paused - dont count the age
            if game_vars.is_paused:
                if not self.pause_time:
                    self.pause_time = time.time()
                self.pause_time_sum = time.time() - self.pause_time
            else:
                self.pause_time = None

            font = pg.font.Font(None, 50)
            text = realtime_to_ingame_formatted(self.elapsed, self.start_date)
            age_indicator = font.render(text, True, pg.Color("black"))
            self.screen.blit(
                age_indicator,
                (int(WIDTH // 2) - int(age_indicator.get_width() // 2), 0),
            ) 
Example #9
Source File: keyboard.py    From Retropie-CRT-Edition with GNU General Public License v3.0 6 votes vote down vote up
def render_text(self, p_sText, p_bShadow = True):
        C_SHADOW = pygame.Color( 19, 14, 56)
        C_TEXT = pygame.Color(202,199,219)

        p_sText = str(p_sText)
        img = self.m_oFontText.render(p_sText, False, C_TEXT)
        rect = img.get_rect()
        sf = pygame.Surface((rect.width, rect.height), pygame.SRCALPHA)
        if p_bShadow:
            shadow = self.m_oFontText.render(p_sText, False, C_SHADOW)
            shadow_rect = img.get_rect()
            shadow_rect.x += 1
            shadow_rect.y += 1
            sf.blit(shadow, shadow_rect)
        sf.blit(img, rect)
        return sf 
Example #10
Source File: ptext.py    From ct-Raspi-Radiowecker with GNU General Public License v3.0 6 votes vote down vote up
def _fitsize(text, size, **kwargs):
	options = _FitsizeOptions(**kwargs)
	key = text, size, options.key()
	if key in _fit_cache: return _fit_cache[key]
	width, height = size
	def fits(fontsize):
		opts = options.copy()
		spans = _wrap(text, fontsize=fontsize, width=width, **opts.towrapoptions())
		wmax, hmax = 0, 0
		for tpiece, tagspec, x, jpara, jline, linewidth in spans:
			tagspec.updateoptions(opts)
			font = getfont(fontsize=fontsize, **opts.togetfontoptions())
			y = font.get_sized_height() * (opts.pspace * jpara + opts.lineheight * jline)
			w, h = font.size(tpiece)
			wmax = max(wmax, x + w)
			hmax = max(hmax, y + h)
		return wmax <= width and hmax <= height
	fontsize = _binarysearch(fits)
	_fit_cache[key] = fontsize
	return fontsize

# Returns the color as a color RGB or RGBA tuple (i.e. 3 or 4 integers in the range 0-255)
# If color is None, fall back to the default. If default is also None, return None.
# Both color and default can be a list, tuple, a color name, an HTML color format string, a hex
# number string, or an integer pixel value. See pygame.Color constructor for specification. 
Example #11
Source File: ct-alarm-radio.py    From ct-Raspi-Radiowecker with GNU General Public License v3.0 6 votes vote down vote up
def cache_idlescreen(self):
        self.idlescreen_cache = {}
        time_string = datetime.now().strftime(
            self.config.setting["timeformat"])
        timefont_size = self.ui.calculate_font_size(30)
        fontcolor = pygame.color.Color(50, 50, 50, 255)
        self.idlescreen_cache["time_text"] = gui.Text(
            time_string, timefont_size, color=fontcolor, font=self.ui.basefont_file, shadowoffset=(0.5, 0.5))
        self.idlescreen_cache["time_text"].Position = self.ui.calculate_position(
            (0, 0), self.idlescreen_cache["time_text"].Surface, "center", "center")

        empty_image = pygame.Surface(
            self.ui.display_size)

        def reset_idle():
            self.is_idle = False

        self.idlescreen_cache["button"] = gui.Button(
            empty_image, self.ui.display_size, reset_idle)
        self.idlescreen_cache["button"].Position = (0, 0) 
Example #12
Source File: ball_shape.py    From PyPhysicsSandbox with MIT License 6 votes vote down vote up
def _draw(self, screen):
        if self._cosmetic:
            p = (self._x, self._y)
        else:
            p = to_pygame(self.body.position)

        pygame.draw.circle(screen, self.color, p, int(self._radius), 0)

        if self.draw_radius_line:
            if self._cosmetic:
                p2 = (self._x+self._radius, self._y)
            else:
                circle_edge = self.body.position + pymunk.Vec2d(self.shape.radius, 0).rotated(self.body.angle)
                p2 = to_pygame(circle_edge)

            pygame.draw.lines(screen, pygame.Color('black'), False, [p, p2], 1) 
Example #13
Source File: render.py    From gym-carla with MIT License 6 votes vote down vote up
def _render_hist_actors(self, surface, actor_polygons, actor_type, world_to_pixel, num):
    lp=len(actor_polygons)
    color = COLOR_SKY_BLUE_0

    for i in range(max(0,lp-num),lp):
      for ID, poly in actor_polygons[i].items():
        corners = []
        for p in poly:
          corners.append(carla.Location(x=p[0],y=p[1]))
        corners.append(carla.Location(x=poly[0][0],y=poly[0][1]))
        corners = [world_to_pixel(p) for p in corners]
        color_value = max(0.8 - 0.8/lp*(i+1), 0)
        if ID == self.hero_id:
          # red
          color = pygame.Color(255, math.floor(color_value*255), math.floor(color_value*255))
        else:
          if actor_type == 'vehicle':
            # green
            color = pygame.Color(math.floor(color_value*255), 255, math.floor(color_value*255))
          elif  actor_type == 'walker':
            # yellow
            color = pygame.Color(255, 255, math.floor(color_value*255))
          
        pygame.draw.polygon(surface, color, corners) 
Example #14
Source File: pygame_functions.py    From Pygame_Functions with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, text, xpos, ypos, width, case, maxLength, fontSize):
        pygame.sprite.Sprite.__init__(self)
        self.text = ""
        self.width = width
        self.initialText = text
        self.case = case
        self.maxLength = maxLength
        self.boxSize = int(fontSize * 1.7)
        self.image = pygame.Surface((width, self.boxSize))
        self.image.fill((255, 255, 255))
        pygame.draw.rect(self.image, (0, 0, 0), [0, 0, width - 1, self.boxSize - 1], 2)
        self.rect = self.image.get_rect()
        self.fontFace = pygame.font.match_font("Arial")
        self.fontColour = pygame.Color("black")
        self.initialColour = (180, 180, 180)
        self.font = pygame.font.Font(self.fontFace, fontSize)
        self.rect.topleft = [xpos, ypos]
        newSurface = self.font.render(self.initialText, True, self.initialColour)
        self.image.blit(newSurface, [10, 5]) 
Example #15
Source File: skin_manager.py    From launcher with GNU General Public License v3.0 6 votes vote down vote up
def SetColors(self):
        Colors = {}
        Colors["High"] = pygame.Color(51, 166, 255)
        Colors["Text"] = pygame.Color(83, 83, 83)
        Colors["ReadOnlyText"] = pygame.Color(130,130,130)
        Colors["Front"] = pygame.Color(131, 199, 219)
        Colors["URL"] = pygame.Color(51, 166, 255)
        Colors["Line"] = pygame.Color(169, 169, 169)
        Colors["TitleBg"] = pygame.Color(228, 228, 228)
        Colors["Active"] = pygame.Color(175, 90, 0)
        Colors["Disabled"] = pygame.Color(204, 204, 204)
        Colors["White"] = pygame.Color(255, 255, 255)
        Colors["Black"] = pygame.Color(0, 0, 0)

        if self.configExists():
            if "Colors" in self._Config.sections():
                colour_opts = self._Config.options("Colors")
                for i in Colors:
                    if i in colour_opts:
                        try:
                            Colors[i] = self.ConvertToRGB(
                                self._Config.get("Colors", i))
                        except Exception, e:
                            print("error in ConvertToRGB %s" % str(e))
                            continue 
Example #16
Source File: aux_functions.py    From DRLwithTL with MIT License 6 votes vote down vote up
def blit_text(surface, text, pos, font, color=pygame.Color('black')):
    words = [word.split(' ') for word in text.splitlines()]  # 2D array where each row is a list of words.
    space = font.size(' ')[0]  # The width of a space.
    max_width, max_height = surface.get_size()
    x, y = pos
    for line in words:
        for word in line:
            word_surface = font.render(word, 0, color)
            word_width, word_height = word_surface.get_size()
            if x + word_width >= max_width:
                x = pos[0]  # Reset the x.
                y += word_height  # Start on new row.
            surface.blit(word_surface, (x, y))
            x += word_width + space
        x = pos[0]  # Reset the x.
        y += word_height  # Start on new row. 
Example #17
Source File: battle.py    From universalSmashSystem with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self,_fighter):
        spriteManager.Sprite.__init__(self)
        self.fighter = _fighter
        self.percent = int(_fighter.damage)
        
        self.bg_sprite = _fighter.franchise_icon
        self.bg_sprite.recolor(self.bg_sprite.image,pygame.Color('#cccccc'),pygame.Color(settingsManager.getSetting('playerColor'+str(_fighter.player_num))))
        self.bg_sprite.alpha(128)
        
        self.image = self.bg_sprite.image
        self.rect = self.bg_sprite.image.get_rect()
        
        #Until I can figure out the percentage sprites
        self.percent_sprites = spriteManager.SheetSprite(settingsManager.createPath('sprites/guisheet.png'), 64)
        self.kerning_values = [49,33,44,47,48,43,43,44,49,43,48] #This is the width of each sprite, for kerning purposes
        
        self.percent_sprite = spriteManager.Sprite()
        self.percent_sprite.image = pygame.Surface((196,64), pygame.SRCALPHA, 32).convert_alpha()
        self.redness = 0
        
        self.updateDamage()
        self.percent_sprite.rect = self.percent_sprite.image.get_rect()
        self.percent_sprite.rect.center = self.rect.center 
Example #18
Source File: pygame_functions.py    From Pygame_Functions with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, text, xpos, ypos, width, case, maxLength, fontSize):
        pygame.sprite.Sprite.__init__(self)
        self.text = ""
        self.width = width
        self.initialText = text
        self.case = case
        self.maxLength = maxLength
        self.boxSize = int(fontSize * 1.7)
        self.image = pygame.Surface((width, self.boxSize))
        self.image.fill((255, 255, 255))
        pygame.draw.rect(self.image, (0, 0, 0), [0, 0, width - 1, self.boxSize - 1], 2)
        self.rect = self.image.get_rect()
        self.fontFace = pygame.font.match_font("Arial")
        self.fontColour = pygame.Color("black")
        self.initialColour = (180, 180, 180)
        self.font = pygame.font.Font(self.fontFace, fontSize)
        self.rect.topleft = [xpos, ypos]
        newSurface = self.font.render(self.initialText, True, self.initialColour)
        self.image.blit(newSurface, [10, 5]) 
Example #19
Source File: Common.py    From PyMenu with GNU General Public License v3.0 6 votes vote down vote up
def blitMultilineText(surface, text, pos, font, color=pygame.Color('black')):
    words = [word.split(' ') for word in text.splitlines()]  # 2D array where each row is a list of words.
    space = font.size(' ')[0]  # The width of a space.
    max_width, max_height = surface.get_size()
    x, y = pos
    for line in words:
        for word in line:
            word_surface = font.render(word, 0, color)
            word_width, word_height = word_surface.get_size()
            if x + word_width >= max_width:
                x = pos[0]  # Reset the x.
                y += word_height  # Start on new row.
            surface.blit(word_surface, (x, y))
            x += word_width + space
        x = pos[0]  # Reset the x.
        y += word_height  # Start on new row. 
Example #20
Source File: pathfinder_visualize.py    From code-for-blog with The Unlicense 5 votes vote down vote up
def draw_messages(screen, rect, message1, message2):
    draw_rimmed_box(screen, rect, (50, 20, 0), 4, Color('white'))

    my_font = pygame.font.SysFont('arial', 18)
    message1_sf = my_font.render(message1, True, Color('white'))
    message2_sf = my_font.render(message2, True, Color('white'))

    screen.blit(message1_sf, rect.move(10, 0))
    screen.blit(message2_sf, rect.move(10, message1_sf.get_height())) 
Example #21
Source File: background.py    From pibooth with MIT License 5 votes vote down vote up
def _write_text(self, text, rect=None, align='center'):
        """Write a text in the given rectangle.
        """
        if not rect:
            rect = self._rect.inflate(-self._text_border, -self._text_border)
        if self._outlines:
            # Build rectangle around text area for debuging purpose
            outlines = pygame.Surface(rect.size, pygame.SRCALPHA, 32)
            pygame.draw.rect(outlines, pygame.Color(255, 0, 0), outlines.get_rect(), 2)
            self._texts.append((outlines, rect))
        self._texts.extend(multiline_text_to_surfaces(text, self._text_color, rect, align)) 
Example #22
Source File: base_shape.py    From PyPhysicsSandbox with MIT License 5 votes vote down vote up
def __init__(self, cosmetic=False):
        self._cosmetic = cosmetic

        if cosmetic:
            self.body = None
            self.shape = []
        else:
            self.body.custom_gravity = space.gravity
            self.body.custom_damping = space.damping
            self.body.constant_velocity = None

        self.elasticity = 0.90
        self.friction = 0.6
        self._color = pygame.Color('black')
        self._wrap_x = False
        self._wrap_y = False
        self._active = True
        self._visible = True
        self._debug = False
        self.custom_velocity_func = False

        BaseShape.next_collision_type += 1
        self._collision_type = BaseShape.next_collision_type

        if type(self.shape) is list:
            for shape in self.shape:
                shape.collision_type = BaseShape.next_collision_type
        else:
            self.shape.collision_type = BaseShape.next_collision_type

        add_observer(self.observer) 
Example #23
Source File: base_shape.py    From PyPhysicsSandbox with MIT License 5 votes vote down vote up
def color(self, value):
        if type(value) == pygame.Color:
            self._color = value
        else:
            print("Color value must be a Color instance") 
Example #24
Source File: __init__.py    From PyPhysicsSandbox with MIT License 5 votes vote down vote up
def color(c):
    """Sets the default color to use for shapes created after this
    call.  The function may be called at any point to change the
    color for new shapes.

    To see available color names go to
    https://sites.google.com/site/meticulosslacker/pygame-thecolors
    and hover the mouse pointer over a color of interest.

    :param c: the color name as a string
    :type c: str
    """
    global default_color

    default_color = Color(c) 
Example #25
Source File: builderWindow.py    From universalSmashSystem with GNU General Public License v3.0 5 votes vote down vote up
def changeActionDropdown(self,*_args):
        global action
        if self.current_action.get() == 'Fighter Properties':
            self.group.pack_forget()
            self.group_list = ["Fighter","Attributes"]
            for i in range(0,8):
                self.group_list.append("Color "+str(i))
            self.refreshDropdowns()
            self.current_group.set('Fighter')
        else:
            self.root.action_string.set(self.current_action.get())
            self.refreshDropdowns()
            self.current_group.set('Properties') 
Example #26
Source File: pygame_functions.py    From Pygame_Functions with GNU General Public License v2.0 5 votes vote down vote up
def parseColour(colour):
    if type(colour) == str:
        # check to see if valid colour
        return pygame.Color(colour)
    else:
        colourRGB = pygame.Color("white")
        colourRGB.r = colour[0]
        colourRGB.g = colour[1]
        colourRGB.b = colour[2]
        return colourRGB 
Example #27
Source File: builderWindow.py    From universalSmashSystem with GNU General Public License v3.0 5 votes vote down vote up
def gameLoop(self):
        global fighter
        #TODO figure out that window snap thing that's messing up a lot
        self.screen = pygame.display.set_mode((self.winfo_width(), self.winfo_height()),pygame.RESIZABLE)
        if fighter: self.centerFighter()
        
        self.screen.fill(pygame.Color("pink"))
        if fighter:
            fighter.mask = None #These don't work inside of the builder
            fighter.draw(self.screen, fighter.sprite.rect.topleft, self.scale)
            for hbox in fighter.active_hitboxes:
                hbox.draw(self.screen,hbox.rect.topleft,self.scale)        
            
        pygame.display.flip()
        #self.after(5, self.gameLoop) #Loop every 5ms 
Example #28
Source File: panel.py    From universalSmashSystem with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, _surface, _parent=None, _width=20, _height=1, corner=(0, 0), _font="unifont-9.0.02", _size=16):
        self.surface = _surface
        self.parent = _parent
        self.corner = _corner
        if _parent is not None:
            _parent.children.append(self)
            bgcolor = _parent.bgcolor-pygame.Color(16, 16, 16)
        else:
            bgcolor = pygame.Color(255, 255, 255)
        pygcurse.PygcurseSurface.__init__(self, _width, _height, font=pygame.font.Font(settingsManager.createPath(_font+".ttf"),_size), fgcolor=pygame.Color(0, 0, 0), bgcolor=bgcolor)
        self.children = []
        self.focused = None 
Example #29
Source File: base_shape.py    From PyPhysicsSandbox with MIT License 5 votes vote down vote up
def inside(self, p):
        mask = pygame.Surface((win_width, win_height))
        color = self.color
        self.color = pygame.Color('white')
        self._draw(mask)
        self.color = color

        mask.lock()
        pixel = mask.get_at(p)
        mask.unlock()

        return pixel == pygame.Color('white') 
Example #30
Source File: pygame_functions.py    From Pygame_Functions with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self):
        self.colour = pygame.Color("black")