Пример #1
0
def getSpotClicked(board, x, y):
    # from the x & y pixel coordinates, get the x & y board coordinates
    pt = sdl2.SDL_Point(x, y)
    for tileX in range(len(board)):
        for tileY in range(len(board[0])):
            left, top = getLeftTopOfTile(tileX, tileY)
            if sdl2.SDL_PointInRect(
                    pt, sdl2.SDL_Rect(left, top, TILESIZE, TILESIZE)):
                return (tileX, tileY)
    return (None, None)
Пример #2
0
 def __init__(self, world, sprite, wposi=0, wposj=0, angle=0):
     pos = calculate.Coord(wpos=(wposi, wposj),
                           win_width=WIN_WIDTH,
                           win_height=WIN_HEIGHT)
     self.world = world
     self.sprite = sprite
     self.sprite.pos = pos
     self.sprite.angle = angle
     self.sprite.position = self.get_origin()
     self.sprite.point = sdl2.SDL_Point(int(self.sprite.size[0] / 2), 0)
Пример #3
0
def getButtonClicked(x, y):
	pt = sdl2.SDL_Point(x, y)
	if sdl2.SDL_PointInRect(pt, sdl2.SDL_Rect(*YELLOWRECT)):
		return YELLOW
	elif sdl2.SDL_PointInRect(pt, sdl2.SDL_Rect(*BLUERECT)):
		return BLUE
	elif sdl2.SDL_PointInRect(pt, sdl2.SDL_Rect(*REDRECT)):
		return RED
	elif sdl2.SDL_PointInRect(pt, sdl2.SDL_Rect(*GREENRECT)):
		return GREEN
	return None
Пример #4
0
 def _рам(к, име_боје):
     п = sdl2.SDL_Point(к.ширина() // 2, к.висина() // 2)
     положај = providers.Object(п)
     рам = providers.Singleton(РамОдСлике,
                               шкработине=к.шкработине,
                               површ=к.главна_површ,
                               положај=положај,
                               име_боје=име_боје)
     стрелице = providers.Singleton(Стрелице,
                                    положај=положај,
                                    обрада_догађаја=к.обрада_догађаја)
     к._листови.append(рам)
     к._листови.append(стрелице)
Пример #5
0
def fline(renderer, x0, y0, x1, y1):
    """
    Modified Bresenham's line algorithm.
    Renders points to form a line between two positions.
    """
    dx = abs(x1 - x0)
    dy = abs(y1 - y0)

    c = 0
    points = (sdl2.SDL_Point * 128)()

    x, y = x0, y0
    sx = -1 if x0 > x1 else 1
    sy = -1 if y0 > y1 else 1
    if dx > dy:
        err = dx / 2.0
        while x != x1:
            points[c] = sdl2.SDL_Point(x, y)
            c += 1
            err -= dy
            if err <= 0:
                y += sy
                err += dx
            x += sx
    else:
        err = dy / 2.0
        while y != y1:
            points[c] = sdl2.SDL_Point(x, y)
            c += 1
            err -= dx
            if err <= 0:
                x += sx
                err += dy
            y += sy
    points[c] = sdl2.SDL_Point(x, y)
    c += 1
    ptr = ctypes.cast(points, ctypes.POINTER(sdl2.SDL_Point))
    sdl2.SDL_RenderDrawPoints(renderer, ptr, c)
Пример #6
0
def draw_rect(surface, x, y, w, h, angle=0, colour=(0, 0, 0, 0)):

    if len(colour) == 3:
        colour = (colour[0] % 256, colour[1] % 256, colour[2] % 256, 255)
    elif len(colour) == 4:
        colour = (colour[0] % 256, colour[1] % 256, colour[2] % 256,
                  colour[3] % 256)

    surf = Surface(w, h)
    surf.fill((colour[0], colour[1], colour[2], colour[3]))
    text = sdl2.SDL_CreateTextureFromSurface(surface.renderer, surf.surface)

    dstrect = sdl2.SDL_Rect(x, y, w, h)

    sdl2.SDL_RenderCopyEx(surface.renderer, text, None, dstrect, -angle,
                          sdl2.SDL_Point(0, 0), sdl2.SDL_FLIP_NONE)
Пример #7
0
    def blit(self, surface, src=None, dest=None, angle=0):
        if src:
            srcrect = sdl2.SDL_Rect(src[0][0], src[0][1],
                                    src[1][0] - src[0][0],
                                    src[1][1] - src[0][1])

        else:
            srcrect = None

        if dest:
            if len(dest) == 2:
                if src:
                    dstrect = sdl2.SDL_Rect(dest[0] - srcrect.w / 2,
                                            dest[1] - srcrect.h / 2, srcrect.w,
                                            srcrect.h)
                else:
                    dstrect = sdl2.SDL_Rect(dest[0] - surface.w / 2,
                                            dest[1] - surface.h / 2, surface.w,
                                            surface.h)

            elif len(dest) == 4:
                dstrect = sdl2.SDL_Rect()
                dstrect.w = dest[1][0] - dest[0][0]
                dstrect.h = dest[1][1] - dest[0][1]
                dstrect.x = dest[0][0] - dstrect.w / 2
                dstrect.y = dest[0][1] - dstrect.h / 2

            else:
                raise IndexError("\'dest\' should have 2 or 4 values. ")
        else:
            if src:
                dstrect = sdl2.SDL_Rect(dest[0] - srcrect.w / 2,
                                        dest[1] - srcrect.h / 2, srcrect.w,
                                        srcrect.h)
            else:
                dstrect = sdl2.SDL_Rect(0 - surface.w / 2, 0 - surface.h / 2,
                                        surface.w, surface.h)

        text = sdl2.SDL_CreateTextureFromSurface(self.renderer,
                                                 surface.surface)

        sdl2.SDL_RenderCopyEx(
            self.renderer, text, srcrect, dstrect, -surface.angle - angle,
            sdl2.SDL_Point(round(surface.w / 2), round(surface.h / 2)),
            sdl2.SDL_FLIP_NONE)
Пример #8
0
    def draw(
            self,
            waveform: list,
            colors: tuple  # background and foreground colors
    ):
        # Compute a Fourier Transform on the Waveform to
        # divide the sound into several "bins". To
        # visualise them as points on the render window.
        self.fft_spectrum = fft_abs(fft(waveform))[:self.fft_bins]

        x = 0  # reset the coordinate on each call
        for idx, bin in enumerate(self.fft_spectrum):
            self.data_points.contents[idx] = sdl2.SDL_Point(
                round(x),
                int(maprange(bin, 0, NP_FFT_MAXVAL, 0,
                             self.viewport['width'])))
            x += self.bar_width

        # Clear the canvas with our selected colour.
        # What it does is repaints the screen
        # the previous frame is overlapped by it.
        sdl2.SDL_SetRenderDrawColor(self.renderer, colors[0][0], colors[0][1],
                                    colors[0][2], colors[0][3])
        sdl2.SDL_RenderClear(self.renderer)

        # Draw the visualization using connected paths which
        # are stroked. When percepted they represent themeselves
        # as "lines".
        sdl2.SDL_SetRenderDrawColor(self.renderer, colors[1][0], colors[1][1],
                                    colors[1][2], colors[1][3])
        sdl2.SDL_RenderDrawLines(self.renderer, self.data_points.contents,
                                 self.fft_bins)

        # Display the contents on the screen which
        # was rendered off-screen.
        sdl2.SDL_RenderPresent(self.renderer)

        # Look for the event when the user closes
        # the render window.
        sdl2.SDL_PollEvent(self.event)
        if self.event.type == sdl2.SDL_QUIT:
            self.close()
            return True
def draw_texture(renderer: sdl2.render.SDL_Renderer,
                 texture: sdl2.render.SDL_Texture, position: Vec2f,
                 rotation: float) -> None:
    w = ctypes.pointer(ctypes.c_int(0))
    h = ctypes.pointer(ctypes.c_int(0))
    sdl(sdl2.SDL_QueryTexture(texture, None, None, w, h))
    width = float(w.contents.value)
    height = float(h.contents.value)

    # Transforms coordinates to center of sprite rather than default upper left
    # corner. This makes centering the sprite on screen easier.
    x = position.x - width / 2
    y = position.y - height / 2

    sdl(
        sdl2.SDL_RenderCopyEx(
            renderer, texture,
            ctypes.byref(sdl2.SDL_Rect(0, 0, int(width), int(height))),
            ctypes.byref(sdl2.SDL_Rect(int(x), int(y), int(width),
                                       int(height))), rotation,
            ctypes.byref(sdl2.SDL_Point(int(width / 2), int(height / 2))),
            sdl2.SDL_FLIP_NONE))
Пример #10
0
def draw(renderer, window_size):
    sdl2.SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255)
    sdl2.SDL_RenderClear(renderer)

    a_base = min(window_size)
    a = A_COEFF_RELATION * a_base
    for part in PARTS:
        points_set = set()
        c_r, c_g, c_b, c_a = part[2]
        sdl2.SDL_SetRenderDrawColor(renderer, c_r, c_g, c_b, c_a)
        t = part[0]
        while t < part[1]:
            x = a * cos(t) * (1 + cos(t)) + window_size[0] / 2 - a
            y = a * sin(t) * (1 + cos(t)) + window_size[1] / 2
            points_set.add((trunc(x), trunc(y)))
            t += STEP

        points_count = len(points_set)
        points_list = [sdl2.SDL_Point(p[0], p[1]) for p in points_set]
        points_array = (sdl2.SDL_Point * points_count)(*points_list)

        sdl2.SDL_RenderDrawPoints(renderer, points_array, points_count)

    sdl2.SDL_RenderPresent(renderer)
Пример #11
0
def xy_distances(
        p1: sdl2.SDL_Point,
        p2: sdl2.SDL_Point) -> sdl2.SDL_Point:  # TODO Needs a better name
    return sdl2.SDL_Point(x_distance(p1, p2), y_distance(p1, p2))
Пример #12
0
 def start_tracking_stroke(click_event: sdl2.SDL_Event) -> None:
     nonlocal tracking_stroke
     nonlocal stroke
     stroke = [sdl2.SDL_Point(click_event.button.x, click_event.button.y)]
     tracking_stroke = True
Пример #13
0
def main():
    #cause I don't want to pass these around
    global REN, SPRITE_FACTORY, SPRITE_RENDERER
    global RESET_BUTTON, NEW_BUTTON, SOLVE_BUTTON

    sdl2.ext.init()

    window = sdl2.ext.Window("Slide Puzzle", size=(WINDOWWIDTH, WINDOWHEIGHT))
    REN = sdl2.ext.Renderer(window)
    window.show()

    font_file = sysfont.get_font("freesans", sysfont.STYLE_BOLD)
    font_manager = sdl2.ext.FontManager(font_file, size=BASICFONTSIZE)

    #fontmanager=font_manager will be default_args passed to every sprite creation method
    SPRITE_FACTORY = sdl2.ext.SpriteFactory(renderer=REN,
                                            fontmanager=font_manager,
                                            free=True)
    SPRITE_RENDERER = SPRITE_FACTORY.create_sprite_render_system(window)

    RESET_BUTTON, reset_rect = make_text(SPRITE_FACTORY,
                                         "Reset",
                                         WINDOWWIDTH - 120,
                                         WINDOWHEIGHT - 90,
                                         bg_color=TILECOLOR)
    NEW_BUTTON, new_rect = make_text(SPRITE_FACTORY,
                                     "New Game",
                                     WINDOWWIDTH - 120,
                                     WINDOWHEIGHT - 60,
                                     bg_color=TILECOLOR)
    SOLVE_BUTTON, solve_rect = make_text(SPRITE_FACTORY,
                                         "Solve",
                                         WINDOWWIDTH - 120,
                                         WINDOWHEIGHT - 30,
                                         bg_color=TILECOLOR)

    mainBoard, solutionSeq = generateNewPuzzle(NUMSLIDES)
    SOLVEDBOARD = getStartingBoard(
    )  # a solved board is the same as the board in a start state.
    allMoves = []  # list of moves made from the solved configuration

    print(NEW_BUTTON.area)

    running = True
    while running:
        slideTo = None  # the direction, if any, a tile should slide
        msg = 'Click tile or press arrow keys to slide.'  # contains the message to show in the upper left corner.
        if mainBoard == SOLVEDBOARD:
            msg = 'Solved!'

        drawBoard(mainBoard, msg)

        for event in sdl2.ext.get_events():
            if event.type == sdl2.SDL_QUIT:
                running = False
                break
            elif event.type == sdl2.SDL_WINDOWEVENT:
                if event.window.event == sdl2.SDL_WINDOWEVENT_EXPOSED:
                    print("window exposed")
                    drawBoard(mainBoard, msg)
            elif event.type == sdl2.SDL_MOUSEBUTTONUP:
                pos = event.button.x, event.button.y
                spotx, spoty = getSpotClicked(mainBoard, pos[0], pos[1])
                pt = sdl2.SDL_Point(pos[0], pos[1])
                if (spotx, spoty) == (None, None):
                    if sdl2.SDL_PointInRect(pt, reset_rect):
                        resetAnimation(mainBoard, allMoves)
                        allMoves = []
                    elif sdl2.SDL_PointInRect(pt, new_rect):
                        mainBoard, solutionSeq = generateNewPuzzle(NUMSLIDES)
                        allMoves = []
                    elif sdl2.SDL_PointInRect(pt, solve_rect):
                        resetAnimation(mainBoard, solutionSeq + allMoves)
                        allMoves = []

                else:
                    #check if clicked tile was next to blank
                    blankx, blanky = getBlankPosition(mainBoard)
                    if spotx == blankx + 1 and spoty == blanky:
                        slideTo = LEFT
                    elif spotx == blankx - 1 and spoty == blanky:
                        slideTo = RIGHT
                    elif spotx == blankx and spoty == blanky + 1:
                        slideTo = UP
                    elif spotx == blankx and spoty == blanky - 1:
                        slideTo = DOWN

            elif event.type == sdl2.SDL_KEYUP:
                # check if the user pressed a key to slide a tile
                sym = event.key.keysym.sym
                if sym in (sdl2.SDLK_LEFT, sdl2.SDLK_a) and isValidMove(
                        mainBoard, LEFT):
                    slideTo = LEFT
                elif sym in (sdl2.SDLK_RIGHT, sdl2.SDLK_d) and isValidMove(
                        mainBoard, RIGHT):
                    slideTo = RIGHT
                elif sym in (sdl2.SDLK_UP, sdl2.SDLK_w) and isValidMove(
                        mainBoard, UP):
                    slideTo = UP
                elif sym in (sdl2.SDLK_DOWN, sdl2.SDLK_s) and isValidMove(
                        mainBoard, DOWN):
                    slideTo = DOWN

                elif event.key.keysym.sym == sdl2.SDLK_ESCAPE:
                    running = False
                    break

        if slideTo:
            slideAnimation(mainBoard, slideTo,
                           'Click tile or press arrow keys to slide.',
                           8)  # show slide on screen
            allMoves.append(slideTo)  # record the slide

        REN.present()
        sdl2.SDL_Delay(1000 // FPS)

    sdl2.ext.quit()
Пример #14
0
def click_position(click_event: sdl2.SDL_Event) -> sdl2.SDL_Point:
    if click_event.type != sdl2.SDL_MOUSEBUTTONDOWN:
        raise IncorrectEvent
    return sdl2.SDL_Point(click_event.button.x, click_event.button.y)
Пример #15
0
def motion_position(motion_event: sdl2.SDL_Event) -> sdl2.SDL_Point:
    if motion_event.type != sdl2.SDL_MOUSEMOTION:
        raise IncorrectEvent
    return sdl2.SDL_Point(motion_event.motion.x, motion_event.motion.y)