Create the tetris game in python
- User
Create the tetris game in python
- Assistant
Create the tetris game in python
Creating a Tetris game in Python involves using a graphics library to render the game on the screen, and managing the game logic such as piece generation, movement, rotation, line clearing, and level progression. Here is a simplified version of Tetris using the pygame library, which is commonly used for writing video games in Python.
pip install pygame
Here's a basic implementation of Tetris in Python using pygame:
import pygame
import random
# Initialize the pygame
pygame.init()
# Constants
SCREEN_WIDTH, SCREEN_HEIGHT = 300, 600
BLOCK_SIZE = 30
GRID_WIDTH, GRID_HEIGHT = SCREEN_WIDTH // BLOCK_SIZE, SCREEN_HEIGHT // BLOCK_SIZE
WHITE, BLACK, GRAY = (255, 255, 255), (0, 0, 0), (128, 128, 128)
SHAPES = [
[['.....',
'.....',
'..00.',
'.00..',
'.....'],
['.....',
'..0..',
'..00.',
'...0.',
'.....']],
[['.....',
'.....',
'.00..',
'..00.',
'.....'],
['.....',
'..0..',
'.00..',
'.0...',
'.....']],
[['.....',
'.....',
'..0..',
'..0..',
'..0..',
'..0..']],
[['.....',
'.....',
'.00..',
'.00..',
'.....']],
[['.....',
'..0..',
'.000.',
'.....',
'.....'],
['.....',
'..0..',
'..00.',
'..0..',
'.....'],
['.....',
'.....',
'.000.',
'..0..',
'.....'],
['.....',
'..0..',
'.00..',
'..0..',
'.....']],
[['.....',
'.....',
'.000.',
'...0.',
'.....'],
['.....',
'..0..',
'..0..',
'.00..',
'.....'],
['.....',
'.0...',
'.000.',
'.....',
'.....'],
['.....',
'..00.',
'..0..',
'..0..',
'.....']],
[['.....',
'.....',
'.000.',
'.0...',
'.....'],
['.....',
'.00..',
'..0..',
'..0..',
'.....'],
['.....',
'...0.',
'.000.',
'.....',
'.....'],
['.....',
'..0..',
'..0..',
'..00.',
'.....']]
]
# Colors for each piece
SHAPE_COLORS = [(0, 255, 255), (255, 165, 0), (0, 0, 255),
(255, 255, 0), (0, 255, 0), (255, 0, 0), (128, 0, 128)]
# Class to define each of the Tetris shapes
class Piece:
def __init__(self, x, y, shape):
self.x = x
self.y = y
self.shape = shape
self.color = SHAPE_COLORS[SHAPES.index(shape)]
self.rotation = 0
def create_grid(locked_positions={}):
grid = [[BLACK for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]
for y in range(GRID_HEIGHT):
for x in range(GRID_WIDTH):
if (x, y) in locked_positions:
grid[y][x] = locked_positions[(x, y)]
return grid
def convert_shape_format(piece):
positions = []
shape_format = piece.shape[piece.rotation % len(piece.shape)]
for y, line in enumerate(shape_format):
row = list(line)
for x, column in enumerate(row):
if column == '0':
positions.append((piece.x + x, piece.y + y))
for i, pos in enumerate(positions):
positions[i] = (pos[0], pos[1])
return positions
def valid_space(piece, grid):
accepted_positions = [[(x, y) for x in range(GRID_WIDTH) if grid[y][x] == BLACK] for y in range(GRID_HEIGHT)]
accepted_positions = [x for item in accepted_positions for x in item]
formatted = convert_shape_format(piece)
for pos in formatted:
if pos not in accepted_positions:
if pos[1] > -1:
return False
return True
def check_lost(positions):
for pos in positions:
x, y = pos
if y < 1:
return True
return False
def get_shape():
return Piece(5, 0, random.choice(SHAPES))
def draw_text_middle(text, size, color, surface):
pass # Simplified for brevity
def draw_grid(surface):
for y in range(GRID_HEIGHT):
pygame.draw.line(surface, GRAY, (0, y * BLOCK_SIZE), (SCREEN_WIDTH, y * BLOCK_SIZE))
for x in range(GRID_WIDTH):
pygame.draw.line(surface, GRAY, (x * BLOCK_SIZE, 0), (x * BLOCK_SIZE, SCREEN_HEIGHT))
def clear_rows(grid, locked):
# Simultaneously remove and score completed lines
increment = 0
for y in range(GRID_HEIGHT - 1, -1, -1):
row = grid[y]
if BLACK not in row:
increment += 1
ind = y
for x in range(GRID_WIDTH):
try:
del locked[(x, y)]
except:
continue
if increment > 0:
for key in sorted(list(locked), key=lambda x: x[1])[::-1]:
x, y = key
if y < ind:
new_key = (x, y + increment)
locked[new_key] = locked.pop(key)
return increment
def draw_next_shape(piece, surface):
pass # Simplified for brevity
def draw_window(surface, grid):
surface.fill(BLACK)
for y in range(GRID_HEIGHT):
for x in range(GRID_WIDTH):
pygame.draw.rect(surface, grid[y][x], (x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)
draw_grid(surface)
pygame.display.update()
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
level_time = 0
while run:
grid = create_grid(locked_positions)
fall_speed = 0.27
fall_time += clock.get_rawtime()
level_time += clock.get_rawtime()
clock.tick()
if level_time/1000 > 5:
level_time = 0
if fall_speed > 0.12:
fall_speed -= 0.005
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()
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)
for x, y in shape_pos:
if y > -1:
grid[y][x] = current_piece.color
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
cleared_rows = clear_rows(grid, locked_positions)
draw_window(win, grid)
if check_lost(locked_positions):
run = False
def main_menu():
run = True
while run:
win.fill(BLACK)
draw_text_middle('Press Any Key to Play', 50, WHITE, win)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
main()
pygame.quit()
win = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Tetris')
main_menu()
Grid and Shapes: The grid is the playfield, and the shapes are defined using a list of matrices, where each sub-list corresponds to a rotation of the shape.
Piece Movement and Rotation: Pieces can be moved left, right, and down using the keyboard. They can also be rotated.
Collision Detection: The game checks for collisions between the falling pieces and the settled pieces in the grid.
Row Clearing: Complete rows are removed from the grid, and the pieces above them are shifted down.
To run the game, ensure you have pygame installed, then execute the script. Use the arrow keys to control the falling pieces.
Not yet included in a published release.