o1-preview-2024-09-12· OpenAI
WildChat-4.8M (AI2)
Write tetris in Python using Pygame
- User
Write tetris in Python using Pygame
- Assistant
Write tetris in Python using Pygame
Sure! Below is a basic implementation of Tetris in Python using Pygame. This version includes the core functionalities:
Note: To run this code, you need to have Pygame installed. You can install it using pip install pygame.
import pygame
import random
# Initialize Pygame
pygame.init()
# Screen dimensions
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 500
GRID_SIZE = 20
GRID_WIDTH = SCREEN_WIDTH // GRID_SIZE
GRID_HEIGHT = SCREEN_HEIGHT // GRID_SIZE
# Colors (R, G, B)
BLACK = (0, 0, 0)
GRAY = (128, 128, 128)
WHITE = (255, 255, 255)
# Tetromino shapes
SHAPES = [
# S Shape
[
['.....',
'.....',
'..XX.',
'.XX..',
'.....'],
['.....',
'..X..',
'..XX.',
'...X.',
'.....']
],
# Z Shape
[
['.....',
'.....',
'.XX..',
'..XX.',
'.....'],
['.....',
'..X..',
'.XX..',
'.X...',
'.....']
],
# I Shape
[
['..X..',
'..X..',
'..X..',
'..X..',
'.....'],
['.....',
'XXXXX',
'.....',
'.....',
'.....']
],
# O Shape
[
['.....',
'.....',
'.XX..',
'.XX..',
'.....']
],
# J Shape
[
['.....',
'.X...',
'.XXX.',
'.....',
'.....'],
['.....',
'..XX.',
'..X..',
'..X..',
'.....'],
['.....',
'.....',
'.XXX.',
'...X.',
'.....'],
['.....',
'..X..',
'..X..',
'.XX..',
'.....']
],
# L Shape
[
['.....',
'...X.',
'.XXX.',
'.....',
'.....'],
['.....',
'..X..',
'..X..',
'..XX.',
'.....'],
['.....',
'.....',
'.XXX.',
'.X...',
'.....'],
['.....',
'.XX..',
'..X..',
'..X..',
'.....']
],
# T Shape
[
['.....',
'..X..',
'.XXX.',
'.....',
'.....'],
['.....',
'..X..',
'..XX.',
'..X..',
'.....'],
['.....',
'.....',
'.XXX.',
'..X..',
'.....'],
['.....',
'..X..',
'.XX..',
'..X..',
'.....']
]
]
# Corresponding colors for the shapes
SHAPE_COLORS = [
(0, 255, 0), # S Shape
(255, 0, 0), # Z Shape
(0, 255, 255), # I Shape
(255, 255, 0), # O Shape
(0, 0, 255), # J Shape
(255, 127, 0), # L Shape
(128, 0, 128) # T Shape
]
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 i in range(GRID_HEIGHT):
for j in range(GRID_WIDTH):
if (j, i) in locked_positions:
grid[i][j] = locked_positions[(j, i)]
return grid
def convert_shape_format(piece):
positions = []
format = piece.shape[piece.rotation % len(piece.shape)]
for i, line in enumerate(format):
row = list(line)
for j, column in enumerate(row):
if column == 'X':
positions.append((piece.x + j - 2, piece.y + i - 4))
return positions
def valid_space(piece, grid):
accepted_positions = [[(j, i) for j in range(GRID_WIDTH) if grid[i][j] == BLACK] for i in range(GRID_HEIGHT)]
accepted_positions = [j for sub in accepted_positions for j in sub]
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(GRID_WIDTH // 2, 0, random.choice(SHAPES))
def draw_text_middle(surface, text, size, color):
font = pygame.font.SysFont('comicsans', size, bold=True)
label = font.render(text, True, color)
surface.blit(label, (SCREEN_WIDTH / 2 - (label.get_width() / 2), SCREEN_HEIGHT / 2 - label.get_height() / 2))
def draw_grid(surface, grid):
for i in range(GRID_HEIGHT):
pygame.draw.line(surface, GRAY, (0, i * GRID_SIZE), (SCREEN_WIDTH, i * GRID_SIZE))
for j in range(GRID_WIDTH):
pygame.draw.line(surface, GRAY, (j * GRID_SIZE, 0), (j * GRID_SIZE, SCREEN_HEIGHT))
def clear_rows(grid, locked):
inc = 0
for i in range(GRID_HEIGHT -1, -1, -1):
row = grid[i]
if BLACK not in row:
inc += 1
ind = i
for j in range(GRID_WIDTH):
try:
del locked[(j, i)]
except:
continue
if inc > 0:
for key in sorted(list(locked), key=lambda x: x[1])[::-1]:
x, y = key
if y < ind:
newKey = (x, y + inc)
locked[newKey] = locked.pop(key)
return inc
def draw_next_shape(piece, surface):
font = pygame.font.SysFont('comicsans', 30)
label = font.render('Next Shape', True, WHITE)
start_x = SCREEN_WIDTH + 10
start_y = SCREEN_HEIGHT / 2 - 100
format = piece.shape[piece.rotation % len(piece.shape)]
for i, line in enumerate(format):
row = list(line)
for j, column in enumerate(row):
if column == 'X':
pygame.draw.rect(surface, piece.color,
(start_x + j * GRID_SIZE, start_y + i * GRID_SIZE, GRID_SIZE, GRID_SIZE), 0)
surface.blit(label, (start_x + 10, start_y - 30))
def draw_window(surface, grid, score=0):
surface.fill(BLACK)
font = pygame.font.SysFont('comicsans', 60)
label = font.render('Tetris', True, WHITE)
surface.blit(label, (SCREEN_WIDTH / 2 - label.get_width() / 2, 30))
# Current score
font = pygame.font.SysFont('comicsans', 30)
label = font.render('Score: ' + str(score), True, WHITE)
surface.blit(label, (10, SCREEN_HEIGHT - 30))
# Draw grid
for i in range(GRID_HEIGHT):
for j in range(GRID_WIDTH):
pygame.draw.rect(surface, grid[i][j],
(j * GRID_SIZE, i * GRID_SIZE, GRID_SIZE, GRID_SIZE), 0)
draw_grid(surface, grid)
pygame.draw.rect(surface, RED, (0, 0, SCREEN_WIDTH, SCREEN_HEIGHT), 5)
def main():
global RED
RED = (255, 0, 0)
win = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Tetris')
locked_positions = {} # (x,y):(255,0,0)
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 # Adjust this to make pieces fall faster or slower
score = 0
while run:
grid = create_grid(locked_positions)
fall_time += clock.get_rawtime()
clock.tick()
# Piece falling logic
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()
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)
# Add piece to the grid
for i in range(len(shape_pos)):
x, y = shape_pos[i]
if y > -1:
grid[y][x] = current_piece.color
# If 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
cleared_rows = clear_rows(grid, locked_positions)
if cleared_rows:
score += cleared_rows * 10
draw_window(win, grid, score)
draw_next_shape(next_piece, win)
pygame.display.update()
# Check if user lost
if check_lost(locked_positions):
draw_text_middle(win, "YOU LOST", 80, WHITE)
pygame.display.update()
pygame.time.delay(2000)
run = False
main()
pygame.quit()
Explanation:
Imports and Initialization:
Tetromino Shapes:
SHAPES is a list of tetromino configurations represented in 5x5 matrices.Piece Class:
Grid Functions:
create_grid: Creates the game grid, filling it with black or locked positions.convert_shape_format: Converts the piece's shape and rotation into grid positions.valid_space: Checks if the piece is in a valid position.check_lost: Checks if any locked positions are above the top of the grid.Game Logic Functions:
get_shape: Randomly selects a new piece.clear_rows: Removes full rows and updates the positions of the locked pieces.draw_grid: Draws grid lines.Drawing Functions:
draw_text_middle: Renders text at the center of the screen.draw_next_shape: Displays the next piece.draw_window: Refreshes the game window with the current grid and score.Main Game Loop:
fall_time and fall_speed).Running the Game:
pip install pygame
tetris.py.python tetris.py
Controls:
Note: This is a basic implementation. You can enhance it by adding features like:
Feel free to modify and expand upon this code to create your own version of Tetris!
Not yet included in a published release.