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

[테트리스] visited 구현중

bay07 2024. 2. 27. 14:58
더보기
# 테트리스 

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/SSAFY/Desktop/tetris/background1.png")
background2 = pygame.image.load("C:/Users/SSAFY/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],2,2],
       # [[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,1,1]]
        # 모양 바꿀 때, 순환이 되도록 똑같은 코드 더 적어주기 
        [[1,1,0,0],[1,1,0,0],[0,0,0,0],[0,0,0,0],2,2],
        [[1,1,0,0],[1,1,0,0],[0,0,0,0],[0,0,0,0],2,2],
        [[1,1,0,0],[1,1,0,0],[0,0,0,0],[0,0,0,0],2,2],
    
    ],
    # 1번 인덱스 ㄴ 모양 , 높이, 너비
    [
        [[1,0,0,0],[1,1,1,0],[0,0,0,0],[0,0,0,0],2,3],
        [[1,1,0,0],[1,0,0,0],[1,0,0,0],[0,0,0,0],3,2],
        [[1,1,1,0],[0,0,1,0],[0,0,0,0],[0,0,0,0],2,3],
        [[0,0,1,0],[0,0,1,0],[0,1,1,0],[0,0,0,0],3,2]
        
    ],
    # 2번 인덱스 ㄱ 모양, 높이, 너비
    [
        [[0,0,1,0],[1,1,1,0],[0,0,0,0],[0,0,0,0],2,3],
        [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0],3,2],
        [[1,1,1,0],[1,0,0,0],[0,0,0,0],[0,0,0,0],2,3],
        [[1,0,0,0],[1,0,0,0],[1,1,0,0],[0,0,0,0],3,2]
        
    ],
    # 3번 인덱스 ㅓ 모양, 높이, 너비
    [
        [[0,1,0,0],[1,1,1,0],[0,0,0,0],[0,0,0,0],2,3],
        [[1,0,0,0],[1,1,0,0],[1,0,0,0],[0,0,0,0],3,2],
        [[1,1,1,0],[0,1,0,0],[0,0,0,0],[0,0,0,0],2,3],
        [[0,1,0,0],[1,1,0,0],[0,1,0,0],[0,0,0,0],3,2]
        
    ],
    # 4번 인덱스 z 모양, 높이, 너비
    [
        [[1,1,0,0],[0,1,1,0],[0,0,0,0],[0,0,0,0],2,3],
        [[0,1,0,0],[1,1,0,0],[1,0,0,0],[0,0,0,0],3,2],
        # 모양 바꿀 때, 순환이 되도록 똑같은 코드 더 적어주기 
        [[1,1,0,0],[0,1,1,0],[0,0,0,0],[0,0,0,0],2,3],
        [[0,1,0,0],[1,1,0,0],[1,0,0,0],[0,0,0,0],3,2]       
        
    ],
    # 5번 인덱스 z y축 대칭 모양, 높이, 너비
    [
        [[0,1,1,0],[1,1,0,0],[0,0,0,0],[0,0,0,0],2,3],
        [[1,0,0,0],[1,1,0,0],[0,1,0,0],[0,0,0,0],3,2],
        # 모양 바꿀 때, 순환이 되도록 똑같은 코드 더 적어주기         
        [[0,1,1,0],[1,1,0,0],[0,0,0,0],[0,0,0,0],2,3],
        [[1,0,0,0],[1,1,0,0],[0,1,0,0],[0,0,0,0],3,2]
    ],
    # 6번 인덱스 l 모양, 높이, 너비
    [
        [[1,1,1,1],[0,0,0,0],[0,0,0,0],[0,0,0,0],1,4],
        [[1,0,0,0],[1,0,0,0],[1,0,0,0],[1,0,0,0],4,1],
        # 모양 바꿀 때, 순환이 되도록 똑같은 코드 더 적어주기 
        [[1,1,1,1],[0,0,0,0],[0,0,0,0],[0,0,0,0],1,4],
        [[1,0,0,0],[1,0,0,0],[1,0,0,0],[1,0,0,0],4,1],   
    ]
]

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

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

# 총 시간
total_time = 4000000

# 총 점수
score_now = 0 


# 블록 랜덤넘버 & 위치 초기세팅
# 블록을 랜덤하게 지정하고 싶으니까 숫자 하나 가져오자
#block_random_number = random.randint(0, 6)
block_random_number = random.randint(0, 6)
block_x_pos = 4
block_y_pos = 3
block_speed = 10 
block_y_bofore_pos = 3
# 키보드 눌렀을 때, x축 방향으로 이동
to_x = 0
# 키보드 눌렀을 때, y축 방향으로 이동 
to_y = 0
# 블록모양 초기설정
change_shape = 0

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

# 전체 맵 설정
# 안쪽 사각형 
# arr = [[1]*9 for _ in range(25)]
arr = [[0]*13 for _ in range(25)]
visited = [[0]*13 for _ in range(25)]
 
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:
                # 이전블록이 있던 곳 지워주기 
                for i in range(4):
                    for j in range(4):
                        block_flag = block[block_random_number][change_shape][i][j]
                        for k in range(to_y+1):
                            arr[block_y_bofore_pos+i+k][block_x_pos+j+to_x] = 0
                # 만약 위치가 맨 아래오지 않았을 때만 모양 바꿀 수 있음 
                if block_y_pos <= 20 - block[block_random_number][change_shape][4]:
                    if block_x_pos+to_x > 0:
                        to_x -= 1
            # 오른쪽 키가 눌렸다면 
            elif event.key == pygame.K_RIGHT:
                # 만약 위치가 맨 아래오지 않았을 때만 모양 바꿀 수 있음 
                if block_y_pos <= 20 - block[block_random_number][change_shape][4]:
                    # block[block_random_number][change_shape][5]은 각각의 블록의 너비를 말함 
                    temp = 9 - block[block_random_number][change_shape][5]
                    if block_x_pos+to_x < temp:
                        # 이전블록이 있던 곳 지워주기 
                        for i in range(4):
                            for j in range(4):
                                block_flag = block[block_random_number][change_shape][i][j]
                                for k in range(to_y+1):
                                    arr[block_y_bofore_pos+i+k][block_x_pos+j+to_x] = 0
                        # X위치 업로드
                        to_x += 1 
            # 위쪽 키가 눌렸다면 
            # 키보드 ↑ 키로 모양을 바꿔주는 변수. 0 부터 3까지 숫자 가능 
            elif event.key == pygame.K_UP:
                # 만약 위치가 맨 아래오지 않았을 때만 모양 바꿀 수 있음 
                if block_y_pos <= 20 - block[block_random_number][change_shape][4]:
                    # 블록 옆에 충분한 자리가 있을 때
                        temp_change_shape = change_shape + 1
                        if temp_change_shape > 3:
                            temp_change_shape = 0 
                        temp3 = block[block_random_number][temp_change_shape][5]
                        if block_x_pos+to_x >= 0 and block_x_pos+to_x <= 9 - temp3:
                            # 이전블록이 있던 곳 지워주기 
                            for i in range(4):
                                for j in range(4):
                                    block_flag = block[block_random_number][change_shape][i][j]
                                   # if block_flag > 0:
                                    arr[block_y_bofore_pos+i+to_y][block_x_pos+j+to_x] = 0
                            change_shape += 1
                            if change_shape > 3:
                                change_shape = 0 

            # 아래쪽 키가 눌렸다면 
            elif event.key == pygame.K_DOWN:
                pass
            
        # 방향키를 떼면 멈춘다
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                pass
            elif event.key == pygame.K_DOWN:
                pass
                
            
    # 타이머 & 스코어
    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()
    
    # 이전블록이 있던 곳 지워주기 
    for i in range(4):
        for j in range(4):
            block_flag = block[block_random_number][change_shape][i][j]
           # if block_x_pos+j+to_x >= 0 and block_x_pos+j+to_x <= 13:
            arr[block_y_bofore_pos+i+to_y][block_x_pos+j+to_x] = 0

    # 새로운 블록 추가해주기 
    for i in range(4):
        for j in range(4):
            block_flag = block[block_random_number][change_shape][i][j]
            if block_x_pos+j+to_x >= - 4 and block_x_pos+j+to_x <= 13:
                arr[block_y_pos+i+to_y][block_x_pos+j+to_x] += block_flag
    
    # 블록이 바닥에 닿으면 멈추기
#   if block_y_pos >= 470:
    #    block_y_pos = 520 - block[block_random_number][0][4]*25
#       block_y_pos = 470
#       block_speed = 0
#       print(block[block_random_number][0][4])
    

    visited_x = []
    # 블록 그리기2
    for i in range(25):
        for j in range(13):
           # arr_flag = arr[i][j]
            arr_flag = arr[i][j]
           # print(f"{i} {j} {block_flag}")
           # box = pygame.Rect(80+25*i,85+25*j, 20*arr_flag, 20*arr_flag) 
            if arr_flag >= 1:
                box = pygame.Rect(85+25*j,45+25*i, 20, 20) 
                pygame.draw.rect(screen,purple,box,10) 
                visited_x.append(j)
    
    pygame.display.update()  
    pygame.time.delay(600)
    
    # 초기화
    visited_pos = 0
    
    # visited 높이 정보 업데이트
    for i in visited_x:
        for j in range(24,0,-1):
            if visited[j][i] == 1:
                visited_pos += 1
        # 밑에서부터 1을 세다가 0이 나오면 다시 그만센다 
        if visited[block_x_pos+to_x][i - 1] == 1 and visited[block_x_pos+j+to_x] == 0:
            break
    
    # 이전 블록 위치정보 저장 
    block_y_bofore_pos = block_y_pos
    # 블록이 떨어지는 속도 만큼 위치 업데이트
    temp2 = 4 - int(block[block_random_number][change_shape][4])
    if block_y_pos + to_y <= (16 + temp2) - visited_pos:
        block_y_pos += 1
    # 이제 바닥에 다 떨어져서 움직이지 않을 때 
    else:
        # visited 배열 업데이트
        for i in range(25):
            for j in range(13):
                visited[i][j] += arr[i][j]
        # 새로운 블록 만들기
        block_random_number = random.randint(0, 6)
        block_x_pos = 4
        block_y_pos = 3
        block_speed = 10 
        block_y_bofore_pos = 3
        # 키보드 눌렀을 때, x축 방향으로 이동
        to_x = 0
        # 키보드 눌렀을 때, y축 방향으로 이동 
        to_y = 0
        # 블록모양 초기설정
        change_shape = 0

    if total_time - elapsed_time <= 0:
        print("Time out")
        running = False
        

print(arr)

# 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()