Write code for making a Tetris game
- User
Write code for making a Tetris game
- Assistant
Write code for making a Tetris game
Certainly! Below is a simple implementation of the classic Tetris game using Python and the Pygame library. This code provides the fundamental features of Tetris, including piece movement, rotation, line clearing, scoring, and increasing difficulty over time.
pip install pygame
tetris.py)import pygame
import random
# Initialize Pygame
pygame.init()
# Global Variables
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 600
BLOCK_SIZE = 30
PLAY_WIDTH = 10 * BLOCK_SIZE # 10 blocks wide
PLAY_HEIGHT = 20 * BLOCK_SIZE # 20 blocks high
TOP_LEFT_X = (SCREEN_WIDTH - PLAY_WIDTH) // 2
TOP_LEFT_Y = SCREEN_HEIGHT - PLAY_HEIGHT - 10
# Shapes definitions
S = [['.....',
'.....',
'..00.',
'.00..',
'.....'],
['.....',
'..0..',
'..00.',
'...0.',
'.....']]
Z = [['.....',
'.....',
'.00..',
'..00.',
'.....'],
['.....',
'..0..',
'.00..',
'.0...',
'.....']]
I = [['..0..',
'..0..',
'..0..',
'..0..',
'.....'],
['.....',
'0000.',
'.....',
'.....',
'.....']]
O = [['.....',
'.....',
'.00..',
'.00..',
'.....']]
J = [['.....',
'.0...',
'.000.',
'.....',
'.....'],
['.....',
'..00.',
'..0..',
'..0..',
'.....'],
['.....',
'.....',
'.000.',
'...0.',
'.....'],
['.....',
'..0..',
'..0..',
'.00..',
'.....']]
L = [['.....',
'...0.',
'.000.',
'.....',
'.....'],
['.....',
'..0..',
'..0..',
'..00.',
'.....'],
['.....',
'.....',
'.000.',
'.0...',
'.....'],
['.....',
'.00..',
'..0..',
'..0..',
'.....']]
T = [['.....',
'..0..',
'.000.',
'.....',
'.....'],
['.....',
'..0..',
'..00.',
'..0..',
'.....'],
['.....',
'.....',
'.000.',
'..0..',
'.....'],
['.....',
'..0..',
'.00..',
'..0..',
'.....']]
# List of shapes and their corresponding colors
SHAPES = [S, Z, I, O, J, L, T]
SHAPE_COLORS = [
(48, 213, 200), # S - Turquoise
(255, 50, 19), # Z - Red
(31, 40, 250), # I - Blue
(255, 255, 0), # O - Yellow
(255, 125, 67), # J - Orange
(135, 206, 250), # L - Light Blue
(128, 0, 128) # T - Purple
]
class Piece:
def __init__(self, x, y, shape):
"""Initialize a tetris piece."""
self.x = x
self.y = y
self.shape = shape
self.color = SHAPE_COLORS[SHAPES.index(shape)]
self.rotation = 0
def create_grid(locked_positions={}):
"""Create a grid with locked positions."""
grid = [[(0, 0, 0) for _ in range(10)] for _ in range(20)]
for i in range(len(grid)):
for j in range(len(grid[i])):
if (j, i) in locked_positions:
c = locked_positions[(j, i)]
grid[i][j] = c
return grid
def convert_shape_format(shape):
"""Convert the shape format for drawing."""
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 == '0':
positions.append((shape.x + j - 2, shape.y + i - 4))
return positions
def valid_space(shape, grid):
"""Check if the current position is valid."""
accepted_positions = [[(j, i) for j in range(10) if grid[i][j] == (0, 0, 0)] for i in range(20)]
accepted_positions = [pos for sublist in accepted_positions for pos in sublist]
formatted_positions = convert_shape_format(shape)
for pos in formatted_positions:
if pos not in accepted_positions:
if pos[1] > -1:
return False
return True
def check_lost(positions):
"""Check if any position is above the screen."""
for pos in positions:
x, y = pos
if y < 1:
return True
return False
def get_shape():
"""Get a random new shape."""
return Piece(5, 0, random.choice(SHAPES))
def draw_text_middle(surface, text, size, color):
"""Draw text in the middle of the screen."""
font = pygame.font.SysFont('comicsans', size, bold=True)
label = font.render(text, True, color)
label_rect = label.get_rect(center=(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2))
surface.blit(label, label_rect)
def draw_grid(surface, grid):
"""Draw grid lines."""
sx = TOP_LEFT_X
sy = TOP_LEFT_Y
for i in range(len(grid)):
# Horizontal lines
pygame.draw.line(surface, (128, 128, 128), (sx, sy + i * BLOCK_SIZE), (sx + PLAY_WIDTH, sy + i * BLOCK_SIZE))
for j in range(len(grid[i])):
# Vertical lines
pygame.draw.line(surface, (128, 128, 128), (sx + j * BLOCK_SIZE, sy),
(sx + j * BLOCK_SIZE, sy + PLAY_HEIGHT))
def clear_rows(grid, locked):
"""Clear completed rows and shift down."""
increment = 0
for i in range(len(grid)-1, -1, -1):
row = grid[i]
if (0, 0, 0) not in row:
increment += 1
# Remove row from locked positions
for j in range(len(row)):
try:
del locked[(j, i)]
except KeyError:
continue
if increment > 0:
# Move every other row up
for key in sorted(locked.keys(), key=lambda x: x[1])[::-1]:
x, y = key
if y < i:
new_key = (x, y + increment)
locked[new_key] = locked.pop(key)
return increment
def draw_next_shape(shape, surface):
"""Draw the next shape preview."""
font = pygame.font.SysFont('comicsans', 30)
label = font.render('Next Shape', True, (255, 255, 255))
sx = TOP_LEFT_X + PLAY_WIDTH + 30
sy = TOP_LEFT_Y + PLAY_HEIGHT / 2 - 100
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 == '0':
pygame.draw.rect(surface, shape.color,
(sx + j * BLOCK_SIZE, sy + i * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE))
surface.blit(label, (sx + 10, sy - 30))
def draw_window(surface, grid, score=0):
"""Draw the main game window."""
surface.fill((0, 0, 0)) # Fill background with black
# Title
font = pygame.font.SysFont('comicsans', 60)
label = font.render('TETRIS', True, (255, 255, 255))
surface.blit(label, (TOP_LEFT_X + PLAY_WIDTH / 2 - label.get_width() / 2, 30))
# Current score
font = pygame.font.SysFont('comicsans', 30)
label = font.render(f'Score: {score}', True, (255, 255, 255))
sx = TOP_LEFT_X - 200
sy = TOP_LEFT_Y + 200
surface.blit(label, (sx + 20, sy + 160))
# Draw playing grid
for i in range(len(grid)):
for j in range(len(grid[i])):
pygame.draw.rect(surface, grid[i][j],
(TOP_LEFT_X + j * BLOCK_SIZE, TOP_LEFT_Y + i * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE))
# Draw grid and border
draw_grid(surface, grid)
pygame.draw.rect(surface, (255, 0, 0),
(TOP_LEFT_X, TOP_LEFT_Y, PLAY_WIDTH, PLAY_HEIGHT), 5)
def main():
"""Main game loop."""
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.5 # Initial fall speed
level_time = 0
score = 0
screen = 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 difficulty over time
if level_time / 1000 > 30:
level_time = 0
if fall_speed > 0.1:
fall_speed -= 0.005
# Handle falling piece
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
# Event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.display.quit()
quit()
if event.type == pygame.KEYDOWN:
# Move left
if event.key == pygame.K_LEFT:
current_piece.x -= 1
if not valid_space(current_piece, grid):
current_piece.x += 1
# Move right
elif event.key == pygame.K_RIGHT:
current_piece.x += 1
if not valid_space(current_piece, grid):
current_piece.x -= 1
# Move down
elif event.key == pygame.K_DOWN:
current_piece.y += 1
if not valid_space(current_piece, grid):
current_piece.y -= 1
# Rotate
elif event.key == pygame.K_UP:
current_piece.rotation += 1
if not valid_space(current_piece, grid):
current_piece.rotation -= 1
shape_positions = convert_shape_format(current_piece)
# Add piece to the grid
for pos in shape_positions:
x, y = pos
if y > -1:
grid[y][x] = current_piece.color
# Piece hit the ground
if change_piece:
for pos in shape_positions:
p = (pos[0], pos[1])
locked_positions[p] = current_piece.color
current_piece = next_piece
next_piece = get_shape()
change_piece = False
# Clear rows and update score
cleared_rows = clear_rows(grid, locked_positions)
if cleared_rows > 0:
score += 10 * cleared_rows
draw_window(screen, grid, score)
draw_next_shape(next_piece, screen)
pygame.display.update()
# Check for game over
if check_lost(locked_positions):
draw_text_middle(screen, "GAME OVER", 80, (255, 255, 255))
pygame.display.update()
pygame.time.delay(2000)
run = False
def main_menu():
"""Game start menu."""
run = True
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Tetris')
while run:
screen.fill((0, 0, 0))
draw_text_middle(screen, 'Press Any Key To Play', 50, (255, 255, 255))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
main() # Start the game
pygame.quit()
if __name__ == "__main__":
main_menu()
Save the Code:
tetris.py.Install Pygame:
pip install pygame to install the Pygame library if you haven't already.Run the Game:
tetris.py is saved.python tetris.py (or python3 tetris.py depending on your setup).←): Move the piece left.→): Move the piece right.↓): Move the piece down faster.↑): Rotate the piece.Feel free to enhance the game by adding features such as:
Have fun playing Tetris! This classic puzzle game is not only entertaining but also a great way to practice your programming skills by exploring and modifying the code.
Note: This implementation is designed to be educational and straightforward. While it captures the essential features of Tetris, the original game includes more sophisticated mechanics. You are encouraged to explore the code, understand how each part works, and make your own improvements or additions.
Not yet included in a published release.