TETRIS.PY
0.00MB

 

      import pygame
import random

# Define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (128, 128, 128)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
CYAN = (0, 255, 255)
MAGENTA = (255, 0, 255)
ORANGE = (255, 165, 0)

# Define shapes
SHAPES = [
    [[1, 1, 1, 1]],  # I
    [[1, 1], [1, 1]],  # O
    [[0, 1, 1], [1, 1, 0]],  # S
    [[1, 1, 0], [0, 1, 1]],  # Z
    [[1, 0, 0], [1, 1, 1]],  # J
    [[0, 0, 1], [1, 1, 1]],  # L
    [[0, 1, 0], [1, 1, 1]]   # T
]

COLORS = [CYAN, YELLOW, GREEN, RED, BLUE, ORANGE, MAGENTA]


class Tetris:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.grid = [[0 for _ in range(width)] for _ in range(height)]
        self.current_piece = None
        self.current_x = 0
        self.current_y = 0
        self.game_over = False
        self.score = 0
        self.speed = 1  # Adjust for game speed
        self.current_color_index = 0

    def new_piece(self):
        self.current_piece = random.choice(SHAPES)
        self.current_x = self.width // 2 - len(self.current_piece[0]) // 2
        self.current_y = 0
        self.current_color_index = SHAPES.index(self.current_piece)

        if self.is_collision(self.current_piece, self.current_x, self.current_y):
            self.game_over = True

    def rotate_piece(self):
        rotated_piece = list(zip(*self.current_piece[::-1]))
        if not self.is_collision(rotated_piece, self.current_x, self.current_y):
            self.current_piece = rotated_piece
            try:
                self.current_color_index = SHAPES.index(self.current_piece)
            except ValueError:
                self.current_color_index = 0

    def move(self, dx):
        if self.is_collision(self.current_piece, self.current_x + dx, self.current_y):
            return
        self.current_x += dx

    def drop(self):
        if self.is_collision(self.current_piece, self.current_x, self.current_y + 1):
            self.lock_piece()
            return True
        self.current_y += 1
        return False

    def lock_piece(self):
        for y in range(len(self.current_piece)):
            for x in range(len(self.current_piece[0])):
                if self.current_piece[y][x]:
                    self.grid[self.current_y + y][self.current_x + x] = 1
        self.clear_lines()
        self.new_piece()

    def is_collision(self, piece, x, y):
        for py in range(len(piece)):
            for px in range(len(piece[0])):
                if piece[py][px]:
                    grid_x = x + px
                    grid_y = y + py
                    if grid_x < 0 or grid_x >= self.width or grid_y >= self.height:
                        return True
                    if self.grid[grid_y][grid_x]:
                        return True
        return False

    def clear_lines(self):
        lines_cleared = 0
        for y in range(self.height):
            if all(self.grid[y]):
                del self.grid[y]
                self.grid.insert(0, [0 for _ in range(self.width)])
                lines_cleared += 1

        if lines_cleared > 0:
            self.score += lines_cleared ** 2 * 100

    def draw(self, screen):
        for y in range(self.height):
            for x in range(self.width):
                if self.grid[y][x]:
                    pygame.draw.rect(screen, GRAY, (x * 30, y * 30, 30, 30), 0)

        if self.current_piece:
            for y in range(len(self.current_piece)):
                for x in range(len(self.current_piece[0])):
                    if self.current_piece[y][x]:
                        pygame.draw.rect(screen, COLORS[self.current_color_index],
                                         ((self.current_x + x) * 30, (self.current_y + y) * 30, 30, 30), 0)

        font = pygame.font.Font(None, 36)
        score_text = font.render(f"Score: {self.score}", True, WHITE)
        screen.blit(score_text, (10, 10))

        if self.game_over:
            game_over_text = font.render("Game Over!", True, RED)
            text_rect = game_over_text.get_rect(center=(self.width * 30 // 2, self.height * 30 // 2))
            screen.blit(game_over_text, text_rect)


def main():
    pygame.init()
    width = 10
    height = 20
    screen_width = width * 30
    screen_height = height * 30
    screen = pygame.display.set_mode((screen_width, screen_height))
    pygame.display.set_caption("Tetris")

    game = Tetris(width, height)
    game.new_piece()

    clock = pygame.time.Clock()
    fall_time = 0
    fall_speed = 500

    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    game.move(-1)
                if event.key == pygame.K_RIGHT:
                    game.move(1)
                if event.key == pygame.K_DOWN:
                    game.drop()
                if event.key == pygame.K_UP:
                    game.rotate_piece()

        fall_time += clock.get_rawtime()
        if fall_time > fall_speed:
            fall_time = 0
            game.drop()

        if game.game_over:
            running = False

        screen.fill(BLACK)
        game.draw(screen)
        pygame.display.flip()

        clock.tick(60)

    pygame.quit()


if __name__ == "__main__":
    main()
    

 

콘트롤 : 방향 키 , 왼쪽, 오른쪽, 아래

블록 변환 : 방향 키 위

 

2025.03.14 - [파이썬 프로그래밍] - 3.파이썬 프로그래밍 Copilot 연동 가능한 비주얼 스튜디오 코드 다운로드해서 설치하기

 

3.파이썬 프로그래밍 Copilot 연동 가능한 비주얼 스튜디오 코드 다운로드해서 설치하기

텍스트 에디터 : 비주얼 스튜디오 코드 현업에서 많이 사용하는 여러 텍스트 에디터 중에서 일반적으로 많이 사용하는 텍스트 에디터 중에 비주얼 스튜디오 코드 라는 프로그램을 설치해 보

suncommq.tistory.com

 

반응형
LIST

+ Recent posts