class Piece:
def init(self, x, y, shape):
self.x = x # Grid position x
self.y = y # Grid position y
self.shape = shape
self.color = SHAPE_COLORS[SHAPES.index(shape)]
self.rotation = 0 # Current rotation state
def load_high_score():
global high_score
if os.path.exists(HIGHSCORE_FILE):
with open(HIGHSCORE_FILE, 'r') as file:
try:
high_score = int(file.read())
except:
high_score = 0
else:
high_score = 0
return high_score
def save_high_score(high_score):
with open(HIGHSCORE_FILE, 'w') as file:
file.write(str(high_score))
def create_grid(locked_positions={}):
grid = [[(0, 0, 0) for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]
code
for (j, i) in locked_positions:
if 0 <= i < GRID_HEIGHT and 0 <= j < GRID_WIDTH:
grid[i][j] = locked_positions[(j, i)]
return grid
def convert_shape_format(piece):
positions = []
format = piece.shape[piece.rotation % len(piece.shape)]
code
for i, line in enumerate(format):
row = list(line)
for j, column in enumerate(row):
if column == '0':
positions.append((piece.x + j - 2, piece.y + i - 4))
# Normalize positions
positions = [(x, y) for (x, y) in positions]
return positions
def valid_space(piece, grid):
accepted_positions = [[(j, i) for j in range(GRID_WIDTH) if grid[i][j] == (0, 0, 0)] for i in range(GRID_HEIGHT)]
accepted_positions = [j for sub in accepted_positions for j in sub]
code
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):
# If any locked position is at or above the second row (y <1), player loses
for pos in positions:
x, y = pos
if y < 1:
return True
return False
def get_shape():
return Piece(GRID_WIDTH // 2, 5, random.choice(SHAPES)) # Spawn position adjusted to y=5
def draw_grid(surface, grid, offset_y=80):
for i in range(GRID_HEIGHT):
# Horizontal lines
pygame.draw.line(surface, (128, 128, 128),
(20, i * BLOCK_SIZE + offset_y),
(20 + GRID_WIDTH * BLOCK_SIZE, i * BLOCK_SIZE + offset_y))
for j in range(GRID_WIDTH):
# Vertical lines
pygame.draw.line(surface, (128, 128, 128),
(j * BLOCK_SIZE + 20, offset_y),
(j * BLOCK_SIZE + 20, GRID_HEIGHT * BLOCK_SIZE + offset_y))
def clear_rows(grid, locked):
inc = 0
lines_cleared = 0
for i in range(len(grid)-1, -1, -1):
row = grid[i]
if (0, 0, 0) not in row:
inc += 1
lines_cleared += 1
ind = i
for j in range(len(row)):
try:
del locked[(j, i)]
except:
continue
if inc > 0:
# Play line clear sound
CLEAR_SOUND.play()
# Shift rows down
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 lines_cleared
while run:
win.fill((0, 0, 0))
# Draw the "Options" title
font_title = pygame.font.SysFont('comicsans', 60, bold=True)
title_label = font_title.render('Options', 1, (255, 255, 255))
win.blit(title_label, (SCREEN_WIDTH / 2 - title_label.get_width() / 2, 50))
# Draw sliders
music_slider.draw(win)
sfx_slider.draw(win)
# Instructions to return to main menu
font_instruct = pygame.font.SysFont('comicsans', 25)
instruct_label = font_instruct.render('Press Esc to return to the main menu.', 1, (255, 255, 255))
win.blit(instruct_label, (SCREEN_WIDTH / 2 - instruct_label.get_width() / 2, 400))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Handle slider events
music_slider.handle_event(event)
sfx_slider.handle_event(event)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
# Update volume settings
set_music_volume(music_slider.value)
set_sfx_volume(sfx_slider.value)
run = False # Exit options_menu
def help_menu():
run = True
while run:
win.fill((0, 0, 0))
code
# Draw the "Help" title
font_title = pygame.font.SysFont('comicsans', 60, bold=True)
title_label = font_title.render('Help', 1, (255, 255, 255))
win.blit(title_label, (SCREEN_WIDTH / 2 - title_label.get_width() / 2, 50))
# Draw help instructions
font_help = pygame.font.SysFont('comicsans', 25)
instructions = [
"Welcome to Tetris!",
"",
"Controls:",
"Arrow Left (←): Move left",
"Arrow Right (→): Move right",
"Arrow Down (↓): Soft drop (increase fall speed)",
"Arrow Up (↑): Rotate piece",
"Spacebar: Pause/Resume the game",
"",
"Objective:",
"Clear lines by filling all blocks in a row.",
"The game increases in speed as you clear more lines.",
"Avoid stacking blocks to the top of the grid to prevent losing.",
]
y_offset = 150
for line in instructions:
label = font_help.render(line, 1, (255, 255, 255))
win.blit(label, (50, y_offset))
y_offset += 35 # Adjust spacing as needed
# Instructions to return to main menu
instruct_label = font_help.render('Press Esc to return to the main menu.', 1, (255, 255, 255))
win.blit(instruct_label, (SCREEN_WIDTH / 2 - instruct_label.get_width() / 2, SCREEN_HEIGHT - 50))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
run = False # Exit help_menu
def main_game():
global high_score
locked_positions = {}
grid = create_grid(locked_positions)
code
change_piece = False
run = True
current_piece = get_shape()
next_piece = get_shape()
clock = pygame.time.Clock()
fall_time = 0
BASE_FALL_SPEED = 0.5 # Base fall speed in seconds
fall_speed = BASE_FALL_SPEED
lines_cleared = 0 # Initialize lines cleared counter
level = 1 # Initialize level
paused = False # Game paused state
the_music_started = False # To ensure music starts only once
# Variables for continuous movement
last_move_left = 0
last_move_right = 0
move_interval = 150 # milliseconds
while run:
grid = create_grid(locked_positions)
fall_time += clock.get_rawtime()
clock.tick()
# Calculate current level based on lines cleared
new_level = (lines_cleared // 10) + 1
if new_level != level:
level = new_level
fall_speed *= 1.15 # Increase speed by 15% each level
# Adjust fall speed
current_fall_speed = fall_speed
keys = pygame.key.get_pressed()
if keys[pygame.K_DOWN]:
current_fall_speed = 0.05 # Fast fall when down key is held
if fall_time / 1000 >= current_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
MOVE_SOUND.play()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.display.quit()
sys.exit()
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
else:
MOVE_SOUND.play()
last_move_left = pygame.time.get_ticks()
elif event.key == pygame.K_RIGHT:
current_piece.x += 1
if not valid_space(current_piece, grid):
current_piece.x -= 1
else:
MOVE_SOUND.play()
last_move_right = pygame.time.get_ticks()
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 = (current_piece.rotation + 1) % len(current_piece.shape)
if not valid_space(current_piece, grid):
current_piece.rotation = (current_piece.rotation - 1) % len(current_piece.shape)
else:
ROTATE_SOUND.play()
elif event.key == pygame.K_SPACE:
paused = not paused # Toggle pause
if paused:
pygame.mixer.music.pause()
else:
pygame.mixer.music.unpause()
# Handle continuous left/right movement
current_time = pygame.time.get_ticks()
if keys[pygame.K_LEFT]:
if current_time - last_move_left > move_interval:
current_piece.x -= 1
if not valid_space(current_piece, grid):
current_piece.x += 1
else:
MOVE_SOUND.play()
last_move_left = current_time
if keys[pygame.K_RIGHT]:
if current_time - last_move_right > move_interval:
current_piece.x += 1
if not valid_space(current_piece, grid):
current_piece.x -= 1
else:
MOVE_SOUND.play()
last_move_right = current_time
if paused:
pause_screen(win)
pygame.time.delay(100) # Prevent high CPU usage while paused
continue # Skip the rest of the loop to effectively pause
shape_pos = convert_shape_format(current_piece)
# Add piece to the grid for drawing
for i in range(len(shape_pos)):
x, y = shape_pos[i]
if y > -1:
if 0 <= x < GRID_WIDTH and 0 <= y < GRID_HEIGHT:
grid[y][x] = current_piece.color
if change_piece:
for pos in shape_pos:
p = (pos[0], pos[1])
if 0 <= p[0] < GRID_WIDTH and 0 <= p[1] < GRID_HEIGHT:
locked_positions[p] = current_piece.color
current_piece = next_piece
next_piece = get_shape()
change_piece = False
cleared = clear_rows(grid, locked_positions)
lines_cleared += cleared # Update lines cleared
# **Immediate Loss Check After Spawning New Piece**
if not valid_space(current_piece, grid):
# **Trigger loss**
GAME_OVER_SOUND.play()
pygame.time.delay(500)
run = False
stop_background_music()
update_high_score_if_needed(lines_cleared)
# Start background music once when the game starts
if not the_music_started and not paused:
play_background_music()
the_music_started = True
draw_window(win, grid, lines_cleared, level, high_score)
draw_next_shape(next_piece, win)
pygame.display.update()
# **Optional: Remove this check if loss is already handled above**
# if check_lost(locked_positions):
# GAME_OVER_SOUND.play()
# pygame.time.delay(500)
# run = False
# stop_background_music()
# update_high_score_if_needed(lines_cleared)
# After the loop ends, show game over screen
game_over_screen(win, lines_cleared, high_score)
def update_high_score_if_needed(current_score):
global high_score
if current_score > high_score:
high_score = current_score
save_high_score(high_score)
def game_over_screen(surface, final_score, _):
global high_score
# Update high score if necessary
if final_score > high_score:
high_score = final_score
save_high_score(high_score)
code
pygame.mixer.music.stop() # Ensure music is stopped on game over
while True:
surface.fill((0, 0, 0))
draw_text_middle("YOU LOST!", 60, (255, 255, 255), surface, y_offset=-60)
# Display final score
font_small = pygame.font.SysFont('comicsans', 30)
score_label = font_small.render(f'Your Score: {final_score}', 1, (255, 255, 255))
high_label = font_small.render(f'High Score: {high_score}', 1, (255, 255, 255))
# **Adjust y positions to prevent overlapping**
surface.blit(score_label, ((SCREEN_WIDTH / 2) - (score_label.get_width() / 2), (SCREEN_HEIGHT / 2) - 40))
surface.blit(high_label, ((SCREEN_WIDTH / 2) - (high_label.get_width() / 2), (SCREEN_HEIGHT / 2) - 10))
# Prompt to return to menu
prompt_label = font_small.render('Press Space to return to the menu.', 1, (255, 255, 255))
surface.blit(prompt_label, ((SCREEN_WIDTH / 2) - (prompt_label.get_width() / 2), (SCREEN_HEIGHT / 2) + 20))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
main_menu() # Return to main menu
def help_menu():
run = True
while run:
win.fill((0, 0, 0))
code
# Draw the "Help" title
font_title = pygame.font.SysFont('comicsans', 60, bold=True)
title_label = font_title.render('Help', 1, (255, 255, 255))
win.blit(title_label, (SCREEN_WIDTH / 2 - title_label.get_width() / 2, 50))
# Draw help instructions
font_help = pygame.font.SysFont('comicsans', 25)
instructions = [
"Welcome to Tetris!",
"",
"Controls:",
"Arrow Left (←): Move left",
"Arrow Right (→): Move right",
"Arrow Down (↓): Soft drop (increase fall speed)",
"Arrow Up (↑): Rotate piece",
"Spacebar: Pause/Resume the game",
"",
"Objective:",
"Clear lines by filling all blocks in a row.",
"The game increases in speed as you clear more lines.",
"Avoid stacking blocks to the top of the grid to prevent losing.",
"",
"Good luck and have fun!"
]
y_offset = 150
for line in instructions:
label = font_help.render(line, 1, (255, 255, 255))
if line == "":
y_offset += 20 # Add extra space for empty lines
continue
win.blit(label, (50, y_offset))
y_offset += 35 # Adjust spacing as needed
# Instructions to return to main menu
instruct_label = font_help.render('Press Esc to return to the main menu.', 1, (255, 255, 255))
win.blit(instruct_label, (SCREEN_WIDTH / 2 - instruct_label.get_width() / 2, SCREEN_HEIGHT - 50))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
run = False # Exit help_menu
if name == 'main':
main_menu()
Make these changes :
When a new piece appears in the grid, it should appear two rows before
Help page : make the instruction smaller because it overflow outside the window on the right
At every level change, make the pieces go 15% faster
Certainly! I'll help you implement the requested changes to your Tetris game:
Spawn New Pieces Two Rows Higher:
Change: Modify the spawn position of new pieces to appear two rows higher in the grid.
Implementation: Adjust the y coordinate in the get_shape() function from 5 to 3.
Adjust Help Page Instructions to Prevent Overflow:
Change: Reduce the font size of the instructions on the help page to prevent text from overflowing the window.
Implementation: Decrease the font size in the help_menu() function and adjust text positioning as necessary.
Increase Fall Speed by 15% on Level Change:
Change: Ensure that at every level change, the fall speed of the pieces increases by 15%.
Implementation: Modify the fall_speed calculation in the main_game() function to decrease the fall_speed by 15% (i.e., multiply by 0.85), making the pieces fall faster.
Below is the updated code with these changes implemented. Comments have been added to highlight where the changes occurred:
python
import pygame
import random
import os
import sys
# Initialize Pygame and Mixer for sounds
pygame.init()
pygame.mixer.init()
# Define grid size
GRID_WIDTH = 10 # Standard Tetris has 10 columns
GRID_HEIGHT = 20 # Standard Tetris has 20 rows
BLOCK_SIZE = 30 # Size of the grid block
# Define margins and offsets
TITLE_HEIGHT = 80
SIDE_PANEL_MARGIN_TOP = 100
SIDE_PANEL_MARGIN_LEFT = GRID_WIDTH * BLOCK_SIZE + 40 # 10 columns * 30 + 40 for margin
# Screen dimensions (grid + side panel + margins)
SIDE_PANEL_WIDTH = 200
SCREEN_WIDTH = GRID_WIDTH * BLOCK_SIZE + SIDE_PANEL_WIDTH + 60 # Additional margin for aesthetics
SCREEN_HEIGHT = TITLE_HEIGHT + GRID_HEIGHT * BLOCK_SIZE + 40 # Additional margin for aesthetics
# Set up the display
win = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Tetris')
# Load Sounds (Ensure you have these sound files in a 'Sounds' directory)
MOVE_SOUND = pygame.mixer.Sound(os.path.join('Sounds', 'move.wav'))
ROTATE_SOUND = pygame.mixer.Sound(os.path.join('Sounds', 'rotate.wav'))
CLEAR_SOUND = pygame.mixer.Sound(os.path.join('Sounds', 'clear.wav'))
GAME_OVER_SOUND = pygame.mixer.Sound(os.path.join('Sounds', 'game_over.wav'))
BACKGROUND_MUSIC = os.path.join('Sounds', 'game.mp3') # Path to background music
# Define paths for high score
HIGHSCORE_FILE = 'high_score.txt'
# Initialize high_score globally
high_score = 0
# Define shapes and their rotations
SHAPES = [
[['.....',
'..0..',
'..0..',
'..0..',
'..0..'],
['.....',
'0000.',
'.....',
'.....',
'.....']],
[['.....',
'..00.',
'..00.',
'.....',
'.....']],
[['.....',
'...0.',
'.000.',
'.....',
'.....'],
['.....',
'..0..',
'..0..',
'..00.',
'.....'],
['.....',
'.....',
'.000.',
'.0...',
'.....'],
['.....',
'.00..',
'..0..',
'..0..',
'.....']],
[['.....',
'.0...',
'.000.',
'.....',
'.....'],
['.....',
'..00.',
'..0..',
'..0..',
'.....'],
['.....',
'.....',
'.000.',
'...0.',
'.....'],
['.....',
'..0..',
'..0..',
'.00..',
'.....']],
[['.....',
'..0..',
'.000.',
'.....',
'.....'],
['.....',
'..0..',
'..00.',
'..0..',
'.....'],
['.....',
'.....',
'.000.',
'..0..',
'.....'],
['.....',
'..0..',
'.00..',
'..0..',
'.....']],
[['.....',
'..0..',
'..00.',
'...0.',
'.....'],
['.....',
'...00',
'..00.',
'.....',
'.....']],
[['.....',
'...0.',
'..00.',
'..0..',
'.....'],
['.....',
'..00.',
'...00',
'.....',
'.....']]
]
# Define colors for each shape
SHAPE_COLORS = [
(0, 255, 255), # Cyan
(255, 255, 0), # Yellow
(255, 165, 0), # Orange
(0, 0, 255), # Blue
(128, 0, 128), # Purple
(0, 255, 0), # Green
(255, 0, 0) # Red
]
# Volume settings (0-10 scale)
music_volume = 5
sfx_volume = 5
class Piece:
def __init__(self, x, y, shape):
self.x = x # Grid position x
self.y = y # Grid position y
self.shape = shape
self.color = SHAPE_COLORS[SHAPES.index(shape)]
self.rotation = 0 # Current rotation state
def load_high_score():
global high_score
if os.path.exists(HIGHSCORE_FILE):
with open(HIGHSCORE_FILE, 'r') as file:
try:
high_score = int(file.read())
except:
high_score = 0
else:
high_score = 0
return high_score
def save_high_score(high_score):
with open(HIGHSCORE_FILE, 'w') as file:
file.write(str(high_score))
def create_grid(locked_positions={}):
grid = [[(0, 0, 0) for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]
for (j, i) in locked_positions:
if 0 <= i < GRID_HEIGHT and 0 <= j < GRID_WIDTH:
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 == '0':
positions.append((piece.x + j - 2, piece.y + i - 4))
# Normalize positions
positions = [(x, y) for (x, y) in positions]
return positions
def valid_space(piece, grid):
accepted_positions = [[(j, i) for j in range(GRID_WIDTH) if grid[i][j] == (0, 0, 0)] 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):
# If any locked position is at or above the second row (y <1), player loses
for pos in positions:
x, y = pos
if y < 1:
return True
return False
def get_shape():
# **Change 1: Spawn new pieces two rows higher by setting y=3 instead of y=5**
return Piece(GRID_WIDTH // 2, 3, random.choice(SHAPES)) # Spawn position adjusted to y=3
def draw_text_middle(text, size, color, surface, y_offset=0):
font = pygame.font.SysFont('comicsans', size, bold=True)
label = font.render(text, 1, color)
surface.blit(label, (
(SCREEN_WIDTH / 2) - (label.get_width() / 2),
(SCREEN_HEIGHT / 2) - (label.get_height() / 2) + y_offset
))
def draw_grid(surface, grid, offset_y=80):
for i in range(GRID_HEIGHT):
# Horizontal lines
pygame.draw.line(surface, (128, 128, 128),
(20, i * BLOCK_SIZE + offset_y),
(20 + GRID_WIDTH * BLOCK_SIZE, i * BLOCK_SIZE + offset_y))
for j in range(GRID_WIDTH):
# Vertical lines
pygame.draw.line(surface, (128, 128, 128),
(j * BLOCK_SIZE + 20, offset_y),
(j * BLOCK_SIZE + 20, GRID_HEIGHT * BLOCK_SIZE + offset_y))
def clear_rows(grid, locked):
inc = 0
lines_cleared = 0
for i in range(len(grid)-1, -1, -1):
row = grid[i]
if (0, 0, 0) not in row:
inc += 1
lines_cleared += 1
ind = i
for j in range(len(row)):
try:
del locked[(j, i)]
except:
continue
if inc > 0:
# Play line clear sound
CLEAR_SOUND.play()
# Shift rows down
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 lines_cleared
def draw_next_shape(piece, surface):
font = pygame.font.SysFont('comicsans', 30)
label = font.render('Next Shape', 1, (255, 255, 255))
sx = SIDE_PANEL_MARGIN_LEFT + 20
sy = SIDE_PANEL_MARGIN_TOP + 100
format = piece.shape[piece.rotation % len(piece.shape)]
surface.blit(label, (sx, sy))
for i, line in enumerate(format):
row = list(line)
for j, column in enumerate(row):
if column == '0':
# Draw block with shading
block_rect = pygame.Rect(sx + j * BLOCK_SIZE, sy + 40 + i * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE)
pygame.draw.rect(surface, piece.color, block_rect)
pygame.draw.rect(surface, (0, 0, 0), block_rect, 2) # Border for better visibility
def draw_window(surface, grid, lines_cleared, level, _):
surface.fill((30, 30, 30)) # Dark background for better contrast
# Draw the "Tetris" title above the grid
font_title = pygame.font.SysFont('comicsans', 60, bold=True)
label_title = font_title.render('Tetris', 1, (255, 255, 255))
surface.blit(label_title, (SIDE_PANEL_MARGIN_LEFT // 2 - label_title.get_width() / 2, 10))
# Display Score and Level in the side panel
font_small = pygame.font.SysFont('comicsans', 30, bold=True)
label_score = font_small.render(f'Score: {lines_cleared}', 1, (255, 255, 255))
label_level = font_small.render(f'Level: {level}', 1, (255, 255, 255))
surface.blit(label_score, (SIDE_PANEL_MARGIN_LEFT + 20, SIDE_PANEL_MARGIN_TOP))
surface.blit(label_level, (SIDE_PANEL_MARGIN_LEFT + 20, SIDE_PANEL_MARGIN_TOP + 50))
# Draw the grid blocks
for i in range(len(grid)):
for j in range(len(grid[i])):
pygame.draw.rect(surface, grid[i][j],
(j * BLOCK_SIZE + 20, i * BLOCK_SIZE + TITLE_HEIGHT, BLOCK_SIZE, BLOCK_SIZE), 0)
# Add shading to blocks for 3D effect
if grid[i][j] != (0, 0, 0):
pygame.draw.rect(surface, (0, 0, 0),
(j * BLOCK_SIZE + 20, i * BLOCK_SIZE + TITLE_HEIGHT, BLOCK_SIZE, BLOCK_SIZE), 2)
draw_grid(surface, grid, offset_y=TITLE_HEIGHT)
# Draw border around the grid
pygame.draw.rect(surface, (255, 255, 255),
(20, TITLE_HEIGHT, GRID_WIDTH * BLOCK_SIZE, GRID_HEIGHT * BLOCK_SIZE), 5)
# Draw border around side panel
pygame.draw.rect(surface, (255, 255, 255),
(SIDE_PANEL_MARGIN_LEFT, 0, SIDE_PANEL_WIDTH, SCREEN_HEIGHT), 5)
def play_background_music():
if os.path.exists(BACKGROUND_MUSIC):
pygame.mixer.music.load(BACKGROUND_MUSIC)
pygame.mixer.music.set_volume(music_volume / 10) # Adjust volume as needed
pygame.mixer.music.play(-1) # -1 for infinite loop
else:
print(f"Background music file not found: {BACKGROUND_MUSIC}")
def stop_background_music():
pygame.mixer.music.stop()
# Slider Class for Options Menu
class Slider:
def __init__(self, x, y, width, height, min_val, max_val, start_val=5, label=''):
self.x = x
self.y = y
self.width = width
self.height = height
self.min_val = min_val
self.max_val = max_val
self.value = start_val
self.knob_radius = height // 2
self.knob_x = self.x + (self.value - self.min_val) / (self.max_val - self.min_val) * self.width
self.knob_y = self.y + self.height // 2
self.dragging = False
self.label = label
def draw(self, surface):
# Draw the bar
pygame.draw.rect(surface, (200, 200, 200), (self.x, self.y + self.height // 4, self.width, self.height // 2))
# Draw the knob
pygame.draw.circle(surface, (255, 255, 255), (int(self.knob_x), int(self.knob_y)), self.knob_radius)
# Draw value
font = pygame.font.SysFont('comicsans', 20)
label = font.render(str(int(self.value)), 1, (255, 255, 255))
surface.blit(label, (self.x + self.width + 10, self.y - self.height // 2))
# Draw slider label
if self.label:
label_text = font.render(self.label, 1, (255, 255, 255))
surface.blit(label_text, (self.x, self.y - 30)) # Position above the slider
def handle_event(self, event):
if event.type == pygame.MOUSEBUTTONDOWN:
mouse_x, mouse_y = event.pos
distance = ((mouse_x - self.knob_x) ** 2 + (mouse_y - self.knob_y) ** 2) ** 0.5
if distance <= self.knob_radius:
self.dragging = True
elif event.type == pygame.MOUSEBUTTONUP:
self.dragging = False
elif event.type == pygame.MOUSEMOTION:
if self.dragging:
mouse_x = event.pos[0]
# Clamp mouse_x to the slider bar
self.knob_x = max(self.x, min(mouse_x, self.x + self.width))
# Update value accordingly
ratio = (self.knob_x - self.x) / self.width
self.value = self.min_val + ratio * (self.max_val - self.min_val)
# Round to nearest integer
self.value = int(round(self.value))
def set_sfx_volume(volume):
global sfx_volume
sfx_volume = volume
MOVE_SOUND.set_volume(sfx_volume / 10)
ROTATE_SOUND.set_volume(sfx_volume / 10)
CLEAR_SOUND.set_volume(sfx_volume / 10)
GAME_OVER_SOUND.set_volume(sfx_volume / 10)
def set_music_volume(volume):
global music_volume
music_volume = volume
pygame.mixer.music.set_volume(music_volume / 10)
def main_menu():
global high_score
load_high_score() # Ensure high_score is loaded before displaying menu
run = True
while run:
win.fill((0, 0, 0))
# Draw the "Tetris" title
font_title = pygame.font.SysFont('comicsans', 60, bold=True)
title_label = font_title.render('Tetris', 1, (255, 255, 255))
win.blit(title_label, (SCREEN_WIDTH / 2 - title_label.get_width() / 2, 100))
# Display High Score
font_high = pygame.font.SysFont('comicsans', 30, bold=True)
high_label = font_high.render(f'High Score: {high_score}', 1, (255, 255, 255))
win.blit(high_label, (SCREEN_WIDTH / 2 - high_label.get_width() / 2, 200))
# Display menu options
font_options = pygame.font.SysFont('comicsans', 30)
option1 = font_options.render('1: New Game', 1, (255, 255, 255))
option2 = font_options.render('2: Options', 1, (255, 255, 255))
option3 = font_options.render('3: Help', 1, (255, 255, 255))
option4 = font_options.render('4: Exit', 1, (255, 255, 255))
win.blit(option1, (SCREEN_WIDTH / 2 - option1.get_width() / 2, 300))
win.blit(option2, (SCREEN_WIDTH / 2 - option2.get_width() / 2, 350))
win.blit(option3, (SCREEN_WIDTH / 2 - option3.get_width() / 2, 400))
win.blit(option4, (SCREEN_WIDTH / 2 - option4.get_width() / 2, 450))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
main_game() # Start new game
elif event.key == pygame.K_2:
options_menu() # Open options menu
elif event.key == pygame.K_3:
help_menu() # Open help menu
elif event.key == pygame.K_4:
run = False
pygame.quit()
sys.exit()
def options_menu():
global music_volume, sfx_volume
run = True
# Create sliders: (x, y, width, height, min_val, max_val, start_val, label)
music_slider = Slider(SCREEN_WIDTH / 2 - 100, 150, 200, 20, 0, 10, music_volume, 'Music Volume')
sfx_slider = Slider(SCREEN_WIDTH / 2 - 100, 250, 200, 20, 0, 10, sfx_volume, 'SFX Volume')
while run:
win.fill((0, 0, 0))
# Draw the "Options" title
font_title = pygame.font.SysFont('comicsans', 60, bold=True)
title_label = font_title.render('Options', 1, (255, 255, 255))
win.blit(title_label, (SCREEN_WIDTH / 2 - title_label.get_width() / 2, 50))
# Draw sliders
music_slider.draw(win)
sfx_slider.draw(win)
# Instructions to return to main menu
font_instruct = pygame.font.SysFont('comicsans', 25)
instruct_label = font_instruct.render('Press Esc to return to the main menu.', 1, (255, 255, 255))
win.blit(instruct_label, (SCREEN_WIDTH / 2 - instruct_label.get_width() / 2, 400))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Handle slider events
music_slider.handle_event(event)
sfx_slider.handle_event(event)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
# Update volume settings
set_music_volume(music_slider.value)
set_sfx_volume(sfx_slider.value)
run = False # Exit options_menu
def help_menu():
run = True
while run:
win.fill((0, 0, 0))
# Draw the "Help" title
font_title = pygame.font.SysFont('comicsans', 60, bold=True)
title_label = font_title.render('Help', 1, (255, 255, 255))
win.blit(title_label, (SCREEN_WIDTH / 2 - title_label.get_width() / 2, 50))
# **Change 2: Reduce font size to prevent text overflow**
font_help = pygame.font.SysFont('comicsans', 20) # Reduced from 25 to 20
instructions = [
"Welcome to Tetris!",
"",
"Controls:",
"Arrow Left (←): Move left",
"Arrow Right (→): Move right",
"Arrow Down (↓): Soft drop",
"Arrow Up (↑): Rotate piece",
"Spacebar: Pause/Resume the game",
"",
"Objective:",
"Clear lines by filling all blocks in a row.",
"The game increases in speed as you clear more lines.",
"Avoid stacking blocks to the top of the grid to prevent losing.",
"",
"Good luck and have fun!"
]
y_offset = 150
for line in instructions:
if len(line) > 50:
# Implement simple text wrapping
words = line.split(' ')
wrapped_lines = []
current_line = ""
for word in words:
if font_help.size(current_line + ' ' + word)[0] > SCREEN_WIDTH - 100:
wrapped_lines.append(current_line)
current_line = word
else:
if current_line != "":
current_line += ' ' + word
else:
current_line = word
if current_line:
wrapped_lines.append(current_line)
for wrapped_line in wrapped_lines:
label = font_help.render(wrapped_line, 1, (255, 255, 255))
win.blit(label, (50, y_offset))
y_offset += 25 # Adjusted spacing
else:
label = font_help.render(line, 1, (255, 255, 255))
if line == "":
y_offset += 20 # Add extra space for empty lines
continue
win.blit(label, (50, y_offset))
y_offset += 30 # Adjusted spacing
# Instructions to return to main menu
instruct_label = font_help.render('Press Esc to return to the main menu.', 1, (255, 255, 255))
win.blit(instruct_label, (SCREEN_WIDTH / 2 - instruct_label.get_width() / 2, SCREEN_HEIGHT - 50))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
run = False # Exit help_menu
def main_game():
global high_score
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
BASE_FALL_SPEED = 0.5 # Base fall speed in seconds
fall_speed = BASE_FALL_SPEED
lines_cleared = 0 # Initialize lines cleared counter
level = 1 # Initialize level
paused = False # Game paused state
the_music_started = False # To ensure music starts only once
# Variables for continuous movement
last_move_left = 0
last_move_right = 0
move_interval = 150 # milliseconds
while run:
grid = create_grid(locked_positions)
fall_time += clock.get_rawtime()
clock.tick()
# Calculate current level based on lines cleared
new_level = (lines_cleared // 10) + 1
if new_level != level:
level = new_level
# **Change 3: Increase speed by 15% on level change by decreasing fall_speed by ~15%**
fall_speed *= 0.85 # Decrease fall_speed to make pieces fall faster
# Adjust fall speed
current_fall_speed = fall_speed
keys = pygame.key.get_pressed()
if keys[pygame.K_DOWN]:
current_fall_speed = 0.05 # Fast fall when down key is held
if fall_time / 1000 >= current_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
MOVE_SOUND.play()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.display.quit()
sys.exit()
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
else:
MOVE_SOUND.play()
last_move_left = pygame.time.get_ticks()
elif event.key == pygame.K_RIGHT:
current_piece.x += 1
if not valid_space(current_piece, grid):
current_piece.x -= 1
else:
MOVE_SOUND.play()
last_move_right = pygame.time.get_ticks()
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 = (current_piece.rotation + 1) % len(current_piece.shape)
if not valid_space(current_piece, grid):
current_piece.rotation = (current_piece.rotation - 1) % len(current_piece.shape)
else:
ROTATE_SOUND.play()
elif event.key == pygame.K_SPACE:
paused = not paused # Toggle pause
if paused:
pygame.mixer.music.pause()
else:
pygame.mixer.music.unpause()
# Handle continuous left/right movement
current_time = pygame.time.get_ticks()
if keys[pygame.K_LEFT]:
if current_time - last_move_left > move_interval:
current_piece.x -= 1
if not valid_space(current_piece, grid):
current_piece.x += 1
else:
MOVE_SOUND.play()
last_move_left = current_time
if keys[pygame.K_RIGHT]:
if current_time - last_move_right > move_interval:
current_piece.x += 1
if not valid_space(current_piece, grid):
current_piece.x -= 1
else:
MOVE_SOUND.play()
last_move_right = current_time
if paused:
pause_screen(win)
pygame.time.delay(100) # Prevent high CPU usage while paused
continue # Skip the rest of the loop to effectively pause
shape_pos = convert_shape_format(current_piece)
# Add piece to the grid for drawing
for i in range(len(shape_pos)):
x, y = shape_pos[i]
if y > -1:
if 0 <= x < GRID_WIDTH and 0 <= y < GRID_HEIGHT:
grid[y][x] = current_piece.color
if change_piece:
for pos in shape_pos:
p = (pos[0], pos[1])
if 0 <= p[0] < GRID_WIDTH and 0 <= p[1] < GRID_HEIGHT:
locked_positions[p] = current_piece.color
current_piece = next_piece
next_piece = get_shape()
change_piece = False
cleared = clear_rows(grid, locked_positions)
lines_cleared += cleared # Update lines cleared
# **Immediate Loss Check After Spawning New Piece**
if not valid_space(current_piece, grid):
# **Trigger loss**
GAME_OVER_SOUND.play()
pygame.time.delay(500)
run = False
stop_background_music()
update_high_score_if_needed(lines_cleared)
# Start background music once when the game starts
if not the_music_started and not paused:
play_background_music()
the_music_started = True
draw_window(win, grid, lines_cleared, level, high_score)
draw_next_shape(next_piece, win)
pygame.display.update()
# **Optional: Remove this check if loss is already handled above**
# if check_lost(locked_positions):
# GAME_OVER_SOUND.play()
# pygame.time.delay(500)
# run = False
# stop_background_music()
# update_high_score_if_needed(lines_cleared)
# After the loop ends, show game over screen
game_over_screen(win, lines_cleared, high_score)
def update_high_score_if_needed(current_score):
global high_score
if current_score > high_score:
high_score = current_score
save_high_score(high_score)
def game_over_screen(surface, final_score, _):
global high_score
# Update high score if necessary
if final_score > high_score:
high_score = final_score
save_high_score(high_score)
pygame.mixer.music.stop() # Ensure music is stopped on game over
while True:
surface.fill((0, 0, 0))
draw_text_middle("YOU LOST!", 60, (255, 255, 255), surface, y_offset=-60)
# Display final score
font_small = pygame.font.SysFont('comicsans', 30)
score_label = font_small.render(f'Your Score: {final_score}', 1, (255, 255, 255))
high_label = font_small.render(f'High Score: {high_score}', 1, (255, 255, 255))
# **Adjust y positions to prevent overlapping**
surface.blit(score_label, ((SCREEN_WIDTH / 2) - (score_label.get_width() / 2), (SCREEN_HEIGHT / 2) - 40))
surface.blit(high_label, ((SCREEN_WIDTH / 2) - (high_label.get_width() / 2), (SCREEN_HEIGHT / 2) - 10))
# Prompt to return to menu
prompt_label = font_small.render('Press Space to return to the menu.', 1, (255, 255, 255))
surface.blit(prompt_label, ((SCREEN_WIDTH / 2) - (prompt_label.get_width() / 2), (SCREEN_HEIGHT / 2) + 20))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
main_menu() # Return to main menu
def update_high_score_if_needed(current_score):
global high_score
if current_score > high_score:
high_score = current_score
save_high_score(high_score)
def pause_screen(surface):
pause_font = pygame.font.SysFont('comicsans', 40, bold=True)
pause_label = pause_font.render('Game Paused', 1, (255, 255, 255))
prompt_font = pygame.font.SysFont('comicsans', 20)
prompt_label = prompt_font.render('Press Space to Resume', 1, (255, 255, 255))
surface.blit(pause_label, ((SCREEN_WIDTH / 2) - (pause_label.get_width() / 2), SCREEN_HEIGHT / 2 - 30))
surface.blit(prompt_label, ((SCREEN_WIDTH / 2) - (prompt_label.get_width() / 2), SCREEN_HEIGHT / 2 + 10))
pygame.display.update()
if __name__ == '__main__':
main_menu()
Summary of Changes
Spawn Position Adjustment:
Location:get_shape() function.
Change: Changed the y coordinate from 5 to 3 to spawn pieces two rows higher.
python
def get_shape():
# Spawn position adjusted to y=3
return Piece(GRID_WIDTH // 2, 3, random.choice(SHAPES))
Help Menu Font Size and Text Wrapping:
Location:help_menu() function.
Changes:
Reduced font size from 25 to 20 to prevent text overflow.
Implemented simple text wrapping for long lines to ensure they fit within the window.
python
font_help = pygame.font.SysFont('comicsans', 20) # Reduced from 25 to 20
Added a check to wrap text if the line length exceeds the screen width minus margins.
Fall Speed Increase on Level Change:
Location:main_game() function.
Change: Multiplied fall_speed by 0.85 instead of 1.15 to increase the speed by 15% (i.e., decrease the fall time).
python
if new_level != level:
level = new_level
# Decrease fall_speed by 15% to make pieces fall faster
fall_speed *= 0.85
Additional Notes
Duplicate help_menu() Function:
The original code had two definitions of the help_menu() function. Ensure that you remove any duplicate definitions to prevent unexpected behavior. In the provided updated code, only one help_menu() function is present with the necessary changes.
Text Wrapping in Help Menu:
For excessively long lines that might still potentially overflow, consider implementing more sophisticated text wrapping or reducing the text further.
Smooth Gameplay Experience:
Adjust the BASE_FALL_SPEED and the multiplier (0.85) as needed to achieve the desired difficulty progression. The current settings decrease the fall_speed by 15% each level, resulting in faster falling pieces.
Volume Control Stability:
Ensure that volume adjustments in the options_menu() are reflected immediately and smoothly during gameplay.
Feel free to further customize and enhance the game as per your requirements. Let me know if you need any more assistance!