create a game of tetris
- User
create a game of tetris
- Assistant
create a game of tetris
Sure! Let's create a simple Tetris game using Python and the Pygame library. This will be a fully functional game where you can move, rotate, and drop Tetris pieces to form complete rows.
Python 3.x: Make sure you have Python installed on your system. You can download it from python.org.
Pygame: Install the Pygame library using the following command:
pip install pygame
Below is the complete code for the Tetris game. Copy and paste it into a file named tetris.py.
import pygame
import random
# Initialize Pygame
pygame.init()
# Screen dimensions
s_width = 800
s_height = 700
play_width = 300 # Meaning 300 // 10 = 30 width per block
play_height = 600 # Meaning 600 // 20 = 30 height per block
block_size = 30
# Top-left coordinates of the play area
top_left_x = (s_width - play_width) // 2
top_left_y = s_height - play_height - 50
# Shapes
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 respective colors
shapes = [S, Z, I, O, J, L, T]
shape_colors = [
(0, 255, 0), # S
(255, 0, 0), # Z
(0, 255, 255), # I
(255, 255, 0), # O
(255, 165, 0), # J
(0, 0, 255), # L
(128, 0, 128) # T
]
# Shape class
class Piece(object):
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
# Create grid
def create_grid(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
# Convert shape format
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 == '0':
positions.append((shape.x + j - 2, shape.y + i - 4))
return positions
# Valid space
def valid_space(shape, grid):
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 sub in accepted_positions for pos 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 random shape
def get_shape():
global shapes, shape_colors
return Piece(5, 0, random.choice(shapes))
# Draw text in the middle
def draw_text_middle(text, size, color, surface):
font = pygame.font.SysFont('comicsans', size, bold=True)
label = font.render(text, True, color)
surface.blit(label, (top_left_x + play_width /2 - (label.get_width()/2),
top_left_y + play_height/2 - label.get_height()/2))
# Draw grid lines
def draw_grid(surface, grid):
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))
# Clear completed rows
def clear_rows(grid, locked):
inc = 0
for i in range(len(grid)-1, -1, -1):
row = grid[i]
if (0,0,0) not in row:
inc += 1
ind = i
# Add positions to remove
for j in range(len(row)):
try:
del locked[(j, i)]
except:
continue
# Shift every row above down
if inc > 0:
for key in sorted(list(locked), key=lambda x:x[1])[::-1]:
x, y = key
if y < ind:
new_key = (x, y + inc)
locked[new_key] = locked.pop(key)
# Draw next shape
def draw_next_shape(shape, surface):
font = pygame.font.SysFont('comicsans', 30)
label = font.render('Next Shape', True, (255,255,255))
sx = top_left_x + play_width + 50
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), 0)
surface.blit(label, (sx + 10, sy - 30))
# Draw window
def draw_window(surface, grid, score=0):
surface.fill((0,0,0))
# 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('Score: ' + str(score), True, (255,255,255))
sx = top_left_x + play_width + 50
sy = top_left_y + play_height /2 - 100
surface.blit(label, (sx + 20, sy + 160))
# Draw blocks
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), 0)
# Draw grid and border
draw_grid(surface, grid)
pygame.draw.rect(surface, (255, 255, 255),
(top_left_x, top_left_y, play_width, play_height), 5)
# Main game loop
def main(win):
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.27
level_time = 0
score = 0
while run:
grid = create_grid(locked_positions)
fall_time += clock.get_rawtime()
level_time += clock.get_rawtime()
clock.tick()
# Increase speed every 5 seconds
if level_time/1000 > 5:
level_time = 0
if fall_speed > 0.12:
fall_speed -= 0.005
# Piece falls
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()
# Movement keys
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
if event.key == pygame.K_RIGHT:
current_piece.x += 1
if not(valid_space(current_piece, grid)):
current_piece.x -=1
if event.key == pygame.K_DOWN:
current_piece.y +=1
if not(valid_space(current_piece, grid)):
current_piece.y -=1
if 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 grid for drawing
for i in range(len(shape_pos)):
x, y = shape_pos[i]
if y > -1:
grid[y][x] = current_piece.color
# 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
# Clear rows and update score
cleared = clear_rows(grid, locked_positions)
if cleared:
score += cleared * 10
draw_window(win, grid, score)
draw_next_shape(next_piece, win)
pygame.display.update()
# Check if game over
if check_lost(locked_positions):
draw_text_middle("YOU LOST", 80, (255, 255, 255), win)
pygame.display.update()
pygame.time.delay(1500)
run = False
# Main menu
def main_menu(win):
run = True
while run:
win.fill((0,0,0))
draw_text_middle('Press Any Key To Play', 60, (255,255,255), win)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
main(win)
pygame.quit()
win = pygame.display.set_mode((s_width, s_height))
pygame.display.set_caption('Tetris')
main_menu(win)
Save the file: Save the code in a file named tetris.py.
Run the game: Open a terminal or command prompt, navigate to the directory containing tetris.py, and run:
python tetris.py
Imports: We import pygame for rendering the game and random for random piece selection.
Global Variables:
s_width, s_height: Screen width and height.play_width, play_height: Dimensions of the Tetris play area.block_size: Size of each block in pixels.Shapes:
'0' represents a block and '.' represents empty space.Piece Class:
Game Functions:
create_grid(): Creates a grid representing the play area, including locked (placed) pieces.convert_shape_format(): Converts the shape format to grid positions for drawing and collision detection.valid_space(): Checks if moving or rotating a piece leads to a valid position.check_lost(): Determines if the new piece overlaps with existing pieces at the top of the grid, indicating a game over.get_shape(): Returns a new random piece.Drawing Functions:
draw_text_middle(): Draws text centered on the screen.draw_grid(): Draws grid lines.draw_next_shape(): Displays the next piece that will be played.draw_window(): Renders the game window, including the current score and game grid.Main Game Loop (main(win)):
Main Menu Loop (main_menu(win)):
This basic version of Tetris can be enhanced with more features:
If you have any questions or need further assistance with the code or game features, feel free to ask!
Not yet included in a published release.