본문 바로가기

Minding's Programming/Pygame

[Pygame] 08. 이미지 객체 추가 및 키보드로 움직이기

728x90
반응형

이 글은 아래 영상을 참고했다.

https://www.youtube.com/watch?v=sltwgj_KLQw&list=PLz2iXe7EqJOMp5LozvYa0qca9E4OBkevW&index=8 


이전에 배웠던 내용들을 토대로 글러브 객체를 추가하고 키보드를 이용해 움직일 수 있도록 만들어보았다.

 

할 것

  • 이전 시간에 배웠던 이미지 튕기기에 글러브 추가하기
  • 글러브가 화면 밖으로 벗어나지 않도록하고, 양 옆으로만 움직일 수 있도록 제한하기
import pygame
pygame.init()

background = pygame.display.set_mode((550, 382)) # 배경 이미지에 맞추어 화면크기 설정함
pygame.display.set_caption('PYGAME_7')

# 이미지 파일 준비
image_bg = pygame.image.load('./image/fungo.png')
image_ball = pygame.image.load('./image/ball_small.png')
image_glove = pygame.image.load('./image/glove_small.png')

# 배경의 사이즈 가져오기
size_bg_width = background.get_size()[0]
size_bg_height = background.get_size()[1]

# glove의 사이즈 가져오기
size_glove_width = image_glove.get_rect().size[0]
size_glove_height = image_glove.get_rect().size[1]

# glove의 좌표값 설정하기
x_pos_glove = size_bg_width/2 - size_glove_width/2 # x좌표값 상 중앙
y_pos_glove = size_bg_height - size_glove_height # 맨 아래 (전체 높이에서 이미지 높이 만큼 뺀 값)

# 키보드 움직임에 의한 좌표 변수 (양 옆으로만 움직일 것이므로 x좌표만)
to_x = 0

# ball의 사이즈 가져오기 (가로, 세로)
size_ball_width = image_ball.get_rect().size[0]
size_ball_height = image_ball.get_rect().size[1]

# ball의 좌표값 설정하기
x_pos_ball = size_bg_width/2 - size_ball_width/2 # 가운데
y_pos_ball = 0 # 맨 위

# ball의 x,y 축 속도 변수 (좌표에 더해줄 목적)
x_speed_ball = 1
y_speed_ball = 1

play = True
while play:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            play = False
        if event.type == pygame.KEYDOWN: # 키보드가 눌렸을때
            if event.key == pygame.K_RIGHT:
                to_x = 1
            elif event.key == pygame.K_LEFT:
                to_x = -1
        if event.type == pygame.KEYUP: # 키보드를 뗐을때
            if event.key == pygame.K_RIGHT:
                to_x = 0
            elif event.key == pygame.K_LEFT:
                to_x = 0
    
    # glove가 화면 밖으로 벗어나지 않도록 제한
    if x_pos_glove < 0:
        x_pos_glove = 0
    elif x_pos_glove > size_bg_width - size_glove_width:
        x_pos_glove = size_bg_width - size_glove_width
    else:
        x_pos_glove += to_x
        
    x_pos_ball += x_speed_ball
    y_pos_ball += y_speed_ball
        
    # x좌표값을 제한하고 speed변수를 음수로 바꿔 방향 전환하기
    if x_pos_ball <= 0:
        x_speed_ball = -x_speed_ball
        x_pos_ball = 0
    elif x_pos_ball >= size_bg_width - size_ball_width:
        x_speed_ball = -x_speed_ball
        x_pos_ball = size_bg_width - size_ball_width
        
    if y_pos_ball <= 0:
        y_speed_ball = -y_speed_ball
        y_pos_ball = 0
    elif y_pos_ball >= size_bg_height-size_ball_height:
        y_speed_ball = -y_speed_ball
        y_pos_ball = size_bg_height-size_ball_height
            
    # 이미지 삽입 및 업데이트
    background.blit(image_bg, (0,0))
    background.blit(image_ball, (x_pos_ball, y_pos_ball))
    background.blit(image_glove, (x_pos_glove, y_pos_glove))
    pygame.display.update()
    
pygame.quit()

이전 코드들 복붙하고 살짝만 수정해주면 어려울게 없다.

화면 밖으로 벗어나지 않도록 좌표를 제한해주는 부분만 신경쓰면 충분히 구현 가능하다.

왼쪽 가장자리가 이미지, 배경 등등 모든 것의 중심좌표라는 것을 잊지말자!

 

시연 영상

 

 

728x90