def draw_middle(self, on_off): i = PATCH_ROWS - 5 j = 4 cur = self.patches_array[i][j] while j < PATCH_COLS - 4: cur = self.patches_array[i][j] for patch in set(cur.neighbors_8()): patch.set_color(Color(100, 100, 100)) i -= 1 j += 1 i = PATCH_ROWS - 5 j = 4 if on_off: cur = self.patches_array[i][j] while j < PATCH_COLS - 4: cur = self.patches_array[i][j] cur.set_color(Color('Black')) i -= 1 j += 1 else: cur = self.patches_array[i][j] while j < PATCH_COLS - 4: cur = self.patches_array[i][j] cur.set_color(Color(100, 100, 100)) i -= 1 j += 1
def draw_label(self): offset = Block.patch_text_offset if isinstance(self, Patch) else Block.agent_text_offset text_center = Pixel_xy((self.rect.x + offset, self.rect.y + offset)) line_color = None if offset == 0 else \ Color('white') if isinstance(self, Patch) and self.color == Color('black') else self.color obj_center = self.rect.center gui.draw_label(self.label, text_center, obj_center, line_color)
def __init__(self, height: int, colour_or_gradient: Color, rule_dimensions: Tuple[int, int] = (-1, 1), has_shade: bool = True, alignment=ALIGN_CENTER): super().__init__(dimensions=(-1, height), should_span=True) self.colour_or_gradient = colour_or_gradient self.rule_dimensions = list(rule_dimensions) self.shade = has_shade self.alignment = alignment if self.shade and isinstance(self.colour_or_gradient, Color): self.med_shade_colour = Color('#00000000') self.light_shade_colour = Color('#00000000') self.med_shade_colour.hsla = (self.colour_or_gradient.hsla[0], self.colour_or_gradient.hsla[1], self.colour_or_gradient.hsla[2], self.colour_or_gradient.hsla[3] * 0.5) self.light_shade_colour.hsla = (self.colour_or_gradient.hsla[0], self.colour_or_gradient.hsla[1], self.colour_or_gradient.hsla[2], self.colour_or_gradient.hsla[3] * 0.25)
class Configuration: S_CAPTION = 'Tetris' S_HEIGHT = 600 S_WIDTH = 800 S_COLOR = Color('black') ASSET_PATH = os.path.join(os.path.dirname(__file__), '..', 'assets') B_COLOR = Color('black') B_LINE_COLOR = Color('white') CEIL = S_HEIGHT // 8 - 20 W_CENTER = S_WIDTH // 3 DROP_HEIGHT = 25 BRICK_DIM = (20, 20) BRICK_WIDTH = BRICK_DIM[0] BRICK_HEIGHT = BRICK_DIM[1] FLOOR = CEIL + DROP_HEIGHT * BRICK_DIM[1] W_LEFT = W_CENTER - 6 * BRICK_DIM[0] W_RIGHT = W_CENTER + 8 * BRICK_DIM[0] W_WIDTH = W_RIGHT - W_LEFT W_HEIGHT = FLOOR - CEIL W_VERTICES = [(W_LEFT - 1, CEIL - 1), (W_LEFT - 1, FLOOR), (W_RIGHT, FLOOR), (W_RIGHT, CEIL - 1)] HORIZONTAL_SPEED = 220 # pixels per sec FALL_SPEED = 20 # pixels per sec DIVE_SPEED = 320 # pixels per sec L_DIMS = (W_RIGHT - W_LEFT, BRICK_DIM[1]) L_NUM_BRICKS = L_DIMS[0] // BRICK_DIM[0] FPS = 60 FLOOR_DIM = (W_LEFT, FLOOR, W_WIDTH, 1) W_RIGHT_DIM = (W_RIGHT, CEIL, 1, W_HEIGHT) W_LEFT_DIM = (W_LEFT - 1, CEIL, 1, W_HEIGHT)
def determine_congestion(self, spawn_rate, highway, move_by_delay): if self.last_here == 0: self.delay = int(self.base_delay / 2) else: self.delay = floor( ((250 / spawn_rate) / (World.ticks - self.last_here + 1)) * self.base_delay) g = 255 + floor(255 * (0.5 - self.delay / self.base_delay)) if g < 100: g = 100 if g > 255: g = 255 if self.delay > 10: self.delay = 10 if self.delay < 4: self.delay = 4 if move_by_delay: self.set_color(Color(g, g, g)) else: if self in highway.top_road: prev_patch = highway.top_road[self.col - 12] else: prev_patch = highway.bottom_road[self.col - 12] prev_patch.set_color(Color(g, g, g))
def draw_label(label, text_center, obj_center, line_color, background='white'): text = gui.FONT.render(label, True, Color('black'), Color(background)) # offset = Block.patch_text_offset if isinstance(self, Patch) else Block.agent_text_offset # text_center = Pixel_xy((self.rect.x + offset, self.rect.y + offset)) gui.blit(text, text_center) # line_color = Color('white') if isinstance(self, Patch) and self.color == Color('black') else self.color if line_color is not None: gui.draw_line(start_pixel=obj_center, end_pixel=text_center, line_color=line_color)
def draw_Player(surface: pygame.Surface, state: GameState, player_idx: int): CARD_SPACING = 5 CARD_W = int((surface.get_width() + CARD_SPACING) / 11) CARD_H = int(surface.get_height() / 3) FORE_C = Color('RED') BACK_C = Color('BLUE') LABEL_SIZE = 24 y = 10 App.draw_centered_text(surface, surface.get_width() / 2, y, f'Player {player_idx + 1}', FORE_C, LABEL_SIZE) y += 20 App.draw_centered_text(surface, surface.get_width() / 2, y, 'Hand', FORE_C, LABEL_SIZE) counts = count_card_types(state.hands[player_idx]) counts = {card: count for card, count in counts.items() if count > 0} y += 10 for k, card in enumerate(counts): count = counts[card] x = k * (CARD_W + CARD_SPACING) App.draw_card(surface.subsurface(Rect(x, y, CARD_W, CARD_H)), card, FORE_C, BACK_C, count) y += CARD_H + 10 App.draw_centered_text(surface, surface.get_width() / 2, y, 'Played', FORE_C, LABEL_SIZE) played_cards = list(state.played_cards[player_idx]) wasabi_combos = pair_wasabi(played_cards) for card in wasabi_combos: played_cards.remove(card) played_cards.remove(SushiCardType.WASABI) counts = count_card_types(played_cards) counts = {card: count for card, count in counts.items() if count > 0} y += 10 for k, card in enumerate(counts): count = counts[card] x = k * (CARD_W + CARD_SPACING) App.draw_card(surface.subsurface(Rect(x, y, CARD_W, CARD_H)), card, FORE_C, BACK_C, count) for k, card in enumerate(wasabi_combos): x = (k + len(counts)) * (CARD_W + CARD_SPACING) App.draw_card(surface.subsurface(Rect(x, y, CARD_W, CARD_H)), card, FORE_C, BACK_C, 1, True) y += CARD_H + 10 pudding = state.puddings[player_idx] score = state.scores[player_idx] App.draw_centered_text(surface, surface.get_width() / 2, y, f'Pudding: {pudding} Score: {score}', FORE_C, LABEL_SIZE)
def generate_color(self): ''' Generates a color with a random hue ''' color = Color(0,0,0) color.hsla = (random.randint(0,360), 100, 51, 1) return color[:-1]
def draw(window): color = Color('black') for j in xrange(WIDTH): for i in xrange(HEIGHT): pygame.draw.rect(window, color, (j * d, i * d, d, d)) pygame.draw.rect(window, Color('red'), ((cherry % WIDTH) * d, (cherry / WIDTH) * d, d, d)) n = len(snake) for i, pos in enumerate(snake): pygame.draw.rect(window, Color(0, (n - i) * 255 / n, i * 255 / n), ((pos % WIDTH) * d, (pos / WIDTH) * d, d, d))
def update(self, actors): for i, actor in enumerate(actors): name_text = self.font.render(actor.name, False, Color('black')) name_point = (self.rect.x, self.rect.y + i * 45) health_text = self.font.render("{:.1e}".format(actor.health), False, Color('black')) health_point = (self.rect.x, self.rect.y + 20 + i * 45) self.names.append((name_text, name_point)) self.healths.append((health_text, health_point))
def gen_random_colour(): """ Creates a random colour using the golden ratio method. Helps make the test layout rects reasonably distinctive from each other. """ golden_ratio = ((5**0.5) - 1) / 2 colour = Color("#000000") colour.hsla = 360 * ( (random.uniform(1.0, 500.0) * golden_ratio) % 1), 50, 70, 100 return colour
def check_middle(self, middle_on, delay_on): if middle_on != self.middle_prev: if middle_on: for patch in self.middle_road: patch.set_color(Color("yellow")) self.middle_prev = middle_on self.check_delay(middle_on, delay_on) else: for patch in self.middle_road: patch.set_color(Color("orange")) self.middle_prev = middle_on self.check_delay(middle_on, delay_on)
def draw_road(self, road_type, start_patch: Patch, stop_patch: Patch): if road_type == VARIABLE_CONGESTION: start_patch = World.patches_array[start_patch.row][start_patch.col + 1] stop_patch = World.patches_array[stop_patch.row][stop_patch.col - 1] #draw and set the middle line for p in self.patches_line(start_patch, stop_patch): p.set_color(Color('White')) p.road_type = VARIABLE_CONGESTION World.patches_array[p.row + 1][p.col].set_color(Color('Grey')) World.patches_array[p.row - 1][p.col].set_color(Color('Grey')) if road_type == CONSTANT_CONGESTION: start_patch = World.patches_array[start_patch.row + 1][start_patch.col] stop_patch = World.patches_array[stop_patch.row - 1][stop_patch.col] # draw and set the middle line for p in self.patches_line(start_patch, stop_patch): p.set_color(Color('Yellow')) p.road_type = VARIABLE_CONGESTION World.patches_array[p.row][p.col + 1].set_color(Color('Grey')) World.patches_array[p.row][p.col - 1].set_color(Color('Grey')) if road_type == BRAESS_ROAD_ENABLED or road_type == BRAESS_ROAD_DISABLED: if road_type == BRAESS_ROAD_ENABLED: edge_color = Color('Grey') middle_color = Color('Orange') else: edge_color = Color(64, 64, 64) middle_color = Color(64, 64, 64) start_patch = World.patches_array[start_patch.row + 1][start_patch.col - 1] stop_patch = World.patches_array[stop_patch.row - 1][stop_patch.col + 1] for p in self.patches_line(start_patch, stop_patch): p.road_type = road_type for p in self.patches_line(start_patch, stop_patch)[1:-1]: p.set_color(middle_color) if p in self.patches_line(start_patch, stop_patch)[3:-1]: World.patches_array[p.row + 2][p.col].set_color(edge_color) World.patches_array[p.row][p.col - 2].set_color(edge_color) if p in self.patches_line(start_patch, stop_patch)[2:-1]: World.patches_array[p.row][p.col - 1].set_color(edge_color) World.patches_array[p.row + 1][p.col].set_color(edge_color)
def __init__(self, x, y): self.velocity = Vector(*((np.random.rand(2)) * 3)) self.position = Vector(x, y) self.view_radius = 100 random_hue = randint(0, 360) self.color = Color(0, 0, 0) self.color.hsla = (random_hue, 100, 75, 1) self.original_color = Color(0, 0, 0) self.original_color.hsla = (random_hue, 100, 75, 1)
def game_over(frames): """Mostrar a pontuação etc, sair de maneira fluída""" score = int(frames / 10) print("Game over, score: {0}".format(score)) canvas = blank_canvas(ACTUAL_SIZE) pygame.draw.line(canvas, Color('red'), (0, 0), (WIDTH - 1, ACTUAL_HEIGHT - 1)) pygame.draw.line(canvas, Color('red'), (WIDTH - 1, 0), (0, ACTUAL_HEIGHT - 1)) sensehat_display(canvas) pygame.time.wait(2000) sense.show_message("Score: " + str(score), text_colour=Color('navyblue')[:3])
def setup_2(self): """ We have finished the animation that drops the weight. Redefine the resting lengths and colors of the two main cords and switch the drivers for the two bars. """ self.top_cord.reset_length() self.left_cord.reset_length() self.top_cord.color = Color('white') self.left_cord.color = Color('white') Braess_World.state = 2 Agent.some_agent_changed = True
def draw(self): """ (Snake) -> None draw the snake and its food every frame """ # paint snake red and paint food black # draw all foods and bodies of the snake for x, y in self.body: pygame.draw.rect(self.screen, Color('red'), (x, y, self.size, self.size)) for x, y in self.food: pygame.draw.rect(self.screen, Color('black'), (x, y, self.size, self.size))
def create_blank_surface(width, height): """Return a completely transparent Surface of the given dimensions. Args: width (int): The width of the Surface in pixels. height (int): The height of the Surface in pixels. """ blank_surf = Surface((width, height)) blank_surf.fill(Color('magenta')) blank_surf.set_colorkey(Color('magenta')) blank_surf.convert() blank_surf.set_alpha(255) return blank_surf
class OnOffPatch(Patch): # These are rgb colors on_color = Color('white') off_color = Color('black') def __init__(self, *args, **kw_args): super().__init__(*args, **kw_args) self.is_on = False def set_on_off(self, is_on: bool): self.is_on = is_on self.set_color( OnOffPatch.on_color if self.is_on else OnOffPatch.off_color)
def insert_chrom_and_sats(chromosome, satisfactions, window_rows=2): """ Scroll the screen and insert the current best chromosome with unhappy genes indicated. """ Segregation_World.scroll_window(window_rows) chrom_string = chromosome.chromosome_string() green = Color('springgreen3') yellow = Color('yellow') indentation = (gui.PATCH_COLS - len(chrom_string))//2 for c in range(len(chrom_string)): World.patches_array[gui.PATCH_ROWS-2, indentation+c].set_color(yellow if chrom_string[c] == '1' else green) red = Color('red') black = Color('black') for c in range(len(satisfactions)): World.patches_array[gui.PATCH_ROWS-1, indentation+c].set_color(black if satisfactions[c] else red)
def draw_label(self): text = gui.FONT.render(self.label, True, Color('black'), Color('white')) offset = Block.patch_text_offset if isinstance( self, Patch) else Block.agent_text_offset text_center = Pixel_xy((self.rect.x + offset, self.rect.y + offset)) # gui.SCREEN.blit(text, text_center) gui.blit(text, text_center) line_color = Color('white') if isinstance( self, Patch) and self.color == Color('black') else self.color # self.draw_line(line_color=line_color, start_pixel=self.rect.center, end_pixel=text_center) gui.draw_line(start_pixel=self.rect.center, end_pixel=text_center, line_color=line_color)
class Constants: """ Contient toutes les constantes du jeu """ WIDTH = 1024 HEIGHT = 576 SIZE = (WIDTH, HEIGHT) FLAGS = pygame.RESIZABLE BOX_WIDTH = 64 BOX_HEIGHT = 64 BOX_COLOR = Color(255, 255, 255) BG_COLOR = Color(50, 50, 125) MS_PER_TICK = 1 / 60
def game_over(frames): """Print score etc, exit cleanly""" score = int(frames / 10) # Tweak as desired print("Game over, score: {0}".format(score)) # Draw a red cross on the Hat, wait a bit, then display the score there, canvas = blank_canvas(ACTUAL_SIZE) pygame.draw.line(canvas, Color('red'), (0, 0), (WIDTH - 1, ACTUAL_HEIGHT - 1)) pygame.draw.line(canvas, Color('red'), (WIDTH - 1, 0), (0, ACTUAL_HEIGHT - 1)) sensehat_display(canvas) pygame.time.wait(2000) sense.show_message("Score: " + str(score), text_colour=Color('navyblue')[:3])
def on_render(self): if self.graphics_on: self.screen.fill(pygame.color.Color('white')) self.__render_sensors() for v in self.game_state.walls: pygame.draw.rect(self.screen, Color('purple'), v) for v in self.game_state.noactor_actions: pygame.draw.rect(self.screen, Color('green'), v.rect) for a in self.game_state.actors: pygame.draw.rect(self.screen, Color('black'), a.rect) self.game_state.hud.render(self.screen) pygame.display.flip()
def _render_contents(self, surface): s = Surface(self.size, pygame.SRCALPHA) for component in self._children: component.render(s) surface.blit(s, self._rect.topleft) pygame.draw.rect(surface, Color(150, 150, 150), self._scrollbar) height = 10 up_arrow = [(self._scrollbar.centerx, self._scrollbar.top + 2), (self._scrollbar.left + 1, self._scrollbar.top + 2 + height), (self._scrollbar.right - 2, self._scrollbar.top + 2 + height)] pygame.draw.aalines(surface, Color(255, 255, 255), True, up_arrow) down_arrow = [(self._scrollbar.centerx, self._scrollbar.bottom - 2), (self._scrollbar.left + 1, self._scrollbar.bottom - 2 - height), (self._scrollbar.right - 2, self._scrollbar.bottom - 2 - height)] pygame.draw.aalines(surface, Color(255, 255, 255), True, down_arrow)
class InventorySlot(ImageButtonWidget): SELECTED_COLOR = Color("yellow") SELECTED_WIDTH = 2 def __init__(self, pos, gd, size): self.item = None super(InventorySlot, self).__init__(pos, gd, None, size) self.add_callback(MOUSEBUTTONDOWN, self.mouse_down) def set_item(self, item): self.item = item def draw(self, surface): if self.item: surface.blit(self.item.get_inventory_image(), self.rect) if self.selected: pygame.draw.rect(surface, self.SELECTED_COLOR, self.rect, self.SELECTED_WIDTH) @property def selected(self): return self.parent.game.tool is self.item def mouse_down(self, event, widget): if event.button != 1 or not self.item: return if self.selected: self.parent.select(None) elif self.item.is_interactive(self.parent.game.tool): result = self.item.interact(self.parent.game.tool) self.parent.screen.handle_result(result) else: self.parent.select(self.item)
def __init__(self, size, rel_pos=(0, 0), parent=None, color_name="black", debug_name=""): # to create a view we need the size as a tuple of int # rel_pos is the topleft relative to the parent # (MainView doesn't have a parent) # color_name is used when the default draw method is used self._surface = pygame.Surface(size) self._parent = parent # _rel_rect stores the position relative to the parent # _abs_rect stores the position relative to the window self._rel_rect = pygame.Rect(rel_pos, size) self._setAbsRect(parent) if parent: parent.addSubView(self) self._subviews = [] self._background = Color(color_name) self._debug_name = debug_name self._click_cb = { Mouse.BUTTON1: None, Mouse.BUTTON2: None, Mouse.BUTTON3: None, }
def setup(self): """ Set up for state 1. Build the contraption piece by piece. """ self.top_spring = Braess_Link.vertical_linked_nodes(Braess_Link, self.x, Braess_World.top) self.top_cord = self.top_spring.extend_linked_nodes(Braess_Cord) self.bottom_spring = self.top_cord.extend_linked_nodes(Braess_Link) self.weight_cord = self.bottom_spring.extend_linked_nodes(Braess_Cord) # Make node_2 of the weight_cord the weight. Braess_World.weight_node = self.weight_cord.node_2 Braess_World.weight_node.shape_name = CIRCLE Braess_World.weight_node.color = Color('plum4') # ## Done with building state 1. ## # self.adjustable_links = [self.top_spring, self.top_cord, self.bottom_spring, self.weight_cord] SimEngine.gui_set(Braess_World.CUT_CORD, enabled=False) Braess_World.state = 1 Agent.some_agent_changed = True # In case we did the animation in slow motion and this is a second run. # Can't do this when animation ends because we want to stay # in slow motion as the springs contract and lift the weight. SimEngine.fps = 60
def __init__(self, row_col: RowCol, color=Color('black')): super().__init__(row_col.patch_to_center_pixel(), color) self.row_col = row_col self.agents = None self._neighbors_4 = None self._neighbors_8 = None self._neighbors_24 = None
def __init__(self, tile, camera, wx=0, wy=0, color=Color(255, 255, 255)): self.size = TileService.size GameObject.__init__(self, self.size, self.size, wx, wy) sprite = Sprite() sprite.image = TileService.getTile(tile, color) sprite.rect = (wx, wy, self.size, self.size) self.addSprites(sprite, camera)
def hsv(h, s, v, a=100): # ranges H = [0, 360], S = [0, 100], V = [0, 100], A = [0, 100] c = Color(0, 0, 0) c.hsva = map(int, (h, s, v, a)) return (c.r, c.g, c.b, c.a)