인프런 커뮤니티 질문&답변

손지석님의 프로필 이미지
손지석

작성한 질문수

파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)

공 튕기기

계속 올라가요

작성

·

285

0

공이 y<0을때 아래로 떨여져야 하는데 계속 올라가요

답변 3

0

if ball_pos_y >= stage_height - stage_height - ball_height:

if ball_pos_y >= screen_height - stage_height - ball_height:

0

손지석님의 프로필 이미지
손지석
질문자

import os
import pygame
import time
###################################################################################################################
#기본 초기화 (반드시 해야 하는 것들)
pygame.init() #초기화 반드시 필요

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

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

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

#1 사용자 게임 초기화 (배경 화면,  게임 이미지, 좌표, 속도, 폰트 등)

#배경 이미지 불러오기
current_path = os.path.dirname(__file__#현재파일 위치 반환
image_path = os.path.join(current_path,"image"#image 폴더 위치 반환
background = pygame.image.load(os.path.join(image_path,"background.png"))
#스테이지 만들기
stage = pygame.image.load(os.path.join(image_path,"stage.png"))
stage_size = stage.get_rect().size
stage_height = stage_size[1#스테이지 위에 캐릭터나 공 놓기
#캐릭터
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-character_width)/2
character_y_pos = screen_height-stage_height-character_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개의 크기에 대해 따로 처리)
ball_image = [
    pygame.image.load(os.path.join(image_path,"balloon_1.png")),
    pygame.image.load(os.path.join(image_path,"balloon_2.png")),
    pygame.image.load(os.path.join(image_path,"balloon_3.png")),
    pygame.image.load(os.path.join(image_path,"balloon_4.png"))
]
#공 크기에 따른 최초 스피드
ball_speed_y=[-18,-15,-12,-9]

#공 여러개
balls = []
#최초 발생하는 큰공
balls.append({
    "pos_x" : 50,
    "pos_y" : 100,
    "img_idx" : 0,
    "to_x" : 3,
    "to_y" : -6,
    "init_spd_y" : ball_speed_y[0]
})
#이벤트 루프
runnung = True #게임이 진행중인가?

while runnung:
    dt = clock.tick(30#게임 화면의 초당 프레임 수를 설정

    #print("fps :  "+ str(clock.get_fps()))
    # 2. 이벤트 처리 (키보드, 마우스 등)
    for event in pygame.event.get(): #어떤 이벤트가 발생하였는가?
        if event.type == pygame.QUIT: #창이 닫히는 이벤트가 발생하였는가?
            runnung = 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 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_image[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 >= stage_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"]

         
    screen.blit(background,(0,0))
    for weapon_x_pos, weapon_y_pos in weapons:
        screen.blit(weapon,(int(weapon_x_pos),int(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_image[ball_img_idx],(int(ball_pos_x),int(ball_pos_y)))
    screen.blit(stage,(0,screen_height-stage_height))
    screen.blit(character,(int(character_x_pos),int(character_y_pos)))

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

#pygame 종료
pygame.quit()





0

나도코딩님의 프로필 이미지
나도코딩
지식공유자

소스코드를 첨부해주시면 도움드리겠습니다

손지석님의 프로필 이미지
손지석

작성한 질문수

질문하기