티스토리 뷰

작성 코드
# 1. 모든 슬라임을 없애면 게임 종료 (성공)
# 2. 캐릭터는 슬라임에 닿으면 게임 종료 (실패)
# 3. 시간 제한 99초 초과 시 게임 종료 (실패)

import pygame
import os

from pygame.display import update
#######################################################################################
# 기본 초기화 (반드시 해야 하는 것들)
pygame.init()

#화면 크기 설정
screen_width = 640 # 가로 크기
screen_height = 480 #  세로 크기
screen = pygame.display.set_mode((screen_width, screen_height))

# 화면 타이틀 설정
pygame.display.set_caption("오락실 게임") # 게임 이름

# FPS
clock = pygame.time.Clock()
#######################################################################################

# 1. 사용자 게임 초기화 (배경 화면, 게임 이미지, 좌표, 속도, 폰트 등)
current_path = os.path.dirname(__file__) # 현재 파일의 위치 반환
image_path = os.path.join(current_path, "images") # images 폴더 위치 반환

# 배경 만들기
background = pygame.image.load(os.path.join(image_path, "background.png")) # os를 통해 좀 더 간결해짐.

# 스테이지 만들기
stage = pygame.image.load(os.path.join(image_path, "stage.png"))
stage_size = stage.get_rect().size
stage_height = stage_size[1] # 1이 높이고 0이 너비임. 스테이지의 높이 위에 캐릭터를 두기 위해 사용

# 캐릭터 만들기
character = pygame.image.load(os.path.join(image_path, "character.png"))
character_size = character.get_rect().size
character_width = character_size[0]
character_height = character_size[1]
character_x_pos = (screen_width / 2) - (character_width / 2)
character_y_pos = screen_height - character_height - stage_height

# 캐릭터 이동 방향
character_to_x = 0

# 캐릭터 이동 속도
character_speed = 5

# 무기 만들기
weapon = pygame.image.load(os.path.join(image_path, "weapon.png"))
weapon_size = weapon.get_rect().size
weapon_width = weapon_size[0]

# 무기는 한 번에 여러 발 발사 가능
weapons = []

# 무기 이동 속도
weapon_speed = 10

# 슬라임 만들기 (4개 크기에 대해 따로 처리)
slime_images = [
    pygame.image.load(os.path.join(image_path, "slime1.png")),
    pygame.image.load(os.path.join(image_path, "slime2.png")),
    pygame.image.load(os.path.join(image_path, "slime3.png")),
    pygame.image.load(os.path.join(image_path, "slime4.png"))]

# 슬라임 크기에 따른 최초 스피드
slime_speed_y = [-18, -15, -12, -9] # index 0, 1, 2, 3에 해당하는 값

# 슬라임들
slimes = []

#최초 발생하는 큰 슬라임 추가
slimes.append({
    "pos_x" : 50, # 슬라임의 x 좌표
    "pos_y" : 50, # 슬라임의 y 좌표
    "img_idx" : 0, # 슬라임의 이미지 인덱스
    "to_x" : 3, # x축 이동방향, -3 이면 왼쪽, 3이면 오른쪽
    "to_y" : -6, # y축 이동방향
    "init_spd_y" : slime_speed_y[0]}) # y 최초 속도

# 사라질 무기, 슬라임 정보 저장 변수
weapon_to_remove = -1
slime_to_remove = -1

# Font 정의
game_font = pygame.font.Font(None, 40)
total_time = 100
start_ticks = pygame.time.get_ticks() # 시작 시간 정의

# 게임 종료 메시지
# Time Over(시간 초과 실패)
# Mission Complete(성공)
# Game Over(캐릭터 슬라임에 맞음, 실패)
game_result = "Game Over"
    
running = True 
while running :
    dt = clock.tick(30)

    # 2. 이벤트 처리 (키보드, 마우스 등)
    for event in pygame.event.get(): 
        if event.type == pygame.QUIT: 
            running = False 
        
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT: # 왼쪽으로
                character_to_x -= character_speed
            elif event.key == pygame.K_RIGHT: # 오른쪽으로
                character_to_x += character_speed
            elif event.key == pygame.K_SPACE: # 무기 발사
                weapon_x_pos = character_x_pos + (character_width / 2) - (weapon_width / 2) # 캐릭터의 중간에서 발사될 수 있도록
                weapon_y_pos = character_y_pos
                weapons.append([weapon_x_pos, weapon_y_pos])

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                character_to_x = 0

    # 3. 게임 캐릭터 위치 정의
    character_x_pos += character_to_x

    if character_x_pos < 0:
        character_x_pos = 0
    elif character_x_pos > screen_width - character_width:
        character_x_pos = screen_width - character_width

    # 무기 위치 조정
    weapons = [[w[0], w[1] - weapon_speed] for w in weapons] # 무기 위치를 위로 (뒤에서부터 해석)

    # 천장에 닿은 무기 없애기
    weapons = [[w[0], w[1]] for w in weapons if w[1] > 0]

    # 슬라임 위치 정의
    for slime_idx, slime_val in enumerate(slimes):
        slime_pos_x = slime_val["pos_x"]
        slime_pos_y = slime_val["pos_y"]
        slime_img_idx = slime_val["img_idx"]

        slime_size = slime_images[slime_img_idx].get_rect().size
        slime_width = slime_size[0]
        slime_height = slime_size[1]

        # 가로벽에 닿았을 때 슬라임 이동 위치 변경 (튕겨 나오는 효과)
        if slime_pos_x <=0 or slime_pos_x > screen_width - slime_width:
            slime_val["to_x"] = slime_val["to_x"] * -1

        # 세로 위치
        # 스테이지에 튕겨서 올라가는 처리
        if slime_pos_y >= screen_height - stage_height - slime_height:
            slime_val["to_y"] = slime_val["init_spd_y"]
        else : # 그 외의 모든 경우에는 속도를 증가
            slime_val["to_y"] += 0.5

        slime_val["pos_x"] += slime_val["to_x"]
        slime_val["pos_y"] += slime_val["to_y"]

    # 4. 충돌 처리

    # 캐릭터 rect 정보 업데이트
    character_rect = character.get_rect()
    character_rect.left = character_x_pos
    character_rect.top = character_y_pos

    for slime_idx, slime_val in enumerate(slimes):
        slime_pos_x = slime_val["pos_x"]
        slime_pos_y = slime_val["pos_y"]
        slime_img_idx = slime_val["img_idx"]

        # 슬라임 rect 정보 업데이트
        slime_rect = slime_images[slime_img_idx].get_rect()
        slime_rect.left = slime_pos_x
        slime_rect.top = slime_pos_y

        # 슬라임과 캐릭터 충돌 체크
        if character_rect.colliderect(slime_rect):
            running = False
            break

        # 슬라임과 무기들 충돌 처리
        for weapon_idx, weapon_val in enumerate(weapons):
            weapon_pos_x = weapon_val[0]
            weapon_pos_y = weapon_val[1]

            # 무기 rect 정보 업데이트
            weapon_rect = weapon.get_rect()
            weapon_rect.left = weapon_pos_x
            weapon_rect.top = weapon_pos_y

            # 충돌 체크
            if weapon_rect.colliderect(slime_rect):
                weapon_to_remove = weapon_idx # 해당 무기 없애기 위한 값 설정
                slime_to_remove = slime_idx # 해당 슬라임 없애기 위한 값 설정
                
                # 가장 작은 크기의 슬라임이 아니라면 다음 단계의 슬라임으로 나눠주기
                if slime_img_idx < 3:
                    # 현재 슬라임 크기 정보를 가지고 옴
                    slime_width = slime_rect.size[0]
                    slime_height = slime_rect.size[1]

                    # 나눠진 슬라임 정보
                    small_slime_rect = slime_images[slime_img_idx + 1].get_rect()
                    small_slime_width = small_slime_rect.size[0]
                    small_slime_height = small_slime_rect.size[1]

                    # 왼쪽으로 튕겨나가는 작은 슬라임
                    slimes.append({
                        "pos_x" : slime_pos_x + (slime_width / 2) - (small_slime_width / 2), # 슬라임의 x 좌표
                        "pos_y" : slime_pos_y + (slime_height / 2) - (small_slime_height), # 슬라임의 y 좌표
                        "img_idx" : slime_img_idx + 1, # 슬라임의 이미지 인덱스
                        "to_x" : -3, # x축 이동방향, -3 이면 왼쪽, 3이면 오른쪽
                        "to_y" : -6, # y축 이동방향
                        "init_spd_y" : slime_speed_y[slime_img_idx + 1]}) # y 최초 속도

                   # 오른쪽으로 튕겨나가는 작은 슬라임
                    slimes.append({
                        "pos_x" : slime_pos_x + (slime_width / 2) - (small_slime_width / 2), # 슬라임의 x 좌표
                        "pos_y" : slime_pos_y + (slime_height / 2) - (small_slime_height), # 슬라임의 y 좌표
                        "img_idx" : slime_img_idx + 1, # 슬라임의 이미지 인덱스
                        "to_x" : 3, # x축 이동방향, -3 이면 왼쪽, 3이면 오른쪽
                        "to_y" : -6, # y축 이동방향
                        "init_spd_y" : slime_speed_y[slime_img_idx + 1]}) # y 최초 속도
                break
        else: # 계속 게임을 진행
            continue # 안쪽 for문 조건이 맞지 않으면 continue, 바깥 for 문 계속 수행
        break # 앞쪽 for문에서 break를 만나면 여기로 진입 가능. 2중 for문을 한번에 탈출.
    

    # 충돌된 슬라임 or 무기 없애기
    if slime_to_remove >-1:
        del slimes[slime_to_remove]
        slime_to_remove = -1

    if weapon_to_remove > -1:
        del weapons[weapon_to_remove]
        weapon_to_remove = -1

    # 모든 슬라임을 없앤 경우 게임 종료 (성공)
    if len(slimes) == 0:
        game_result = "Mission Complete"
        running = False

    # 5. 화면에 그리기
    screen.blit(background, (0, 0))
    
    for weapon_x_pos, weapon_y_pos in weapons: # 캐릭터 위로 무기가 지나가지 않도록 하기 위해서 캐릭터 전에 무기를 그려준다.
        screen.blit(weapon, (weapon_x_pos, weapon_y_pos))

    for idx, val in enumerate(slimes):
        slime_pos_x = val["pos_x"]
        slime_pos_y = val["pos_y"]
        slime_img_idx = val["img_idx"]
        screen.blit(slime_images[slime_img_idx], (slime_pos_x, slime_pos_y))

    screen.blit(stage, (0, screen_height - stage_height))
    screen.blit(character, (character_x_pos, character_y_pos))
    
    # 경과 시간 계산
    elapsed_time = (pygame.time.get_ticks() - start_ticks) / 1000 # ms -> s
    timer = game_font.render("Time : {}".format(int(total_time - elapsed_time)), True, (255, 255, 255))
    screen.blit(timer, (10, 10))

    # 시간 초과했다면
    if total_time - elapsed_time <=0:
        game_result = "Time Over"
        running = False

    pygame.display.update() # 게임화면을 다시 그리기! (필수)

# 게임 오버 메시지
msg = game_font.render(game_result, True, (255, 255, 0)) # 노란색
msg_rect = msg.get_rect(center=(int(screen_width /2), int(screen_height / 2)))
screen.blit(msg, msg_rect)
pygame.display.update()

# 2초 정도 대기
pygame.time.delay(2000)

# pygame 종료
pygame.quit()

코드 정리

* 게임을 만들 때, 슬라임의 변수를 ball로 설정했었고, 게임을 다 만들고 난 후, slime으로 변경하였습니다.

slime으로 변경하기 전에 정리했던 내용이기 때문에 ball로 정리되어 있습니다.

 

좌표의 경우, 만들어지는 창의 맨 왼쪽 위 모서리가 (0, 0)이다.

import pygame
import os

from pygame.display import update
#######################################################################################
# 기본 초기화 (반드시 해야 하는 것들)
pygame.init()

#화면 크기 설정
screen_width = 640 # 가로 크기
screen_height = 480 #  세로 크기
screen = pygame.display.set_mode((screen_width, screen_height))
 
import os
 

Operating System의 약자로, 운영체제에 제공되는 여러 기능을 파이썬에서 수행할 수 있게 해준다.

 

from pygame.display import update
 

pygame.display 모듈에 있는 update라는 함수를 import 하겠다는 의미이다.

--> 이렇게 하는 이유는 update라는 함수가 여러 모듈에 동시 존재 가능하기 때문이다.

pygame.init()
 

pygame 라이브러리 초기화! (하지 않을 경우, 일부 기능이 정상 작동하지 않는다.)

 

screen = pygame.display.set_mode((screen_width, screen_height))
 

화면 해상도를 설정하고, 전체 화면 모드, 하드웨어 가속 사용, 더블 버퍼 모드로 초기화하는 경우에는

screen = pygame.display.set_mode((screen_width, screen_height), | FULLSCREEN | HWSURFACE | DOUBLEBUF)

 

- FULLSCREEN : 전체 화면 모드를 사용

- HWSURFACE : 하드웨어 가속 사용. 전체 화면 모드에서만 가능.

- DOUBLEBUF : 더블 버퍼 모드 사용. (*더블 버퍼 : 전자 교환기에서 통화 메모리를 2개를 만들어 써넣고 읽어내는 것을 각 통화 메모리에 따로 기억시키는 방식)

 

# 화면 타이틀 설정
pygame.display.set_caption("Kogomong Pang") # 게임 이름

# FPS
clock = pygame.time.Clock()
#######################################################################################

# 1. 사용자 게임 초기화 (배경 화면, 게임 이미지, 좌표, 속도, 폰트 등)
current_path = os.path.dirname(__file__) # 현재 파일의 위치 반환
image_path = os.path.join(current_path, "images") # images 폴더 위치 반환

# 배경 만들기
background = pygame.image.load(os.path.join(image_path, "background.png")) # os를 통해 좀 더 간결해짐.

# 스테이지 만들기
stage = pygame.image.load(os.path.join(image_path, "stage.png"))
stage_size = stage.get_rect().size
stage_height = stage_size[1] # 1이 높이고 0이 너비임. 스테이지의 높이 위에 캐릭터를 두기 위해 사용

# 캐릭터 만들기
character = pygame.image.load(os.path.join(image_path, "character.png"))
character_size = character.get_rect().size
character_width = character_size[0]
character_height = character_size[1]
character_x_pos = (screen_width / 2) - (character_width / 2)
character_y_pos = screen_height - character_height - stage_height

# 캐릭터 이동 방향
character_to_x = 0

# 캐릭터 이동 속도
character_speed = 5
 
current_path = os.path.dirname(__file__) # 현재 파일의 위치 반환
 

현재 프로그램이 있는 위치를 반환한다.

image_path = os.path.join(current_path, "images") # images 폴더 위치 반환
 

현재 파일 위치에서 images 폴더 위치를 반환!

만약 images 폴더 안의 다른 폴더가 있는데 그걸 선택하고 싶다면 "images" 뒤에, "(이름)" 을 하면 된다.

stage_size = stage.get_rect().size
 

get_rect()는 x, y 좌표 크기 정보를 가지고 있다.

stage_height = stage_size[1]

[] 안에 들어가는 숫자 중, 0은 너비를 의미하고, 1은 높이를 의미한다.

 

# 무기 만들기
weapon = pygame.image.load(os.path.join(image_path, "weapon.png"))
weapon_size = weapon.get_rect().size
weapon_width = weapon_size[0]

# 무기는 한 번에 여러 발 발사 가능
weapons = []

# 무기 이동 속도
weapon_speed = 10

# 공 만들기 (4개 크기에 대해 따로 처리)
ball_images = [
    pygame.image.load(os.path.join(image_path, "ballon1.png")),
    pygame.image.load(os.path.join(image_path, "ballon2.png")),
    pygame.image.load(os.path.join(image_path, "ballon3.png")),
    pygame.image.load(os.path.join(image_path, "ballon4.png"))]
 
# 공 크기에 따른 최초 스피드
ball_speed_y = [-18, -15, -12, -9] # index 0, 1, 2, 3에 해당하는 값

# 공들
balls = []

#최초 발생하는 큰 공 추가
balls.append({
    "pos_x" : 50, # 공의 x 좌표
    "pos_y" : 50, # 공의 y 좌표
    "img_idx" : 0, # 공의 이미지 인덱스
    "to_x" : 3, # x축 이동방향, -3 이면 왼쪽, 3이면 오른쪽
    "to_y" : -6, # y축 이동방향
    "init_spd_y" : ball_speed_y[0]}) # y 최초 속도

# 사라질 무기, 공 정보 저장 변수
weapon_to_remove = -1
ball_to_remove = -1

# Font 정의
game_font = pygame.font.Font(None, 40)
total_time = 100
start_ticks = pygame.time.get_ticks() # 시작 시간 정의
 
start_ticks = pygame.time.get_ticks() # 시작 시간 정의
 

get_ticks() : 밀리 초 단위로 시간을 얻는다.

--> pygame.init() 이 호출된 이후의 밀리 초 수를 반환한다. 파이 게임이 초기화되기 전에 항상 0이다.

# 게임 종료 메시지
# Time Over(시간 초과 실패)
# Mission Complete(성공)
# Game Over(캐릭터 공에 맞음, 실패)
game_result = "Game Over"
    
running = True 
while running :
    dt = clock.tick(30)

    # 2. 이벤트 처리 (키보드, 마우스 등)
    for event in pygame.event.get(): 
        if event.type == pygame.QUIT: 
            running = False
        
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT: # 왼쪽으로
                character_to_x -= character_speed
            elif event.key == pygame.K_RIGHT: # 오른쪽으로
                character_to_x += character_speed
            elif event.key == pygame.K_SPACE: # 무기 발사
                weapon_x_pos = character_x_pos + (character_width / 2) - (weapon_width / 2) # 캐릭터의 중간에서 발사될 수 있도록
                weapon_y_pos = character_y_pos
                weapons.append([weapon_x_pos, weapon_y_pos])

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                character_to_x = 0
 
dt = clock.tick(30)
 

이전에 불린 시점으로부터 현재 불리는 시점까지의 시간을 밀리 초로 반환해 준다.

clock.tick(30) 이라고 함으로써 최대한 30 fps 내에서만 동작이 되도록 보정해 주는 역할을 한다.

pygame.QUIT:
 

게임 종료 버튼(창 닫기 버튼) 클릭 시 발생.

if event.type == pygame.KEYDOWN:
 

키를 눌렀을 때

weapon_x_pos = character_x_pos + (character_width / 2) - (weapon_width / 2) # 캐릭터의 중간에서 발사될 수 있도록
 

캐릭터의 왼쪽 끝에서 캐릭터 너비의 절반을 더하고 무기 너비의 절반을 빼면 캐릭터의 중간에서 무기가 발사되도록 설정할 수 있다.

if event.type == pygame.KEYUP:
 

키를 떼고 있을 때

    # 3. 게임 캐릭터 위치 정의
    character_x_pos += character_to_x

    if character_x_pos < 0:
        character_x_pos = 0
    elif character_x_pos > screen_width - character_width:
        character_x_pos = screen_width - character_width

    # 무기 위치 조정
    weapons = [[w[0], w[1] - weapon_speed] for w in weapons] # 무기 위치를 위로 (뒤에서부터 해석)

    # 천장에 닿은 무기 없애기
    weapons = [[w[0], w[1]] for w in weapons if w[1] > 0]

    # 공 위치 정의
    for ball_idx, ball_val in enumerate(balls):
        ball_pos_x = ball_val["pos_x"]
        ball_pos_y = ball_val["pos_y"]
        ball_img_idx = ball_val["img_idx"]

        ball_size = ball_images[ball_img_idx].get_rect().size
        ball_width = ball_size[0]
        ball_height = ball_size[1]
 
if character_x_pos < 0:
        character_x_pos = 0
    elif character_x_pos > screen_width - character_width:
        character_x_pos = screen_width - character_width
 

캐릭터의 위치가 화면을 벗어나지 않도록 설정해 주는 것이다.

weapons = [[w[0], w[1] - weapon_speed] for w in weapons] # 무기 위치를 위로 (뒤에서부터 해석)
 

*뒤에서부터 앞으로 해석해주면 된다.*

weapons 배열에 있던 것을 w에 넣어준다.

w[0]은 무기의 너비이고, w[1]은 무기의 높이이다.

무기를 발사했을 때 무기의 높이는 점점 위로 올라가는 방향이어야 하므로 weapon_speed를 빼준 것이다.

for ball_idx, ball_val in enumerate(balls):
        ball_pos_x = ball_val["pos_x"]
        ball_pos_y = ball_val["pos_y"]
        ball_img_idx = ball_val["img_idx"]

        ball_size = ball_images[ball_img_idx].get_rect().size
        ball_width = ball_size[0]
        ball_height = ball_size[1]
 

enumerate는 "열거하다"라는 뜻을 가지고 있다.

이 함수는 순서가 있는 자료형을 입력으로 받아 인덱스 값을 포함하는 enumerate 객체를 리턴한다.

즉, ball_idx에는 balls 안에 있는 공의 개수만큼 인덱스가 0부터 차례로 새겨진다.

ball_val에는 balls 안에 있는 것들이 들어간다.

        # 가로벽에 닿았을 때 공 이동 위치 변경 (튕겨 나오는 효과)
        if ball_pos_x <=0 or ball_pos_x > screen_width - ball_width:
            ball_val["to_x"] = ball_val["to_x"] * -1

        # 세로 위치
        # 스테이지에 튕겨서 올라가는 처리
        if ball_pos_y >= screen_height - stage_height - ball_height:
            ball_val["to_y"] = ball_val["init_spd_y"]
        else : # 그 외의 모든 경우에는 속도를 증가
            ball_val["to_y"] += 0.5

        ball_val["pos_x"] += ball_val["to_x"]
        ball_val["pos_y"] += ball_val["to_y"]
 
ball_val["to_x"] = ball_val["to_x"] * -1
 

-1을 곱하는 이유는 반대 방향으로 가야하기 때문이다.

    # 4. 충돌 처리

    # 캐릭터 rect 정보 업데이트
    character_rect = character.get_rect()
    character_rect.left = character_x_pos
    character_rect.top = character_y_pos

    for ball_idx, ball_val in enumerate(balls):
        ball_pos_x = ball_val["pos_x"]
        ball_pos_y = ball_val["pos_y"]
        ball_img_idx = ball_val["img_idx"]

        # 공 rect 정보 업데이트
        ball_rect = ball_images[ball_img_idx].get_rect()
        ball_rect.left = ball_pos_x
        ball_rect.top = ball_pos_y
 
        # 공과 캐릭터 충돌 체크
        if character_rect.colliderect(ball_rect):
            running = False
            break

        # 공과 무기들 충돌 처리
        for weapon_idx, weapon_val in enumerate(weapons):
            weapon_pos_x = weapon_val[0]
            weapon_pos_y = weapon_val[1]

            # 무기 rect 정보 업데이트
            weapon_rect = weapon.get_rect()
            weapon_rect.left = weapon_pos_x
            weapon_rect.top = weapon_pos_y
 
if character_rect.colliderect(ball_rect):
 

충돌을 감지하기 위해 필요한 함수. colliderect()

            # 충돌 체크
            if weapon_rect.colliderect(ball_rect):
                weapon_to_remove = weapon_idx # 해당 무기 없애기 위한 값 설정
                ball_to_remove = ball_idx # 해당 공 없애기 위한 값 설정
                
                # 가장 작은 크기의 공이 아니라면 다음 단계의 공으로 나눠주기
                if ball_img_idx < 3:
                    # 현재 공 크기 정보를 가지고 옴
                    ball_width = ball_rect.size[0]
                    ball_height = ball_rect.size[1]

                    # 나눠진 공 정보
                    small_ball_rect = ball_images[ball_img_idx + 1].get_rect()
                    small_ball_width = small_ball_rect.size[0]
                    small_ball_height = small_ball_rect.size[1]

                    # 왼쪽으로 튕겨나가는 작은 공
                    balls.append({
                        "pos_x" : ball_pos_x + (ball_width / 2) - (small_ball_width / 2), # 공의 x 좌표
                        "pos_y" : ball_pos_y + (ball_height / 2) - (small_ball_height), # 공의 y 좌표
                        "img_idx" : ball_img_idx + 1, # 공의 이미지 인덱스
                        "to_x" : -3, # x축 이동방향, -3 이면 왼쪽, 3이면 오른쪽
                        "to_y" : -6, # y축 이동방향
                        "init_spd_y" : ball_speed_y[ball_img_idx + 1]}) # y 최초 속도

                    # 오른쪽으로 튕겨나가는 작은 공
                    balls.append({
                        "pos_x" : ball_pos_x + (ball_width / 2) - (small_ball_width / 2), # 공의 x 좌표
                        "pos_y" : ball_pos_y + (ball_height / 2) - (small_ball_height), # 공의 y 좌표
                        "img_idx" : ball_img_idx + 1, # 공의 이미지 인덱스
                        "to_x" : 3, # x축 이동방향, -3 이면 왼쪽, 3이면 오른쪽
                        "to_y" : -6, # y축 이동방향
                        "init_spd_y" : ball_speed_y[ball_img_idx + 1]}) # y 최초 속도
                break
        else: # 계속 게임을 진행 
            continue # 안쪽 for문 조건이 맞지 않으면 continue, 바깥 for 문 계속 수행
        break # 앞쪽 for문에서 break를 만나면 여기로 진입 가능. 2중 for문을 한번에 탈출.
 
    # 충돌된 공 or 무기 없애기
    if ball_to_remove >-1:
        del balls[ball_to_remove]
        ball_to_remove = -1

    if weapon_to_remove > -1:
        del weapons[weapon_to_remove]
        weapon_to_remove = -1

    # 모든 공을 없앤 경우 게임 종료 (성공)
    if len(balls) == 0:
        game_result = "Mission Complete"
        running = False
 
    # 5. 화면에 그리기
    screen.blit(background, (0, 0))
    
    for weapon_x_pos, weapon_y_pos in weapons: # 캐릭터 위로 무기가 지나가지 않도록 하기 위해서 캐릭터 전에 무기를 그려준다.
        screen.blit(weapon, (weapon_x_pos, weapon_y_pos))

    for idx, val in enumerate(balls):
        ball_pos_x = val["pos_x"]
        ball_pos_y = val["pos_y"]
        ball_img_idx = val["img_idx"]
        screen.blit(ball_images[ball_img_idx], (ball_pos_x, ball_pos_y))

    screen.blit(stage, (0, screen_height - stage_height))
    screen.blit(character, (character_x_pos, character_y_pos))
 
    # 경과 시간 계산
    elapsed_time = (pygame.time.get_ticks() - start_ticks) / 1000 # ms -> s
    timer = game_font.render("Time : {}".format(int(total_time - elapsed_time)), True, (255, 255, 255))
    screen.blit(timer, (10, 10))

    # 시간 초과했다면
    if total_time - elapsed_time <=0:
        game_result = "Time Over"
        running = False

    pygame.display.update() # 게임화면을 다시 그리기! (필수)

# 게임 오버 메시지
msg = game_font.render(game_result, True, (255, 255, 0)) # 노란색
msg_rect = msg.get_rect(center=(int(screen_width /2), int(screen_height / 2)))
screen.blit(msg, msg_rect)
pygame.display.update()

# 2초 정도 대기
pygame.time.delay(2000)

# pygame 종료
pygame.quit()
 

 

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함