Python_10. pygame_2
- 본 게시글은 인프런의 파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 수강 후 작성하였습니다.
# 프레임
# setting => linting => False
import pygame
import os
#################################################################################
# 0. 필수 선행(기본 초기화)
# 초기화
pygame.mixer.pre_init(44100, -16, 2, 512)
pygame.mixer.init()
pygame.init()
# 화면 크기 설정 480*640
screen_width = 640
screen_height = 480
screen = pygame.display.set_mode((screen_width, screen_height))
# 화면 타이틀 설정
pygame.display.set_caption("ball destroy")
# FPS
clock = pygame.time.Clock()
#################################################################################
# 1. 사용자 게임 초기화 (배경 화면, 게임 이미지, 좌표, 속도, 폰트 등)
current_path = os.path.dirname(__file__)
image_path = os.path.join(current_path, "images")
bounce = pygame.mixer.Sound(os.path.join(image_path, "bounce.wav"))
split = pygame.mixer.Sound(os.path.join(image_path, "split.wav"))
attack = pygame.mixer.Sound(os.path.join(image_path, "attack.wav"))
# 배경 만들기
background = pygame.image.load(os.path.join(image_path, "background.jpg"))
# 스테이지 만들기
stage = pygame.image.load(os.path.join(image_path, "stage.jpg"))
stage_size = stage.get_rect().size
stage_height = stage_size[1]
# 캐릭터 만들기
character = pygame.image.load(os.path.join(image_path, "character2.png"))
character_size = character.get_rect().size
character_width = character_size[0]
character_height = character_size[1]
character_rect = character.get_rect()
character_x_pos = screen_width / 2 - character_width / 2
character_y_pos = screen_height - stage_height - character_height + 5
# 캐릭터 이동 방향
character_to_x = 0
# 캐릭터 이동 속도
character_speed = 0.8
# 무기 만들기
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 = 1
# 공 만들기
ball_images = [pygame.image.load(os.path.join(image_path, "ball1.png")),
pygame.image.load(os.path.join(image_path, "ball2.png")),
pygame.image.load(os.path.join(image_path, "ball3.png")),
pygame.image.load(os.path.join(image_path, "ball4.png"))]
# 공 크기에 따른 초기 속도
ball_speed_y = [-0.5, -0.4, -0.35, -0.3] # index 0, 1, 2, 3 에 해당
# 공들
balls = []
# 최초 발생하는 큰 공
balls.append({
"pos_x":200, # 공의 x좌표
"pos_y":0, # 공의 y좌표
"img_idx":0, # 공의 이미지 인덱스
"to_x":0.2, # 공의 이동 방향, -3은 왼쪽, 3은 오른쪽
"to_y":-0.05, # y축 이동 방향
"init_spd_y":ball_speed_y[0]}) # y 최초 속도
# 사라질 무기 & 공 변수
weapon_to_remove = -1
ball_to_remove = -1
game_font = pygame.font.Font(None, 40)
total_time = 60
start_ticks = pygame.time.get_ticks()
game_result = "Game Over!"
running = True
while running:
dt = clock.tick(61)
# 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:
if len(weapons) <= 0:
pygame.mixer.Sound.play(attack)
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:
character_to_x += character_speed
elif event.key ==pygame.K_RIGHT:
character_to_x -= character_speed
elif event.key == pygame.K_SPACE:
pass
# 3. 게임 캐릭터 위치 정의
character_x_pos += character_to_x * dt
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 * dt] 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 ball_pos_x <= 0 or ball_pos_x >= screen_width - ball_width:
pygame.mixer.Sound.play(bounce)
ball_val["to_x"] *= -1
# 공 바닥 튕기기
if ball_pos_y >= screen_height - stage_height - ball_height:
pygame.mixer.Sound.play(bounce)
ball_val["to_y"] = ball_val["init_spd_y"]
else:
ball_val["to_y"] += 0.005
ball_val["pos_x"] += ball_val["to_x"] * dt
ball_val["pos_y"] += ball_val["to_y"] * dt
# 4. 충돌 처리
# 캐릭터 rect wjdqh
character_rect = character.get_rect()
character_rect.left = character_x_pos
character_rect.top = character_y_pos
# 공 rect 정보
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_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):
game_result = "Game Over!"
running = False
break
# 공과 무기들 충돌
for weapon_idx, weapon_val in enumerate(weapons):
weapon_x_pos = weapon_val[0]
weapon_y_pos = weapon_val[1]
weapon_rect = weapon.get_rect()
weapon_rect.left = weapon_x_pos
weapon_rect.top = weapon_y_pos
if weapon_rect.colliderect(ball_rect):
pygame.mixer.Sound.play(split)
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 / 2, # 공의 y좌표
"img_idx":ball_img_idx + 1, # 공의 이미지 인덱스
"to_x":-0.2, # 공의 이동 방향, -3은 왼쪽, 3은 오른쪽
"to_y":-0.05, # y축 이동 방향
"init_spd_y":ball_speed_y[ball_img_idx + 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 / 2, # 공의 y좌표
"img_idx":ball_img_idx + 1, # 공의 이미지 인덱스
"to_x":0.2, # 공의 이동 방향, -3은 왼쪽, 3은 오른쪽
"to_y":-0.05, # y축 이동 방향
"init_spd_y":ball_speed_y[ball_img_idx + 1]})
break
else:
continue
break
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 = "Clear!"
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
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, 255))
msg_rect = msg.get_rect(center=(int(screen_width / 2), int(screen_height / 2)))
screen.blit(msg, msg_rect)
pygame.display.update()
pygame.time.delay(2000)
pygame.quit()
Author And Source
이 문제에 관하여(Python_10. pygame_2), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@drrobot409/Python10.-pygame2저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)