본문 바로가기
프로그래밍/파이썬

파이썬 테트리스 코드 Python Tetris game example

by 젤리씨 2023. 1. 22.
728x90

파이썬 테트리스 코드  입니다

 

import pygame

# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

# This class represents the individual blocks that make up a tetromino
class Block(pygame.sprite.Sprite):
    def __init__(self, color, width, height):
        super().__init__()
        self.image = pygame.Surface([width, height])
        self.image.fill(color)
        self.rect = self.image.get_rect()

# This class represents the tetromino as a whole
class Tetromino(pygame.sprite.Group):
    def __init__(self, blocks):
        super().__init__()
        self.add(blocks)

# Initialize pygame
pygame.init()

# Set the width and height of the screen (width, height).
size = (700, 500)
screen = pygame.display.set_mode(size)

pygame.display.set_caption("Tetris")

# Loop until the user clicks the close button.
done = False

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

# Create a tetromino
block1 = Block(WHITE, 20, 20)
block2 = Block(WHITE, 20, 20)
block3 = Block(WHITE, 20, 20)
block4 = Block(WHITE, 20, 20)
tetromino = Tetromino([block1, block2, block3, block4])

# Position the tetromino
block1.rect.x = 20
block1.rect.y = 20
block2.rect.x = 40
block2.rect.y = 20
block3.rect.x = 60
block3.rect.y = 20
block4.rect.x = 80
block4.rect.y = 20

# -------- Main Program Loop -----------
while not done:
    # --- Main event loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    # --- Game logic should go here

    # --- Drawing code should go here

    # First, clear the screen to black. Don't put other drawing commands
    # above this, or they will be erased with this command.
    screen.fill(BLACK)

    # Draw the tetromino
    tetromino.draw(screen)

    # --- Go ahead and update the screen with what we've drawn.
    pygame.display.flip()

    # --- Limit to 60 frames per second
    clock.tick(60)

# Close the window and quit.
pygame.quit()
728x90

댓글