python으로 게임 만들기/테트리스

[테트리스] 전체적인 코드 수정 + 타이머 & 점수판

bay07 2024. 2. 25. 23:18
# 전체 스크린의 가로, 세로 설정
screen_width = 480
screen_height = 640

 

스크린을 생성하는 데 있어서, 화면 비율도 중요합니다. 일반적인 TV나 모니터의 경우에는 4:3의 비율을 갖기 때문에 여기에 맞춰서 640x480으로 비율을 재조정하였습니다. 추가로 배경화면과 블록을 그리는 코드를 while문 안에 넣었습니다. 

 

*  화면 비율 
일반적인 TV나 모니터 
4:3 = 400x300 / 640x480 / 800x600 / 1024x768 / 1152x864 / 1280x960
DVD 등

16:9 = 760x480 / 1200x900 

 

# 타이머 설정
# 총 시간
total_time = 40

# 시작시간 정보
start_ticks = pygame.time.get_ticks()

# 시간이 얼마나 지났는지 
elapsed_time = (pygame.time.get_ticks() - start_ticks)/1000

# timeout 종료조건
   if total_time - elapsed_time <= 0:
        print("Time out")
        running = False

 

타이머 설정 시, elapsed_time = (pygame.time.get_ticks() - start_ticks)/1000 에서 값을 1000으로 나눠준 이유는 ticks가 시간을 ms(밀리세컨드) 단위로 측정하기 때문입니다. 이것을 초로 바꿔주기 위해서 1000으로 나눠주었습니다. 

# 타이머 그리기
# 폰트 지정
game_font = pygame.font.Font(None, 30)

# 화면에 그리기
timer = game_font.render(" Time   "+str(int(total_time - elapsed_time)), True, (255,51,102))
screen.blit(timer, (344,40))

 

game_font.render의 경우는 결국 따라 올라가면 pygame에서 제공해주는 함수 중 하나입니다. 이 안에 인자값으로 (출력학 싶은 것, True, 색상값)을 넣어주면 우리가 원하는 대로 출력을 해줍니다. 

# 점수판 설정

# 폰트 지정
game_font = pygame.font.Font(None, 30)

# 총 점수
score_now = 0 

# 점수판 그리기 
score_temp = game_font.render("Score  "+str(int(score_now)), True, (255,51,102))
screen.blit(score_temp, (350,70))

 

▷ 시연 그림 

 

▷ 전체코드

더보기
# 테트리스 

import pygame
import random
import sys

# 초기화 & 기능 사용 시작을 알림 
pygame.init()

# 전체 스크린의 가로, 세로 설정
screen_width = 480
screen_height = 640 

# FPS
clock = pygame.time.Clock()

# 컬러셋팅
white = (255,255,255)
black = (0,0,0)
organe = (255,204,153)
green = (204,255,229)
blue = (204,229,255)
pink = (255,204,229)
purple = (204,204,255)


# 스크린 생성하기 
screen = pygame.display.set_mode((screen_width, screen_height))
screen.fill(blue)
print(screen)
background = pygame.image.load("C:/Users/Soyoung/Desktop/tetris/background1.png")
background2 = pygame.image.load("C:/Users/Soyoung/Desktop/tetris/background2.png")

def screen_set():
    # 맨 밑에 바닥깔기
    for i in range(11):
    # (100,50) 는 스크린에서의 위치
        box = pygame.Rect(60 + 25*i,570,20,20)
        pygame.draw.rect(screen,pink,box,10)
        
    # 왼쪽벽 만들어보쟈 
    for j in range(18):
    # (100,50) 는 스크린에서의 위치
        box = pygame.Rect(60,570-25*j,20,20)
        pygame.draw.rect(screen,pink,box,10)   
        
    # 오른쪽벽 만들어보쟈 
    for j in range(18):
    # (100,50) 는 스크린에서의 위치
        box = pygame.Rect(310,570-25*j,20,20)
        pygame.draw.rect(screen,pink,box,10)   

block = [
    # 0번 인덱스 ㅁ 모양
    [
        [[1,1,0,0],[1,1,0,0],[0,0,0,0],[0,0,0,0]]
    
    ],
    # 1번 인덱스 ㄴ 모양
    [
        [[0,0,0,0],[1,0,0,0],[1,1,1,0],[0,0,0,0]],
        [[1,1,0,0],[1,0,0,0],[1,0,0,0],[0,0,0,0]],
        [[1,1,1,0],[0,0,1,0],[0,0,0,0],[0,0,0,0]],
        [[0,0,1,0],[0,0,1,0],[0,1,1,0],[0,0,0,0]]
        
    ],
    # 2번 인덱스 ㄱ 모양
    [
        [[0,0,0,0],[0,0,1,0],[1,1,1,0],[0,0,0,0]],
        [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]],
        [[1,1,1,0],[1,0,0,0],[0,0,0,0],[0,0,0,0]],
        [[1,0,0,0],[1,0,0,0],[1,1,0,0],[0,0,0,0]]
        
    ],
    # 3번 인덱스 ㅓ 모양
    [
        [[0,0,0,0],[0,1,0,0],[1,1,1,0],[0,0,0,0]],
        [[1,0,0,0],[1,1,0,0],[1,0,0,0],[0,0,0,0]],
        [[1,1,1,0],[0,1,0,0],[0,0,0,0],[0,0,0,0]],
        [[0,0,1,0],[0,1,1,0],[0,0,1,0],[0,0,0,0]]
        
    ],
    # 4번 인덱스 z 모양
    [
        [[0,0,0,0],[1,1,0,0],[0,1,1,0],[0,0,0,0]],
        [[0,1,0,0],[1,1,0,0],[1,0,0,0],[0,0,0,0]]
    ],
    # 5번 인덱스 z y축 대칭 모양
    [
        [[0,0,0,0],[0,1,1,0],[1,1,0,0],[0,0,0,0]],
        [[0,1,0,0],[0,1,1,0],[0,0,1,0],[0,0,0,0]]
    ],
    # 6번 인덱스 l 모양
    [
        [[1,1,1,1],[0,0,0,0],[0,0,0,0],[0,0,0,0]],
        [[0,0,1,0],[0,0,1,0],[0,0,1,0],[0,0,1,0]]
    ]
]


# 게임창 이름 설정        
pygame.display.set_caption("Tetris game")
screen_set()

# 폰트 지정
game_font = pygame.font.Font(None, 30)

# 총 시간
total_time = 40

# 총 점수
score_now = 0 

# 블록 랜덤넘버 & 위치 초기세팅
block_random_number = 0
block_x_pos = 165
block_y_pos = 90

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

#########################################


running = True
while running:
    dt = clock.tick(30)
    
    # 이벤트 처리
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False 
            
    # 타이머 & 스코어
    elapsed_time = (pygame.time.get_ticks() - start_ticks)/1000
    timer = game_font.render(" Time   "+str(int(total_time - elapsed_time)), True, (255,51,102))
    score_temp = game_font.render("Score  "+str(int(score_now)), True, (255,51,102))
    
    # 배경화면 그리기
    screen.blit(background, (0,0))
    screen.blit(timer, (344,40))
    screen.blit(score_temp, (350,70))
    
    # 벽 그리기
    screen_set()
    
    # 블록 만들기 
    # 블록을 랜덤하게 지정하고 싶으니까 숫자 하나 가져오자
    # 블록은 7개 있음 (0번 인덱스부터 6번 인덱스까지)
    if block_y_pos  > screen_height:
        block_random_number = random.randint(0, 6)
        block_y_pos  = 60
        block_x_pos  = random.randint(120, 570)   
        
    for i in range(4):
        for j in range(4):
            block_flag = block[block_random_number][0][i][j]
            box = pygame.Rect(block_x_pos+25*i,block_y_pos+25*j, 20*block_flag, 20*block_flag) 
            pygame.draw.rect(screen,purple,box,10) 
    pygame.display.update()   
    
    if total_time - elapsed_time <= 0:
        print("Time out")
        running = False

# gama finish 화면 
screen.blit(background2, (0,0))
pygame.display.update()
end_message = game_font.render("Game Finished", True, (102,0,153))
screen.blit(end_message, (160,200))
pygame.display.update()
# 게임이 꺼지기 전에 4초정도 대기하기
pygame.time.delay(4000)

pygame.quit()

tetris_image.zip
0.00MB