Sure! I'll create a Python program that allows you to select a Tetris piece, and then an AI will solve and place it on a 10x20 grid. We'll use the pygame library for rendering the grid and the pieces.
First, make sure you have pygame installed. You can install it using:
pip install pygame
Now, here's the complete code:
import pygame
import sys
import random
# Initialize pygame
pygame.init()
# Grid dimensions
GRID_WIDTH = 10
GRID_HEIGHT = 20
CELL_SIZE = 30
# Screen dimensions
SCREEN_WIDTH = GRID_WIDTH * CELL_SIZE
SCREEN_HEIGHT = GRID_HEIGHT * CELL_SIZE
# Colors
BLACK = (0, 0, 0)
GRAY = (128, 128, 128)
COLORS = [
(0, 240, 240), # I
(0, 0, 240), # J
(240, 0, 0), # Z
(0, 240, 0), # S
(240, 160, 0), # L
(160, 0, 240), # T
(240, 240, 0) # O
]
# Tetris shapes
SHAPES = {
'I': [[1, 1, 1, 1]],
'J': [[1, 0, 0],
[1, 1, 1]],
'L': [[0, 0, 1],
[1, 1, 1]],
'O': [[1, 1],
[1, 1]],
'S': [[0, 1, 1],
[1, 1, 0]],
'T': [[0, 1, 0],
[1, 1, 1]],
'Z': [[1, 1, 0],
[0, 1, 1]]
}
PIECES = list(SHAPES.keys())
def create_grid(locked_positions={}):
grid = [[BLACK for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]
for i in range(GRID_HEIGHT):
for j in range(GRID_WIDTH):
if (j, i) in locked_positions:
color = locked_positions[(j, i)]
grid[i][j] = color
return grid
def draw_grid(surface, grid):
for i in range(GRID_HEIGHT):
pygame.draw.line(surface, GRAY, (0, i * CELL_SIZE), (SCREEN_WIDTH, i * CELL_SIZE))
for j in range(GRID_WIDTH):
pygame.draw.line(surface, GRAY, (j * CELL_SIZE, 0), (j * CELL_SIZE, SCREEN_HEIGHT))
def draw_window(surface, grid):
surface.fill(BLACK)
for i in range(GRID_HEIGHT):
for j in range(GRID_WIDTH):
pygame.draw.rect(surface, grid[i][j], (j * CELL_SIZE, i * CELL_SIZE, CELL_SIZE, CELL_SIZE))
draw_grid(surface, grid)
pygame.display.update()
def rotate_shape(shape):
return [ [ shape[y][x]
for y in range(len(shape)) ]
for x in range(len(shape[0]) -1, -1, -1) ]
def valid_space(shape, grid, offset):
off_x, off_y = offset
for y, row in enumerate(shape):
for x, cell in enumerate(row):
if cell:
try:
if grid[y + off_y][x + off_x] != BLACK:
return False
except IndexError:
return False
return True
def get_piece_shape(piece_letter):
return SHAPES[piece_letter]
def ai_place_piece(piece_shape, grid):
# Simple AI that tries all possible positions and rotations and selects the best one based on height
min_height = GRID_HEIGHT
best_position = (0, 0)
best_shape = piece_shape
for rotation in range(4):
temp_shape = piece_shape
for _ in range(rotation):
temp_shape = rotate_shape(temp_shape)
for x in range(GRID_WIDTH - len(temp_shape[0]) + 1):
y = 0
while y < GRID_HEIGHT - len(temp_shape):
if not valid_space(temp_shape, grid, (x, y)):
break
y += 1
y -= 1
if y < min_height:
min_height = y
best_position = (x, y)
best_shape = temp_shape
return best_position, best_shape
def lock_piece(shape, grid, position, color, locked_positions):
off_x, off_y = position
for y, row in enumerate(shape):
for x, cell in enumerate(row):
if cell:
locked_positions[(x + off_x, y + off_y)] = color
def main():
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('AI Tetris Solver')
locked_positions = {}
grid = create_grid(locked_positions)
run = True
clock = pygame.time.Clock()
while run:
grid = create_grid(locked_positions)
draw_window(screen, grid)
# Let the user select a piece
print("Select a Tetris piece:")
for idx, piece in enumerate(PIECES):
print(f"{idx + 1}: {piece}")
choice = input("Enter the number of the piece you want to place: ")
try:
choice = int(choice) - 1
if choice < 0 or choice >= len(PIECES):
raise ValueError
piece_letter = PIECES[choice]
piece_shape = get_piece_shape(piece_letter)
color = COLORS[choice]
except ValueError:
print("Invalid choice. Please try again.")
continue
# AI places the piece
position, rotated_shape = ai_place_piece(piece_shape, grid)
if not valid_space(rotated_shape, grid, position):
print("Game Over!")
run = False
continue
lock_piece(rotated_shape, grid, position, color, locked_positions)
# Clear full rows
for i in range(GRID_HEIGHT -1, -1, -1):
row = [grid[i][j] != BLACK for j in range(GRID_WIDTH)]
if all(row):
del locked_positions[(j, i) for j in range(GRID_WIDTH)]
for k in range(i, 0, -1):
for j in range(GRID_WIDTH):
if (j, k -1) in locked_positions:
locked_positions[(j, k)] = locked_positions.pop((j, k -1))
break # Remove one line per piece
draw_window(screen, grid)
pygame.time.delay(500)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
clock.tick(10)
pygame.quit()
sys.exit()
if __name__ == '__main__':
main()
Explanation:
- Grid Setup: We create a grid of size 10x20 using a 2D list. Each cell can be empty (
BLACK) or filled with a color representing a piece.
- Shapes and Pieces: Defined the standard Tetris pieces using matrices.
- Drawing Functions: Functions to draw the grid, window, and handle the rendering.
- AI Placement Function (
ai_place_piece):
- A simple AI that tries all possible positions and orientations of the selected piece.
- It selects the position that results in the lowest height (to keep the stack low).
- Main Loop:
- Asks the user to select a piece.
- The AI computes the best position and places the piece on the grid.
- Checks for filled rows and clears them.
- Updates the display.
How to Run:
-
Save the code to a file, for example, tetris_ai.py.
-
Make sure pygame is installed.
-
Run the script using:
python tetris_ai.py
-
The game window will open.
-
Follow the prompts in the console to select a piece by entering the corresponding number.
-
The AI will place the piece, and the grid will update.
-
The game continues until there's no valid space to place a piece.
Note: This is a basic implementation to demonstrate the requested functionality. The AI uses a simple heuristic and does not implement advanced Tetris AI strategies. For a more sophisticated AI, you might consider implementing algorithms like:
- Genetic algorithms
- Deep learning models
- Look-ahead searches with scoring functions considering features like holes, bumpiness, and heights
Feel free to expand upon this code to improve the AI or add more features!