inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

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

기본기 - 텍스트 부분에서 시간이 화면에 나오지 않아요

해결된 질문

687

양유진

작성한 질문수 3

0

안녕하세요. 잘따라가고 있다 생각했는데 화면에 시간이 출력되지 않아 당황스럽네요 ㅠㅠ

10초뒤에 화면 꺼지는건 되는데 (= 시간은 가는데)

그 시간 가는게 나도코딩님처럼 게임화면에 나타나지 않네요 아래는 제 코드입니다..!

import pygame

pygame.init() # 초기화 (반드시 필요)

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

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

# FPS
clock = pygame.time.Clock()

# 배경 이미지 불러오기
background = pygame.image.load("C:/realc/PythonWorkSpace/pygame_basic/background.png")

# 캐릭터(스프라이트) 불러오기

character = pygame.image.load("C:/realc/PythonWorkSpace/pygame_basic/ch.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 # 화면 세로 크기 가장 아래에 해당하는 곳에 위치

# 이동할 좌표
to_x = 0
to_y = 0

# 이동 속도
character_speed = 1

# 적 enemy 캐릭터

enemy = pygame.image.load("C:/realc/PythonWorkSpace/pygame_basic/enemy.png")
enemy_size = enemy.get_rect().size # 이미지의 크기를 구해옴
enemy_width = enemy_size[0] # 캐릭터의 가로 크기
enemy_height = enemy_size[1] # 캐릭터의 세로 크기
enemy_x_pos = screen_width / 2 - enemy_width / 2 # 화면 가로의 절반 크기에 해당하는 곳에 위치
enemy_y_pos = screen_height / 2 - enemy_height / 2 # 화면 세로 크기 가장 아래에 해당하는 곳에 위치

# 폰트 정의
game_font = pygame.font.Font(None, 40) # 폰트 객체 생성 (폰트, 크기)

# 총 시간
total_time = 10

# 시작 시간 정보
start_ticks = pygame.time.get_ticks() # 현재 tick 을 받아옴


# 이벤트 루프
running = True # 게임이 진행중인가?
while running:
    dt = clock.tick(60) # 게임화면의 초당 프레임 수를 설정
    
    for event in pygame.event.get(): # 어떤 이벤트가 발생하였는가?
        if event.type == pygame.QUIT: # 창이 닫히는 이벤트가 발생하였는가?
            running = False # 게임이 진행중이 아님

        if event.type == pygame.KEYDOWN: # 키가 눌러졌는지 확인
            if event.key == pygame.K_LEFT:
                to_x -= character_speed
            elif event.key == pygame.K_RIGHT:
                to_x += character_speed
            elif event.key == pygame.K_UP:
                to_y -= character_speed
            elif event.key == pygame.K_DOWN:
                to_y += character_speed

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                to_x = 0
            elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                to_y = 0

    character_x_pos += to_x * dt
    character_y_pos += to_y * 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

    if character_y_pos < 0:
        character_y_pos = 0
    elif character_y_pos > screen_height - character_height :
        character_y_pos = screen_height - character_height

    # 충돌 처리를 위한 rect 정보 업데이트
    charcter_rect = character.get_rect()
    charcter_rect.left = character_x_pos
    charcter_rect.top = character_y_pos

    enemy_rect = enemy.get_rect()
    enemy_rect.left = enemy_x_pos
    enemy_rect.top = enemy_y_pos

    # 충돌 체크
    if charcter_rect.colliderect(enemy_rect):
        print("충돌했어요")
        running=False


    # 타이머 집어 넣기
    # 경과 시간 계산
    elapsed_time = (pygame.time.get_ticks() - start_ticks) / 1000 
    # 경과 시간(ms)을 1000으로 나누어서 초(s) 단위로 표시 

    timer = game_font.render(str(int(total_time - elapsed_time)), True, (255,255,255))
    # 출력할 글자, True, 글자 색상
    screen.blit(timer, (10,10))

    # 만약 시간이 0 이하이면 게임 종료
    if total_time - elapsed_time <= 0 :
        print("타임아웃")
        running = False

    screen.blit(background, (0,0)) # 배경 그리기

    screen.blit(character, (character_x_pos,character_y_pos))
    screen.blit(enemy, (enemy_x_pos,enemy_y_pos))
    
    pygame.display.update() # 게임 화면을 다시 그리기!

# 잠시 대기
pygame.time.delay(2000) # 2초 정도 대기
# pygame 종료
pygame.quit()

python GUI pygame

답변 2

1

나도코딩

screen.blit 의 순서에 따라 하단 레이어부터 하나씩 그림이 그려집니다. 그런데 timer 를 먼저 입력하고 나서 아래에서 배경, 캐릭터 등을 그리기 때문에 묻히게 되겠네요.

순서를 바꾸어서

screen.blit(timer, (10,10))

부분을 

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

바로 윗줄로 옮겨보세요

0

양유진

감사합니다 배경 다음에 그려야 하는데 그 위에 배경이 깔려 묻힌거였군요 좋은 강의 감사합니다! 

pygame 설치오류

0

123

1

pip install pygame 이 실패합니다

0

205

1

pip install pygame 이 안되요

0

887

1

(4:00) linting enabled 항목이 보이지 않습니다

0

155

1

마지막 프로젝트 그림 파일들을 올려주실 수는 없을까요?

0

202

1

import pygame에서 계속 오류가 발생해요

0

3580

2

무기 Y포지션 speed 감소

0

294

1

pygame 공부

0

504

0

마지막 부분 스프라이트가 맨 왼쪽에 위치해있습니다

0

264

1

공 쪼개기 문제

0

305

0

실행시 글자가 깨집니다.

0

309

1

키보드 이벤트 오류

0

569

1

스크린의 높이를 680으로 설정했을 때 오류?

0

294

1

pygame.time.get_ticks() 질문있습니다.

0

534

0

캐릭터의 이동

0

328

0

적(똥)과 케릭터가 충돌했을 때 게임 오버가 뜨게 만들려고..

0

298

1

시작을 하기에 앞서...

0

388

0

이미지 배경을 투명하게 하려면?

0

374

0

파이게임이 실행은 되는데....

0

227

0

실행이 안됩니다.

0

320

0

똑같이 따라 쳤는데 오류가 생겨요

0

302

0

배경색이 안 나와요

0

328

0

import pygame 실행이 안 돼요

0

2697

1

Error

0

151

0