굵은 글씨(볼드체)로 한 것이 전번 시간에 했던 코드에서 추가된 내용입니다.
import pygame
#pygmme초기화
pygame.init()
#창 크기 설정
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
#창 설정
display_surface = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("이미지 충돌 이벤트")
clock = pygame.time.Clock()
#코끼리 이미지 붙이고 설정
elephant_image = pygame.image.load("elephant.png")
elephant_rect = elephant_image.get_rect()
elephant_rect.centerx = (WINDOW_WIDTH//2)
elephant_rect.bottom = (WINDOW_HEIGHT//2)
**#쥐 이미지 붙이고 설정
mouse_image = pygame.image.load("mouse.png")
mouse_rect = mouse_image.get_rect()
mouse_rect.centerx = (WINDOW_WIDTH//2)
elephant_rect.bottom = (WINDOW_HEIGHT//3)**
#게임이 동작하는 동안 이벤트
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
#키보드가 눌러졌을 때 발생하는 이벤트 지정
keys = pygame.key.get_pressed()
#방향키에 대한 키보드 이벤트, 알파벳을 이용한 키보드 이벤트
#캐릭터가 화면 밖으로 나가지 않도록 제한
if keys[pygame.K_LEFT] or keys[pygame.K_a] and elephant_rect.left > 0:
elephant_rect.x -= 5
if keys[pygame.K_RIGHT] or keys[pygame.K_d] and elephant_rect.right < WINDOW_WIDTH:
elephant_rect.x += 5
if keys[pygame.K_UP] or keys[pygame.K_w] and elephant_rect.top > 0:
elephant_rect.y -= 5
if keys[pygame.K_DOWN] or keys[pygame.K_s] and elephant_rect.bottom < WINDOW_HEIGHT:
elephant_rect.y += 5
**#캐릭터 충돌 이벤트 구현
if elephant_rect.colliderect(mouse_rect):
print("충돌")**
#바탕화면, 그림을 나타냄
display_surface.fill((0,0,0))
display_surface.blit(elephant_image, elephant_rect)
**display_surface.blit(mouse_image, mouse_rect)**
#디스플레이 업데이트
pygame.display.update()
#분당 프레임 설정
clock.tick(60)
pygame.quit()