[python] pygame 원 그리기 샘플

pygame에서 원을 그릴 때 좌표계는 아래와 같습니다.


아래는 샘플코드입니다.


import pygame

class Particle:
    def __init__(self, position, size):
        self.x, self.y = position
        self.size = size
        self.colour = (0, 0, 255)
        self.thickness = 1

    def display(self):
        pygame.draw.circle(screen, self.colour, (self.x, self.y), self.size, self.thickness)

# 윈도우 타이틀
pygame.display.set_caption('Tutorial 2')

# 배경화면 색상
background_color = (255,255,255)

# 윈도우 사이즈
(width, height) = (300, 200)
screen = pygame.display.set_mode((width, height))
screen.fill(background_color)

# 파티클 생성
my_first_particle = Particle((150, 50), 15)
my_first_particle.display()

# 윈도우 표기
pygame.display.flip()

running = True
while running:
    for event in pygame.event.get():
        # 닫기 버튼 감지
        if event.type == pygame.QUIT:
            running = False



아래는 실행결과입니다.


위 코드를 활용하여 여러 원형 파티클(particle)을 만들어 봅니다. 아래는 최종코드입니다.


import pygame
import random

class Particle():
    def __init__(self, position, size):
        self.x, self.y = position
        self.size = size
        self.colour = (0, 0, 255)
        self.thickness = 1

    def display(self):
        pygame.draw.circle(screen, self.colour, (self.x, self.y), self.size, self.thickness)

# 윈도우 타이틀
pygame.display.set_caption('Tutorial 3')

# 배경화면 색상
background_color = (255,255,255)

# 윈도우 사이즈
(width, height) = (300, 200)
screen = pygame.display.set_mode((width, height))
screen.fill(background_color)

# 파티클 생성
number_of_particles = 10
my_particles = []

for n in range(number_of_particles):
    size = random.randint(10, 20)
    x = random.randint(size, width-size)
    y = random.randint(size, height-size)
    my_particles.append(Particle((x, y), size))

for particle in my_particles:
    particle.display()

# 윈도우 표기
pygame.display.flip()

running = True
while running:
    for event in pygame.event.get():
        # 닫기 버튼 감지
        if event.type == pygame.QUIT:
            running = False



아래는 실행결과입니다.


끝.

댓글

이 블로그의 인기 게시물

[PLC] PLC 아날로그 입출력 기본

전력(kW) 계산하기 (직류, 교류 단상, 교류 삼상)

NPN, PNP 트랜지스터 차이점

3선 결선식 센서의 타입 PNP, NPN

[아두이노] 가변저항(Potential Divider)과 전압분배(Voltage Divider)

제너 다이오드에 저항을 연결하는 이유

커패시터에 저장된 에너지 계산

[공압밸브] 5포트 2웨이 & 4포트 2웨이, 단동 VS 복동 차이점

3상 모터 전력에서 전류 계산하기 (How to Convert Three-Phase Power to Amps)

SSR과 기계식 릴레이 차이점