Пример #1
0
def undo_move(board, row, col):
    drop_piece(board, row, col, 0)
    filled_circle(screen, int(row), int(col), radius, black)
    aacircle(screen, int(row), int(col), radius, black)
    draw_black_coin(
        int(col * sq_size) + 5, height - int(row * sq_size + sq_size - 5))
    print_board(board)
Пример #2
0
    def disp_board(self):
        score = [0, 0]
        RED = (255, 0, 0)
        BLUE = (0, 0, 255)
        self.Black = (0, 0, 0)

        for i, point in enumerate(self.gamm.board):

            gfxdraw.filled_circle(self.SURF, point.x, point.y, 5, self.Black)
            gfxdraw.aacircle(self.SURF, point.x, point.y, 5, self.Black)
            dot_num = self.dot_font.render(str(i), True, self.Black)
            self.SURF.blit(dot_num, (point.x + 10, point.y - 20))

        if len(self.gamm.moves_done) > 0:
            for move in self.gamm.moves_done:
                p1 = self.gamm.board[self.gamm.id_to_index(move.partners[0])]
                p2 = self.gamm.board[self.gamm.id_to_index(move.partners[1])]
                thickness = 3
                if move.O == "X":
                    pygame.draw.line(self.SURF, BLUE, (p1.x, p1.y),
                                     (p2.x, p2.y), thickness)
                elif move.O == "O":
                    pygame.draw.line(self.SURF, RED, (p1.x, p1.y),
                                     (p2.x, p2.y), thickness)

            pygame.display.update()
Пример #3
0
    def render(self, surf: pygame.Surface):
        color = self.color
        n = len(self.points) - 1

        i = 0
        last_pos = None
        for t in range(self.reso):
            t /= self.reso
            tt = 1 - t

            end = V2(0, 0)
            for k, p in enumerate(self.points):
                end += comb(n, k) * p * t**k * tt**(n - k)

            if end.ti == last_pos:
                i += 1
                continue
            else:
                last_pos = end.ti

            if callable(self.color):
                color = self.color(t)

            if self.line_width < 2:
                surf.set_at(end.ti, color)
            else:
                x, y = end.ti
                gfxdraw.aacircle(surf, x, y, round(self.line_width / 2), color)
                gfxdraw.filled_circle(surf, x, y, round(self.line_width / 2),
                                      color)

        print(i, self.reso, sep='/')
Пример #4
0
 def draw(self, ctx):
     if self.img != None:
         ctx.blit(self.img, (int(self.x) - self.r, int(self.y) - self.r))
     else:
         gfxdraw.filled_circle(ctx, int(self.x), int(self.y), self.r,
                               self.color)
         gfxdraw.aacircle(ctx, int(self.x), int(self.y), self.r, self.color)
Пример #5
0
    def _do_graphics(self, y_r1, y_r2, x_ball, y_ball):
        """
        Draw the main game graphics.

        :param y_r1: y coordinate of the first pad
        :param y_r2: y coordinate of the second pad
        :param x_ball: x coordinate of the ball
        :param y_ball: y coordinate of the ball
        :return: None
        """
        self.__screen.fill(COLOR_LIGHT_GRAY)
        for i in range(int(self.__width / self.__grid_width)):
            for j in range(int(self.__height / self.__grid_width)):
                gfxdraw.aacircle(self.__screen,
                                 self.__grid_x_offset + i * self.__grid_width,
                                 self.__grid_y_offset + j * self.__grid_width,
                                 self.__grid_radius, COLOR_SILVER)

        aa_rounded_rect(self.__screen,
                        (self.__x_r1, y_r1, self.__width_r, self.__height_r),
                        COLOR_BLUE_2, 1)
        aa_rounded_rect(self.__screen,
                        (self.__x_r2, y_r2, self.__width_r, self.__height_r),
                        COLOR_RED_2, 1)
        gfxdraw.aacircle(self.__screen, round(x_ball), round(y_ball),
                         self.__ball_radius, COLOR_GRAY)
        gfxdraw.filled_circle(self.__screen, round(x_ball), round(y_ball),
                              self.__ball_radius, COLOR_GRAY)

        pygame.display.flip()
Пример #6
0
	def draw(self, surface):
		if self.status == 'dead':
			return
		elif self.status == 'dying':
			N = int(np.sqrt(self.power) * 10 * 4 * (float(self.death_animation) / clock.GOAL_FPS)**2)
		else:
			N = int(10 * np.sqrt(self.power))

		c_inner, c_outer = self.colouring()

		r = self.radius
		x = self.position[0]
		y = self.position[1]

		for i in range(N):

			# d = rn.uniform(0,360)
			# gfx.pixel(surface, int(x+r*np.cos(d)), int(y+r*np.sin(d)), 3, c_inner)
			if self.direction is None:
				d = rn.uniform(0,360)
			else:
				s = 180 * 4 * (float(self.death_animation) / clock.GOAL_FPS)**2
				d = self.direction + rn.uniform(-s,s)
			gfx.filled_circle(surface, int(x+r*np.cos(np.radians(d))), int(y+r*np.sin(np.radians(d))), 3, c_inner)
			gfx.aacircle(surface, int(x+r*np.cos(np.radians(d))), int(y+r*np.sin(np.radians(d))), 3, c_outer)
Пример #7
0
    def draw(self):
        pygame.draw.rect(self.win, self.colour,
                         (self.x, self.y, self.width, self.height))

        if self.vertical:
            if self.curved:
                pygame.draw.circle(self.win, self.colour,
                                   (self.x + self.width // 2, self.y),
                                   self.radius)
                pygame.draw.circle(
                    self.win, self.colour,
                    (self.x + self.width // 2, self.y + self.height),
                    self.radius)
            circle = (self.x + self.width // 2,
                      int(self.y + (self.max - self.value) /
                          (self.max - self.min) * self.height))
        else:
            if self.curved:
                pygame.draw.circle(self.win, self.colour,
                                   (self.x, self.y + self.height // 2),
                                   self.radius)
                pygame.draw.circle(
                    self.win, self.colour,
                    (self.x + self.width, self.y + self.height // 2),
                    self.radius)
            circle = (int(self.x + (self.value - self.min) /
                          (self.max - self.min) * self.width),
                      self.y + self.height // 2)

        gfxdraw.filled_circle(self.win, *circle, self.handleRadius,
                              self.handleColour)
        gfxdraw.aacircle(self.win, *circle, self.handleRadius,
                         self.handleColour)
Пример #8
0
 def draw(self):
     gfxdraw.aacircle(environment.explosionSurface,
                 self.x,self.y,
                 self.r,self.col)
     gfxdraw.filled_circle(environment.explosionSurface,
                 self.x,self.y,
                 self.r,self.col)
Пример #9
0
    def circle(self, center, radius, color=Color.DEFAULT, width=1, filled=False,
               alpha=-1, aalias=True):
        """
        Draw a circle given a location and a radius.
        :param center:
        :param radius:
        :param color:
        :param width:
        :param filled:
        :param alpha:
        :param aalias:
        :return:
        """
        if filled:
            width = 0
        if aalias == False or width > 1 or filled:
            sdl.draw.circle(self._surface,
                            self._csv_rgb2sdl_color(color, alpha),
                            center, int(radius), int(width))
        else:
            gfxdraw.aacircle(self._surface, int(center[0]), int(center[1]),
                             int(radius), self._csv_rgb2sdl_color(color, alpha))

        cen = tuple(int(x) for x in center)
        self._svg.add(self._svg.circle(center=cen, r=radius))

        return None
Пример #10
0
    def render(self, screen):
        """Renders the selected and unselected lines and the handle

        Parameters
        ----------
        screen: pygame.Surface
            pygame screen
        """
        pygame.draw.line(screen, self.line_a_color, self.start_a, self.end_a,
                         2)
        pygame.draw.line(screen, self.line_b_color, self.start_b, self.end_b,
                         2)
        if self.pressed:
            shadow = pygame.Surface((50, 50), pygame.SRCALPHA)
            pygame.draw.circle(shadow, (66, 134, 244, 50), (25, 25), 25)
            screen.blit(shadow,
                        (self.ellipse_pos[0] - 25, self.ellipse_pos[1] - 25))
        elif self.hover:
            shadow = pygame.Surface((40, 40), pygame.SRCALPHA)
            pygame.draw.circle(shadow, (66, 134, 244, 50), (20, 20), 20)
            screen.blit(shadow,
                        (self.ellipse_pos[0] - 20, self.ellipse_pos[1] - 20))
        gfxdraw.filled_circle(screen, self.ellipse_pos[0], self.ellipse_pos[1],
                              10, self.ellipse_color)
        gfxdraw.aacircle(screen, self.ellipse_pos[0], self.ellipse_pos[1], 10,
                         self.ellipse_color)
Пример #11
0
def circle(surface: Surface, x: int, y: int, r: int, colour):
    x = int(x)
    y = int(y)
    r = int(r)

    aacircle(surface, x, y, r, colour)
    filled_circle(surface, x, y, r, colour)
Пример #12
0
 def getDiceSurface(self, surface, n, rectArgs):
     if (n > 0):
         x, y, width, height = rectArgs
         dice = {
             1: [[False] * 3, [False, True, False], [False] * 3],
             2: [[True, False, False], [False] * 3, [False, False, True]],
             3: [[True, False, False], [False, True, False],
                 [False, False, True]],
             4: [[True, False, True], [False] * 3, [True, False, True]],
             5: [[True, False, True], [False, True, False],
                 [True, False, True]],
             6: [[True, False, True]] * 3
         }
         diceList = dice[n]
         spacing = width / 7
         for i in range(3):
             for j in range(3):
                 x = 2 * i + 1
                 y = 2 * j + 1
                 x0 = int(x * spacing)
                 y0 = int(y * spacing)
                 x1 = int(x0 + spacing)
                 y1 = int(y0 + spacing)
                 r = spacing / 2
                 cx, cy = x0 + r, y0 + r
                 cx, cy = int(cx), int(cy)
                 r = int(r * 1.5)
                 if (diceList[i][j]):
                     gfxdraw.aacircle(surface, cx, cy, r, Colors.WHITE)
                     gfxdraw.filled_circle(surface, cx, cy, r, Colors.WHITE)
Пример #13
0
    def draw(self, surface):

        # cast to center
        sx = ((self.x - width / 2) / self.z) * width
        sy = ((self.y - height / 2) / self.z) * height

        # cast back for drawing
        sx = math.floor(sx + width / 2)
        sy = math.floor(sy + height / 2)

        # radius
        r = math.floor(-(r_max / width) * self.z + r_max)

        # draw star
        gfxdraw.aacircle(surface, sx, sy, r, (255, 255, 255))
        gfxdraw.filled_circle(surface, sx, sy, r, (255, 255, 255))

        # calculate previous location
        psx = math.floor(((self.x - width / 2) / self.pz) * width + width / 2)
        psy = math.floor(((self.y - height / 2) / self.pz) * height +
                         height / 2)

        # draw linne
        pygame.draw.line(surface, (255, 255, 255), (psx, psy), (sx, sy), 1)

        # set current depth
        self.pz = (self.z + 2 * speed)
Пример #14
0
    def draw(self, game_data: GameData):
        """
        Draws the game state, including the board and the pieces.
        :param game_data: All of the data associated with the game.
        """
        if game_data.action == "undo":
            filled_circle(
                self.screen,
                game_data.last_move_row,
                game_data.last_move_col,
                self.game_data.radius,
                black,
            )

            aacircle(
                self.screen,
                game_data.last_move_row,
                game_data.last_move_col,
                self.game_data.radius,
                black,
            )

            self.draw_black_coin(
                game_data.last_move_col * self.game_data.sq_size + 5,
                self.game_data.height -
                (game_data.last_move_row * self.game_data.sq_size +
                 self.game_data.sq_size - 5),
            )

            game_data.game_board.print_board()
            game_data.action = None

        self.draw_board(game_data.game_board)
Пример #15
0
 def draw_o(self, loc):
     B = self.board
     loc = B.resolve_loc(loc)
     rad = iround((B.tilesize/2) * 0.6)
     gfxdraw.filled_circle(B.sfc, loc[0], loc[1], rad, (120,120,120))
     gfxdraw.aacircle(B.sfc, loc[0], loc[1], rad + 2, black)
     B.scr.blit(B.sfc, (0,0))
Пример #16
0
 def draw(self,screen):
     if not self.selected:
         self.reDrawImage()
     else:
         #pygame.draw.circle(self.image,(255,0,0), (self.cellSize// 2, self.cellSize// 2),25,1)
         gfxdraw.aacircle(self.image, self.cellSize// 2, self.cellSize// 2, 20,self.color)
     screen.blit(self.image,self.rect)
Пример #17
0
	def draw(self):
		global BLINDMODE
		for s in self.mainplayer.selected:
			gfxdraw.aacircle(self.screen,s.x,s.y,s.radius+5,selectedcolor)
			gfxdraw.filled_circle(self.screen,s.x,s.y,s.radius+5,selectedcolor)
		
			gfxdraw.aacircle(self.screen,s.x,s.y,s.radius+3,(0,0,0))
			gfxdraw.filled_circle(self.screen,s.x,s.y,s.radius+3,(0,0,0))
		
		for planet in self.planets:
			planet.draw(self.screen)
			if not BLINDMODE:
				planet.drawpower(self.screen)
			else:
				if planet.team==self.mainplayer.team or planet.team==0:
					planet.drawpower(self.screen)
		for fleet in self.fleets:
			fleet.draw(self.screen)
		self.drawselectionbox(self.screen)
		if self.paused:
			pause=pygame.Rect(0,0,30,100)
			pause.center=map(lambda l:l/2,self.screen.get_size())
			pause.x-=30
			pygame.draw.rect(self.screen,(255,255,255),pause)
			pause.x+=60
			pygame.draw.rect(self.screen,(255,255,255),pause)
Пример #18
0
 def draw(self, screen, aa=False, color=None, image=None):
     if image is not None and color is not None:
         planet_texture = GUI.Background(
             'physics_weed.png',
             [round(self.pos_x), round(self.pos_y)])
         planet_texture.image = GUI.colorize(planet_texture.image, color)
         screen.blit(planet_texture.image, planet_texture.rect)
     elif image is not None:
         planet_texture = GUI.Background(
             'physics_weed.png',
             [round(self.pos_x), round(self.pos_y)])
         screen.blit(planet_texture.image, planet_texture.rect)
     elif not aa:
         if color is None:
             pg.draw.circle(screen, (self.R, self.G, self.B),
                            (round(self.pos_x), round(self.pos_y)),
                            self.radius)
         else:
             pg.draw.circle(screen, color,
                            (round(self.pos_x), round(self.pos_y)),
                            self.radius)
     else:
         if color is None:
             gfx.aacircle(screen, round(self.pos_x), round(self.pos_y),
                          self.radius, (self.R, self.G, self.B))
             gfx.filled_circle(screen, round(self.pos_x), round(self.pos_y),
                               self.radius, (self.R, self.G, self.B))
         else:
             gfx.aacircle(screen, round(self.pos_x), round(self.pos_y),
                          self.radius, color)
             gfx.filled_circle(screen, round(self.pos_x), round(self.pos_y),
                               self.radius, color)
Пример #19
0
 def display(self, screen):
     if self.typen == 'c':
         gfx.aaellipse(screen, self.x, self.y, self.size, self.sizeb, self.colour)
         gfx.aacircle(screen, self.x, self.y, 2, (0,0,0))
     elif self.typen == 'r':
         gfx.rectangle(screen, pg.Rect(self.x-self.size/2, self.y-self.sizeb/2, self.size, self.sizeb), self.colour)
         gfx.aacircle(screen, self.x, self.y, 2, (0,0,0))
Пример #20
0
 def update(self):
     self.rect = pygame.draw.circle(self.screen, self.color, CITY_LOCATION[self.areaname], CITY_SCALE_LIST[self.citysize])
     gfxdraw.aacircle(self.screen, 
                      CITY_LOCATION[self.areaname][0], CITY_LOCATION[self.areaname][1], 
                      CITY_SCALE_LIST[self.citysize], self.color)
     gfxdraw.filled_circle(self.screen,
                      CITY_LOCATION[self.areaname][0], CITY_LOCATION[self.areaname][1], 
                      CITY_SCALE_LIST[self.citysize], self.color)
Пример #21
0
	def draw(self, surface):
		c_inner, c_outer = self.colouring()

		for arm in self.arms:
			pdraw.aaline(surface, c_outer, arm.p1, arm.p2, 1)

		gfx.filled_circle(surface, int(self.position[0]), int(self.position[1]), self.radius, c_inner)
		gfx.aacircle(surface, int(self.position[0]), int(self.position[1]), self.radius, c_outer)
Пример #22
0
 def _aa_render_region(self, image, rect, color, rad):
     corners = rect.inflate(-2 * rad - 1, -2 * rad - 1)
     for attribute in ("topleft", "topright", "bottomleft", "bottomright"):
         x, y = getattr(corners, attribute)
         gfxdraw.aacircle(image, x, y, rad, color)
         gfxdraw.filled_circle(image, x, y, rad, color)
     image.fill(color, rect.inflate(-2 * rad, 0))
     image.fill(color, rect.inflate(0, -2 * rad))
Пример #23
0
 def draw(self, screen):
     self.g = max(self.g - 10, 40)
     self.b = max(self.b - 10, 0)
     gfxdraw.aacircle(screen, int(self.position.x), int(self.position.y),
                      self.size, (self.r, self.g, self.b))
     gfxdraw.filled_circle(screen, int(self.position.x),
                           int(self.position.y), self.size,
                           (self.r, self.g, self.b))
Пример #24
0
 def draw(self):
     """
     Рисует шарик по координатам
     :return: параметр обновленного экрана
     """
     gfxdraw.aacircle(self.screen, int(self.coords[0]), int(self.coords[1]), self.radius, self.color)
     gfxdraw.filled_circle(self.screen, int(self.coords[0]), int(self.coords[1]), self.radius, self.color)
     return self.screen
Пример #25
0
 def draw_circle(self, x, y, radius, color=(0, 0, 0)):
     x, y, radius = math.ceil(x), math.ceil(y), math.ceil(radius)
     try:
         gfxdraw.aacircle(self.window, x, y, radius, color)
         gfxdraw.filled_circle(self.window, x, y, radius, color)
     except:
         print(f"x={x}, y={y}, radius={radius}, color={color}")
         sys.exit()
Пример #26
0
 def draw_circle(self, surface):
     gfxdraw.aacircle(surface, self.pos[0], self.pos[1], self.radius,
                      color_W)
     gfxdraw.filled_circle(surface, self.pos[0], self.pos[1], self.radius,
                           color_W)
     gfxdraw.aacircle(surface, self.pos[0], self.pos[1], self.radius - 2,
                      self.color)
     gfxdraw.filled_circle(surface, self.pos[0], self.pos[1],
                           self.radius - 2, self.color)
Пример #27
0
 def draw_ring(self, surface, thickness):
     gfxdraw.aacircle(surface, self.pos[0], self.pos[1],
                      self.radius + thickness // 2, self.color)
     gfxdraw.filled_circle(surface, self.pos[0], self.pos[1],
                           self.radius + thickness // 2, self.color)
     gfxdraw.aacircle(surface, self.pos[0], self.pos[1],
                      self.radius - thickness // 2, BG_COLOR)
     gfxdraw.filled_circle(surface, self.pos[0], self.pos[1],
                           self.radius - thickness // 2, BG_COLOR)
Пример #28
0
def single_circle(surface, progress, mood):
    width, height = surface.get_size()
    r = int(progress*(sqrt((width/2)**2+(height/2)**2)+width//20))
    w = width//40
    aacircle(surface, width//2, height//2, r, mood.primary_color)
    filled_circle(surface, width//2, height//2, r, mood.primary_color)
    if r-w > 0:
        aacircle(surface, width//2, height//2, r-w, (0, 0, 0))
        filled_circle(surface, width//2, height//2, r-w, (0, 0, 0))
Пример #29
0
def draw():
    for bird in birds:
        #gfxdraw.filled_circle(screen, bird.x_pos, bird.y_pos, bird.radius, bird_color)
        gfxdraw.aacircle(screen, bird.x_pos, round(bird.y_pos), bird.radius, bird_color)
        #pygame.draw.circle(screen, bird_color, (bird.x_pos, bird.y_pos), bird.radius)

    for obs in obstacles:
        pygame.draw.rect(screen, obstacle_color, (obs.x_pos, 0, obs.width, obs.gap_y))
        pygame.draw.rect(screen, obstacle_color, (obs.x_pos, obs.gap_y + obs.gap_size, obs.width, screen_size[1] - obs.gap_y - obs.gap_size))
Пример #30
0
def draw_circle(screen, pos, size, color, color_border=None, size_border=1):
    if color_border:
        if size_border > 1:
            filled_circle(screen, pos[0], pos[1], size + size_border,
                          color_border)
        aacircle(screen, pos[0], pos[1], size + size_border, color_border)
        # inner color circle
        filled_circle(screen, pos[0], pos[1], size, color)
    aacircle(screen, pos[0], pos[1], size, color)
Пример #31
0
def _aa_render_region(image, rect, color, rad):
    """Helper function for aa_round_rect."""
    corners = rect.inflate(-2*rad-1, -2*rad-1)
    for attribute in ("topleft", "topright", "bottomleft", "bottomright"):
        x, y = getattr(corners, attribute)
        gfxdraw.aacircle(image, x, y, rad, color)
        gfxdraw.filled_circle(image, x, y, rad, color)
    image.fill(color, rect.inflate(-2*rad,0))
    image.fill(color, rect.inflate(0,-2*rad))
Пример #32
0
def draw():
    global screen, curve
    screen.fill((0, 0, 0))
    for point in points:
        gfxdraw.aacircle(screen, point[0], point[1], 4, (255, 255, 255))
        gfxdraw.filled_circle(screen, point[0], point[1], 4, (255, 255, 255))

    if len(curve) > 1:
        pygame.draw.aalines(screen, (255, 255, 255), False, curve, True)
Пример #33
0
    def render_piece(self, output, circle_pos):
        """Renders the piece on the board"""
        # note: rendering is XY system
        y, x = circle_pos[self.position]

        # Experimental features PyGame may break it in the future
        gfxdraw.filled_circle(output, x, y, 32, self.color)
        gfxdraw.aacircle(output, x, y, 32, color.BLACK)
        gfxdraw.aacircle(output, x, y, 31, color.BLACK)
Пример #34
0
 def __init__(self):
     pg.sprite.Sprite.__init__(self)
     self.rect = pg.Rect((0, 0), GRID_SIZE)
     self.image = pg.Surface(GRID_SIZE, pg.SRCALPHA)
     self.radius = RADIUS
     gdraw.aacircle(self.image, self.rect.center[0], self.rect.center[1],
                    int(self.radius), WHITE)
     gdraw.filled_circle(self.image, self.rect.center[0],
                         self.rect.center[1], int(self.radius), WHITE)
Пример #35
0
def draw_circle(pos, r, color, filled=False, global_coords=True):
    if global_coords:
        pos =  world_to_win_pt(pos, c.player.center)
        r = world_to_win_length(r)
    
    if filled:
        gfxdraw.filled_circle(screen, pos[0], pos[1], r, color)
    else:
        gfxdraw.circle(screen, pos[0], pos[1], r, color)
    gfxdraw.aacircle(screen, pos[0], pos[1], r, color)
Пример #36
0
 def draw(self):
     if self.kind == "dot":
         pixel_points = CoorsAndPixels.coor_to_pixel(self.pos, scale, size)
         radius = int((self.charge)**(1.0/3.0)*scale)
         gfxdraw.filled_circle(screen, pixel_points[0], pixel_points[1], radius, self.color)
         if radius > 1:
             gfxdraw.aacircle(screen, pixel_points[0], pixel_points[1], radius, self.color)
     elif self.kind == "line":
         #pygame.draw.aaline(screen, self.color, CoorsAndPixels.coor_to_pixel(self.pos, scale, size, True), CoorsAndPixels.coor_to_pixel([self.pos[0]+self.length*self.cos_a, self.pos[1]+self.length*self.sin_a], scale, size, True))
         pygame.draw.line(screen, self.color, CoorsAndPixels.coor_to_pixel(self.pos, scale, size, True), CoorsAndPixels.coor_to_pixel([self.pos[0]+self.length*self.cos_a, self.pos[1]+self.length*self.sin_a], scale, size, True), int(self.charge**(1.0/3.0)/5.0)+1)
Пример #37
0
    def draw(self):
        
        #Draws a circle, 
        w = []
        if self.lit: # has it been clicked?
            thickness = 0
        else:
            self.color = [255,255,255]
            thickness = 1

        gfxdraw.aacircle(self.screen, self.pos_x, self.pos_y, self.radius - 5, (255,255,255))

        # Draws a square
        pygame.draw.rect(self.screen,self.color,(self.pos_x-25, self.pos_y-25, 50,50),thickness)
Пример #38
0
    def draw(self, screen):
        """
        Argument:
        screen : the surface to draw on

        This function draws an antialiased circle at the X,Y of the piece.
        Unfortuately, antialiased filled circles don't exsist so we draw
        the antialiased outline before drawing the filled inside, as recommneded
        by the offical docs (otherwise the circles look horrendously ugly).

        """
        cur_color = self.COLORS[self.STATUS]
        gfxdraw.aacircle(screen, self.X, self.Y, self.radius, cur_color)
        gfxdraw.filled_circle(screen, self.X, self.Y, self.radius, cur_color)
Пример #39
0
def redraw_screen():
    global gunX
    global gunY
    pygame.draw.rect(window, (0, 0, 0), (0, 0, windowX, windowY))
    if(mouseX==playerX and mouseY==playerY):
        gunX=mouseX
        gunY=mouseY  
    else:
        gunX=playerX+playerSize*(mouseX-playerX)/math.sqrt((mouseX-playerX)**2+(mouseY-playerY)**2)
        gunY=playerY+playerSize*(mouseY-playerY)/math.sqrt((mouseX-playerX)**2+(mouseY-playerY)**2)
    gfxdraw.aacircle(window, int(playerX),int(playerY),playerSize,(255,255,255))
    #gfxdraw.line(window,int(playerX),int(playerY),int(gunX),int(gunY),(255,255,255))
    pygame.draw.aaline(window, (255,255,255),(int(playerX),int(playerY)),(int(gunX),int(gunY)))
    playerBulletList.draw()
    pygame.display.flip()
Пример #40
0
 def draw(self):
     if self.kind == "dot":
         pixel_points = coor_to_pixel(self.pos)
         radius = int((self.charge)**(1.0/3.0)*scale)
         gfxdraw.filled_circle(screen, pixel_points[0], pixel_points[1], radius, self.color)
         if radius > 1:
             gfxdraw.aacircle(screen, pixel_points[0], pixel_points[1], radius, self.color)
     elif self.kind == "box":
         pixel_pos = coor_to_pixel(self.pos, True)
         end_pos = [self.pos[0]+self.length*self.cos_a, self.pos[1]+self.length*self.sin_a]
         pixel_end_pos = coor_to_pixel(end_pos)
         #pygame.draw.aaline(screen, self.color, (pixel_pos[0], pixel_pos[1]), coor_to_pixel([self.pos[0]+self.length*self.cos_a, self.pos[1]+self.length*self.sin_a], True))
         pygame.draw.line(screen, self.color, (pixel_pos[0], pixel_pos[1]), coor_to_pixel([self.pos[0]+self.length*self.cos_a, self.pos[1]+self.length*self.sin_a]), int(self.charge**(1.0/3.0)/scale/2.0)+1)
         #pygame.draw.line(screen, self.color, (int(pixel_pos[0]), int(pixel_pos[1])), ())
         gfxdraw.aacircle(screen, int(pixel_pos[0]), int(pixel_pos[1]), 10, self.color)
Пример #41
0
    def draw(self, screen):
        h = screen.get_height()
        s = self.scale_sim_to_vis

        if self.shape == 'quad':
            verts = self.fixture.shape.vertices
            verts = [self.body.transform * vert for vert in verts]
            verts = [(s * x, h - s * y) for (x, y) in verts]

            gfxdraw.aapolygon(screen, verts, self.object_color)
        elif self.shape == 'circle':
            x = self.body.position[0]
            y = self.body.position[1]
            gfxdraw.aacircle(screen, int(s * x), int(h - s * y), int(s *
                self.HALF_H * self.scale_real_to_sim), self.object_color)
Пример #42
0
    def mkgui_tile(self, loc, only_clear=False):
        """ Redraw the gui tile or just clear the tile.

            only_clear: use to clear 'unmovable' tiles; if False, clear and then redraw tile
        """
        loc = self.resolve_loc(loc)
        ts = self.tilesize
        if self.circle:
            gfxdraw.filled_circle(self.sfc, loc[0], loc[1], iround(ts/2), white)
            if not only_clear:
                gfxdraw.aacircle(self.sfc, loc[0], loc[1], iround(ts/2-4), gray)
        else:
            r = center_square(loc, ts)
            draw.rect(self.sfc, white, r, 0)
            if not only_clear:
                gfxdraw.rectangle(self.sfc, r, gray)
        self.scr.blit(self.sfc, (0,0))
Пример #43
0
    def draw(self, screen):
        h = screen.get_height()
        s = self.scale_sim_to_vis

        center = self.body.position
        top = self.body.GetWorldPoint((0.0, self.sim_radius))

        if center.x < 0 or center.y < 0:
            print(center)
            return

        cx = int(round(s * center.x))
        cy = int(round(h - s * center.y))

        top_x = int(round(s * top.x))
        top_y = int(round(h - s * top.y))

        gfxdraw.aacircle(screen, cx, cy, self.pixel_radius, self.circle_color)
        draw.aaline(screen, self.line_color, (cx, cy), (top_x, top_y))
Пример #44
0
	def update(self):
	
		CommandableSprite.update(self)
		
		mx = int(self.get_x())
		my = int(self.get_y())
		
		l = int(self.get_left())
		t = int(self.get_top())
		
		if self.circled:
			if self.border_width == 0: # no border --- just draw the background
				pygame.draw.circle(self.screen, self.circle_color, (mx, my), min(self.width/2,self.height/2) )
			else: 
				filled_circle(self.screen, mx, my, min(self.width/2,self.height/2), (0,0,0) ) # draw a black outer rim
				aacircle(self.screen, mx, my, min(self.width/2,self.height/2), (0,0,0) ) # draw a black outer rim
				
				filled_circle(self.screen, mx, my, min(self.width/2-self.border_width,self.height/2-self.border_width), self.circle_color) 
				aacircle(self.screen, mx, my, min(self.width/2-self.border_width,self.height/2-self.border_width), self.circle_color) # and the inside the color we want
				
		# And draw each dot position
		for i in xrange(self.N):
			dx,dy = self.dot_positions[i]
			r = self.radii[i]
			
			# here we draw twice to antialias the edges
			filled_circle(self.screen, int(dx+l), int(dy+t), int(r), self.dot_color)
			aacircle(self.screen, int(dx+l), int(dy+t), int(r), self.dot_color)
Пример #45
0
    def draw(self, transparent_colour, zoom):
        """
        Main draw function for nodes. It will return a surface containing the drawing of the node.
        :return:
        """

        print zoom
        size = int(self.size / zoom)

        # Create the surface for this node
        surface = pygame.surface.Surface((self.size, self.size))
        surface.fill(transparent_colour)

        third_size = size / 3

        x = surface.get_rect().centerx
        y = surface.get_rect().centery

        draw.aacircle(surface, x, y, third_size, (0, 255, 128))
        draw.filled_circle(surface, x, y, third_size, (0, 255, 128))

        return surface
Пример #46
0
def draw_cell(cell):
    font_size = 16
    virus_sizes = {100:1, 106:2, 113:3, 119:4, 125:5, 131:6, 136:7}

    cx,cy = world_to_win_pt(cell.pos,c.player.center)
    try:
        mov_ang = cell.movement_angle
        p2 = cell.pos + Vec( math.cos(mov_ang + mechanics.eject_delta*math.pi/180), math.sin(mov_ang + mechanics.eject_delta*math.pi/180) ) * (cell.size+700)
        p3 = cell.pos + Vec( math.cos(mov_ang - mechanics.eject_delta*math.pi/180), math.sin(mov_ang - mechanics.eject_delta*math.pi/180) ) * (cell.size+700)

        cx2,cy2 = world_to_win_pt(p2,c.player.center)
        cx3,cy3 = world_to_win_pt(p3,c.player.center)
    except (AttributeError, TypeError):
        cx2,cy2=cx,cy
        cx3,cy3=cx,cy

    radius = world_to_win_length(cell.size)

    if cell.is_virus:
            color = (0,255,0)
            color2 = (100,255,0)
            polygon = generate_virus(int(cell.size*0.3), 10*zoom, radius, (cx, cy))
            polygon2 = generate_virus(int(cell.size*0.3), 10*zoom, radius-10, (cx, cy))
            
            gfxdraw.filled_polygon(screen, polygon, color2)
            gfxdraw.polygon(screen, polygon, (0,0,0))
            gfxdraw.aapolygon(screen, polygon, (0,0,0))
            
            gfxdraw.filled_polygon(screen, polygon2, color)
            gfxdraw.aapolygon(screen, polygon2, color)
            
            draw_text((cx, cy), "%s / 7" % virus_sizes.get(cell.size, "?"), (64,0,0), font_size*2, False, True)
            draw_text((cx, cy + radius + 10), str(cell.cid), (0,0,0), font_size, False, True)
    else:
        color=(int(cell.color[0]*255), int(cell.color[1]*255), int(cell.color[2]*255))

        
        if not (cell.is_ejected_mass or cell.is_food):
            gfxdraw.aapolygon(screen, [(cx,cy),(cx2,cy2),(cx3,cy3),(cx,cy)] ,(255,127,127))
            
            gfxdraw.filled_circle(screen, cx, cy, radius, color)
            gfxdraw.aacircle(screen, cx, cy, radius, (0,0,0))
            
            gfxdraw.aacircle(screen, cx, cy, int(radius/2), (255,255,255))
            gfxdraw.circle(screen, cx, cy, int(radius/2), (255,255,255))
            
            draw_text((cx, cy + radius + 10), cell.name, (0, 0, 0), font_size, False, True)
            draw_text((cx, cy + radius + 10 + font_size), str(cell.cid), (0,0,0), font_size, False, True)
            # surface = draw_text(cell.name, (0, 0, 0), font_size)
            # screen.blit(surface, (cx - (surface.get_width()/2), cy + radius + 5))
            
            draw_text((cx, cy), str(int(cell.mass))+"/"+str(int(cell.size)), (255, 255, 255), font_size, False, True)
            # surface = draw_text(str(int(cell.mass)), (255, 255, 255), font_size)
            # screen.blit(surface, (cx - (surface.get_width()/2), cy - (surface.get_height()/2)))
        else:
            gfxdraw.aacircle(screen, cx, cy, radius, color)
            gfxdraw.filled_circle(screen, cx, cy, radius, color)
Пример #47
0
def circle(surface, pos, radius, color, width=0):
    if width == 0:    
        # we need the aacircle even when the hole is filled
        # because filled circles look like shit
        aacircle(surface, pos[0], pos[1], radius, color)
        filled_circle(surface, pos[0], pos[1], radius, color)
    elif width == 1:
        aacircle(surface, pos[0], pos[1], radius, color)
    else:
        for i in range(1, width):
            aacircle(surface, pos[0], pos[1], radius-i, color)
    return
while True:
    screen.fill(pygame.Color(200, 200, 200))

    # screen.fill((0, 0, 0))

    # Filling with black makes the following work...
    # It therefore seems that somehow aacircle is getting it's blue
    #  value from max(background_blue_channel, specified_blue_channel)
    # The left circle is still blue when drawn on black. This is only
    # for aa circle though, aalines seems to just override specified 
    # channel value with background blue channel value...

    gfxdraw.aacircle(
        screen,
        50,
        150,
        30,
        (0, 0, 255)
    )

    gfxdraw.aacircle(
        screen,
        130,
        150,
        30,
        (255, 0, 0)
    )

    pygame.draw.aalines(
        screen,
        (0, 0, 255, 0),
Пример #49
0
 def circle(surf,c,coord,r,w):
     x,y = coord
     x,y,r = int(x),int(y),int(r)
     filled_circle(surf,x,y,r,(20,20,60))
     aacircle(surf,x,y,r,c)
     aacircle(surf,x,y,r-1,c)
                time_step = time_step + 0.01
            elif event.key == K_MINUS:
                time_step = time_step - 0.01

    env['light_pos'] = light_pos

    # draw labyrinth and object
    screen.fill((0, 0, 0, 0))
    labyrinth.draw(screen)
    push_object.draw(screen)

    # draw light
    light_pos = env['light_pos']
    lx = int(SCALE_REAL_TO_VIS * light_pos[0, 0])
    ly = int(screen.get_height() - SCALE_REAL_TO_VIS * light_pos[0, 1])
    gfxdraw.aacircle(screen, lx, ly, 5, (255, 255, 0, 255))

    # handle kilobot movement and drawing
    for kb in kilobots:
        kb.step()
        kb.setVelocities()
        kb.draw(screen)

    if not paused:
        # step physics objects using 10 pos and vel update iterations
        world.Step(time_step, 10, 10)

        curr_time = curr_time + time_step
        pygame.display.set_caption('kbsim - {:.2f}s - ts: {:.0f}ms'.
                format(curr_time, time_step * 1000))
Пример #51
0
 def draw(self): 
     gfxdraw.aacircle(window, int(self.X),int(self.Y),int(self.size),self.color)
Пример #52
0
def main():
    """
    The main game function. Welcome to the beginning of the end.
    :return:
    """

    # First we must initialize the pygame module and game clock before most things happen
    pygame.init()
    game_clock = pygame.time.Clock()

    # Grab the settings from the settings file. They are placed in a dictionary.
    settings = settings_parse.parse_settings('settings.cfg')

    window_name = 'Pong'
    window_resolution = settings['x_resolution'], settings['y_resolution']

    # Check to see if the game should run in full screen
    flags = 0
    if settings['full_screen']:
        flags = pygame.FULLSCREEN

    # Build the main game window according to the settings provided
    pygame.display.set_caption(window_name)
    window = pygame.display.set_mode(window_resolution, flags, 32)
    window_rect = window.get_rect()

    # Get the joysticks/gamepads connected
    joysticks = [pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count())]
    for joystick in joysticks:
        joystick.init()

    # Create the game and score area
    # The score area is along the top with a height 1/10th of the window
    score_height = window_rect.height / 10
    game_height = window_rect.height - score_height
    score_surface = pygame.Surface((window_rect.width, score_height))
    game_surface = pygame.Surface((window_rect.width, game_height))

    game_resolution = (settings['x_resolution'], game_height)

    # Font used for FPS counter
    fps_font = pygame.font.SysFont(None, 48)

    # Font used for score
    score_font = pygame.font.SysFont(None, score_height - 4)

    # The number of players in the game
    number_players = 2

    # Determine the players of the game
    if settings['player_one'] == 'human':

        pass

    else:

        pass

    if settings['player_two'] == 'human':

        pass

    else:

        pass

    # Create the starting game objects
    balls = [Ball(10, 200, window.get_rect().center)]
    players = [Player(0, (0, window.get_rect().centery - 50)),
               skynet.AiPlayer(0, (window.get_rect().right - 10, window.get_rect().centery - 50))]
    winner = players[1]

    # Initialize the variable game loop time step
    last_time = time.time()

    while True:

        # The heart of the variable game loop. Keeps track of how long a frame takes to complete
        current_time = time.time()
        time_elapsed = current_time - last_time
        last_time = current_time

        # Game clock used for fps calculation
        game_clock.tick()

        # Handle the pygame events
        # TODO: Move this to a more sensible place
        for event in pygame.event.get():

            if event.type == pygame.QUIT:
                pygame.quit()

            if event.type == pygame.KEYDOWN:

                if event.key == pygame.K_ESCAPE:
                    pygame.quit()

                elif event.key == pygame.K_UP:

                    [player.paddle.move_up() for player in players]

                elif event.key == pygame.K_DOWN:

                    [player.paddle.move_down() for player in players]

                elif event.key == pygame.K_SPACE:

                    balls.append(Ball(10, 200, window.get_rect().center))

            if event.type == pygame.KEYUP:

                [player.paddle.stop() for player in players]

            if (event.type == pygame.JOYAXISMOTION) and (event.axis == 1):

                players[event.joy].paddle.direction = -event.value

            if (event.type == pygame.JOYBUTTONUP) and (event.button == 0):

                player_paddle = players[event.joy].paddle

                ball = Ball(10, 200, player_paddle.position)
                ball.direction = Direction(True, event.joy)
                ball.position = [player_paddle.get_front(), player_paddle.get_center()]
                if not event.joy:
                    ball.position[0] = player_paddle.get_front() + player_paddle.size[0]
                balls.append(ball)

        # Update game objects
        for player in players:
            player.paddle.update(time_elapsed, game_resolution)

            for ball in balls:

                if player.paddle.collision(ball):
                    ball.paddle_bounce()

                if not (ball.update(time_elapsed, game_resolution, players)):

                    balls.remove(ball)

        if not balls:

            balls.append(Ball(10, 200, game_surface.get_rect().center))

        # Run AI
        for player in players:

            try:
                player.target_ball(balls)
                player.update()
            except AttributeError:
                pass

        # Render all game objects
        window.fill((0, 0, 0))

        # Draw the playing field
        board_colour = (232, 221, 203)
        line_colour = (205, 179, 128)
        width = game_surface.get_rect().width
        height = game_surface.get_rect().height
        center_x = game_surface.get_rect().centerx
        center_y = game_surface.get_rect().centery
        game_surface.fill(board_colour)
        pygame.draw.line(game_surface, line_colour, (0, 0), (width, 0), 4)
        pygame.draw.line(game_surface, line_colour, (width - 2, 0), (width - 2, height), 4)
        pygame.draw.line(game_surface, line_colour, (0, 0), (0, height), 4)
        pygame.draw.line(game_surface, line_colour, (0, height - 2), (width, height - 2), 4)
        pygame.draw.line(game_surface, line_colour, (center_x, 0), (center_x, height), 2)
        gfxdraw.aacircle(game_surface, center_x, center_y, 100, line_colour)
        gfxdraw.aacircle(game_surface, center_x, center_y, 101, line_colour)

        for ball in balls:
            game_surface.blit(ball.surface, ball.position)

        for player in players:
            game_surface.blit(player.paddle.surface, player.paddle.position)

        window.blit(game_surface, (0, score_height))

        # Draw The score
        score_string = str(players[0].score) + '   ' + str(players[1].score)
        score = score_font.render(score_string, True, board_colour, (0, 0, 0))
        score_surf_rect = score_surface.get_rect()
        score_rect = score.get_rect()
        score_surface.blit(score, (score_surf_rect.centerx - score_rect.centerx,
                                   score_surf_rect.centery - score_rect.centery))
        pygame.draw.line(score_surface, line_colour, (score_surf_rect.centerx, 0),
                         (score_surf_rect.centerx, score_surf_rect.height), 2)
        window.blit(score_surface, (0, 0))

        if settings['show_fps']:
            fps = fps_font.render(str(int(game_clock.get_fps())), True, (255, 255, 255), (0, 0, 0))
            window.blit(fps, (0, 0))

        # Update the display
        pygame.display.update()
Пример #53
0
 def draw(self): 
     gfxdraw.aacircle(window, int(self.X), int(self.Y), 10, self.color)
     for i in self.list:
         i.movement()
         i.draw()
 def _draw_circle(self, x, y, r, c):
     if drawing == "gfxdraw":
         gfxdraw.aacircle(self.screen, x, y, r, c)
     elif drawing == "draw":
         pygame.draw.circle(self.screen, c, (x,y), r, 1)
Пример #55
0
 def draw(self): 
     gfxdraw.aacircle(window, int(self.globalX),int(self.globalY),3,self.color)
     gfxdraw.aacircle(window, int(self.globalX),int(self.globalY),2, (255,255,255))
Пример #56
0
                if e.key == K_q and ctrl_held:
                    sys.exit()
                elif e.key == K_SPACE:
                    lockscreen = False

        # Check if lock icon should drag

        if mb[0] == 1 and lock_icon_rect.collidepoint(mpos):
            drag_lock_icon = True
        elif mb[1] == 0:
            drag_lock_icon = False

        # Drag lock icon

        if drag_lock_icon:
            gfxdraw.aacircle(main, 250, 540, 140, (255,255,255))
            lock_icon_pos_x = mx - 40
            lock_icon_pos_y = my - 40
            lock_icon_dist = hypot(mx - 250, my - 540)
            if abs(lock_icon_dist) >= 150:
                time.wait(150)
                lockscreen = False
        else:

            # Set normal lock icon

            lock_icon_pos_x = 210
            lock_icon_pos_y = 500

        # Lockscreen time text
    def _generateSamples(self):
        # create kilobots
        self.kilobots = []
        for i in range(self.numKilobots):
            kilobot = Kilobot(self.world, self.SCALE_REAL_TO_SIM,
                self.SCALE_REAL_TO_VIS, [0, 0])
            kilobot.fixture.friction = 20

            self.kilobots += [kilobot]

        self.pushObject = Object(self.world, self.SCALE_REAL_TO_SIM,
                self.SCALE_REAL_TO_VIS, [0, 0], self.objectShape)

        numSamples = self.numEpisodes * self.numStepsPerEpisode

        # fixed object start position
        objStartX = 1.0
        objStartY = 0.5
        objStart = array([objStartX, objStartY])

        # kilobots start in a circel around the object
        r = 1.5 * self.pushObject.HALF_W
        A = linspace(0, 2 * math.pi, self.numEpisodes + 1)[0:self.numEpisodes]
        startPositions = c_[objStartX + np.cos(A) * r,
                            objStartY + np.sin(A) * r];

        r = self.kilobots[0].RADIUS
        kilobotOffsets = array([[-r, -r], [r, -r], [-r, r], [r, r]])

        # s: light.x light.y kb.x1 kb.y1 ... kb.xn kb.yn
        #    everything is relative to the object position
        # a: light movement (dx, dy)
        S = asmatrix(empty((numSamples, 2 + 2 * self.numKilobots)))
        A = asmatrix(empty((numSamples, 2)))
        R = asmatrix(empty((numSamples, 1)))
        S_ = asmatrix(empty((numSamples, 2 + 2 * self.numKilobots)))

        for ep in range(startPositions.shape[0]):
            self.pushObject.body.position = vec2(objStartX, objStartY) *\
                    self.SCALE_REAL_TO_SIM
            self.pushObject.body.angle = 0

            # light starts in circel around the object
            start = startPositions[ep, :]
            lightPos = matrix(start)

            # kilobots start at the light position in a fixed formation
            for (i, kilobot) in zip(range(self.numKilobots), self.kilobots):
                x = start[0] + (1 + i / 4) * kilobotOffsets[i % 4, 0]
                y = start[1] + (1 + i / 4) * kilobotOffsets[i % 4, 1]
                kilobot.body.position = vec2(x, y) * self.SCALE_REAL_TO_SIM

            for step in range(self.numStepsPerEpisode):
                """ user interaction """
                # handle keys
                for event in pygame.event.get():
                    if event.type == KEYDOWN:
                        if event.key == K_PLUS:
                            self.stepsPerSec *= 2
                        elif event.key == K_MINUS:
                            self.stepsPerSec = np.max([1, self.stepsPerSec / 2])

                """ drawing """
                self.screen.fill((0, 0, 0, 0))

                self.pushObject.draw(self.screen)

                for kilobot in self.kilobots:
                    kilobot.draw(self.screen)

                # draw light
                lx = int(self.SCALE_REAL_TO_VIS * lightPos[0, 0])
                ly = int(self.screen.get_height() - self.SCALE_REAL_TO_VIS *
                        lightPos[0, 1])
                lr = int(self.SCALE_REAL_TO_VIS * 0.02)
                gfxdraw.aacircle(self.screen, lx, ly, lr, (255, 255, 0))

                pygame.display.set_caption(('ep: {} - step: {} - ' +
                    'stepsPerSec: {}').format(ep + 1, step + 1, self.stepsPerSec))

                pygame.display.flip()
                self.clock.tick(self.stepsPerSec)

                """ simulation """
                # current state
                objPos = self.pushObject.getRealPosition()
                objPosOld = objPos

                s = asmatrix(empty((1, S.shape[1])))
                s[0, 0] = lightPos[0, 0] - objPos[0, 0]
                s[0, 1] = lightPos[0, 1] - objPos[0, 1]

                for (i, kilobot) in zip(range(self.numKilobots), self.kilobots):
                    kbPos = kilobot.getRealPosition()
                    s[0, 2 + 2 * i + 0] = kbPos[0, 0] - objPos[0, 0]
                    s[0, 2 + 2 * i + 1] = kbPos[0, 1] - objPos[0, 1]

                # choose action
                if self.useMean:
                    a = self.policy.getMeanAction(s)
                else:
                    if random.random() <= self.epsilon:
                        a = self.policy.getRandomAction()
                    else:
                        a = self.policy.sampleActions(s)

                # take action
                n = linalg.norm(a)
                if n > 0.015:
                    lightPos += (a * 0.015 / n)
                else:
                    lightPos += a

                # move directly toward the light
                for kilobot in self.kilobots:
                    kbPos = kilobot.getRealPosition()

                    v = lightPos - kbPos

                    # cap max velocity
                    n = linalg.norm(v)
                    if n > 0.01:
                        v *= (0.01 / n)

                    kilobot.body.linearVelocity = vec2(v[0, 0], v[0, 1]) * \
                            self.SCALE_REAL_TO_SIM
                    kilobot.body.linearDamping = 0.0

                for i in range(10):
                    self.world.Step(0.1, 10, 10)

                # next state
                objPos = self.pushObject.getRealPosition()

                s_ = asmatrix(empty((1, S.shape[1])))
                s_[0, 0] = lightPos[0, 0] - objPos[0, 0]
                s_[0, 1] = lightPos[0, 1] - objPos[0, 1]

                for (i, kilobot) in zip(range(self.numKilobots), self.kilobots):
                    kbPos = kilobot.getRealPosition()
                    s_[0, 2 + 2 * i + 0] = kbPos[0, 0] - objPos[0, 0]
                    s_[0, 2 + 2 * i + 1] = kbPos[0, 1] - objPos[0, 1]

                # reward: learn to move the object to the right
                objMovement = objPos - objPosOld
                r = objMovement[0, 0] - 0.5 * np.abs(objMovement[0, 1])

                # record sample
                sampleIdx = ep * self.numStepsPerEpisode + step

                S[sampleIdx, :] = s
                A[sampleIdx, :] = a
                R[sampleIdx, :] = r
                S_[sampleIdx, :] = s_

        return S, A, R, S_
    def _testMazePolicy(self):
        # create kilobots
        self.kilobots = []
        for i in range(self.numKilobots):
            kilobot = Kilobot(self.world, self.SCALE_REAL_TO_SIM,
                self.SCALE_REAL_TO_VIS, [0, 0])
            kilobot.fixture.friction = 20

            self.kilobots += [kilobot]

        self.pushObject = Object(self.world, self.SCALE_REAL_TO_SIM,
                self.SCALE_REAL_TO_VIS, [0, 0], self.objectShape)

        # fixed object start position
        objStartX = 1.25
        objStartY = 0.75

        r = self.kilobots[0].RADIUS
        kilobotOffsets = array([[-r, -r], [r, -r], [-r, r], [r, r]])

        self.pushObject.body.position = vec2(objStartX, objStartY) *\
                self.SCALE_REAL_TO_SIM
        self.pushObject.body.angle = 0

        # light starts over the object
        lightPos = matrix([objStartX, objStartY])

        HALF_W = self.pushObject.HALF_W

        # kilobots start left of the object
        for (i, kilobot) in zip(range(self.numKilobots), self.kilobots):
            x = objStartX - 2.0 * HALF_W + (1 + i / 4) * kilobotOffsets[i % 4, 0]
            y = objStartY + (1 + i / 4) * kilobotOffsets[i % 4, 1]
            kilobot.body.position = vec2(x, y) * self.SCALE_REAL_TO_SIM

        s = asmatrix(empty((1, 2 + 2 * self.numKilobots)))
        targetPos = matrix([objStartX, objStartY])

        while True:
            """ user interaction """
            # handle keys
            for event in pygame.event.get():
                if event.type == KEYDOWN:
                    if event.key == K_PLUS:
                        self.stepsPerSec *= 2
                    elif event.key == K_MINUS:
                        self.stepsPerSec = np.max([1, self.stepsPerSec / 2])

            """ drawing """
            self.screen.fill((0, 0, 0, 0))

            self.maze.draw(self.screen)
            self.pushObject.draw(self.screen)

            for kilobot in self.kilobots:
                kilobot.draw(self.screen)

            # draw light
            lx = int(self.SCALE_REAL_TO_VIS * lightPos[0, 0])
            ly = int(self.screen.get_height() - self.SCALE_REAL_TO_VIS *
                    lightPos[0, 1])
            lr = int(self.SCALE_REAL_TO_VIS * 0.02)
            gfxdraw.aacircle(self.screen, lx, ly, lr, (255, 255, 0))

            objPos = self.pushObject.getRealPosition()

            # draw line from object to target position
            ox = int(self.SCALE_REAL_TO_VIS * objPos[0, 0])
            oy = int(self.screen.get_height() - self.SCALE_REAL_TO_VIS *
                    objPos[0, 1])
            tx = int(self.SCALE_REAL_TO_VIS * targetPos[0, 0])
            ty = int(self.screen.get_height() - self.SCALE_REAL_TO_VIS *
                    targetPos[0, 1])

            pygame.draw.aaline(self.screen, (0, 0, 255), (ox, oy), (tx, ty))

            pygame.display.flip()
            self.clock.tick(self.stepsPerSec)

            """ simulation """
            # current state
            s[0, 0] = lightPos[0, 0] - objPos[0, 0]
            s[0, 1] = lightPos[0, 1] - objPos[0, 1]

            for (i, kilobot) in zip(range(self.numKilobots), self.kilobots):
                kbPos = kilobot.getRealPosition()
                s[0, 2 + 2 * i + 0] = kbPos[0, 0] - objPos[0, 0]
                s[0, 2 + 2 * i + 1] = kbPos[0, 1] - objPos[0, 1]

            # solve maze
            targetPos = self.mazePolicy.getTargetPosition(objPos)

            # rotate state
            direction = targetPos - objPos
            angle = -math.atan2(direction[0, 1], direction[0, 0])

            sx = s.flat[0::2] * math.cos(angle) - s.flat[1::2] * math.sin(angle)
            sy = s.flat[1::2] * math.cos(angle) + s.flat[0::2] * math.sin(angle)

            s.flat[0::2] = sx
            s.flat[1::2] = sy

            # choose action
            a = self.objPolicy.getMeanAction(s)

            # rotate action
            ax = a[0, 0] * math.cos(-angle) - a[0, 1] * math.sin(-angle)
            ay = a[0, 1] * math.cos(-angle) + a[0, 0] * math.sin(-angle)

            a[0, 0] = ax
            a[0, 1] = ay

            # take action
            n = linalg.norm(a)
            if n > 0.015:
                lightPos += (a * 0.015 / n)
            else:
                lightPos += a

            # move directly toward the light
            for kilobot in self.kilobots:
                kbPos = kilobot.getRealPosition()

                v = lightPos - kbPos

                # cap max velocity
                n = linalg.norm(v)
                if n > 0.01:
                    v *= (0.01 / n)

                kilobot.body.linearVelocity = vec2(v[0, 0], v[0, 1]) * \
                        self.SCALE_REAL_TO_SIM
                kilobot.body.linearDamping = 0.0

            for i in range(10):
                self.world.Step(0.1, 10, 10)
Пример #59
0
    #for x in stars:
     #   pixel_pos = CoorsAndPixels.coor_to_pixel(x, scale, size)
      #  screen.blit(star_image, [int(pixel_pos[0]-radius*2.5), int(pixel_pos[1]-radius*2.5)])

    #draw player ball
    pixel_points = CoorsAndPixels.coor_to_pixel(my_dot_pos, scale, size, True)
    screen.blit(my_dot_image, [pixel_points[0]-radius, pixel_points[1]-radius])

    #gfxdraw.filled_circle(screen, pixel_points[0], pixel_points[1], radius, my_dot_color)
    #if radius > 1:
    #    gfxdraw.aacircle(screen, pixel_points[0], pixel_points[1], radius, my_dot_color)

    #draw line if aiming to shoot
    if clicked_my_dot:
        pygame.draw.aaline(screen, (0, 0, 0), pixel_points, mouse_pos)

    #pixel_square_coors = coor_to_pixel([square[0], square[1]])
    #pixel_square_to = [square[2]/scale, size, square[3]/scale]
    #screen.fill((0, 255, 0), [pixel_square_coors[0], pixel_square_coors[1], pixel_square_to[0], pixel_square_to[1]])
    #draw objective
    pixel_points = CoorsAndPixels.coor_to_pixel(objective, scale, size)
    gfxdraw.filled_circle(screen, pixel_points[0], pixel_points[1], int((objective_size)**(1.0/3.0)*scale), (0, 255, 0))
    gfxdraw.aacircle(screen, pixel_points[0], pixel_points[1], int((objective_size)**(1.0/3.0)*scale), (0, 255, 0))

    display_info()
    pygame.display.update()
    elapsed = clock.tick(60) #60 hz refresh rate

#save level locks
with open("level_locks.txt", 'w') as lock_files:
    lock_files.writelines(locks)