PyGame 모듈은 다양한 기능을 지원하는데, 그 중에서 여러가지 도형을 그릴 수 있는 메소드들을 소개하도록 하겠습니다.


00. PyGame 지원되는 도형

PyGame에서 지원되는 도형은 다음과 같습니다.

메소드

도형

설명

 pygame.draw.rect

 사각형

 화면에 사각형을 그려줍니다.

 pygame.draw.polygon

 삼각형

 화면에 삼각혁을 그려줍니다.

 pygame.draw.circle

 원

 화면에 원을 그려줍니다.

 pygame.draw.ellipse

 타원

 화면에 타원을 그려줍니다.

 pygame.draw.arc

 원

 화면에 원하는 만큼의 원을 그려줍니다.

 원을 얼마나 그려줄지 정할 수 있습니다.

 pygame.draw.line

 선

 화면에 선을 그려줍니다.

 pygame.draw.lines

 여러 개의 선

 화면에 여러 개의 선을 이어서 그립니다.

 pygame.draw.aaline

 부드러운 선

 화면에 부드러운 선을 그려줍니다.

 pygame.draw.aalines

 부드러운 선들

 화면에 부드러운 선을 여러 개 이어서 그립니다.


여기서는 pygame.draw.lines를 이용하여 여러 개의 선을 그리는 방법을 살펴볼 것입니다.

만약 다른 draw 메소드를 참고하고 싶으시다면 아래의 링크에서 선택하시면 될 것 같습니다.




사각형 - pygame.draw.rect

삼각형 - pygame.draw.polygon

원 - pygame.draw.circle

타원 - pygame.draw.ellipse

원(특정 부분까지 그리기) - pygame.draw.arc

선 - pygame.draw.line

부드러운 선 - pygame.draw.aaline

여러 개의 부드러운 선 - pygame.draw.aalines



01. pygame.draw.lines 함수

pygame에서 지원하는 여러 개의 선 그리기 함수인 lines 함수는 다음과 같은 인자값들을 받습니다.



 pygame.draw.lines(Surface, Color, Closed, PointList, Width=1)

  Draw a sequence of lines on a Surface. The pointlist argument is a series of points that are connected by a line. If the closed argument is true an additional line segment is drawn between the first and last points.

  This does not draw any endcaps or miter joints. Lines with sharp corners and wide line widths can have improper looking corners.




변수 

설명

Surface

 pygame을 실행할 때 전체적으로 화면을 선언한 변수 값

Color

 선의 색깔로 (R, G, B)의 형태로 데이터의 값을 삽입함

Closed

 이어지는 여러 개의 선을 다 그리고 하나의 구역으로 설정할지 결정

PointList

 여러 개의 선을 그릴 위치들을 입력함

Width

 선의 두께를 말하며, 기본적으로 1으로 설정됨


위의 변수들은 예제 소스코드를 통해 설명하도록 하겠습니다.


02. pygame.draw.lines를 이용한 여러 개의 선 그리기(예제)

먼저 소스코드를 살펴보면 다음과 같습니다.


Source

# Import a library of functions called 'pygame'
import pygame

# Initialize the game engine
pygame.init()
 
# Define the colors we will use in RGB format
BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)
BLUE  = (  0,   0, 255)
GREEN = (  0, 255,   0)
RED   = (255,   0,   0)
 
# Set the height and width of the screen
size   = [400, 300]
screen = pygame.display.set_mode(size)
 
pygame.display.set_caption("Drawing Rectangle")
 
#Loop until the user clicks the close button.
done = False
clock = pygame.time.Clock()
 
while not done:
 
    # This limits the while loop to a max of 10 times per second.
    # Leave this out and we will use all CPU we can.
    clock.tick(10)
     
    for event in pygame.event.get(): # User did something
        if event.type == pygame.QUIT: # If user clicked close
            done=True # Flag that we are done so we exit this loop
 
    # All drawing code happens after the for loop and but
    # inside the main while done==False loop.
     
    # Clear the screen and set the screen background
    screen.fill(WHITE)

    # Draw on the screen a RED lines from (0,80) to (50, 90) to (200, 80) to (220, 30) 
    # 5 pixels wide.
    pygame.draw.lines(screen, RED, False, [[0, 80], [50, 90], [200, 80], [220, 30]], 5)

    # Draw on the screen a BLUE lines from (100,180) to (150,190) to (300,180) to (320,130) 
    # 5 pixels wide.
    pygame.draw.lines(screen, BLUE, True, [[100, 180], [150, 190], [300, 180], [320, 130]], 5)
     
    # Go ahead and update the screen with what we've drawn.
    # This MUST happen after all the other drawing commands.
    pygame.display.flip()
 
# Be IDLE friendly
pygame.quit()

전체적인 소스는 위와 같습니다.

이제 아래에서는 소스를 특정하여 나눠서 설명을 해보도록 하겠습니다.



Variable - Surface

# Set the height and width of the screen
size   = [400, 300]
screen = pygame.display.set_mode(size)

먼저, 16번째 줄의 screen 변수를 보면, 해당 변수에는 화면 전체를 설정하기 위한 값이 들어가 있습니다.

화면을 새로고침 해주거나, 화면을 채워주거나 할 때 해당 변수를 이용합니다.

pygame.draw.lines 함수의 Surface는 이러한 화면 설정 변수를 넣어주시면 됩니다.


Variable - Color

# Define the colors we will use in RGB format
BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)
BLUE  = (  0,   0, 255)
GREEN = (  0, 255,   0)
RED   = (255,   0,   0)

다음으로, 8 ~ 12번 라인을 보시면, Tuple 형태의 값이 설정되어 있는 것을 보실 수 있습니다.

세 개의 값이 0 ~ 255의 범위를 가지게 되는데, 이렇게 설정된 값이 색깔(RGB) 값으로 Color 변수가 들어갈 곳에 넣어주시면 됩니다.


Variable - Closed

    # Draw on the screen a RED lines from (0,80) to (50, 90) to (200, 80) to (220, 30) 
    # 5 pixels wide.
    pygame.draw.lines(screen, RED, False, [[0, 80], [50, 90], [200, 80], [220, 30]], 5)

    # Draw on the screen a BLUE lines from (100,180) to (150,190) to (300, 180) to (320, 130) 
    # 5 pixels wide.
    pygame.draw.lines(screen, BLUE, True, [[100, 180], [150, 190], [300, 180], [320, 130]], 5)

먼저 42번째 라인과 46번째 라인을 살펴보면 False와 True로 되어 있는 인자값을 보실 수 있습니다.

42번째 라인의 값의 False일 경우는 빨간색 선으로 보시면 되고,

46번째 라인의 값의 True일 경우는 파란색 선으로 보시면 됩니다.



빨간색 선을 보면 하나의 구역으로 나눠지지 않고, 선분만 이어져있는 것을 볼 수 있습니다.

파란색 선을 보면 하나의 구역으로 나눠져서 선분들이 이어져 있는 곳을 사각형으로 만들어낸 모습으로 보입니다.

파란색 선처럼 구역을 Closed 하고 싶을 때는 True, 빨간색 선처럼 구역이 없이 선만 그리고 싶을 때는 False를 하면 됩니다.


Variable - Width

    # Draw on the screen a RED lines from (0,80) to (50, 90) to (200, 80) to (220, 30) 
    # 5 pixels wide.
    pygame.draw.lines(screen, RED, False, [[0, 80], [50, 90], [200, 80], [220, 30]], 5)

    # Draw on the screen a BLUE lines from (100,180) to (150,190) to (300, 180) to (320, 130) 
    # 5 pixels wide.
    pygame.draw.lines(screen, BLUE, True, [[100, 180], [150, 190], [300, 180], [320, 130]], 5)

42번째 라인과 46번째 라인을 보시면 두 함수의 선 두께가 모두 5로 같은 것을 볼 수 있습니다.

기본적으로 lines 함수의 경우 Width가 1로 되어 있으나, 이를 수정해줄 수 있습니다.

단, 0 이하의 수는 사용할 수 없습니다.

만약 사용하더라도 선이 그려지지 않습니다.(선의 두께가 0이라는 것은 선이 없다라는 걸 의미하지요.)



PyGame 모듈은 다양한 기능을 지원하는데, 그 중에서 여러가지 도형을 그릴 수 있는 메소드들을 소개하도록 하겠습니다.


00. PyGame 지원되는 도형

PyGame에서 지원되는 도형은 다음과 같습니다.

메소드

도형

설명

 pygame.draw.rect

 사각형

 화면에 사각형을 그려줍니다.

 pygame.draw.polygon

 삼각형

 화면에 삼각혁을 그려줍니다.

 pygame.draw.circle

 원

 화면에 원을 그려줍니다.

 pygame.draw.ellipse

 타원

 화면에 타원을 그려줍니다.

 pygame.draw.arc

 원

 화면에 원하는 만큼의 원을 그려줍니다.

 원을 얼마나 그려줄지 정할 수 있습니다.

 pygame.draw.line

 선

 화면에 선을 그려줍니다.

 pygame.draw.lines

 여러 개의 선

 화면에 여러 개의 선을 이어서 그립니다.

 pygame.draw.aaline

 부드러운 선

 화면에 부드러운 선을 그려줍니다.

 pygame.draw.aalines

 부드러운 선들

 화면에 부드러운 선을 여러 개 이어서 그립니다.


여기서는 pygame.draw.line을 이용하여 선을 그리는 방법을 살펴볼 것입니다.

만약 다른 draw 메소드를 참고하고 싶으시다면 아래의 링크에서 선택하시면 될 것 같습니다.




사각형 - pygame.draw.rect

삼각형 - pygame.draw.polygon

원 - pygame.draw.circle

타원 - pygame.draw.ellipse

원(특정 부분까지 그리기) - pygame.draw.arc

여러 개의 선 - pygame.draw.lines

부드러운 선 - pygame.draw.aaline

여러 개의 부드러운 선 - pygame.draw.aalines



01. pygame.draw.line 함수

pygame에서 지원하는 선 그리기 함수인 line 함수는 다음과 같은 인자값들을 받습니다.



 pygame.draw.line(Surface, Color, Start_pos, End_pos, Width=1)

  Draw a straight line segment.

  Draw a straight line segment on a Surface. There are no endcaps, the ends are squared off for thick lines.




변수 

설명

Surface

 pygame을 실행할 때 전체적으로 화면을 선언한 변수 값

Color

 선의 색깔로 (R, G, B)의 형태로 데이터의 값을 삽입함

Start_pos

 선이 시작하는 점을 말하며 [x, y]형태로 값을 삽입함

End_pos

 선이 끝나는 점을 말하며 [x, y]형태로 값을 삽입함

Width

 선의 두께를 말하며, 기본적으로 1으로 설정됨


위의 변수들은 예제 소스코드를 통해 설명하도록 하겠습니다.


02. pygame.draw.line을 이용한 선 그리기(예제)

먼저 소스코드를 살펴보면 다음과 같습니다.


Source

# Import a library of functions called 'pygame'
import pygame

# Initialize the game engine
pygame.init()
 
# Define the colors we will use in RGB format
BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)
BLUE  = (  0,   0, 255)
GREEN = (  0, 255,   0)
RED   = (255,   0,   0)
 
# Set the height and width of the screen
size   = [400, 300]
screen = pygame.display.set_mode(size)
 
pygame.display.set_caption("Drawing Rectangle")
 
#Loop until the user clicks the close button.
done = False
clock = pygame.time.Clock()
 
while not done:
 
    # This limits the while loop to a max of 10 times per second.
    # Leave this out and we will use all CPU we can.
    clock.tick(10)
     
    for event in pygame.event.get(): # User did something
        if event.type == pygame.QUIT: # If user clicked close
            done=True # Flag that we are done so we exit this loop
 
    # All drawing code happens after the for loop and but
    # inside the main while done==False loop.
     
    # Clear the screen and set the screen background
    screen.fill(WHITE)

    # Draw on the screen a GREEN line from (0,0) to (100, 150) 
    # 5 pixels wide.
    pygame.draw.line(screen, GREEN, [0, 0], [100,150], 5)

    # Draw on the screen a GREEN line from (0,300) to (100, 150) 
    # 5 pixels wide.
    pygame.draw.line(screen, BLUE, [0, 300], [100,150], 5)
     
    # Go ahead and update the screen with what we've drawn.
    # This MUST happen after all the other drawing commands.
    pygame.display.flip()
 
# Be IDLE friendly
pygame.quit()

전체적인 소스는 위와 같습니다.

이제 아래에서는 소스를 특정하여 나눠서 설명을 해보도록 하겠습니다.



Variable - Surface

# Set the height and width of the screen
size   = [400, 300]
screen = pygame.display.set_mode(size)

먼저, 16번째 줄의 screen 변수를 보면, 해당 변수에는 화면 전체를 설정하기 위한 값이 들어가 있습니다.

화면을 새로고침 해주거나, 화면을 채워주거나 할 때 해당 변수를 이용합니다.

pygame.draw.line 함수의 Surface는 이러한 화면 설정 변수를 넣어주시면 됩니다.


Variable - Color

# Define the colors we will use in RGB format
BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)
BLUE  = (  0,   0, 255)
GREEN = (  0, 255,   0)
RED   = (255,   0,   0)

다음으로, 8 ~ 12번 라인을 보시면, Tuple 형태의 값이 설정되어 있는 것을 보실 수 있습니다.

세 개의 값이 0 ~ 255의 범위를 가지게 되는데, 이렇게 설정된 값이 색깔(RGB) 값으로 Color 변수가 들어갈 곳에 넣어주시면 됩니다.


Variable - Start_pos, End_pos

    # Draw on the screen a GREEN line from (0,0) to (100, 150) 
    # 5 pixels wide.
    pygame.draw.line(screen, GREEN, [0, 0], [100,150], 5)

    # Draw on the screen a GREEN line from (0,300) to (100, 150) 
    # 5 pixels wide.
    pygame.draw.line(screen, BLUE, [0, 300], [100,150], 5)

먼저 42번째 라인과 46번째 라인을 살펴보면 리스트 형태의 값이 인자값으로 사용된 것을 보실 수 있습니다.

42번째 라인의 값을 예시로 살펴보면, Start_pos의 값인 경우 [0, 0]이고, End_pos의 경우 [100, 150]입니다.

Start_pos와 End_pos는 모두 [x, y]의 형태로 값을 삽입합니다.

Start_pos의 x축의 값은 0, y축의 값은 0

End_pos의 x축의 값은 100, y축의 값은 150

이라고 보시면 됩니다.


또한 두 선은 다른 시작 위치 같은 끝 위치를 가지고 있습니다.

이를 그림으로 표현해보면 다음과 같습니다.




초록색 선은 ( 0, 0 )에서 ( 100, 150 )으로 그려지고,

파란색 선은 ( 0, 300 )에서 ( 100, 150 )으로 그려집니다.


Variable - Width

    # Draw on the screen a GREEN line from (0,0) to (100, 150) 
    # 5 pixels wide.
    pygame.draw.line(screen, GREEN, [0, 0], [100,150], 5)

    # Draw on the screen a GREEN line from (0, 300) to (100, 150) 
    # 5 pixels wide.
    pygame.draw.line(screen, BLUE, [0, 300], [100,150], 5)

42번째 라인과 46번째 라인을 보시면 두 함수의 선 두께가 모두 5로 같은 것을 볼 수 있습니다.

기본적으로 line 함수의 경우 Width가 1로 되어 있으나, 이를 수정해줄 수 있습니다.

단, 0 이하의 수는 사용할 수 없습니다.

만약 사용하더라도 선이 그려지지 않습니다.(선의 두께가 0이라는 것은 선이 없다라는 걸 의미하지요.)



PyGame 모듈은 다양한 기능을 지원하는데, 그 중에서 여러가지 도형을 그릴 수 있는 메소드들을 소개하도록 하겠습니다.



00. PyGame 지원되는 도형

PyGame에서 지원되는 도형은 다음과 같습니다.

메소드

도형

설명

 pygame.draw.rect

 사각형

 화면에 사각형을 그려줍니다.

 pygame.draw.polygon

 삼각형

 화면에 삼각혁을 그려줍니다.

 pygame.draw.circle

 원

 화면에 원을 그려줍니다.

 pygame.draw.ellipse

 타원

 화면에 타원을 그려줍니다.

 pygame.draw.arc

 원

 화면에 원하는 만큼의 원을 그려줍니다.

 원을 얼마나 그려줄지 정할 수 있습니다.

 pygame.draw.line

 선

 화면에 선을 그려줍니다.

 pygame.draw.lines

 여러 개의 선

 화면에 여러 개의 선을 이어서 그립니다.

 pygame.draw.aaline

 부드러운 선

 화면에 부드러운 선을 그려줍니다.

 pygame.draw.aalines

 부드러운 선들

 화면에 부드러운 선을 여러 개 이어서 그립니다.


여기서는 pygame.draw.arc를 이용하여 타원을 그리는 방법을 살펴볼 것입니다.

만약 다른 draw 메소드를 참고하고 싶으시다면 아래의 링크에서 선택하시면 될 것 같습니다.




사각형 - pygame.draw.rect

삼각형 - pygame.draw.polygon

원 - pygame.draw.circle

타원 - pygame.draw.ellipse

선 - pygame.draw.line

여러 개의 선 - pygame.draw.lines

부드러운 선 - pygame.draw.aaline

여러 개의 부드러운 선 - pygame.draw.aalines




01. pygame.draw.arc 함수

pygame에서 지원하는 타원 그리기 함수인 arc 함수는 다음과 같은 인자값들을 받습니다.



 pygame.draw.arc(Surface, Color, Rect, Start_angle, Stop_angle, Width=1)

  Draws an elliptical arc on the Surface. The rect argument is the area that the ellipse will fill. The two angle arguments are the initial and final angle in radians, with the zero on the right. The width argument is the thickness to draw the outer edge.




변수 

설명

Surface

 pygame을 실행할 때 전체적으로 화면을 선언한 변수 값

Color

 원의 색깔로 (R, G, B)의 형태로 데이터의 값을 삽입함

Rect

 원의 [x축, y축, 가로, 세로]의 형태로 삽입함

Start_angle

 원을 그릴 시작 위치(0 혹은 원주율인 pi를 기준으로 입력함)

Stop_angle

 원을 그릴 끝 위치(0 혹은 원주율인 pi를 기준으로 입력함)

Width

 타원의 선 크기를 말하며, 기본적으로 0으로 설정됨


위의 변수들은 예제 소스코드를 통해 설명하도록 하겠습니다.



02. pygame.draw.arc를 이용한 원 그리기(예제)

먼저 소스코드를 살펴보면 다음과 같습니다.


Source

# Import a library of functions called 'pygame'
import pygame
from math import pi

# Initialize the game engine
pygame.init()
 
# Define the colors we will use in RGB format
BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)
BLUE  = (  0,   0, 255)
GREEN = (  0, 255,   0)
RED   = (255,   0,   0)
 
# Set the height and width of the screen
size   = [400, 300]
screen = pygame.display.set_mode(size)
 
pygame.display.set_caption("Drawing Rectangle")
 
#Loop until the user clicks the close button.
done = False
clock = pygame.time.Clock()
 
while not done:
 
    # This limits the while loop to a max of 10 times per second.
    # Leave this out and we will use all CPU we can.
    clock.tick(10)
     
    for event in pygame.event.get(): # User did something
        if event.type == pygame.QUIT: # If user clicked close
            done=True # Flag that we are done so we exit this loop
 
    # All drawing code happens after the for loop and but
    # inside the main while done==False loop.
     
    # Clear the screen and set the screen background
    screen.fill(WHITE)

    # Draw an arc as part of an ellipse. 
    # Use radians to determine what angle to draw.
    # pi : 3.141592653589793
    pygame.draw.arc(screen, BLACK,[210, 75, 150, 125], 0, pi/2, 5)
    pygame.draw.arc(screen, GREEN,[210, 75, 150, 125], pi/2, pi, 2)
    pygame.draw.arc(screen, BLUE, [210, 75, 150, 125], pi,3*pi/2, 2)
    pygame.draw.arc(screen, RED,  [210, 75, 150, 125], 3*pi/2, 2*pi, 2)
     
    # Go ahead and update the screen with what we've drawn.
    # This MUST happen after all the other drawing commands.
    pygame.display.flip()
 
# Be IDLE friendly
pygame.quit()


Variable - Surface

# Set the height and width of the screen
size   = [400, 300]
screen = pygame.display.set_mode(size)

먼저, 17번째 줄의 screen 변수를 보면, 해당 변수에는 화면 전체를 설정하기 위한 값이 들어가 있습니다.

화면을 새로고침 해주거나, 화면을 채워주거나 할 때 해당 변수를 이용합니다.

pygame.draw.arc 함수의 Surface는 이러한 화면 설정 변수를 넣어주시면 됩니다.


Variable - Color

# Define the colors we will use in RGB format
BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)
BLUE  = (  0,   0, 255)
GREEN = (  0, 255,   0)
RED   = (255,   0,   0)

다음으로, 9 ~ 13번 라인을 보시면, Tuple 형태의 값이 설정되어 있는 것을 보실 수 있습니다.

세 개의 값이 0 ~ 255의 범위를 가지게 되는데, 이렇게 설정된 값이 색깔(RGB) 값으로 Color 변수가 들어갈 곳에 넣어주시면 됩니다.


Variable - Rect

    # Draw an arc as part of an ellipse. 
    # Use radians to determine what angle to draw.
    # pi : 3.141592653589793
    pygame.draw.arc(screen, BLACK,[210, 75, 150, 125], 0, pi/2, 2)
    pygame.draw.arc(screen, GREEN,[210, 75, 150, 125], pi/2, pi, 2)
    pygame.draw.arc(screen, BLUE, [210, 75, 150, 125], pi,3*pi/2, 2)
    pygame.draw.arc(screen, RED,  [210, 75, 150, 125], 3*pi/2, 2*pi, 2)

먼저 44번째 라인부터 47번째 라인을 살펴보면 리스트 형태의 값이 인자값으로 사용된 것을 보실 수 있습니다.

모두 같은 값으로 되어 있습니다. 해당 Rect 변수에 들어갈 값인 [210, 75, 150, 125]으로 된 값을 살펴보면 [x, y, w, h]라고 설정된 값이 들어가 있다고 보시면 됩니다.

즉, x축의 위치는 210, y축의 위치는 75, 가로는 150, 세로는 125이라고 보시면 됩니다.


단, 여기서 원을 그리는데 필요한 변수가 왜 Rect(사각형)라고 되어있는가에 대한 의문이 들 수 있으실 것입니다.

이는 다음과 같은 그림으로 예시를 들 수 있겠습니다.


위의 그림을 설명하면 다음과 같습니다.

먼저 사각형 Rect 변수의 값을 통해 사각형을 그릴 위치와 가로, 세로 값을 정해줍니다.

그 다음 우리가 그릴 원을 그려주는 것입니다.


Variable -Start_angle, Stop_angle

    # Draw an arc as part of an ellipse. 
    # Use radians to determine what angle to draw.
    # pi : 3.141592653589793
    pygame.draw.arc(screen, BLACK,[210, 75, 150, 125], 0, pi/2, 2)
    pygame.draw.arc(screen, GREEN,[210, 75, 150, 125], pi/2, pi, 2)
    pygame.draw.arc(screen, BLUE, [210, 75, 150, 125], pi,3*pi/2, 2)
    pygame.draw.arc(screen, RED,  [210, 75, 150, 125], 3*pi/2, 2*pi, 2)

다음으로 원을 원을 그리기 위한 첫 번째 위치인 시작 위치(Start_angle)와 끝 위치(Stop_angle)를 살펴봅시다.

위의 그림으로 설명드리면, 시작 위치는 0, pi/2, 3*pi/2, 2*pi인 네 가지가 있다고 봅시다.

4개의 위치를 기반으로 시작 위치를 잡아주고, 끝 위치도 잡아주시면 됩니다.

각각의 색깔별로 설명드리면 다음과 같습니다.

검정색으로 그릴 원은 0 ~ pi/2로 시계방향으로 원을 그렸을 때 0에서 1/4만큼 그려주는 것입니다.

빨간색으로 그릴 원은 pi/2 ~ pi로 시계방향으로 원을 그렸을 때 1/4에서 2/4만큼 그려주는 것입니다.

파란색으로 그릴 원은 pi ~ 3*pi/2로 시계방향으로 원을 그렸을 때 2/4에서 3/4만큼 그려주는 것입니다.

초록색으로 그릴 원은 3*pi/2 ~ 2*pi로 시계방향으로 원을 그렸을 때 3/4에서 4/4만큼 그려주는 것입니다.


Variable - Width

    # Draw an arc as part of an ellipse. 
    # Use radians to determine what angle to draw.
    # pi : 3.141592653589793
    pygame.draw.arc(screen, BLACK,[210, 75, 150, 125], 0, pi/2, 2)
    pygame.draw.arc(screen, GREEN,[210, 75, 150, 125], pi/2, pi, 2)
    pygame.draw.arc(screen, BLUE, [210, 75, 150, 125], pi,3*pi/2, 2)
    pygame.draw.arc(screen, RED,  [210, 75, 150, 125], 3*pi/2, 2*pi, 2)

다음으로 두 타원 함수를 비교해보도록 하겠습니다.

44번째 라인과 47번째 라인을 보시면 선 두께를 2로 고정해준 것을 볼 수 있습니다.

Arc 함수의 경우 기본적으로 Width의 크기가 1이기 때문에 그려주는 원의 부분만 색깔 채움을 적용할 수 없습니다.

즉, 반드시 선으로만 그릴 수 있는 원이라는 의미입니다.





PyGame 모듈은 다양한 기능을 지원하는데, 그 중에서 여러가지 도형을 그릴 수 있는 메소드들을 소개하도록 하겠습니다.



00. PyGame 지원되는 도형

PyGame에서 지원되는 도형은 다음과 같습니다.

메소드

도형

설명

 pygame.draw.rect

 사각형

 화면에 사각형을 그려줍니다.

 pygame.draw.polygon

 삼각형

 화면에 삼각혁을 그려줍니다.

 pygame.draw.circle

 원

 화면에 원을 그려줍니다.

 pygame.draw.ellipse

 타원

 화면에 타원을 그려줍니다.

 pygame.draw.arc

 원

 화면에 원하는 만큼의 원을 그려줍니다.

 원을 얼마나 그려줄지 정할 수 있습니다.

 pygame.draw.line

 선

 화면에 선을 그려줍니다.

 pygame.draw.lines

 여러 개의 선

 화면에 여러 개의 선을 이어서 그립니다.

 pygame.draw.aaline

 부드러운 선

 화면에 부드러운 선을 그려줍니다.

 pygame.draw.aalines

 부드러운 선들

 화면에 부드러운 선을 여러 개 이어서 그립니다.


여기서는 pygame.draw.ellipse를 이용하여 타원을 그리는 방법을 살펴볼 것입니다.

만약 다른 draw 메소드를 참고하고 싶으시다면 아래의 링크에서 선택하시면 될 것 같습니다.




사각형 - pygame.draw.rect

삼각형 - pygame.draw.polygon

원 - pygame.draw.circle

원(특정 부분까지 그리기) - pygame.draw.arc

선 - pygame.draw.line

여러 개의 선 - pygame.draw.lines

부드러운 선 - pygame.draw.aaline

여러 개의 부드러운 선 - pygame.draw.aalines




01. pygame.draw.ellipse 함수

pygame에서 지원하는 타원 그리기 함수인 ellipse 함수는 다음과 같은 인자값들을 받습니다.



 pygame.draw.ellipse(Surface, Color, Rect, Width=0)

  Draw a round shape inside a rectangle.

  Draws an elliptical shape on the Surface. The given rectangle is the area that the circle will fill. The width argument is the thickness to draw the outer edge. If width is zero then the ellipse will be filled.




변수 

설명

Surface

 pygame을 실행할 때 전체적으로 화면을 선언한 변수 값

Color

 타원의 색깔로 (R, G, B)의 형태로 데이터의 값을 삽입함

Rect

 타원의 [x축, y축, 가로, 세로]의 형태로 삽입함

Width

 타원의 선 크기를 말하며, 기본적으로 0으로 설정됨


위의 변수들은 예제 소스코드를 통해 설명하도록 하겠습니다.



02. pygame.draw.ellipse를 이용한 타원 그리기(예제)

먼저 소스코드를 살펴보면 다음과 같습니다.



Source

# Import a library of functions called 'pygame'
import pygame
 
# Initialize the game engine
pygame.init()
 
# Define the colors we will use in RGB format
BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)
BLUE  = (  0,   0, 255)
GREEN = (  0, 255,   0)
RED   = (255,   0,   0)
 
# Set the height and width of the screen
size   = [400, 300]
screen = pygame.display.set_mode(size)
 
pygame.display.set_caption("Drawing Rectangle")
 
#Loop until the user clicks the close button.
done = False
clock = pygame.time.Clock()
 
while not done:
 
    # This limits the while loop to a max of 10 times per second.
    # Leave this out and we will use all CPU we can.
    clock.tick(10)
     
    for event in pygame.event.get(): # User did something
        if event.type == pygame.QUIT: # If user clicked close
            done=True # Flag that we are done so we exit this loop
 
    # All drawing code happens after the for loop and but
    # inside the main while done==False loop.
     
    # Clear the screen and set the screen background
    screen.fill(WHITE)

    # Draw an ellipse outline, using a rectangle as the outside boundaries
    pygame.draw.ellipse(screen, RED, [225, 10, 50, 20], 2) 

    # Draw an solid ellipse, using a rectangle as the outside boundaries
    pygame.draw.ellipse(screen, RED, [300, 10, 50, 20]) 
     
    # Go ahead and update the screen with what we've drawn.
    # This MUST happen after all the other drawing commands.
    pygame.display.flip()
 
# Be IDLE friendly
pygame.quit()


Variable - Surface

# Set the height and width of the screen
size   = [400, 300]
screen = pygame.display.set_mode(size)

먼저, 16번째 줄의 screen 변수를 보면, 해당 변수에는 화면 전체를 설정하기 위한 값이 들어가 있습니다.

화면을 새로고침 해주거나, 화면을 채워주거나 할 때 해당 변수를 이용합니다.

pygame.draw.ellipse 함수의 Surface는 이러한 화면 설정 변수를 넣어주시면 됩니다.


Variable - Color

# Define the colors we will use in RGB format
BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)
BLUE  = (  0,   0, 255)
GREEN = (  0, 255,   0)
RED   = (255,   0,   0)

다음으로, 8 ~ 12번 라인을 보시면, Tuple 형태의 값이 설정되어 있는 것을 보실 수 있습니다.

세 개의 값이 0 ~ 255의 범위를 가지게 되는데, 이렇게 설정된 값이 색깔(RGB) 값으로 Color 변수가 들어갈 곳에 넣어주시면 됩니다.


Variable - Rect

    # Draw an ellipse outline, using a rectangle as the outside boundaries
    pygame.draw.ellipse(screen, RED, [225, 10, 50, 20], 2) 

    # Draw an solid ellipse, using a rectangle as the outside boundaries
    pygame.draw.ellipse(screen, RED, [300, 10, 50, 20]) 

먼저 41번째 라인과 44번째 라인을 살펴보면 리스트 형태의 값이 인자값으로 사용된 것을 보실 수 있습니다.

41번째 라인의 값을 예시로 살펴보면, [225, 10, 50, 20]으로 된 값에는 [x, y, w, h]라고 설정된 값이 들어가 있다고 보시면 됩니다.

즉, x축의 위치는 225, y축의 위치는 10, 가로는 50, 세로는 20이라고 보시면 됩니다.


단, 여기서 왜 Rect라고 되어있는가에 대한 의문이 들 수 있으실 것입니다.

이는 다음과 같은 그림으로 예시를 들 수 있겠습니다.



위의 그림을 설명하면 다음과 같습니다.

먼저 사각형 Rect 변수의 값을 통해 사각형을 그릴 위치와 가로, 세로 값을 정해줍니다.

그 다음 우리가 그릴 타원을 그려주는 것입니다.


Variable - Width

    # Draw an ellipse outline, using a rectangle as the outside boundaries
    pygame.draw.ellipse(screen, RED, [225, 10, 50, 20], 2) 

    # Draw an solid ellipse, using a rectangle as the outside boundaries
    pygame.draw.ellipse(screen, RED, [300, 10, 50, 20]) 

다음으로 두 타원 함수를 비교해보도록 하겠습니다.

41번째 라인과 44번째 라인을 보시면 두 가지 방법으로 타원을 그린 것을 볼 수 있습니다.

41번째 라인의 타원은 Width의 값을 2로 변경해준 것이고, 44번째 라인의 타원은 값을 따로 지정해주지 않아 기본으로 지정된 Width=0을 사용하겠다고하여 변수의 값을 따로 지정해주지 않은 형태입니다.

만약 Width의 값을 지정해주게 되면, 색깔 채움 없는 빈 상자로 그려주는 것을 의미합니다.

즉, 타원의 선의 두께를 지정해준 것과 같은 것입니다.

그리고 44번째 라인의 타원은 Width의 값을 따로 지정해주지 않아 0으로 사용함을 의미합니다.

이는 타원의 바깥 선의 두께를 지정해주지 않고, 타원에 색을 채운 채로 그리는 것을 의미합니다.


41번째 라인의 ellipse 함수는 첫 번째 하얀 타원이고,

44번째 라인의 ellipse 함수는 두 번째 빨간 타원입니다.



41번째 라인의 ellipse 함수의 선 두께가 2로 지정되어 있으니, 적당한 두께의 형태로 출력이되었습니다.

또한 44번째 라인의 ellipse 함수는 선이 따로 없는 빨간색으로 채운 타원이 출력됩니다.


PyGame 모듈은 다양한 기능을 지원하는데, 그 중에서 여러가지 도형을 그릴 수 있는 메소드들을 소개하도록 하겠습니다.



00. PyGame 지원되는 도형

PyGame에서 지원되는 도형은 다음과 같습니다.

메소드

도형

설명

 pygame.draw.rect

 사각형

 화면에 사각형을 그려줍니다.

 pygame.draw.polygon

 삼각형

 화면에 삼각혁을 그려줍니다.

 pygame.draw.circle

 원

 화면에 원을 그려줍니다.

 pygame.draw.ellipse

 타원

 화면에 타원을 그려줍니다.

 pygame.draw.arc

 원

 화면에 원하는 만큼의 원을 그려줍니다.

 원을 얼마나 그려줄지 정할 수 있습니다.

 pygame.draw.line

 선

 화면에 선을 그려줍니다.

 pygame.draw.lines

 여러 개의 선

 화면에 여러 개의 선을 이어서 그립니다.

 pygame.draw.aaline

 부드러운 선

 화면에 부드러운 선을 그려줍니다.

 pygame.draw.aalines

 부드러운 선들

 화면에 부드러운 선을 여러 개 이어서 그립니다.


여기서는 pygame.draw.circle을 이용하여 원을 그리는 방법을 살펴볼 것입니다.

만약 다른 draw 메소드를 참고하고 싶으시다면 아래의 링크에서 선택하시면 될 것 같습니다.




사각형 - pygame.draw.rect

삼각형 - pygame.draw.polygon

타원 - pygame.draw.ellipse

원(특정 부분까지 그리기) - pygame.draw.arc

선 - pygame.draw.line

여러 개의 선 - pygame.draw.lines

부드러운 선 - pygame.draw.aaline

여러 개의 부드러운 선 - pygame.draw.aalines




01. pygame.draw.circle 함수

pygame에서 지원하는 원 그리기 함수인 circle 함수는 다음과 같은 인자값들을 받습니다.



 pygame.draw.circle(Surface, Color, Pos, Radius, Width=0)

  Draws a circular shape on the Surface. The pos argument is the center of the circle, and radius is the size. The width argument is the thickness to draw the outer edge. If width is zero then the circle will be filled.




변수 

설명

Surface

 pygame을 실행할 때 전체적으로 화면을 선언한 변수 값

Color

 원의 색깔로 (R, G, B)의 형태로 데이터의 값을 삽입함

 Pos

 원을 그릴 위치를 지정해주는 x, y 좌표 값

Radius

 원의 반지름의 길이값

Width

 원의 선 크기를 말하며, 기본적으로 0으로 설정됨


위의 변수들은 예제 소스코드를 통해 설명하도록 하겠습니다.



02. pygame.draw.circle을 이용한 원 그리기(예제)

먼저 소스코드를 살펴보면 다음과 같습니다.


Source

# Import a library of functions called 'pygame'
import pygame
 
# Initialize the game engine
pygame.init()
 
# Define the colors we will use in RGB format
BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)
BLUE  = (  0,   0, 255)
GREEN = (  0, 255,   0)
RED   = (255,   0,   0)
 
# Set the height and width of the screen
size   = [400, 300]
screen = pygame.display.set_mode(size)
 
pygame.display.set_caption("Drawing Rectangle")
 
#Loop until the user clicks the close button.
done = False
clock = pygame.time.Clock()
 
while not done:
 
    # This limits the while loop to a max of 10 times per second.
    # Leave this out and we will use all CPU we can.
    clock.tick(10)
     
    for event in pygame.event.get(): # User did something
        if event.type == pygame.QUIT: # If user clicked close
            done=True # Flag that we are done so we exit this loop
 
    # All drawing code happens after the for loop and but
    # inside the main while done==False loop.
     
    # Clear the screen and set the screen background
    screen.fill(WHITE)

    # Draw a circle outline
    pygame.draw.circle(screen, BLUE, [60, 250], 40, 2)

    # Draw a solid circle
    pygame.draw.circle(screen, BLUE, [60, 100], 40)
     
    # Go ahead and update the screen with what we've drawn.
    # This MUST happen after all the other drawing commands.
    pygame.display.flip()
 
# Be IDLE friendly
pygame.quit()


Variable - Surface

# Set the height and width of the screen
size   = [400, 300]
screen = pygame.display.set_mode(size)

먼저, 16번째 줄의 screen 변수를 보면, 해당 변수에는 화면 전체를 설정하기 위한 값이 들어가 있습니다.

화면을 새로고침 해주거나, 화면을 채워주거나 할 때 해당 변수를 이용합니다.

pygame.draw.circle 함수의 Surface는 이러한 화면 설정 변수를 넣어주시면 됩니다.


Variable - Color

# Define the colors we will use in RGB format
BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)
BLUE  = (  0,   0, 255)
GREEN = (  0, 255,   0)
RED   = (255,   0,   0)

다음으로, 8 ~ 12번 라인을 보시면, Tuple 형태의 값이 설정되어 있는 것을 보실 수 있습니다.

세 개의 값이 0 ~ 255의 범위를 가지게 되는데, 이렇게 설정된 값이 색깔(RGB) 값으로 Color 변수가 들어갈 곳에 넣어주시면 됩니다.


Variable - Pos

    # Draw a circle outline
    pygame.draw.circle(screen, BLUE, [60, 250], 40, 2)

    # Draw a solid circle
    pygame.draw.circle(screen, BLUE, [60, 100], 40)

먼저 41번째 라인과 44번째 라인을 살펴보면 리스트 형태의 값이 인자값으로 사용된 것을 보실 수 있습니다.

41번째 라인의 값을 예시로 살펴보면, [60, 250]으로 된 값은 x축의 위치가 60, y축의 위치가 250임을 나타냅니다.

이렇게 점의 위치(Position) 값을 리스트 형태 인자값으로 설정해주시면 됩니다.


Variable - Radius

    # Draw a circle outline
    pygame.draw.circle(screen, BLUE, [60, 250], 40, 2)

    # Draw a solid circle
    pygame.draw.circle(screen, BLUE, [60, 100], 40)

원을 그리기 위해서는 원의 위치(Position)과 함께 얼마나 큰 원을 그릴지를 정해주어야 합니다.

원의 크기를 결정하는 것은 원의 반지름입니다.

41번 라인과 44번 라인에서 40으로 되어 있는 인자값이 바로 반지름의 값입니다.

Radius 값에 원하는 반지름의 길이를 설정해주시면 원하시는 원의 크기를 설정하실 수 있습니다.


Variable - Width

    # Draw a circle outline
    pygame.draw.circle(screen, BLUE, [60, 250], 40, 2)

    # Draw a solid circle
    pygame.draw.circle(screen, BLUE, [60, 100], 40)

다음으로 두 원 함수를 비교해보도록 하겠습니다.

41번째 라인과 44번째 라인을 보시면 두 가지 방법으로 원을 그린 것을 볼 수 있습니다.

41번째 라인의 원은 Width의 값을 2로 변경해준 것이고, 44번째 라인의 원은 값을 따로 지정해주지 않아 기본으로 지정된 Width=0을 사용하겠다고하여 변수의 값을 따로 지정해주지 않은 형태입니다.

만약 Width의 값을 지정해주게 되면, 색깔 채움 없는 빈 상자로 그려주는 것을 의미합니다.

즉, 원의 선의 두께를 지정해준 것과 같은 것입니다.

그리고 44번째 라인의 원은 Width의 값을 따로 지정해주지 않아 0으로 사용함을 의미합니다.

이는 원의 바깥 선의 두께를 지정해주지 않고, 원에 색을 채운 채로 그리는 것을 의미합니다.


44번째 라인의 circle 함수는 첫 번째 파란 원이고,

41번째 라인의 circle 함수는 두 번째 하얀 원입니다.



41번째 라인의 circle 함수의 선 두께가 2로 지정되어 있으니, 적당한 두께의 형태로 출력이되었습니다.

또한 44번째 라인의 circle 함수는 선이 따로 없는 파란색으로 채운 원이 출력됩니다.


PyGame 모듈은 다양한 기능을 지원하는데, 그 중에서 여러가지 도형을 그릴 수 있는 메소드들을 소개하도록 하겠습니다.


00. PyGame 지원되는 도형

PyGame에서 지원되는 도형은 다음과 같습니다.

메소드

도형

설명

 pygame.draw.rect

 사각형

 화면에 사각형을 그려줍니다.

 pygame.draw.polygon

 삼각형

 화면에 삼각혁을 그려줍니다.

 pygame.draw.circle

 원

 화면에 원을 그려줍니다.

 pygame.draw.ellipse

 타원

 화면에 타원을 그려줍니다.

 pygame.draw.arc

 원

 화면에 원하는 만큼의 원을 그려줍니다.

 원을 얼마나 그려줄지 정할 수 있습니다.

 pygame.draw.line

 선

 화면에 선을 그려줍니다.

 pygame.draw.lines

 여러 개의 선

 화면에 여러 개의 선을 이어서 그립니다.

 pygame.draw.aaline

 부드러운 선

 화면에 부드러운 선을 그려줍니다.

 pygame.draw.aalines

 부드러운 선들

 화면에 부드러운 선을 여러 개 이어서 그립니다.


여기서는 pygame.draw.polygon을 이용하여 삼각형을 그리는 방법을 살펴볼 것입니다.

만약 다른 draw 메소드를 참고하고 싶으시다면 아래의 링크에서 선택하시면 될 것 같습니다.




사각형 - pygame.draw.rect

원 - pygame.draw.circle

타원 - pygame.draw.ellipse

원(특정 부분까지 그리기) - pygame.draw.arc

선 - pygame.draw.line

여러 개의 선 - pygame.draw.lines

부드러운 선 - pygame.draw.aaline

여러 개의 부드러운 선 - pygame.draw.aalines




01. pygame.draw.polygon 함수

pygame에서 지원하는 삼각형 그리기 함수인 polygon 함수는 다음과 같은 인자값들을 받습니다.



 pygame.draw.polygon(Surface, Color, PointList, Width=0)

  Draws a polygonal shape on the Surface. The pointlist argument is the vertices of the polygon. The width argument is the thickness to draw the outer edge. If width is zero then the polygon will be filled.

  For aapolygon, use aalines with the 'closed' parameter.




변수 

설명

Surface

 pygame을 실행할 때 전체적으로 화면을 선언한 변수 값

Color

 삼각형의 색깔로 (R, G, B)의 형태로 데이터의 값을 삽입함

PointList

 삼각형의 세 개의 점을 [[x축, y축], [x축, y축], [x축, y축]의 형태로 삽입함

Width

 삼각형의 선 크기를 말하며, 기본적으로 0으로 설정됨


위의 변수들은 예제 소스코드를 통해 설명하도록 하겠습니다.



02. pygame.draw.polygon을 이용한 삼각형 그리기(예제)

먼저 소스코드를 살펴보면 다음과 같습니다.


Source

# Import a library of functions called 'pygame'
import pygame
 
# Initialize the game engine
pygame.init()
 
# Define the colors we will use in RGB format
BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)
BLUE  = (  0,   0, 255)
GREEN = (  0, 255,   0)
RED   = (255,   0,   0)
 
# Set the height and width of the screen
size   = [400, 300]
screen = pygame.display.set_mode(size)
 
pygame.display.set_caption("Drawing Rectangle")
 
#Loop until the user clicks the close button.
done = False
clock = pygame.time.Clock()
 
while not done:
 
    # This limits the while loop to a max of 10 times per second.
    # Leave this out and we will use all CPU we can.
    clock.tick(10)
     
    for event in pygame.event.get(): # User did something
        if event.type == pygame.QUIT: # If user clicked close
            done=True # Flag that we are done so we exit this loop
 
    # All drawing code happens after the for loop and but
    # inside the main while done==False loop.
     
    # Clear the screen and set the screen background
    screen.fill(WHITE)

    # This draws a triangle using the polygon command
    # Draw a polygon outline
    pygame.draw.polygon(screen, BLACK, [[50, 50], [0, 100], [100, 100]], 5)

    # Draw a solid polygon
    pygame.draw.polygon(screen, BLACK, [[200, 50], [150, 100], [250, 100]])
     
    # Go ahead and update the screen with what we've drawn.
    # This MUST happen after all the other drawing commands.
    pygame.display.flip()
 
# Be IDLE friendly
pygame.quit()

전체적인 소스는 위와 같습니다.

이제 아래에서는 소스를 특정하여 나눠서 설명을 해보도록 하겠습니다.



Variable - Surface

# Set the height and width of the screen
size   = [400, 300]
screen = pygame.display.set_mode(size)

먼저, 16번째 줄의 screen 변수를 보면, 해당 변수에는 화면 전체를 설정하기 위한 값이 들어가 있습니다.

화면을 새로고침 해주거나, 화면을 채워주거나 할 때 해당 변수를 이용합니다.

pygame.draw.polygon 함수의 Surface는 이러한 화면 설정 변수를 넣어주시면 됩니다.


Variable - Color

# Define the colors we will use in RGB format
BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)
BLUE  = (  0,   0, 255)
GREEN = (  0, 255,   0)
RED   = (255,   0,   0)

다음으로, 8 ~ 12번 라인을 보시면, Tuple 형태의 값이 설정되어 있는 것을 보실 수 있습니다.

세 개의 값이 0 ~ 255의 범위를 가지게 되는데, 이렇게 설정된 값이 색깔(RGB) 값으로 Color 변수가 들어갈 곳에 넣어주시면 됩니다.


Variable - PointList

    # This draws a triangle using the polygon command
    # Draw a polygon outline
    pygame.draw.polygon(screen, BLACK, [[50, 50], [0, 100], [100, 100]], 5)

    # Draw a solid polygon
    pygame.draw.polygon(screen, BLACK, [[200, 50], [150, 100], [250, 100]])

먼저 42번째 라인과 45번째 라인을 살펴보면 리스트 형태의 값이 인자값으로 사용된 것을 보실 수 있습니다.

42번째 라인의 값을 예시로 살펴보면, [[50, 50], [0, 100], [100, 100]]으로 된 값은 세 개의 점을 나타냅니다.

첫 번째 점의 x좌표와 y좌표 : [50, 50]

두 번째 점의 x좌표와 y좌표 : [0, 100]

세 번째 점의 x좌표와 y좌표 : [100, 100]

이렇게 세 점의 값을 리스트 형태로 묶어서 인자값으로 설정해주시면 됩니다.


Variable - Width

    # This draws a triangle using the polygon command
    # Draw a polygon outline
    pygame.draw.polygon(screen, BLACK, [[50, 50], [0, 100], [100, 100]], 5)

    # Draw a solid polygon
    pygame.draw.polygon(screen, BLACK, [[200, 50], [150, 100], [250, 100]])

다음으로 두 삼각형 함수를 비교해보도록 하겠습니다.

42번째 라인과 45번째 라인을 보시면 두 가지 방법으로 삼각형을 그린 것을 볼 수 있습니다.

42번째 라인의 삼각형은 Width의 값을 5로 변경해준 것이고, 45번째 라인의 삼각형은 값을 따로 지정해주지 않아 기본으로 지정된 Width=0을 사용하겠다고하여 변수의 값을 따로 지정해주지 않은 형태입니다.

만약 Width의 값을 지정해주게 되면, 색깔 채움 없는 빈 상자로 그려주는 것을 의미합니다.

즉, 삼각형의 선의 두께를 지정해준 것과 같은 것입니다.

그리고 45번째 라인의 삼각형은 Width의 값을 따로 지정해주지 않아 0으로 사용함을 의미합니다.

이는 삼각형의 바깥 선의 두께를 지정해주지 않고, 삼각형에 색을 채운 채로 그리는 것을 의미합니다.


42번째 라인의 삼각형첫 번째 하얀 삼각형이고,

45번째 라인의 삼각형두 번째 검은 삼각형입니다.



42번째 라인의 삼각형의 선 두께가 5로 지정되어 있으니, 꽤 두꺼운 형태로 출력이되었습니다.

또한 45번째 라인의 삼각형은 선이 따로 없는 검은색으로 채운 삼각형이 출력됩니다.


PyGame 모듈은 다양한 기능을 지원하는데, 그 중에서 여러가지 도형을 그릴 수 있는 메소드들을 소개하도록 하겠습니다.



00. PyGame 지원되는 도형

PyGame에서 지원되는 도형은 다음과 같습니다.

메소드

도형

설명

 pygame.draw.rect

 사각형

 화면에 사각형을 그려줍니다.

 pygame.draw.polygon

 삼각형

 화면에 삼각혁을 그려줍니다.

 pygame.draw.circle

 원

 화면에 원을 그려줍니다.

 pygame.draw.ellipse

 타원

 화면에 타원을 그려줍니다.

 pygame.draw.arc

 원

 화면에 원하는 만큼의 원을 그려줍니다.

 원을 얼마나 그려줄지 정할 수 있습니다.

 pygame.draw.line

 선

 화면에 선을 그려줍니다.

 pygame.draw.lines

 여러 개의 선

 화면에 여러 개의 선을 이어서 그립니다.

 pygame.draw.aaline

 부드러운 선

 화면에 부드러운 선을 그려줍니다.

 pygame.draw.aalines

 부드러운 선들

 화면에 부드러운 선을 여러 개 이어서 그립니다.


여기서는 pygame.draw.rect를 이용하여 사각형을 그리는 방법을 살펴볼 것입니다.

만약 다른 draw 메소드를 참고하고 싶으시다면 아래의 링크에서 선택하시면 될 것 같습니다.




삼각형 - pygame.draw.polygon

원 - pygame.draw.circle

타원 - pygame.draw.ellipse

원(특정 부분까지 그리기) - pygame.draw.arc

선 - pygame.draw.line

여러 개의 선 - pygame.draw.lines

부드러운 선 - pygame.draw.aaline

여러 개의 부드러운 선 - pygame.draw.aalines




01. pygame.draw.rect 함수

pygame에서 지원하는 사각형 그리기 함수인 rect 함수는 다음과 같은 인자값들을 받습니다.



 pygame.draw.rect(Surface, color, Rect, Width=0)

  Draws a rectangular shape on the Surface. The given Rect is the area of the rectangle. The width argument is the thickness to draw the outer edge. If width is zero then the rectangle will be filled.

  Keep in minde the Surface.fill() method works just as well for drawing filled rectangles. In fact the Surface.fill() can be hardware accelerated on some platforms with both software and hardware display modes.




변수 

설명

 Surface

 pygame을 실행할 때 전체적으로 화면을 선언한 변수 값

 color

 사각형의 색깔로 (R, G, B)의 형태로 데이터의 값을 삽입함

 Rect

 사각형의 [x축, y축, 가로, 세로]의 형태로 삽입함

 Width

 사각형의 선 크기를 말하며, 기본적으로 0으로 설정됨


위의 변수들은 예제 소스코드를 통해 설명하도록 하겠습니다.



02. pygame.draw.rect를 이용한 사각형 그리기(예제)

먼저 소스코드를 살펴보면 다음과 같습니다.


Source

# Import a library of functions called 'pygame'
import pygame
 
# Initialize the game engine
pygame.init()
 
# Define the colors we will use in RGB format
BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)
BLUE  = (  0,   0, 255)
GREEN = (  0, 255,   0)
RED   = (255,   0,   0)
 
# Set the height and width of the screen
size   = [400, 300]
screen = pygame.display.set_mode(size)
 
pygame.display.set_caption("Drawing Rectangle")
 
#Loop until the user clicks the close button.
done = False
clock = pygame.time.Clock()
 
while not done:
 
    # This limits the while loop to a max of 10 times per second.
    # Leave this out and we will use all CPU we can.
    clock.tick(10)
     
    for event in pygame.event.get(): # User did something
        if event.type == pygame.QUIT: # If user clicked close
            done=True # Flag that we are done so we exit this loop
 
    # All drawing code happens after the for loop and but
    # inside the main while done==False loop.
     
    # Clear the screen and set the screen background
    screen.fill(WHITE)

    # Draw a rectangle outline
    pygame.draw.rect(screen, BLACK, [75, 10, 50, 20], 2)
     
    # Draw a solid rectangle
    pygame.draw.rect(screen, BLACK, [150, 10, 50, 20])
     
    # Go ahead and update the screen with what we've drawn.
    # This MUST happen after all the other drawing commands.
    pygame.display.flip()
 
# Be IDLE friendly
pygame.quit()

전체적인 소스는 위와 같습니다.

이제 아래에서는 소스를 특정하여 나눠서 설명을 해보도록 하겠습니다.



Variable - Surface

# Set the height and width of the screen
size   = [400, 300]
screen = pygame.display.set_mode(size)

먼저, 16번째 줄의 screen 변수를 보면, 해당 변수에는 화면 전체를 설정하기 위한 값이 들어가 있습니다.

화면을 새로고침 해주거나, 화면을 채워주거나 할 때 해당 변수를 이용합니다.

pygame.draw.rect 함수의 Surface는 이러한 화면 설정 변수를 넣어주시면 됩니다.


Variable - Color

# Define the colors we will use in RGB format
BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)
BLUE  = (  0,   0, 255)
GREEN = (  0, 255,   0)
RED   = (255,   0,   0)

다음으로, 8 ~ 12번 라인을 보시면, Tuple 형태의 값이 설정되어 있는 것을 보실 수 있습니다.

세 개의 값이 0 ~ 255의 범위를 가지게 되는데, 이렇게 설정된 값이 색깔(RGB) 값으로 Color 변수가 들어갈 곳에 넣어주시면 됩니다.


Variable - Rect

    # Draw a rectangle outline
    pygame.draw.rect(screen, BLACK, [75, 10, 50, 20], 2)
     
    # Draw a solid rectangle
    pygame.draw.rect(screen, BLACK, [150, 10, 50, 20])

먼저 41번째 라인과 44번째 라인을 살펴보면 리스트 형태의 값이 인자값으로 사용된 것을 보실 수 있습니다.

41번째 라인의 값을 예시로 살펴보면, [75, 10, 50, 20]으로 된 값에는 x, y, w, h 라고 설정된 값이 들어가 있다고 보시면 됩니다.

즉, x축의 값은 75, y축의 값은 10, 가로는 50, 세로는 20이라고 보시면 됩니다.


Variable - Width

    # Draw a rectangle outline
    pygame.draw.rect(screen, BLACK, [75, 10, 50, 20], 2)
     
    # Draw a solid rectangle
    pygame.draw.rect(screen, BLACK, [150, 10, 50, 20])

다음으로 두 사각형 함수를 비교해보도록 하겠습니다.

41번째 라인과 44번째 라인을 보시면 두 가지 방법으로 사각형을 그린 것을 볼 수 있습니다.

41번째 라인의 사각형은 Width의 값을 2로 변경해준 것이고, 44번째 라인의 사각형은 값을 따로 지정해주지 않아 기본으로 지정된 Width=0을 사용하겠다고하여 변수의 값을 따로 지정해주지 않은 형태입니다.

만약 Width의 값을 지정해주게 되면, 색깔 채움 없는 빈 상자로 그려주는 것을 의미합니다.

즉, 사각형의 선의 두께를 지정해준 것과 같은 것입니다.

그리고 44번째 라인의 사각형은 Width의 값을 따로 지정해주지 않아 0으로 사용함을 의미합니다.

이는 사각형의 바깥 선의 두께를 지정해주지 않고, 사각형에 색을 채운 채로 그리는 것을 의미합니다.


41번째 라인의 사각형첫 번째 하얀 상자이고,

44번째 라인의 사각형두 번째 검은 상자입니다.


41번째 라인의 사각형의 선 두께가 2로 지정되어 있으니, 꽤 두꺼운 형태로 출력이되었습니다.

또한 44번째 라인의 사각형은 선이 따로 없는 검은색으로 채운 사각형이 출력됩니다.






가끔 클래스를 사용하다 보면, 선언과 Type에 대한 에러 때문에 갈필을 못잡을 때가 있습니다.

여기서는 TypeError 중에 missing argument에 대해 이야기해보고자 합니다.


01. TypeError: [여러분의 함수] missing [숫자] required positional argument: [여러분의 함수의 인자값]

TypeError: [여러분의 함수] missing [숫자] required positional argument: [여러분의 함수의 인자값]

위의 에러에서는 분명히 Class를 입력했음에도 불구하고 TypeError로 우리가 인자값에 제대로 된 값을 넣어주지 않았다는 에러 메시지를 출력합니다.

이런 경우 정말 억울하기도 하고, 혹시 내가 잘못 입력한 건 아닌가 하며 시간을 낭비하기도 합니다.

저도 이런 에러 때문에 시간을 많이 잡아먹혔었지요.


예제를 먼저 보도록 합시다.


class 선언

#python 3.x source
#FileName : TestClass.py

class Test:
	def __init__(self):
		print('init')
		
	def TestFunc(self, Argument):
		print('Type of Argument  : ', type(Argument))
		print('Value of Argument : ', Argument)


main 선언

#python 3.x source
#FileName : TestMain.py

from TestClass import Test

def main():
	Data = 0x01234567
	
	Test.TestFunc(Data)
	
if __name__ == "__main__":
	main()


여기서 class 파일의 8번 째 줄을 보면, self와 Argument라는 인자값을 받는 것을 볼 수 있습니다.

따라서 TestFunc() 함수에서는 self를 제외한 다른 하나의 인자값이 필요합니다.

즉, TestClass의 TestFunc() 함수를 하기 위해 Data라는 값을 Argument 인자값에 넣어주어 실행시켜봅니다.


이때 발생하는 에러 메시지는 다음과 같을 것입니다.


TypeError: TestFunc() missing 1 required positional argument: 'Argument'


이때의 에러 메시지는 1개의 인자값이 필요합니다, 라는 직역으로 해석이 가능합니다.

하지만 에러가 발생하는 원인은 따로 있습니다.


바로 Class의 선언이 없기 때문입니다.


이러한 에러를 해결하기 위해서는 main 소스를 다음과 같이 수정해볼 수 있습니다.


main 선언(오류 해결)

#python 3.x source
#FileName : TestMain.py

from TestClass import Test

def main():
	T = Test()

	Data = 0x01234567
	
	T.TestFunc(Data)
	
if __name__ == "__main__":
	main()


오류가 해결된 소스의 7번 줄과 11번 줄을 보면 Test라는 클래스를 따로 선언을 해준 뒤 이를 이용하여 함수를 불러오는 것을 확인할 수 있습니다.

즉, Class의 선언 없이 해당 클래스의 함수를 사용하려 했기 때문에 발생하는 오류를 해결해준 것입니다.



<다른 Type Error는 차차 업로드 예정...>


만약 여러분께서 pip를 사용하려고 할 때 사용이 안 될 경우가 있습니다.

간혹, 이런 오류 문구를 보실 것입니다.


 Fatal error in launcher: Unable to create process using '"C:\....."  "C:\....." install [module]' 


이런 경우 해결할 수 있는 방법은 다음과 같습니다.


01. pip upgrade

첫 번째로, python 명령을 통해 pip를 업그레이드 해주시면 됩니다.

이 경우의 해결할 수 있는 명령어는 다음과 같습니다.


 python -m pip install pip --upgrade pip 


여기서 python의 -m 옵션은 library 모듈을 스크립트의 형태로 실행시키는 것을 의미합니다.

이 경우는 pip를 업그레이드 하여 상위의 버전으로 설치한다는 의미입니다.


이후 pip 명령을 통해 설치하고자 하는 모듈을 설치해주시면 됩니다.

'

 pip install [설치하고자 하는 모듈] 




02. python -m install

두 번째로, python 명령의 옵션을 이용하여 pip 설치를 해주는 방법입니다.

위의 방법대로 pip가 업그레이드 되었음에도 불구하고 pip를 이용하여 설치가 되지 않을 경우 해당 방법을 사용하면 됩니다.

여기서는 위의 업그레이드 방법과 유사한 방법으로, python의 -m 옵션을 이용하여 설치하시면 됩니다.

python 옵션을 이용한 모듈 설치 명령은 다음과 같습니다.


 python -m pip install [설치하고자 하는 모듈]


해당 명령을 통해 pip를 실행시켜 설치하고자 하는 모듈을 설치하시면 됩니다.



'PYTHON > Python 관련 오류잡기' 카테고리의 다른 글

python 클래스 TypeError 오류 해결  (3) 2018.07.24

+ Recent posts