- 19th Nov 2023
- 12:56 pm
This code sets up a basic Tetris game in Python using Pygame. Pieces fall down the screen, and you can move them left or right using the arrow keys. The game includes collision detection, row clearing, and random generation of tetrominos.
import pygame
import random
# Initialize Pygame
pygame.init()
# Constants
WIDTH, HEIGHT = 300, 600
BLOCK_SIZE = 30
ROWS, COLS = HEIGHT // BLOCK_SIZE, WIDTH // BLOCK_SIZE
FPS = 10
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
CYAN = (0, 255, 255)
YELLOW = (255, 255, 0)
MAGENTA = (255, 0, 255)
ORANGE = (255, 165, 0)
# Tetromino shapes
tetrominos = [
[[1, 1, 1, 1]], # I-shape
[[1, 1, 1], [0, 1, 0]], # T-shape
[[1, 1, 1], [1, 0, 0]], # L-shape
[[1, 1, 1], [0, 0, 1]], # J-shape
[[0, 1, 1], [1, 1, 0]], # S-shape
[[1, 1], [1, 1]], # O-shape
[[1, 1, 0], [0, 1, 1]] # Z-shape
]
# Create the game window
win = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Tetris Game")
# Game variables
board = [[0 for _ in range(COLS)] for _ in range(ROWS)]
piece = random.choice(tetrominos)
piece_x = COLS // 2 - len(piece[0]) // 2
piece_y = 0
piece_color = random.choice([RED, GREEN, BLUE, CYAN, YELLOW, MAGENTA, ORANGE])
fall_time = 0
fall_speed = 0.5
# Functions
def draw_block(x, y, color):
pygame.draw.rect(win, color, (x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE))
pygame.draw.rect(win, BLACK, (x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 2)
def draw_board():
for row in range(ROWS):
for col in range(COLS):
if board[row][col]:
draw_block(col, row, board[row][col])
def draw_piece():
for row in range(len(piece)):
for col in range(len(piece[0])):
if piece[row][col]:
draw_block(piece_x + col, piece_y + row, piece_color)
def valid_move():
for row in range(len(piece)):
for col in range(len(piece[0])):
if piece[row][col]:
new_x, new_y = piece_x + col, piece_y + row
if not(0 <= new_x < COLS) or not(0 <= new_y < ROWS) or board[new_y][new_x]:
return False
return True
def freeze_piece():
global piece_x, piece_y, piece_color, piece, fall_time
for row in range(len(piece)):
for col in range(len(piece[0])):
if piece[row][col]:
board[piece_y + row][piece_x + col] = piece_color
# Check for completed rows
for row in range(ROWS):
if all(board[row]):
for r in range(row, 1, -1):
board[r] = board[r-1][:]
board[0] = [0 for _ in range(COLS)]
piece = random.choice(tetrominos)
piece_x = COLS // 2 - len(piece[0]) // 2
piece_y = 0
piece_color = random.choice([RED, GREEN, BLUE, CYAN, YELLOW, MAGENTA, ORANGE])
fall_time = 0
def rotate_piece():
global piece
piece = [list(row[::-1]) for row in zip(*piece)]
# Game loop
clock = pygame.time.Clock()
running = True
while running:
win.fill(BLACK)
dt = clock.tick(FPS)
fall_time += dt / 1000
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and valid_move():
piece_x -= 1
elif event.key == pygame.K_RIGHT and valid_move():
piece_x += 1
elif event.key == pygame.K_DOWN:
if valid_move():
piece_y += 1
fall_time = 0
elif event.key == pygame.K_UP:
rotate_piece()
if fall_time >= fall_speed:
piece_y += 1
fall_time = 0
if not valid_move():
piece_y -= 1
freeze_piece()
draw_board()
draw_piece()
pygame.display.flip()
# Quit Pygame
pygame.quit()
About The Author - Janhavi Gupta
Seasoned programmer with 6 years of experience in designing, developing, and deploying software solutions. Strong problem-solving skills coupled with the ability to collaborate effectively in multidisciplinary teams. Continuously learning and adapting to new technologies and methodologies to drive innovation and deliver high-quality, user-centric solutions.