[weapon_game.py]
from math import gamma
from multiprocessing import current_process
from selectors import EVENT_WRITE
from signal import pthread_sigmask
from tracemalloc import start
from unittest import runner
import pygame
#################################################################################################################################
# 0.기본 화면 초기화 부분
pygame.init() #초기화
#화면 크기 조정하기
screen_width = 640
screen_height = 480
screen = pygame.display.set_mode((screen_width,screen_height))
#화면 타이틀 설정
pygame.display.set_caption("Weapon Game")
#FPS
clock = pygame.time.Clock()
#################################################################################################################################
# 1.사용자화 게임 초기화 (배경이미지, 게임캐릭터 불러오기, 좌표이동, 폰트, )
#배경이미지 파일경로 설정
# current_path = os.path.dirname(__file__)
# image_path = os.path.join(current_path, "images")
# background = pygame.image.load(os.path.join(image_path, "background.PNG"))
background = pygame.image.load("/Users/dlgpdnjs_99/Desktop/VSCode/pygame/pygame_project/images/background_w.PNG")
stage = pygame.image.load("/Users/dlgpdnjs_99/Desktop/VSCode/pygame/pygame_project/images/stage.png")
stage_size = stage.get_rect().size
stage_height = stage_size[1]
# 게임 캐릭터 불러오기
character = pygame.image.load("/Users/dlgpdnjs_99/Desktop/VSCode/pygame/pygame_project/images/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 = 8
weapon = pygame.image.load("/Users/dlgpdnjs_99/Desktop/VSCode/pygame/pygame_project/images/weapon.png")
weapon_size = weapon.get_rect().size #이미지의 크기를 가져와
weapon_width = weapon_size[0] #가로
weapons = []
weapon_speed = 10
ball_images = [
pygame.image.load("/Users/dlgpdnjs_99/Desktop/VSCode/pygame/pygame_project/images/ballon1.png"),
pygame.image.load("/Users/dlgpdnjs_99/Desktop/VSCode/pygame/pygame_project/images/ballon2.png"),
pygame.image.load("/Users/dlgpdnjs_99/Desktop/VSCode/pygame/pygame_project/images/ballon3.png"),
pygame.image.load("/Users/dlgpdnjs_99/Desktop/VSCode/pygame/pygame_project/images/ballon4.png")
]
ball_speed_y = [-18, -15, -12, -9]
balls = []
balls.append({
"pos_x" : 50,
"pos_y" : 50,
"img_index" : 0,
"to_x" : 3,
"to_y" : -6,
"init_spd_y" : ball_speed_y[0]
})
weapon_to_remove = -1
ball_to_remove = -1
game_font = pygame.font.Font(None, 40)
total_time = 100
start_ticks = pygame.time.get_ticks()
game_result = "Game Over"
#################################################################################################################################
# 2.이벤트 처리 (키보드, 마우스 등)
running = True # 게임이 실행 중이라면 이후 모든 이벤트를 실행
while running : # 게임이 실행중인동안 이벤트 실행
dt = clock.tick(60) # 게임화면의 초당 프레임 설정
# print("FPS : " + str(clock.get_fps()))
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.게임 캐릭터 위치 정의 (while 문 안에서)
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] # x값은 그대로 , y 값은 점점 줄어들다가 사라져야 하므로 스피드만큼 빠짐
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_index"]
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 :
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"]
# # 4.적과 캐릭터의 충돌 처리를 위한 rect 정보 업데이트 (while 문 안에서)
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_index"]
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) : # 충돌시
print('충돌!충돌!')
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) :
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),
"pos_y" : ball_pos_y + (ball_height / 2) - (small_ball_height/2),
"img_index" : ball_img_idx + 1,
"to_x" : -3,
"to_y" : -6,
"init_spd_y" : ball_speed_y[ball_img_idx + 1]
})
balls.append({
"pos_x" : ball_pos_x + (ball_width / 2) - (small_ball_width/2),
"pos_y" : ball_pos_y + (ball_height / 2) - (small_ball_height/2),
"img_index" : ball_img_idx + 1,
"to_x" : 3,
"to_y" : -6,
"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 = "Mission Success!"
running = False
# 5.화면 그리기 (while 문 안에서)
screen.blit(background, (0,0)) # 변수,(위치)
for weapon_x_pos, weapon_y_pos in weapons :
screen.blit(weapon, (weapon_x_pos, weapon_y_pos))
for index, val in enumerate(balls) :
ball_pos_x = val["pos_x"]
ball_pos_y = val["pos_y"]
ball_img_idx = val["img_index"]
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 Out!"
running = False
# 6.화면 업데이트 : 무조건 실행 (while 문 안에서)
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()
#################################################################################################################################
pygame.time.delay(1000)
# 7.종료
pygame.quit()
'source Code > Python' 카테고리의 다른 글
| Python | py_basic_week1 (0) | 2022.09.02 |
|---|---|
| Python | py_basic_week1 (0) | 2022.09.01 |
| Python | poo_game.py (0) | 2022.09.01 |
| Python | memory_game.py (0) | 2022.08.26 |
| Python | calculator.py (0) | 2022.08.18 |