write tetris in python
- User
write tetris in python
- Assistant
write tetris in python
Certainly! Let's create a simple Tetris game using Python and the pygame library. Tetris is a classic puzzle game where players rotate and position falling blocks called tetrominoes to create complete horizontal lines, which then disappear, granting points.
Below is a step-by-step guide along with the complete code. Make sure you have pygame installed:
pip install pygame
Now, let's dive into the code.
import pygame
import random
# Initialize Pygame
pygame.init()
# Screen dimensions
SCREEN_WIDTH = 300
SCREEN_HEIGHT = 600
BLOCK_SIZE = 30
# Grid dimensions
COLS = SCREEN_WIDTH // BLOCK_SIZE
ROWS = SCREEN_HEIGHT // BLOCK_SIZE
# Colors (R, G, B)
BLACK = (0, 0, 0)
GRAY = (128, 128, 128)
# Tetromino shapes
SHAPES = [
[[1, 1, 1, 1]], # I shape
[[2, 0, 0],
[2, 2, 2]], # J shape
[[0, 0, 3],
[3, 3, 3]], # L shape
[[4, 4],
[4, 4]], # O shape
[[0, 5, 5],
[5, 5, 0]], # S shape
[[0, 6, 0],
[6, 6, 6]], # T shape
[[7, 7, 0],
[0, 7, 7]] # Z shape
]
# Colors for tetrominoes
SHAPES_COLORS = [
(0, 255, 255), # Cyan
(0, 0, 255), # Blue
(255, 165, 0), # Orange
(255, 255, 0), # Yellow
(0, 255, 0), # Green
(128, 0, 128), # Purple
(255, 0, 0) # Red
]
# Create the grid
def create_grid(locked_positions={}):
grid = [[(0, BLACK) for _ in range(COLS)] for _ in range(ROWS)]
for i in range(ROWS):
for j in range(COLS):
if (j, i) in locked_positions:
color = locked_positions[(j, i)]
grid[i][j] = (0, color)
return grid
# Convert shape formats
def convert_shape_format(shape):
positions = []
format = shape.shape[shape.rotation % len(shape.shape)]
for i, line in enumerate(format):
row = list(line)
for j, column in enumerate(row):
if column:
positions.append((shape.x + j, shape.y + i))
return positions
# Check for valid space
def valid_space(shape, grid):
accepted_positions = [[(j, i) for j in range(COLS) if grid[i][j][0] == 0] for i in range(ROWS)]
accepted_positions = [j for sub in accepted_positions for j in sub]
formatted = convert_shape_format(shape)
for pos in formatted:
if pos not in accepted_positions:
if pos[1] > -1:
return False
return True
# Check if user lost
def check_lost(positions):
for pos in positions:
x, y = pos
if y < 1:
return True
return False
# Get a random shape
def get_shape():
return Piece(5, 0, random.randint(0, len(SHAPES) - 1))
# Draw text in the middle of the screen
def draw_text_middle(surface, text, size, color):
font = pygame.font.SysFont('Verdana', size, bold=True)
label = font.render(text, True, color)
surface.blit(label, (SCREEN_WIDTH / 2 - label.get_width() / 2, SCREEN_HEIGHT / 2 - label.get_height() / 2))
# Draw the grid lines
def draw_grid(surface, grid):
for i in range(ROWS):
pygame.draw.line(surface, GRAY, (0, i * BLOCK_SIZE), (SCREEN_WIDTH, i * BLOCK_SIZE))
for j in range(COLS):
pygame.draw.line(surface, GRAY, (j * BLOCK_SIZE, 0), (j * BLOCK_SIZE, SCREEN_HEIGHT))
# Clear completed rows
def clear_rows(grid, locked):
inc = 0
for i in range(ROWS - 1, -1, -1):
row = grid[i]
if all([cell[0] != 0 for cell in row]):
inc += 1
ind = i
for j in range(COLS):
try:
del locked[(j, i)]
except:
continue
if inc > 0:
for key in sorted(list(locked), key=lambda x: x[1])[::-1]:
x, y = key
if y < ind:
newKey = (x, y + inc)
locked[newKey] = locked.pop(key)
return inc
# Draw window
def draw_window(surface, grid, score=0):
surface.fill(BLACK)
# Draw title
font = pygame.font.SysFont('Verdana', 40)
label = font.render('Tetris', True, (255, 255, 255))
surface.blit(label, (SCREEN_WIDTH / 2 - label.get_width() / 2, 30))
# Draw score
font = pygame.font.SysFont('Verdana', 20)
label = font.render('Score: ' + str(score), True, (255, 255, 255))
surface.blit(label, (10, 10))
for i in range(ROWS):
for j in range(COLS):
pygame.draw.rect(surface, grid[i][j][1], (j * BLOCK_SIZE, i * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)
draw_grid(surface, grid)
pygame.display.update()
# Piece class
class Piece(object):
def __init__(self, x, y, shape_index):
self.x = x
self.y = y
self.shape = SHAPES[shape_index]
self.color = SHAPES_COLORS[shape_index]
self.rotation = 0
# Main function
def main():
locked_positions = {}
grid = create_grid(locked_positions)
change_piece = False
run = True
current_piece = get_shape()
next_piece = get_shape()
clock = pygame.time.Clock()
fall_time = 0
fall_speed = 0.3
level_time = 0
score = 0
win = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Tetris')
while run:
grid = create_grid(locked_positions)
fall_time += clock.get_rawtime()
level_time += clock.get_rawtime()
clock.tick()
# Increase speed over time
if level_time / 1000 > 5:
level_time = 0
if fall_speed > 0.1:
fall_speed -= 0.005
# Piece falling logic
if fall_time / 1000 >= fall_speed:
fall_time = 0
current_piece.y += 1
if not valid_space(current_piece, grid) and current_piece.y > 0:
current_piece.y -= 1
change_piece = True
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.display.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
current_piece.x -= 1
if not valid_space(current_piece, grid):
current_piece.x += 1
elif event.key == pygame.K_RIGHT:
current_piece.x += 1
if not valid_space(current_piece, grid):
current_piece.x -= 1
elif event.key == pygame.K_DOWN:
current_piece.y += 1
if not valid_space(current_piece, grid):
current_piece.y -= 1
elif event.key == pygame.K_UP:
current_piece.rotation += 1
if not valid_space(current_piece, grid):
current_piece.rotation -= 1
shape_pos = convert_shape_format(current_piece)
# Add piece to the grid for drawing
for i in range(len(shape_pos)):
x, y = shape_pos[i]
if y > -1:
grid[y][x] = (0, current_piece.color)
# If piece hit the ground
if change_piece:
for pos in shape_pos:
p = (pos[0], pos[1])
locked_positions[p] = current_piece.color
current_piece = next_piece
next_piece = get_shape()
change_piece = False
score += clear_rows(grid, locked_positions) * 10
draw_window(win, grid, score)
# Check if user lost
if check_lost(locked_positions):
draw_text_middle(win, "GAME OVER", 40, (255, 255, 255))
pygame.display.update()
pygame.time.delay(2000)
run = False
pygame.display.quit()
if __name__ == '__main__':
main()
Imports and Initialization:
pygame for graphics and random for randomizing tetrominoes.Tetromino Shapes and Colors:
SHAPES.SHAPES_COLORS.Grid Creation:
create_grid function generates a 2D list representing the game grid.Shape Management:
convert_shape_format converts the shape's rotation and position into grid coordinates.valid_space checks if a new position for a tetromino is valid (i.e., within bounds and not colliding).check_lost determines if any locked positions have reached the top of the grid, indicating game over.get_shape randomly selects a new tetromino.Drawing Functions:
draw_text_middle displays text centered on the screen.draw_grid draws the lines of the grid.draw_window handles all the drawing on the main game window, including the current score and grid.Game Mechanics:
clear_rows checks for and removes completed rows, updating the score.Piece class represents a tetromino with its position, shape, color, and rotation.Main Game Loop (main function):
Save the code above in a file named tetris.py.
Ensure you have pygame installed:
pip install pygame
Run the game:
python tetris.py
This implementation is a basic version of Tetris to illustrate the core concepts. There are many ways to enhance it, such as adding a hold piece function, implementing soft and hard drops, adding sound effects, and improving the graphics and user interface.
Feel free to experiment with the code and add new features!