Create the tetris game in python.
- User
Create the tetris game in python.
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Create the tetris game in python.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Creating a fully functional Tetris game in Python is a great way to improve your programming skills, especially if you're interested in game development. Below, I'll guide you through building a basic Tetris game using the pygame library. This guide includes the complete source code along with explanations to help you understand each part.
Python Installed: Make sure you have Python 3.x installed on your system. You can download it from python.org.
Pygame Library: We'll use pygame for handling graphics and game mechanics. Install it using pip:
pip install pygame
Before diving into the code, let's outline the main components we'll implement:
Below is the complete Python code for a basic Tetris game using pygame. You can save this code in a file named tetris.py and run it.
import pygame
import random
# Initialize Pygame
pygame.init()
# Screen dimensions
SCREEN_WIDTH = 300
SCREEN_HEIGHT = 600
GRID_SIZE = 30
# Colors (R, G, B)
BLACK = (0, 0, 0)
GRAY = (128, 128, 128)
WHITE = (255, 255, 255)
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
]
# Define the shape formats
SHAPES = [
[['.....',
'.....',
'..O..',
'..O..',
'..O..',
'..O..',
'.....']],
[['.....',
'.....',
'.O...',
'.OOO.',
'.....']],
[['.....',
'.....',
'...O.',
'.OOO.',
'.....']],
[['.....',
'.....',
'.OO.',
'.OO.',
'.....']],
[['.....',
'.....',
'..OO.',
'.OO..',
'.....']],
[['.....',
'.....',
'..O..',
'.OOO.',
'.....']],
[['.....',
'.....',
'.O...',
'.OOO.',
'.....']]
]
# Tetromino class
class Tetromino:
def __init__(self, x, y, shape):
self.x = x
self.y = y
self.shape = shape
self.color = COLORS[SHAPES.index(shape)]
self.rotation = 0
def image(self):
return self.shape[self.rotation % len(self.shape)]
# Create the grid
def create_grid(locked_positions={}):
grid = [[BLACK 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:
grid[i][j] = locked_positions[(j, i)]
return grid
# Convert shape to grid positions
def convert_shape_format(shape):
positions = []
format = shape.image()
for i, line in enumerate(format):
row = list(line)
for j, column in enumerate(row):
if column == 'O':
positions.append((shape.x + j - 2, shape.y + i - 4))
return positions
# Check if position is valid
def valid_space(shape, grid):
accepted_positions = [[(j, i) for j in range(10) if grid[i][j] == BLACK] for i in range(20)]
accepted_positions = [j for sub in accepted_positions for j 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 for game over
def check_lost(positions):
for pos in positions:
x, y = pos
if y < 1:
return True
return False
# Get a random shape
def get_shape():
return Tetromino(5, 0, random.choice(SHAPES))
# Draw text in the middle
def draw_text_middle(surface, text, size, color):
font = pygame.font.SysFont('Arial', 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))
# Draw the grid lines
def draw_grid(surface, grid):
sx = 0
sy = 0
for i in range(len(grid)):
pygame.draw.line(surface, GRAY, (sx, sy + i*GRID_SIZE), (sx + SCREEN_WIDTH, sy + i * GRID_SIZE))
for j in range(len(grid[i])):
pygame.draw.line(surface, GRAY, (sx + j*GRID_SIZE, sy), (sx + j*GRID_SIZE, sy + SCREEN_HEIGHT))
# Clear rows
def clear_rows(grid, locked):
inc = 0
for i in range(len(grid)-1, -1, -1):
row = grid[i]
if BLACK not in row:
inc += 1
ind = i
for j in range(len(row)):
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
# Draw the window
def draw_window(surface, grid, score=0):
surface.fill(BLACK)
# Title
font = pygame.font.SysFont('Arial', 30)
label = font.render('Tetris', True, WHITE)
surface.blit(label, (SCREEN_WIDTH//2 - label.get_width()/2, 10))
# Current Score
font = pygame.font.SysFont('Arial', 20)
label = font.render(f'Score: {score}', True, WHITE)
surface.blit(label, (SCREEN_WIDTH - label.get_width() - 10, 10))
# Draw grid
for i in range(len(grid)):
for j in range(len(grid[i])):
pygame.draw.rect(surface, grid[i][j], (j*GRID_SIZE, i*GRID_SIZE + 50, GRID_SIZE, GRID_SIZE), 0)
# Draw grid lines
draw_grid(surface, grid)
pygame.display.update()
def main():
global SCREEN_WIDTH, SCREEN_HEIGHT
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Tetris')
clock = pygame.time.Clock()
grid = create_grid()
change_piece = False
run = True
current_piece = get_shape()
next_piece = get_shape()
locked_positions = {}
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 over time or levels
if level_time/1000 > 5:
level_time = 0
if fall_speed > 0.12:
fall_speed -= 0.005
# Piece falling mechanism
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 drawing
for pos in shape_pos:
x, y = pos
if y > -1:
grid[y][x] = current_piece.color
# If piece hit the ground
if change_piece:
for pos in shape_pos:
locked_positions[pos] = current_piece.color
current_piece = next_piece
next_piece = get_shape()
change_piece = False
# Clear rows
cleared = clear_rows(grid, locked_positions)
if cleared > 0:
score += cleared * 10
draw_window(screen, grid, score)
# Check if user lost
if check_lost(locked_positions):
run = False
draw_text_middle(screen, "GAME OVER", 40, WHITE)
pygame.display.update()
pygame.time.delay(2000)
pygame.quit()
def main_menu():
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Tetris')
run = True
while run:
screen.fill(BLACK)
draw_text_middle(screen, 'Press Any Key To Play', 30, WHITE)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
main()
pygame.quit()
if __name__ == "__main__":
main_menu()
Let's break down the key parts of the code to understand how the game works.
import pygame
import random
pygame.init()
We import the necessary libraries and initialize Pygame.
# Screen dimensions
SCREEN_WIDTH = 300
SCREEN_HEIGHT = 600
GRID_SIZE = 30
# Colors (R, G, B)
BLACK = (0, 0, 0)
GRAY = (128, 128, 128)
WHITE = (255, 255, 255)
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
]
We define the screen size, grid size, and colors for the tetrominoes.
# Define the shape formats
SHAPES = [
[['.....',
'.....',
'..O..',
'..O..',
'..O..',
'..O..',
'.....']],
# ... other shapes
]
Each tetromino shape is defined in a grid format using a list of strings. The 'O' represents a block part of the tetromino.
class Tetromino:
def __init__(self, x, y, shape):
self.x = x
self.y = y
self.shape = shape
self.color = COLORS[SHAPES.index(shape)]
self.rotation = 0
def image(self):
return self.shape[self.rotation % len(self.shape)]
The Tetromino class represents each piece in the game, handling its position, shape, color, and rotation.
def create_grid(locked_positions={}):
grid = [[BLACK for _ in range(10)] for _ in range(20)]
# Populate grid with locked positions
return grid
Creates a 10x20 grid initialized with the background color. Locked positions (where tetrominoes have settled) are stored in a dictionary.
def valid_space(shape, grid):
# Check if tetromino is within grid and not colliding
return True or False
Checks if the current tetromino position is valid (inside the grid and not overlapping with locked positions).
def draw_window(surface, grid, score=0):
# Draw the game title, score, grid, and locked positions
pygame.display.update()
Handles rendering the game window, including the grid, current score, and any locked tetrominoes.
def main():
# Initialize game variables
while run:
# Handle events, move pieces, check for line clears and game over
draw_window(screen, grid, score)
Contains the main game loop, which continuously updates the game state, handles user input, moves tetrominoes, clears rows, updates the score, and checks for game over conditions.
def main_menu():
# Show the start screen and wait for user input to start the game
main()
Displays the start menu and begins the game when the user presses any key.
Save the Code: Save the above code in a file named tetris.py.
Run the Game:
python tetris.py
Controls:
Gameplay: As tetrominoes fall, you can move and rotate them to fill and clear horizontal lines. The game ends when the stack of tetrominoes reaches the top of the grid.
The provided code is a basic implementation of Tetris. Here are some ideas to enhance the game:
Implementing these features will provide a more complete and engaging Tetris experience.
Building Tetris in Python using pygame is a rewarding project that covers essential game development concepts such as handling user input, managing game states, collision detection, and rendering graphics. By following the code and explanations above, you can create a functioning version of Tetris and further expand upon it to add more features and polish.
Feel free to experiment with the code, modify the shapes, colors, or add new functionalities to make the game your own!