Ball 클래스
Coddy의 Pygame으로 게임 만들기 코스 레슨. 41개 중 38번째.
공은 Rect와 두 개의 숫자, 그리고 공이 하는 일인 이동, 튕기기, 그려지기로 이루어져 있습니다. 스프라이트에서 했던 것처럼 클래스로 만들어 보세요. 클래스는 데이터와 그 데이터를 사용하는 함수를 함께 묶어 둡니다.
class Ball:
def __init__(self):
self.rect = pygame.Rect(293, 193, 14, 14)
self.vx = 5
self.vy = 4
def move(self):
self.rect.x += self.vx
self.rect.y += self.vyball = Ball()은 공 객체를 만들고 __init__을 실행합니다. 클래스 안에서 self는 객체이므로 self.vx는 이 공의 vx입니다. 클래스 안의 함수는 메서드입니다. ball.move()는 메서드를 호출합니다.
클래스 바깥에서는 공의 Rect가 이제 ball.rect이고 속도는 ball.vx와 ball.vy이므로, 패들과 점수 계산 코드는 이 값들을 사용합니다. 게임은 이전과 똑같이 진행됩니다.
챌린지
어려움공이 스스로 움직이고 그리도록 클래스로 만드세요.
- 맨 위에
class Ball과__init__(self.rect,self.vx = 5,self.vy = 4),move()(움직이고 위쪽과 아래쪽 경계에서 튕기기),draw(surface)를 작성하세요. ball = Ball()을 만들고, 반복문에서ball.move()와ball.draw(screen)를 호출하세요.- 그 밖의 모든 곳에서는
ball.rect,ball.vx,ball.vy를 작성하세요.
‘플레이’를 누르세요. 게임은 이전과 정확히 똑같이 진행됩니다. 그런 다음 ‘확인’을 누르세요.
직접 해보기
import pygame
pygame.init()
screen = pygame.display.set_mode((600, 400))
pygame.display.set_caption("Pong")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 36)
ball = pygame.Rect(293, 193, 14, 14)
vx, vy = 5, 4
left = pygame.Rect(20, 160, 12, 80)
right = pygame.Rect(568, 160, 12, 80)
left_score = 0
right_score = 0
waiting = False
winner = None
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
if winner is None:
waiting = False
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
left.y -= 6
if keys[pygame.K_s]:
left.y += 6
if keys[pygame.K_UP]:
right.y -= 6
if keys[pygame.K_DOWN]:
right.y += 6
left.clamp_ip(screen.get_rect())
right.clamp_ip(screen.get_rect())
if not waiting:
ball.x += vx
ball.y += vy
if ball.top <= 0 or ball.bottom >= 400:
vy = -vy
if ball.colliderect(left):
vx = abs(vx)
vy = (ball.centery - left.centery) // 6
if ball.colliderect(right):
vx = -abs(vx)
vy = (ball.centery - right.centery) // 6
if ball.left > 600:
left_score += 1
ball.center = (300, 200)
vx = -vx
waiting = True
if ball.right < 0:
right_score += 1
ball.center = (300, 200)
vx = -vx
waiting = True
if left_score == 5:
winner = "Left player wins!"
elif right_score == 5:
winner = "Right player wins!"
screen.fill((30, 30, 46))
pygame.draw.rect(screen, (80, 160, 255), left)
pygame.draw.rect(screen, (235, 80, 80), right)
pygame.draw.rect(screen, (255, 196, 0), ball)
score = font.render(f"{left_score} : {right_score}", True, (240, 240, 240))
screen.blit(score, score.get_rect(center=(300, 30)))
if winner is not None:
message = font.render(winner, True, (240, 240, 240))
screen.blit(message, message.get_rect(center=(300, 120)))
elif waiting:
message = font.render("Press Space to serve", True, (240, 240, 240))
screen.blit(message, message.get_rect(center=(300, 360)))
pygame.display.flip()
clock.tick(60)
pygame.quit()
Pygame으로 게임 만들기의 모든 레슨
직접 연습해 보세요: Pygame 플레이그라운드