PyGame에서 마우스 드래그를위한 고무 밴드를 어떻게 추가합니까? [닫은]

Nov 17 2020

두 번째 코드를 첫 번째 코드와 분리하여 마우스로 선을 그리는 두 번째 코드와 동일한 기능을 구현하고 싶었습니다. 두 번째 코드를 첫 번째 코드와 분리하여 두 번째 코드와 동일한 기능을 구현하고 싶었습니다. 마우스로 선을 그리는 것

SCREEN_WIDTH = 1500
SCREEN_HEIGHT = 750
background = pygame.image.load(r'C:\Users\ga-sa\Downloads\honeycomb.png')
background = pygame.transform.scale(BACKGROUND, (SCREEN_WIDTH, SCREEN_HEIGHT))

img1 = pygame.image.load(r"C:\Users\ga-sa\Downloads\As.png")
img2 = pygame.image.load(r"C:\Users\ga-sa\Downloads\AssetsXOR.png")
img3 = pygame.image.load(r"C:\Users\ga-sa\Downloads\AssetsNOT.png")
img4 = pygame.image.load(r"C:\Users\ga-sa\Downloads\AssetsAND.png")
images = [img1, img2, img3, img4]
current_image = -1
img_rects = [images[i].get_rect(topleft=(20 + 40 * i, 20)) for i in range(len(images))]
img_angles = [0 for _ in range(len(images))]

LeftButton = 0
while 1:
    for e in pygame.event.get():
        if e.type == QUIT:
            pygame.quit()
            exit(0)

        if e.type == pygame.MOUSEBUTTONDOWN:
            mouse_rect = pygame.Rect(e.pos, (1, 1))
            current_image = mouse_rect.collidelist(img_rects)

        if e.type == MOUSEMOTION:
            if e.buttons[LeftButton]:
                rel = e.rel
                if 0 <= current_image < len(images):
                    img_rects[current_image].x += rel[0]
                    img_rects[current_image].y += rel[1]

    keys = pygame.key.get_pressed()
    if keys[pygame.K_RIGHT]:
        img_angles[current_image] -= 1
    if keys[pygame.K_LEFT]:
        img_angles[current_image] += 1

    screen.blit(background, (0,0))

    for i in range(len(images)):
        rotated_image = pygame.transform.rotate(images[i], img_angles[i])
        rotated_rect = rotated_image.get_rect(center=img_rects[i].center)
        screen.blit(rotated_image, rotated_rect)

    pygame.display.flip()

이 코드에서 아래 코드와 같은 줄을 어떻게 추가 할 수 있습니까?

def main()
    pygame.init()
    pygame.display.set_caption("Mouse Draw")
    surface = pygame.display.set_mode((800, 600))
    clock = pygame.time.Clock()
    rect = surface.get_rect()
    fps = 60

    line_surface = pygame.Surface(rect.size, pygame.SRCALPHA)
    line_surface.fill((0, 0, 0, 0))

    mouse_position = None
    display_line = None
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.MOUSEMOTION:
                if mouse_position:
                    display_line = mouse_position, event.pos
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:
                    if mouse_position:
                        pygame.draw.line(line_surface, pygame.Color("red"), mouse_position, event.pos)
                        mouse_position = None
                        display_line = None
                    else:
                        mouse_position = event.pos

        surface.fill(pygame.Color('black'))
        surface.blit(line_surface, (0, 0))

        if display_line:
            pygame.draw.line(surface, pygame.Color('lawngreen'), *display_line)

        pygame.display.update()
        clock.tick(fps)
main ()

첫 번째 코드에 def main을 넣고 싶지만 항상 검은 화면이 표시되지 않거나 오류가 발생하며 누군가 나를 도울 수 있다면 매우 감사하겠습니다. 사실 두 코드를 결합하고 싶지만 첫 번째 코드에 맞게 조정하는 방법을 모르겠습니다.

답변

2 Rabbid76 Nov 17 2020 at 18:51

클릭과 클릭으로 선을 그리지 않으려면 첫 번째 클릭으로 시작 위치를 저장하고 두 번째 클릭으로 선을 끝내야합니다. 라인은 목록에 저장되어야합니다. 선취권 목록과 변수를 추가하고 다음을 통해 line_start초기화합니다 None.

lines = []
line_start = None

첫 번째 클릭으로 시작을 설정하고 두 번째 클릭 ( MOUSEBUTTONDOWN)으로 선을 끝냅니다 . 라인 목록에 완성 된 라인을 추가합니다.

if e.type == pygame.MOUSEBUTTONDOWN:
        # [...]

        if line_start:
            lines.append((line_start, e.pos))
            line_start = None
        else:
            line_start = e.pos

루프로 선을 그립니다. 선이 시작된 번트가 끝나지 않은 경우 시작 위치에서 현재 마우스 위치까지 선을 그립니다.

for line in lines:
    pygame.draw.line(screen, pygame.Color('lawngreen'), *line)
if line_start:
    pygame.draw.line(screen, pygame.Color('lawngreen'), line_start, pygame.mouse.get_pos())

최소한의 예 :

import pygame

pygame.init()
SCREEN_WIDTH = 1500
SCREEN_HEIGHT = 750
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
clock = pygame.time.Clock()

background = pygame.image.load(r'C:\Users\ga-sa\Downloads\honeycomb.png')
background = pygame.transform.scale(BACKGROUND, (SCREEN_WIDTH, SCREEN_HEIGHT))

img1 = pygame.image.load(r"C:\Users\ga-sa\Downloads\As.png")
img2 = pygame.image.load(r"C:\Users\ga-sa\Downloads\AssetsXOR.png")
img3 = pygame.image.load(r"C:\Users\ga-sa\Downloads\AssetsNOT.png")
img4 = pygame.image.load(r"C:\Users\ga-sa\Downloads\AssetsAND.png")

images = [img1, img2, img3, img4]

current_image = -1
img_rects = [images[i].get_rect(topleft=(20 + 80 * i, 20)) for i in range(len(images))]
img_angles = [0 for _ in range(len(images))]

lines = []
line_start = None

LeftButton = 0
while 1:
    clock.tick(60)
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            pygame.quit()
            exit(0)

        if e.type == pygame.MOUSEBUTTONDOWN:
            mouse_rect = pygame.Rect(e.pos, (1, 1))
            current_image = mouse_rect.collidelist(img_rects)
            if line_start:
                lines.append((line_start, e.pos))
                line_start = None
            else:
                line_start = e.pos

        if e.type == pygame.MOUSEMOTION:
            if e.buttons[LeftButton]:
                rel = e.rel
                if 0 <= current_image < len(images):
                    img_rects[current_image].x += rel[0]
                    img_rects[current_image].y += rel[1]

    keys = pygame.key.get_pressed()
    if 0 <= current_image < len(img_angles):
        if keys[pygame.K_RIGHT]:
            img_angles[current_image] -= 1
        if keys[pygame.K_LEFT]:
            img_angles[current_image] += 1

    screen.blit(background,(0,0))

    for line in lines:
        pygame.draw.line(screen, pygame.Color('lawngreen'), *line)
    if line_start:
        pygame.draw.line(screen, pygame.Color('lawngreen'), line_start, pygame.mouse.get_pos())

    for i in range(len(images)):
        rotated_image = pygame.transform.rotate(images[i], img_angles[i])
        rotated_rect = rotated_image.get_rect(center = img_rects[i].center)
        screen.blit(rotated_image, rotated_rect)

    pygame.display.flip()


아이콘을 드래그하면서 고 무선을 그리려면 선의 시작 부분을 저장해야합니다. 변수를 추가하고 line_start`None :

line_start = None

마우스를 눌렀을 때 시작 위치 설정 ( MOUSEBUTTONDOWN) :

if e.type == pygame.MOUSEBUTTONDOWN:
    mouse_rect = pygame.Rect(e.pos, (1, 1))
    current_image = mouse_rect.collidelist(img_rects)
    line_start = e.pos

line_start = None마우스를 놓을 때 설정 ( MOUSEBUTTONUP) :

if e.type == pygame.MOUSEBUTTONUP:
    line_start = None

line_start가 설정된 경우 시작 위치에서 현재 마우스 위치의 선을 그립니다.

if line_start:
    pygame.draw.line(screen, pygame.Color('lawngreen'), line_start, pygame.mouse.get_pos())

최소한의 예 :

import pygame

pygame.init()
SCREEN_WIDTH = 1500
SCREEN_HEIGHT = 750
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
clock = pygame.time.Clock()

background = pygame.image.load(r'C:\Users\ga-sa\Downloads\honeycomb.png')
background = pygame.transform.scale(BACKGROUND, (SCREEN_WIDTH, SCREEN_HEIGHT))

img1 = pygame.image.load(r"C:\Users\ga-sa\Downloads\As.png")
img2 = pygame.image.load(r"C:\Users\ga-sa\Downloads\AssetsXOR.png")
img3 = pygame.image.load(r"C:\Users\ga-sa\Downloads\AssetsNOT.png")
img4 = pygame.image.load(r"C:\Users\ga-sa\Downloads\AssetsAND.png")

images = [img1, img2, img3, img4]

current_image = -1
img_rects = [images[i].get_rect(topleft=(20 + 80 * i, 20)) for i in range(len(images))]
img_angles = [0 for _ in range(len(images))]

line_start = None

LeftButton = 0
while 1:
    clock.tick(60)
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            pygame.quit()
            exit(0)

        if e.type == pygame.MOUSEBUTTONDOWN:
            mouse_rect = pygame.Rect(e.pos, (1, 1))
            current_image = mouse_rect.collidelist(img_rects)
            line_start = e.pos

        if e.type == pygame.MOUSEBUTTONUP:
            line_start = None

        if e.type == pygame.MOUSEMOTION:
            if e.buttons[LeftButton]:
                rel = e.rel
                if 0 <= current_image < len(images):
                    img_rects[current_image].x += rel[0]
                    img_rects[current_image].y += rel[1]

    keys = pygame.key.get_pressed()
    if 0 <= current_image < len(img_angles):
        if keys[pygame.K_RIGHT]:
            img_angles[current_image] -= 1
        if keys[pygame.K_LEFT]:
            img_angles[current_image] += 1

    screen.blit(background,(0,0))

    if line_start:
        pygame.draw.line(screen, pygame.Color('lawngreen'), line_start, pygame.mouse.get_pos())

    for i in range(len(images)):
        rotated_image = pygame.transform.rotate(images[i], img_angles[i])
        rotated_rect = rotated_image.get_rect(center = img_rects[i].center)
        screen.blit(rotated_image, rotated_rect)

    pygame.display.flip()


아이콘이 드래그되는 방식을 따라 선을 그리려면 선 목록이 필요합니다. 각 라인은 포인트 목록입니다.

lines = []

마우스를 누르면 새 목록 시작 ( MOUSEMOTION) :

if e.type == pygame.MOUSEBUTTONDOWN:
    mouse_rect = pygame.Rect(e.pos, (1, 1))
    current_image = mouse_rect.collidelist(img_rects)
    lines.append([e.pos])                                 # <---

마우스를 움직일 때 줄 목록의 마지막 줄에 점 추가 ( MOUSEMOTION) :

if e.type == pygame.MOUSEMOTION:
    if e.buttons[LeftButton]:
        rel = e.rel
        if 0 <= current_image < len(images):
            img_rects[current_image].x += rel[0]
            img_rects[current_image].y += rel[1]
            lines[-1].append(e.pos)                      # <---

루프로 선을 그립니다 pygame.draw.lines.

for line in lines:
    if len(line) > 1:
        pygame.draw.lines(screen, pygame.Color('lawngreen'), False, line)

직선을 원하면 마우스를 움직일 때 선의 두 번째 점을 새 마우스 위치로 바꿔야합니다.

while 1:
    clock.tick(60)
    for e in pygame.event.get():
        # [...]

        if e.type == pygame.MOUSEMOTION:
            if e.buttons[LeftButton]:
                rel = e.rel
                if 0 <= current_image < len(images):
                    img_rects[current_image].x += rel[0]
                    img_rects[current_image].y += rel[1]
                    
                    # lines[-1].append(e.pos)
                    if len(lines[-1]) < 2:
                        lines[-1].append(e.pos)
                    else:
                        lines[-1][1] = e.pos


최소한의 예 :

의 값을 변경하여 두 구현간에 전환 할 수 있습니다 straight_lines.

import pygame

pygame.init()
SCREEN_WIDTH = 1500
SCREEN_HEIGHT = 750
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
clock = pygame.time.Clock()

background = pygame.image.load(r'C:\Users\ga-sa\Downloads\honeycomb.png')
background = pygame.transform.scale(BACKGROUND, (SCREEN_WIDTH, SCREEN_HEIGHT))

img1 = pygame.image.load(r"C:\Users\ga-sa\Downloads\As.png")
img2 = pygame.image.load(r"C:\Users\ga-sa\Downloads\AssetsXOR.png")
img3 = pygame.image.load(r"C:\Users\ga-sa\Downloads\AssetsNOT.png")
img4 = pygame.image.load(r"C:\Users\ga-sa\Downloads\AssetsAND.png")

images = [img1, img2, img3, img4]

current_image = -1
img_rects = [images[i].get_rect(topleft=(20 + 80 * i, 20)) for i in range(len(images))]
img_angles = [0 for _ in range(len(images))]

lines = []

# straight_lines = False 
straight_lines = True

LeftButton = 0
while 1:
    clock.tick(60)
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            pygame.quit()
            exit(0)

        if e.type == pygame.MOUSEBUTTONDOWN:
            mouse_rect = pygame.Rect(e.pos, (1, 1))
            current_image = mouse_rect.collidelist(img_rects)
            lines.append([e.pos])

        if e.type == pygame.MOUSEMOTION:
            if e.buttons[LeftButton]:
                rel = e.rel
                if 0 <= current_image < len(images):
                    img_rects[current_image].x += rel[0]
                    img_rects[current_image].y += rel[1]
                    
                    if len(lines[-1]) < 2 or not straight_lines:
                        lines[-1].append(e.pos)
                    else:
                        lines[-1][1] = e.pos

    keys = pygame.key.get_pressed()
    if 0 <= current_image < len(img_angles):
        if keys[pygame.K_RIGHT]:
            img_angles[current_image] -= 1
        if keys[pygame.K_LEFT]:
            img_angles[current_image] += 1

    screen.blit(background,(0,0))

    for line in lines:
        if len(line) > 1:
            pygame.draw.lines(screen, pygame.Color('lawngreen'), False, line)
    
    for i in range(len(images)):
        rotated_image = pygame.transform.rotate(images[i], img_angles[i])
        rotated_rect = rotated_image.get_rect(center = img_rects[i].center)
        screen.blit(rotated_image, rotated_rect)

    pygame.display.flip()