import sys import pygame import random pygame.init() WIDTH, HEIGHT = 300, 600 GRID_SIZE = 30 WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) SHAPES = [ [['.....', '.....', '.....', 'OOOO.', '.....'], # O shape ['.....', '..O..', '..O..', '..O..', '..O..']], # More shapes ... ] class Tetromino: def __init__(self, x, y, shape): self.x = x self.y = y self.shape = shape self.color = random.choice([RED, (0, 255, 0), (0, 0, 255)]) # Random color self.rotation = 0 class Tetris: def __init__(self): self.grid = [[0 for _ in range(WIDTH // GRID_SIZE)] for _ in range(HEIGHT // GRID_SIZE)] self.current_piece = self.new_piece() self.game_over = False def new_piece(self): shape = random.choice(SHAPES) return Tetromino(WIDTH // GRID_SIZE // 2, 0, shape) def valid_move(self, piece, dx, dy): # Check if the piece can move to the new position for i, row in enumerate(piece.shape[piece.rotation]): for j, cell in enumerate(row): if cell == 'O': if (piece.x + j + dx < 0 or piece.x + j + dx >= len(self.grid[0]) or piece.y + i + dy >= len(self.grid) or self.grid[piece.y + i + dy][piece.x + j + dx] != 0): return False return True def main(): screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Tetris") clock = pygame.time.Clock() game = Tetris() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # Handle user input for moving/rotating pieces screen.fill(BLACK) # Draw the grid and current pieces here pygame.display.flip() clock.tick(60) if __name__ == "__main__": main()