Sure! Let's go through each of your requests step by step, providing explanations and code modifications to enhance your Tetris game accordingly.
A. Ensure Multiple Lines are Counted When Collected
Issue: The current remove_complete_lines method may not correctly handle the removal and counting of multiple lines due to modifying the grid while iterating over it.
Solution: Modify the method to collect all the lines to be removed first and then remove them after the iteration. This ensures all complete lines are counted and removed correctly.
Code Modification:
def remove_complete_lines(self):
lines_cleared = 0
new_grid = []
for row in self.grid:
if not all(row):
new_grid.append(row)
else:
lines_cleared += 1
for _ in range(lines_cleared):
new_grid.insert(0, [0 for _ in range(GRID_WIDTH)])
self.grid = new_grid
self.score += lines_cleared ** 2 * 100
B. Add a Main Menu with a "Start Game" Button
Goal: Create a main menu screen that appears when the game starts, featuring a "Start Game" button centered on the screen.
Solution: Implement a game state system to manage different screens (menu, playing, paused, game over). Use the show_menu method to display the main menu and handle the button click to start the game.
Code Modifications:
Initialize the game state in the __init__ method:
self.game_state = 'menu' # Possible states: 'menu', 'playing', 'paused', 'game_over'
Implement the show_menu method:
def show_menu(self):
menu = True
while menu:
self.screen.fill(BLACK)
font = pygame.font.Font(None, 74)
title_text = font.render("Tetris", True, WHITE)
self.screen.blit(title_text, (SCREEN_WIDTH // 2 - title_text.get_width() // 2, SCREEN_HEIGHT // 4))
button_font = pygame.font.Font(None, 50)
button_text = button_font.render("Start Game", True, WHITE)
button_rect = button_text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2))
pygame.draw.rect(self.screen, WHITE, button_rect.inflate(20, 20), 2)
self.screen.blit(button_text, button_rect)
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
menu = False
self.game_over = True
if event.type == pygame.MOUSEBUTTONDOWN:
if button_rect.collidepoint(event.pos):
menu = False
self.game_state = 'playing'
self.clock.tick(60)
Modify the run method to handle game states:
def run(self):
fall_time = 0
normal_fall_speed = 0.5
fall_speed = normal_fall_speed
key_down_pressed = False
down_key_timer = 0
while not self.game_over:
if self.game_state == 'menu':
self.show_menu()
elif self.game_state == 'playing':
# Existing game loop code goes here...
elif self.game_state == 'paused':
# Implement paused state handling (see section H)
pass
elif self.game_state == 'game_over':
# Implement game over handling (see section E)
pass
C. Implement Delayed Fast Falling When Holding Down Key
Goal: When the down key is held for more than 0.15 seconds, the piece should start falling faster at a rate of 4 squares per second.
Solution: Track the duration the down key is held. After a 0.15-second delay, adjust the fall_speed to make the piece fall faster.
Code Modifications:
Initialize variables:
def run(self):
fall_time = 0
normal_fall_speed = 0.5 # Normal fall speed
fast_fall_speed = 0.25 # Fast fall speed (4 squares per second)
fall_speed = normal_fall_speed
key_down_pressed = False
down_key_timer = 0
Modify event handling:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_DOWN:
key_down_pressed = True
down_key_timer = 0 # Start timing
if event.type == pygame.KEYUP:
if event.key == pygame.K_DOWN:
key_down_pressed = False
down_key_timer = 0
fall_speed = normal_fall_speed
Adjust fall speed based on the down key:
if key_down_pressed:
down_key_timer += self.clock.get_time()
if down_key_timer >= 150: # After 0.15 seconds
fall_speed = fast_fall_speed
else:
fall_speed = normal_fall_speed
Update the falling logic:
fall_time += self.clock.get_rawtime()
self.clock.tick()
if fall_time > fall_speed * 1000:
if self.valid_move(self.current_piece, self.current_piece['x'], self.current_piece['y'] + 1):
self.current_piece['y'] += 1
else:
# Place piece and get new one
fall_time = 0
D. Display the Next 2 Pieces in the Queue During Gameplay
Goal: Show the current piece and the next two upcoming pieces to the right of the game grid.
Solution: Implement a queue system for pieces and display the next pieces using a new method draw_next_pieces.
Code Modifications:
Initialize the piece queue in __init__:
self.piece_queue = [self.create_random_piece() for _ in range(3)]
self.current_piece = self.piece_queue.pop(0)
Modify the piece generation methods:
def create_random_piece(self):
shape = random.choice(SHAPES)
color = random.choice(COLORS)
return {
'shape': shape,
'color': color,
'x': 0,
'y': 0
}
def get_next_piece(self):
next_piece = self.piece_queue.pop(0)
next_piece['x'] = GRID_WIDTH // 2 - len(next_piece['shape'][0]) // 2
next_piece['y'] = 0
self.piece_queue.append(self.create_random_piece())
return next_piece
Update the code where a new piece is needed:
self.current_piece = self.get_next_piece()
Implement the draw_next_pieces method:
def draw_next_pieces(self):
font = pygame.font.Font(None, 36)
next_text = font.render("Next:", True, WHITE)
self.screen.blit(next_text, (GRID_WIDTH * BLOCK_SIZE + 10, 100))
for index, piece in enumerate(self.piece_queue[:2]):
for i, row in enumerate(piece['shape']):
for j, cell in enumerate(row):
if cell:
pygame.draw.rect(
self.screen,
piece['color'],
(GRID_WIDTH * BLOCK_SIZE + 10 + j * BLOCK_SIZE,
130 + index * 100 + i * BLOCK_SIZE,
BLOCK_SIZE, BLOCK_SIZE)
)
pygame.draw.rect(
self.screen,
WHITE,
(GRID_WIDTH * BLOCK_SIZE + 10 + j * BLOCK_SIZE,
130 + index * 100 + i * BLOCK_SIZE,
BLOCK_SIZE, BLOCK_SIZE), 1
)
Call draw_next_pieces in the main loop:
self.draw_next_pieces()
E. Pause for 0.5 Seconds on Game Over Before Returning to Main Menu
Goal: When the player loses, pause the game for 0.5 seconds, display the "Game Over" message, and then return to the main menu.
Solution: Change the game state to 'game_over', implement a show_game_over method, and reset the game after displaying the message.
Code Modifications:
Set the game state to 'game_over' when the game is over:
if not self.valid_move(self.current_piece, self.current_piece['x'], self.current_piece['y']):
self.game_state = 'game_over'
Implement the show_game_over method:
def show_game_over(self):
self.screen.fill(BLACK)
font = pygame.font.Font(None, 74)
game_over_text = font.render("Game Over", True, RED)
self.screen.blit(
game_over_text,
(SCREEN_WIDTH // 2 - game_over_text.get_width() // 2,
SCREEN_HEIGHT // 2 - game_over_text.get_height() // 2)
)
pygame.display.flip()
pygame.time.delay(500)
self.reset_game()
self.game_state = 'menu'
Add a reset_game method to reset game variables:
def reset_game(self):
self.grid = [[0 for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]
self.piece_queue = [self.create_random_piece() for _ in range(3)]
self.current_piece = self.piece_queue.pop(0)
self.score = 0
self.total_lines_cleared = 0
self.hold_piece = None
self.hold_used = False
Update the run method to handle 'game_over' state:
elif self.game_state == 'game_over':
self.show_game_over()
F. Add a Hold Feature for the Current Piece
Goal: Allow players to hold the current piece in reserve and swap it out with the current piece during gameplay. Display the held piece on the top right.
Solution: Implement holding logic with hold_piece and hold_used variables. Update event handling to manage swaps, and display the held piece using draw_hold_piece.
Code Modifications:
Initialize hold variables in __init__:
self.hold_piece = None
self.hold_used = False
Implement the hold_piece_swap method:
def hold_piece_swap(self, current, hold):
current['x'] = GRID_WIDTH // 2 - len(current['shape'][0]) // 2
current['y'] = 0
if hold is None:
hold = current
current = self.get_next_piece()
else:
hold, current = current, hold
current['x'] = GRID_WIDTH // 2 - len(current['shape'][0]) // 2
current['y'] = 0
return current, hold
Modify event handling to listen for the hold action (e.g., pressing 'C'):
elif event.key == pygame.K_c:
if not self.hold_used:
self.current_piece, self.hold_piece = self.hold_piece_swap(self.current_piece, self.hold_piece)
self.hold_used = True
Reset hold_used after placing a piece:
self.place_piece(self.current_piece)
self.remove_complete_lines()
self.current_piece = self.get_next_piece()
self.hold_used = False # Allow holding again
Implement the draw_hold_piece method:
def draw_hold_piece(self):
font = pygame.font.Font(None, 36)
hold_text = font.render("Hold:", True, WHITE)
self.screen.blit(hold_text, (GRID_WIDTH * BLOCK_SIZE + 10, 10))
if self.hold_piece:
for i, row in enumerate(self.hold_piece['shape']):
for j, cell in enumerate(row):
if cell:
pygame.draw.rect(
self.screen,
self.hold_piece['color'],
(GRID_WIDTH * BLOCK_SIZE + 10 + j * BLOCK_SIZE,
40 + i * BLOCK_SIZE,
BLOCK_SIZE, BLOCK_SIZE)
)
pygame.draw.rect(
self.screen,
WHITE,
(GRID_WIDTH * BLOCK_SIZE + 10 + j * BLOCK_SIZE,
40 + i * BLOCK_SIZE,
BLOCK_SIZE, BLOCK_SIZE), 1
)
Call draw_hold_piece in the main loop:
self.draw_hold_piece()
G. Adapt Items B and F for Mobile Devices with Touch Controls
Goal: Make the main menu and hold feature accessible on mobile devices, and adapt controls for touch input.
Solution: Implement on-screen buttons that respond to touch input. Map touch events to game actions, and adjust the UI to be touch-friendly.
Code Modifications:
Define button rectangles in __init__:
self.left_button_rect = pygame.Rect(10, SCREEN_HEIGHT - 60, 50, 50)
self.right_button_rect = pygame.Rect(70, SCREEN_HEIGHT - 60, 50, 50)
self.rotate_button_rect = pygame.Rect(SCREEN_WIDTH - 60, SCREEN_HEIGHT - 120, 50, 50)
self.down_button_rect = pygame.Rect(SCREEN_WIDTH - 60, SCREEN_HEIGHT - 60, 50, 50)
self.hold_button_rect = pygame.Rect(SCREEN_WIDTH - 60, 10, 50, 50)
self.pause_button_rect = pygame.Rect(SCREEN_WIDTH - 60, 70, 50, 50)
Handle touch input in the run method:
if event.type == pygame.MOUSEBUTTONDOWN:
pos = event.pos
if self.left_button_rect.collidepoint(pos):
if self.valid_move(self.current_piece, self.current_piece['x'] - 1, self.current_piece['y']):
self.current_piece['x'] -= 1
elif self.right_button_rect.collidepoint(pos):
if self.valid_move(self.current_piece, self.current_piece['x'] + 1, self.current_piece['y']):
self.current_piece['x'] += 1
elif self.rotate_button_rect.collidepoint(pos):
rotated_piece = self.rotate_piece(self.current_piece)
if self.valid_move(rotated_piece, rotated_piece['x'], rotated_piece['y']):
self.current_piece = rotated_piece
elif self.down_button_rect.collidepoint(pos):
if self.valid_move(self.current_piece, self.current_piece['x'], self.current_piece['y'] + 1):
self.current_piece['y'] += 1
elif self.hold_button_rect.collidepoint(pos):
if not self.hold_used:
self.current_piece, self.hold_piece = self.hold_piece_swap(self.current_piece, self.hold_piece)
self.hold_used = True
elif self.pause_button_rect.collidepoint(pos):
self.game_state = 'paused'
Implement the draw_buttons method to display on-screen buttons:
def draw_buttons(self):
# Draw left button
pygame.draw.rect(self.screen, WHITE, self.left_button_rect)
left_text = pygame.font.Font(None, 36).render("<", True, BLACK)
self.screen.blit(left_text, (self.left_button_rect.x + 15, self.left_button_rect.y + 5))
# Draw right button
pygame.draw.rect(self.screen, WHITE, self.right_button_rect)
right_text = pygame.font.Font(None, 36).render(">", True, BLACK)
self.screen.blit(right_text, (self.right_button_rect.x + 15, self.right_button_rect.y + 5))
# Draw rotate button
pygame.draw.rect(self.screen, WHITE, self.rotate_button_rect)
rotate_text = pygame.font.Font(None, 24).render("Rotate", True, BLACK)
self.screen.blit(rotate_text, (self.rotate_button_rect.x + 5, self.rotate_button_rect.y + 15))
# Draw down button
pygame.draw.rect(self.screen, WHITE, self.down_button_rect)
down_text = pygame.font.Font(None, 36).render("v", True, BLACK)
self.screen.blit(down_text, (self.down_button_rect.x + 15, self.down_button_rect.y + 5))
# Draw hold button
pygame.draw.rect(self.screen, WHITE, self.hold_button_rect)
hold_text = pygame.font.Font(None, 24).render("Hold", True, BLACK)
self.screen.blit(hold_text, (self.hold_button_rect.x + 5, self.hold_button_rect.y + 15))
# Draw pause button
pygame.draw.rect(self.screen, WHITE, self.pause_button_rect)
pause_text = pygame.font.Font(None, 24).render("Pause", True, BLACK)
self.screen.blit(pause_text, (self.pause_button_rect.x + 5, self.pause_button_rect.y + 15))
Call draw_buttons in the main loop:
self.draw_buttons()
H. Add a Pause Button in the Upper Right Corner
Goal: Implement a pause functionality accessible via a button in the upper right corner.
Solution: Use the pause button implemented in the previous step. Handle game state changes when the pause button is pressed, and display a pause screen.
Code Modifications:
Handle pause button in event handling:
elif event.key == pygame.K_p or self.pause_button_rect.collidepoint(event.pos):
if self.game_state == 'playing':
self.game_state = 'paused'
elif self.game_state == 'paused':
self.game_state = 'playing'
Implement the show_pause_screen method:
def show_pause_screen(self):
paused = True
while paused:
self.screen.fill(BLACK)
font = pygame.font.Font(None, 74)
pause_text = font.render("Paused", True, WHITE)
self.screen.blit(
pause_text,
(SCREEN_WIDTH // 2 - pause_text.get_width() // 2,
SCREEN_HEIGHT // 2 - pause_text.get_height() // 2)
)
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
paused = False
self.game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_p:
paused = False
self.game_state = 'playing'
elif event.type == pygame.MOUSEBUTTONDOWN:
if self.pause_button_rect.collidepoint(event.pos):
paused = False
self.game_state = 'playing'
self.clock.tick(60)
Update the run method to handle 'paused' state:
elif self.game_state == 'paused':
self.show_pause_screen()
I. Increase Game Speed by 1.005x for Every Line Collected
Goal: Make the game progressively faster by increasing the speed by 0.5% for each line cleared.
Solution: Adjust the fall_speed based on the total number of lines cleared using an exponential formula.
Code Modifications:
Initialize total_lines_cleared in __init__:
self.total_lines_cleared = 0
Update remove_complete_lines method to track total lines cleared:
def remove_complete_lines(self):
lines_cleared = 0
new_grid = []
for row in self.grid:
if not all(row):
new_grid.append(row)
else:
lines_cleared += 1
for _ in range(lines_cleared):
new_grid.insert(0, [0 for _ in range(GRID_WIDTH)])
self.grid = new_grid
self.score += lines_cleared ** 2 * 100
self.total_lines_cleared += lines_cleared
Adjust fall_speed based on total_lines_cleared:
fall_speed = normal_fall_speed / (1.005 ** self.total_lines_cleared)
Place this line after updating the fall_speed variable in the main loop, ensuring it gets updated each loop iteration.
By implementing these modifications, your Tetris game will have enhanced functionality, including proper line counting, a main menu, delayed fast falling, next piece display, game over handling, hold feature, mobile touch controls, a pause button, and dynamic game speed. Remember to test each feature thoroughly to ensure they work together seamlessly.
If you have any questions or need further assistance with any of these steps, feel free to ask!