Exemplo n.º 1
0
def spawn():
    x = 0
    y = 0
    for i in range(30):
        objectives.append(Objective())
        x = random.randint(0, map_width - 20)
        y = random.randint(0, map_width - 20)
        objectives[-1].box.rect.center = (x, y)
    for i in players:
        x = random.randint(0, map_width - 20)
        y = random.randint(0, map_width - 20)
        i.box.rect.center = (x, y)
        i.box.color = Color(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
Exemplo n.º 2
0
    def __init__(self, start, end, color=[None]):
        if None in color:
            color = [random()*255, random()*255, random()*255]
        self.pos = np.array(start, dtype=np.float64)
        self.end = np.array(end)
        self.velocity = np.zeros(2)

        self.max_speed = 2*(1.75+random()*0.5)
        self.mass = 0.2*(0.9+random()*0.2)

        self.color = Color(int(color[0]),
                                  int(color[1]),
                                  int(color[2]))
Exemplo n.º 3
0
    def render(self, disp, font):
        img_num = int(self.amount / self.capacity * 4)

        if self.over:
            img_num = 5

        self.image = image.load("img/tank/" + str(img_num) + ".png")
        disp.blit(self.image, self.rect)

        text_surface = font.render(str(self.water), True, Color("#111111"))
        text_rect = text_surface.get_rect()
        text_rect.center = (self.rect.centerx - 12, self.rect.centery - 12)
        disp.blit(text_surface, text_rect)
Exemplo n.º 4
0
    def display_dungeon_node_bindings(self):
        alternative_path_index = 0
        dungeon_alternative_index = 0
        for index, stage_rect_node in enumerate(self.stage_rect_node_list):
            if self.current_realm_map[index].right_child is not None:
                if self.current_realm_map[
                        index].right_child.dungeon_node is not None:

                    current_stage_alternative_center = self.stage_rect_alternative_node_list[
                        alternative_path_index].center
                    current_stage_dungeon_center = self.stage_rect_dungeon_node[
                        dungeon_alternative_index].center

                    draw.line(self.surface, Color('Brown'),
                              current_stage_alternative_center,
                              current_stage_dungeon_center,
                              int(self.binding_height * 1.5))
                    draw.line(self.surface, Color('Tomato'),
                              current_stage_alternative_center,
                              current_stage_dungeon_center,
                              int(self.binding_height / 1.2))

                    dungeon_alternative_index += 1
                alternative_path_index += 1

            if self.current_realm_map[index].dungeon_node is not None:
                current_stage_node_center = stage_rect_node.center
                current_stage_dungeon_center = self.stage_rect_dungeon_node[
                    dungeon_alternative_index].center
                draw.line(self.surface, Color('Brown'),
                          current_stage_node_center,
                          current_stage_dungeon_center,
                          int(self.binding_height * 1.5))
                draw.line(self.surface, Color('Tomato'),
                          current_stage_node_center,
                          current_stage_dungeon_center,
                          int(self.binding_height / 1.2))

                dungeon_alternative_index += 1
Exemplo n.º 5
0
def convert_color(c: Union[str, tuple]) -> Tuple[float, float, float, float]:
    """Convert a color to an RGBA tuple."""
    if isinstance(c, str):
        try:
            col = Color(c)
        except ValueError:
            if c.startswith('#'):
                raise ValueError(f"Malformed hex color {c!r}") from None
            raise
        return np.array(memoryview(col), dtype='u1').astype('f4') / 255.0
    else:
        assert 3 <= len(c) <= 4, "Invalid color length"
        return np.array(tuple(c) + (1,) * (4 - len(c)), dtype='f4')
Exemplo n.º 6
0
    def __init__(self, width=1024, height=768):
        self.screen = None
        self.width = width
        self.height = height
        self.done = False
        self.thumbs = []
        self.thumb_w = 64
        self.screen = pygame.display.set_mode((width, height))
        self.color_bg = Color("gray20")

        pygame.init()
        pygame.display.set_caption("colors.py : ninmonkey v{}".format(VERSION))
        self.clock = pygame.time.Clock()
Exemplo n.º 7
0
    def __init__(self, size=(0, 0)):
        super().__init__(size, (0, 0, 0, 255))

        self._txt_col = Color(25, 75, 255)
        self._hsva_buf = self._txt_col.hsva
        self._start = 0
        self._speed = 1

        self._should_advance = False

        title = GameObject("Title")
        title.add_behaviour(FontRenderer("HErC presents", 100, self._txt_col))
        self.add_game_object(title, UI)
Exemplo n.º 8
0
 def __init__(self):
     self.image = pygame.surface.Surface((13,13))
     pygame.draw.line(self.image, Color('yellow'), (6,0), (6,12), 5)
     pygame.draw.line(self.image, Color('yellow'), (0,6), (12,6), 5)
     pygame.draw.line(self.image, Color(0,0,99), (6,0), (6,12), 3)
     pygame.draw.line(self.image, Color(0,0,99), (0,6), (12,6), 3)
     pygame.draw.line(self.image, Color('black'), (6,0), (6,120), 1)
     pygame.draw.line(self.image, Color('black'), (0,6), (12,6), 1)
     self.image.set_colorkey(Color('black'))
     self.rect = self.image.get_rect(center=(0,0))
     pygame.mouse.set_visible(False)
Exemplo n.º 9
0
def make_stats_box(screen, player, dungeon_level, box_x_start, box_heigth,
                   box_width):
    """Create the box displaying the stats
       @param screen: the screen to draw on
       @param player: the player object
       @param dungeon_level: the current dungeon level
       @param box_x_start: rectangle upper left corner x-coordinate 
       @param box_heigth: height of rectangle
       @param box_width: width of rectangle
    """

    #create the rectangle
    stats_box = Rect(box_x_start, 0, box_width, box_heigth)
    #set font type
    stats_font = font.SysFont('arial', 20)
    #render game info
    player_HP = stats_font.render("Hit Points: " + str(player.getHP()), True,
                                  Color('white'))
    player_AP = stats_font.render(
        "Attack Power: " + str(player.getAttackPower()), True, Color('white'))
    player_Armor = stats_font.render("Armor: " + str(player.getArmor()), True,
                                     Color('white'))
    level = stats_font.render("Dungeon Level: " + str(dungeon_level), True,
                              Color('white'))

    #For each line of text, draw it on the screen and move the rectangle for the next line
    screen.fill(Color('Black'), stats_box)
    screen.blit(player_HP, stats_box)
    screen.blit(player_AP, stats_box.move(0, player_HP.get_height()))
    screen.blit(
        player_Armor,
        stats_box.move(0,
                       player_HP.get_height() + player_AP.get_height()))
    screen.blit(
        level,
        stats_box.move(
            0,
            player_HP.get_height() + player_AP.get_height() +
            player_Armor.get_height()))
Exemplo n.º 10
0
    def draw_agent(self, agent, agent_color):
        # Draw a circle and a line representing the heading
        line_color = Color(255,255,255)
        radius = agent.radius
        angle = agent.theta

        endpoint_x = agent.px + (radius * math.cos(angle))
        endpoint_y = agent.py + (radius * math.sin(angle))

        rect = pygame.draw.circle(self.surface, agent_color, (agent.px, agent.py), agent.radius)
        pygame.draw.line(self.surface, line_color, (agent.px, agent.py), (endpoint_x, endpoint_y))
        # Add bounding rect to dict
        self.agent_rects[agent.id] = rect
Exemplo n.º 11
0
def draw_tree_angle(window, x1, y1, x2, y2, depth, angle):
    if depth == 0:
        return

    x3, y3 = rotate(x1, y1, x2, y2, -90)
    x4, y4 = rotate(x2, y2, x1, y1, 90)

    # color = Color(255, 0, 0, 255) if depth % 2 == 0 else Color(255, 255, 255, 255)
    colors = [
        Color(255, 0, 0, 255),
        Color(255, 255, 255, 255),
    ]
    color = colors[depth % len(colors)]

    gfxdraw.line(window, x1, y1, x2, y2, color)
    gfxdraw.line(window, x1, y1, x3, y3, color)
    gfxdraw.line(window, x2, y2, x4, y4, color)
    gfxdraw.line(window, x3, y3, x4, y4, color)

    new_x, new_y = rotate(x3, y3, x4, y4, -angle)
    draw_tree_angle(window, x3, y3, new_x, new_y, depth - 1, angle)
    draw_tree_angle(window, new_x, new_y, x4, y4, depth - 1, angle)
Exemplo n.º 12
0
 def __init__(self, env_size, background_color, start_color, end_color,
              reflection_order):
     self.width = env_size[0]
     self.height = env_size[1]
     self.background_color = background_color
     self.reflection_order = reflection_order
     self.particles_per_source = 360
     self.sources = []
     self.particles = []
     self.source_size = 10
     self.source_color = Color("Red")
     self.graduated_colors = create_range_of_colors(start_color, end_color,
                                                    self.reflection_order)
class CustomCell1(NewCell):
    # subclass all of your actual cells from your base cell
    # a cells type is a way for other cells to identiy it
    type = 0
    # add the color they begin as (if not stay as the whole time)
    origin_color = Color(255, 0, 0, 255)
    # add the rules they follow, this is an array with string versions of methods
    # rules shared by multiple cells can be placed on the NewCell equivalent
    rules = ['first_rule']

    def first_rule(self):
        if hasattr(self, 'have_fun'):
            self.next_type = CustomCell2
Exemplo n.º 14
0
    def _ensure_color(self, value) -> Color:
        if isinstance(value, Color):
            return value
        if isinstance(value, (tuple, list)):
            self._check_size(value)
            return Color(*value)
        if self._is_hex(value):
            return Color(value)

        try:
            return Color(value)
        except:
            pass

        try:
            return Color(*value)
        except:
            pass

        raise ValueError(
            f'bad color value "{value}", must be a color name, hex (6 or 8 length), or a list/tuple (3 or 4 length)'
        )
Exemplo n.º 15
0
    def __init__(self, game, cfg_display):
        self._game = game
        self._world = None  #This may be unstable, get it on construct()
        self._interface = None  #Again, wait until construct()
        self.cfg_display = cfg_display
        self._w = self.cfg_display["window_width"]
        self._h = self.cfg_display["window_height"]
        self.bg_color = Color(self.cfg_display["background_color"])

        self.asset_manager = AssetManager(self.cfg_display["assets_url"])

        self.actor_sprites = []
        self.background_sprites = None  #TODO does not handle 'fancy' backgrounds yet
Exemplo n.º 16
0
def draw_background(screen, tile_img, field_rect):
    img_rect = tile_img.get_rect()

    nrows = int(screen.get_height() / img_rect.height) + 1
    ncols = int(screen.get_width() / img_rect.width) + 1

    for y in range(nrows):
        for x in range(ncols):
            img_rect.topleft = (x * img_rect.width, y * img_rect.height)
            screen.blit(tile_img, img_rect)

    field_color = (109, 41, 1)
    draw_rimmed_box(screen, field_rect, field_color, 4, Color('black'))
Exemplo n.º 17
0
    def __init__(self, width=64):
        self.surface_thumb = Rect(0, 0, width, width)
        self.rect_thumb = Rect(0, 0, width, width)

        # ex [1] the standard pygame.Color("white") , same as Color("#ffffff")
        self.color_bg = Color("white")
        # ex [2] random color with a filter:
        self.color_bg = random_color('light')
        self.color_border = random_color('dark')

        # create empty surface;  fill it
        self.surface_thumb = pygame.Surface([width, width])
        self.surface_thumb.fill(self.color_bg)
Exemplo n.º 18
0
class Colors:
    GOJIRA_BG_ACCENT = Color("#3840b0")
    GOJIRA_BG_LIGHT = Color("#7c8ce0")
    WHITE = Color("#FFFFFF")
    BLACK = Color("#000000")

    SHADOW_ACCENT = Color("#444466")
    SHADOW = Color("#AAAAAA")
Exemplo n.º 19
0
 def init(self, pid):
     """Initialize the player."""
     # Attributes
     self.id = pid
     self.border = self.parent.border
     self.resource = self.control.resource
     # Player rectangle
     self.size = self.resource.image.get(self.ref)[0].get_size()
     self.rect = Rect((0, 0), self.size)
     if pid == 1:
         self.rect.bottomleft = self.border.rect.bottomleft
     else:
         self.rect.bottomright = self.border.rect.bottomright
     # Player state
     self.speed = self.remainder = xytuple(0.0, 0.0)
     self.control_dir = Dir.NONE
     self.save_dir = Dir.NONE
     self.pos = Dir.DOWN
     self.fixed = True
     self.ko = False
     self.steps = [self.rect]
     # Animation timer
     self.timer = Timer(self, stop=self.period, periodic=True).start()
     # Loading timer
     self.loading_timer = Timer(
         self, start=self.init_speed, stop=self.max_loading_speed
     )
     # Delay timer
     self.delay_timer = Timer(self, stop=self.pre_jump, callback=self.delay_callback)
     # Dying timer
     self.blinking_timer = Timer(
         self.parent.parent, stop=self.blinking_period, periodic=True
     )
     # Debug
     if self.control.settings.debug_mode:
         RectModel(self, "head", Color("red"))
         RectModel(self, "body", Color("green"))
         RectModel(self, "legs", Color("blue"))
Exemplo n.º 20
0
    def render(self, close=False, debug_info=None):
        if close:
            self.drawer = None
            return

        if self.drawer is None or self.drawer.terminated:
            self.drawer = PygameViewer(
                self.render_size,
                self.render_size,
                x_bounds=(-self.BOUNDARY_DIST, self.BOUNDARY_DIST),
                y_bounds=(-self.BOUNDARY_DIST, self.BOUNDARY_DIST),
                render_onscreen=self.render_onscreen,
            )

        self.drawer.fill(Color('white'))
        self.drawer.draw_solid_circle(
            self._target_position,
            self.TARGET_RADIUS,
            Color('green'),
        )
        self.drawer.draw_solid_circle(
            self._position,
            self.BALL_RADIUS,
            Color('blue'),
        )

        if debug_info is not None:
            debug_subgoals = debug_info.get('subgoal_seq', None)
            if debug_subgoals is not None:
                plasma_cm = plt.get_cmap('plasma')
                num_goals = len(debug_subgoals)
                for i, subgoal in enumerate(debug_subgoals):
                    color = plasma_cm(float(i) / num_goals)
                    # RGBA, but RGB need to be ints
                    color = Color(
                        int(color[0] * 255),
                        int(color[1] * 255),
                        int(color[2] * 255),
                        int(color[3] * 255),
                    )
                    self.drawer.draw_solid_circle(
                        subgoal,
                        self.BALL_RADIUS / 2,
                        color,
                    )
            best_action = debug_info.get('oracle_qmax_action', None)
            if best_action is not None:
                self.drawer.draw_segment(self._position,
                                         self._position + best_action,
                                         Color('red'))
            policy_action = debug_info.get('learned_action', None)
            if policy_action is not None:
                self.drawer.draw_segment(self._position,
                                         self._position + policy_action,
                                         Color('green'))

        self.drawer.render()
        self.drawer.tick(self.render_dt_msec)
Exemplo n.º 21
0
def Spawn(type):
    if type == 0:  # Default
        life = Life()
        x, y = 10, 10
        life.Birth(surface, "0 Default", x, y, Color(128, 128, 128, 0), 2, 2,
                   2)
        LifeForms.append(life)
    elif type == 1:  # Violence
        life = Life()
        x, y = width - 10, 10
        life.Birth(surface,
                   "1 Violence",
                   x,
                   y,
                   Color(255, 0, 0, 0),
                   1,
                   1,
                   1,
                   Violence=2)
        LifeForms.append(life)
    elif type == 2:  # Speed
        life = Life()
        x, y = 10, height - 10
        life.Birth(surface, "2 Speed", x, y, Color(0, 255, 0, 0), 3, 1, 1)
        LifeForms.append(life)
    elif type == 3:  # Intelligence
        life = Life()
        x, y = width - 10, height - 10
        life.Birth(surface,
                   "3 Intelligence",
                   x,
                   y,
                   Color(0, 0, 255, 0),
                   1,
                   1,
                   4,
                   Altruism=1)
        LifeForms.append(life)
Exemplo n.º 22
0
    def render(self, close=False, tick=True):
        if close:
            self.drawer = None
            return

        if self.drawer is None or self.drawer.terminated:
            self.drawer = PygameViewer(
                self.render_size,
                self.render_size,
                x_bounds=(-self.boundary_dist - self.ball_radius,
                          self.boundary_dist + self.ball_radius),
                y_bounds=(-self.boundary_dist - self.ball_radius,
                          self.boundary_dist + self.ball_radius),
                render_onscreen=self.render_onscreen,
            )
        self.drawer.fill(Color('white'))
        if self.show_goal:
            self.drawer.draw_solid_circle(
                self._target_position,
                self.target_radius,
                Color('green'),
            )
        self.drawer.draw_solid_circle(
            self._position,
            self.ball_radius,
            Color('blue'),
        )

        for wall in self.walls:
            self.drawer.draw_segment(
                wall.endpoint1,
                wall.endpoint2,
                Color('black'),
            )
            self.drawer.draw_segment(
                wall.endpoint2,
                wall.endpoint3,
                Color('black'),
            )
            self.drawer.draw_segment(
                wall.endpoint3,
                wall.endpoint4,
                Color('black'),
            )
            self.drawer.draw_segment(
                wall.endpoint4,
                wall.endpoint1,
                Color('black'),
            )

        self.drawer.render()
        if tick:
            self.drawer.tick(self.render_dt_msec)
Exemplo n.º 23
0
    def __init__(self):
        # Initialize pygame, create a window,
        # and create clock to limit FPS
        pygame.init()
        self.window = pygame.display.set_mode((1001, 601))
        pygame.display.set_caption("Conway's Game of Life")
        self.fpsClock = pygame.time.Clock()
        self.fpsLimit = 2
        self.simRunning = False

        # Create a 40x30 array of cells
        self.grid_width = 40
        self.grid_height = 30

        self.grid = [[Cell() for x in xrange(self.grid_height)]
                     for x in xrange(self.grid_width)]

        # Set each square's location
        for i in xrange(self.grid_width):
            for j in xrange(self.grid_height):
                self.grid[i][j] = Cell((i * 20, j * 20))

        # Create interface control buttons
        self.startButton = pygame.Rect((840, 60), (120, 41))
        self.startButtonText = pygame.font.Font(None, 20).render(
            "Start Simulation", 1, Color("black"))
        self.resetButton = pygame.Rect((840, 140), (120, 41))
        self.resetButtonText = pygame.font.Font(None, 20).render(
            "Reset Simulation", 1, Color("black"))
        self.speedText = pygame.font.Font(None,
                                          20).render("Simulation Speed", 1,
                                                     Color("black"))
        self.speedDisplayBox = pygame.Rect((870, 230), (61, 31))
        self.speedUpButton = TriButton((959, 245), (935, 230), (935, 260))
        self.speedDownButton = TriButton((840, 245), (865, 230), (865, 260))

        # Get multithreading ready
        self.thread = Thread(target=self.run)
Exemplo n.º 24
0
def update():
    if keyboard.up: cars[0].speed += .15
    if keyboard.down: cars[0].speed -= .15
    if(cars[0].speed != 0):
        if keyboard.left: cars[0].angle += 2
        if keyboard.right: cars[0].angle -= 2
    for c in range(4):
        crash = False
        for i in range(4):
            if cars[c].collidepoint(cars[i].center) and c != i:
                crash = True
                cars[c].speed = -(randint(0,1)/10)
        if crash:
            newPos = calcNewXY(cars[c].center, 2, math.radians(randint(0,360)-cars[c].angle))
        else:
            newPos = calcNewXY(cars[c].center, cars[c].speed*2, math.radians(180-cars[c].angle))
        if c == 0:
            ccol = controlimage1.get_at((int(newPos[0]),int(newPos[1])))
        else:
            ccol = controlimage2.get_at((int(newPos[0]),int(newPos[1])))
        if cars[c].speed != 0:
            if ccol != Color('blue') and ccol != Color('red'):
                cars[c].center = newPos
            else:
                if c > 0:
                    if ccol == Color('blue'):
                        cars[c].angle += 5
                    if ccol == Color('red'):
                        cars[c].angle -= 5
                cars[c].speed = cars[c].speed/1.1
        if c > 0 and cars[c].speed < 1.8+(c/10):
            cars[c].speed += randint(0,1)/10
            if crash:
                cars[c].angle += ((ccol[1]-136)/136)*(2.8*cars[c].speed)
            else:
                cars[c].angle -= ((ccol[1]-136)/136)*(2.8*cars[c].speed)
        else:
            cars[c].speed = cars[c].speed/1.1
Exemplo n.º 25
0
    def __init__(self, width, height, background=None):
        self.sprites = []
        self.mainLoop = True
        self.width = width
        self.height = height
        self.size = (self.width, self.height)
        self.win = pygame.display.set_mode((width, height))
        self.clock = pygame.time.Clock()
        self.FPS = 60
        self.bg_color = Color("white")
        self.background = background
        self.keyList = None
        self.stage = None

        self.frame_count = 0

        self.pen_surface = pygame.surface.Surface((width, height))
        self.pen_surface.fill(Color("white"))

        self.show_hit_box = False

        self.default_costume = None
        self.load_default_costume()
Exemplo n.º 26
0
	def water(self, surface, city_map):
		if self.counter > 1:
			pygame.draw.line(surface, Color("lightblue"), self.bumper_rect.center, self.destination.rect.center, 5)
			self.counter -= 1
		else:
			for fire in city_map.flames:
				if fire.rect == self.destination.rect:
					fire.location.on_fire = False
					city_map.flames.remove(fire)
			self.destination = self.origin
			self.destination = self.origin
			self.find_goal(self.rect.centerx, self.rect.centery)
			self.stopped = False
			self.watering = False
Exemplo n.º 27
0
    def main_loop(self):
        """ events, physics, render"""
        while not self.done:
            self.event_loop()
            self.screen.fill(Color("gray20"))

            self.player.update(self.screen, self.keys)
            #self.objects.update()

            self.player.draw(self.screen)
            #self.objects.draw()

            pg.display.flip()
            self.clock.tick(self.fps)
Exemplo n.º 28
0
def actual_color(c):
	if type(c) is tuple:
		if len(c) == 3:
			r, g, b = c
			c = Color(r, g, b)
		else:
			r, g, b, a = c
			c = Color(r, g, b, a)
	elif type(c) is Color:
		c = Color(c.r, c.g, c.b, c.a)
	else:
		c = Color(c)
	
	if invert_colors:
		h, s, v, a = c.hsva
		#h = (h + 180.0) % 360.0
		#s = (s + 50.0) % 100.0
		v = (v + 99.9) % 100.0
		c.hsva = (h, s, v, a)
		return c
		return Color(255 - c.r, 255 - c.g, 255 - c.b, c.a)
	else:
		return c
Exemplo n.º 29
0
    def draw_head(self, surface, space):
        """Draws skeletons head"""
        head = self.body["Head"]
        neck = self.body["Neck"]
        radius = int(round(float(space) * HEAD_RADIUS))
        pygame.draw.ellipse(
            surface, Color(self.color),
            Rect(head["X"] - radius, head["Y"] - radius + space, 2 * radius,
                 2 * radius), 5)
        self.draw_line(surface, (head["X"], head["Y"] + space),
                       (head["X"], head["Y"] + space))

        self.draw_line(surface, (head["X"], head["Y"] + space),
                       (neck["X"], neck["Y"] + space))
Exemplo n.º 30
0
 def __init__(self, x, y):
     Sprite.__init__(self)
     self.vel_x = 0
     self.vel_y = 0
     self.camera = 0
     self.image = Surface((40, 40))
     self.image.fill(Color('Red'))
     self.rect = Rect(x, y, 40, 40)
     self.death_pos = (0, 0)
     self.on_ground = False
     self.direction = 'right'
     self.state = 'regular'
     self.platform_check = False
     self.frame = 0