import pygame
**import random**
#pygmme초기화
pygame.init()
#창 크기 설정
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
#색깔 설정
GREEN = (0, 255, 0)
BLACK = (0, 0, 0)
#창 설정
display_surface = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("이미지 충돌과 점수판 만들기")
clock = pygame.time.Clock()
score_live = 5
#코끼리 이미지 붙이고 설정
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)
#텍스트 객체 만들기
system_font = pygame.font.SysFont('verdanai', 30)
game_live = system_font.render("Lives: " + str(score_live), True, GREEN, BLACK)
game_live_rect = game_live.get_rect()
game_live_rect.topleft = (10, 10)
#게임이 동작하는 동안 이벤트
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("충돌")
score_live = score_live - 1
mouse_rect.x = random.randint(0, WINDOW_WIDTH - 50)
mouse_rect.y = random.randint(0, WINDOW_HEIGHT - 50)
#점수판 표시
if score_live > 0:
game_live = system_font.render("Lives: " + str(score_live), True, GREEN, BLACK)
else:
game_live = system_font.render("GAME OVER", True, GREEN, BLACK)**
#바탕화면, 그림을 나타냄
display_surface.fill((0,0,0))
display_surface.blit(elephant_image, elephant_rect)
display_surface.blit(mouse_image, mouse_rect)
#텍스트 표시
display_surface.blit(game_live, game_live_rect)
#디스플레이 업데이트
pygame.display.update()
#분당 프레임 설정
clock.tick(60)
pygame.quit()
https://youtu.be/0nOengt-hFE