write a code for the game Tetris
- User
write a code for the game Tetris
- Assistant
write a code for the game Tetris
Certainly! Creating a Tetris-like game is a great way to practice programming and understand game development concepts. Below is an example of how you can create a simple version of the game using Python and the Pygame library. This example will set up the game window, handle user input, and implement the core mechanics of falling blocks and line clearing.
Python 3.x installed on your system.
Pygame library installed. You can install it using pip:
pip install pygame
import pygame
import random
# Initialize Pygame
pygame.init()
# Screen dimensions
SCREEN_WIDTH = 300
SCREEN_HEIGHT = 600
BLOCK_SIZE = 30
# Define the shapes of the single tetrominoes
SHAPES = [
[[1, 1, 1, 1]], # I
[[1, 0, 0],
[1, 1, 1]], # J
[[0, 0, 1],
[1, 1, 1]], # L
[[1, 1],
[1, 1]], # O
[[0, 1, 1],
[1, 1, 0]], # S
[[0, 1, 0],
[1, 1, 1]], # T
[[1, 1, 0],
[0, 1, 1]] # Z
]
# Colors for the shapes
SHAPE_COLORS = [
(0, 255, 255), # I - Cyan
(0, 0, 255), # J - Blue
(255, 165, 0), # L - Orange
(255, 255, 0), # O - Yellow
(0, 255, 0), # S - Green
(128, 0, 128), # T - Purple
(255, 0, 0) # Z - Red
]
# Create the game window
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Tetris')
# Clock for controlling the frame rate
clock = pygame.time.Clock()
# Grid dimensions
GRID_WIDTH = SCREEN_WIDTH // BLOCK_SIZE
GRID_HEIGHT = SCREEN_HEIGHT // BLOCK_SIZE
# Initialize the grid
grid = [[(0, 0, 0) for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]
def create_shape():
"""Create a new random shape."""
index = random.randint(0, len(SHAPES) - 1)
shape = SHAPES[index]
color = SHAPE_COLORS[index]
return {'shape': shape, 'color': color, 'x': GRID_WIDTH // 2 - len(shape[0]) // 2, 'y': 0}
def draw_grid(surface, grid):
"""Draw the grid on the given surface."""
for y in range(len(grid)):
for x in range(len(grid[y])):
pygame.draw.rect(surface, grid[y][x],
(x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)
# Draw gridlines
for x in range(GRID_WIDTH + 1):
pygame.draw.line(surface, (128, 128, 128), (x * BLOCK_SIZE, 0), (x * BLOCK_SIZE, SCREEN_HEIGHT))
for y in range(GRID_HEIGHT + 1):
pygame.draw.line(surface, (128, 128, 128), (0, y * BLOCK_SIZE), (SCREEN_WIDTH, y * BLOCK_SIZE))
def draw_shape(surface, shape_data):
"""Draw the current shape on the given surface."""
shape = shape_data['shape']
color = shape_data['color']
x_offset = shape_data['x']
y_offset = shape_data['y']
for y, row in enumerate(shape):
for x, cell in enumerate(row):
if cell:
pygame.draw.rect(surface, color,
((x + x_offset) * BLOCK_SIZE, (y + y_offset) * BLOCK_SIZE,
BLOCK_SIZE, BLOCK_SIZE), 0)
def valid_space(shape_data, grid):
"""Check if the shape is in a valid position."""
shape = shape_data['shape']
x_offset = shape_data['x']
y_offset = shape_data['y']
for y, row in enumerate(shape):
for x, cell in enumerate(row):
if cell:
new_x = x + x_offset
new_y = y + y_offset
if new_x < 0 or new_x >= GRID_WIDTH or new_y >= GRID_HEIGHT:
return False
if new_y >= 0 and grid[new_y][new_x] != (0, 0, 0):
return False
return True
def lock_shape(shape_data, grid):
"""Lock the shape in the grid."""
shape = shape_data['shape']
color = shape_data['color']
x_offset = shape_data['x']
y_offset = shape_data['y']
for y, row in enumerate(shape):
for x, cell in enumerate(row):
if cell and y + y_offset >= 0:
grid[y + y_offset][x + x_offset] = color
def clear_lines(grid):
"""Clear completed lines from the grid."""
lines_cleared = 0
for y in range(len(grid) - 1, -1, -1):
if (0, 0, 0) not in grid[y]:
del grid[y]
grid.insert(0, [(0, 0, 0) for _ in range(GRID_WIDTH)])
lines_cleared += 1
return lines_cleared
def rotate_shape(shape_data):
"""Rotate the shape clockwise."""
shape_data['shape'] = [list(row) for row in zip(*shape_data['shape'][::-1])]
def main():
grid = [[(0, 0, 0) for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]
current_shape = create_shape()
fall_time = 0
fall_speed = 0.5
running = True
while running:
clock.tick(60)
fall_time += clock.get_rawtime() / 1000
# Handle falling of the shape
if fall_time > fall_speed:
fall_time = 0
current_shape['y'] += 1
if not valid_space(current_shape, grid):
current_shape['y'] -= 1
lock_shape(current_shape, grid)
clear_lines(grid)
current_shape = create_shape()
if not valid_space(current_shape, grid):
print("Game Over")
running = False
# Event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Key controls
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
current_shape['x'] -= 1
if not valid_space(current_shape, grid):
current_shape['x'] += 1
elif event.key == pygame.K_RIGHT:
current_shape['x'] += 1
if not valid_space(current_shape, grid):
current_shape['x'] -= 1
elif event.key == pygame.K_DOWN:
current_shape['y'] += 1
if not valid_space(current_shape, grid):
current_shape['y'] -= 1
elif event.key == pygame.K_UP:
rotate_shape(current_shape)
if not valid_space(current_shape, grid):
# Rotate back if not valid
for _ in range(3):
rotate_shape(current_shape)
# Drawing
screen.fill((0, 0, 0))
draw_grid(screen, grid)
draw_shape(screen, current_shape)
pygame.display.flip()
pygame.quit()
if __name__ == '__main__':
main()
Shape Representation:
SHAPES), where 1 represents a filled block and 0 represents empty space.SHAPE_COLORS.Game Grid:
(0, 0, 0) representing black (empty).Main Functions:
create_shape(): Creates and returns a new random shape.draw_grid(): Draws the game grid and the locked blocks.draw_shape(): Draws the current moving shape.valid_space(): Checks if the current position of the shape is valid (within bounds and not colliding).lock_shape(): Locks the shape into the grid when it can't move down anymore.clear_lines(): Removes completed lines from the grid.Event Handling:
Game Loop:
fall_time and fall_speed).Scoring System:
Levels and Speed Increase:
fall_speed as the player clears more lines to raise the game's difficulty.Next Shape Preview:
Hold Functionality:
Sound Effects and Music:
Improved Graphics:
By building this game, you will:
Feel free to ask if you have any questions or need further assistance with customizing the game!
Not yet included in a published release.