Untitled
import pygame import random # Initialize Pygame pygame.init() # Constants SCREEN_WIDTH = 300 SCREEN_HEIGHT = 600 BLOCK_SIZE = 30 WHITE = (255, 255, 255) BLACK = (0, 0, 0) # Tetris shapes SHAPES = [ [[1, 1, 1, 1]], [[1, 1, 1], [1]], [[1, 1, 1], [0, 0, 1]], [[1, 1, 1], [0, 1]], [[1, 1], [1, 1]], [[0, 1, 1], [1, 1]], [[1, 1, 0], [0, 1, 1]] ] # Initialize game variables screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) clock = pygame.time.Clock() def draw_block(x, y): pygame.draw.rect(screen, WHITE, (x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE)) pygame.draw.rect(screen, BLACK, (x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 2) def draw_board(board): for y, row in enumerate(board): for x, value in enumerate(row): if value: draw_block(x, y) def generate_shape(): return random.choice(SHAPES) def can_move(board, shape, offset): for y, row in enumerate(shape): for x, value in enumerate(row): if value: if x + offset[0] < 0 or x + offset[0] >= len(board[0]) or y + offset[1] >= len(board) or board[y + offset[1]][x + offset[0]]: return False return True def merge_shape(board, shape, position): for y, row in enumerate(shape): for x, value in enumerate(row): if value: board[y + position[1]][x + position[0]] = 1 def clear_lines(board): lines_to_clear = [i for i, row in enumerate(board) if all(row)] for line in lines_to_clear: del board[line] board.insert(0, [0] * len(board[0])) def main(): # Initialize game variables board = [[0] * (SCREEN_WIDTH // BLOCK_SIZE) for _ in range(SCREEN_HEIGHT // BLOCK_SIZE)] current_shape = generate_shape() current_position = [5, 0] while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT and can_move(board, current_shape, [current_position[0] - 1, current_position[1]]): current_position[0] -= 1 elif event.key == pygame.K_RIGHT and can_move(board, current_shape, [current_position[0] + 1, current_position[1]]): current_position[0] += 1 elif event.key == pygame.K_DOWN and can_move(board, current_shape, [current_position[0], current_position[1] + 1]): current_position[1] += 1 # Move the shape down if can_move(board, current_shape, [current_position[0], current_position[1] + 1]): current_position[1] += 1 else: merge_shape(board, current_shape, current_position) clear_lines(board) current_shape = generate_shape() current_position = [5, 0] # Draw everything screen.fill(BLACK) draw_board(board) for y, row in enumerate(current_shape): for x, value in enumerate(row): if value: draw_block(x + current_position[0], y + current_position[1]) pygame.display.update() clock.tick(5) # Adjust the speed of the game if __name__ == "__main__": main()
Leave a Comment