Sure! Let's address each of your requested changes step by step and provide the updated code accordingly.
1. Reduce the Font Size of "Press Any Key To Play"
The oversized text "Press Any Key To Play" is causing it to overflow outside the window. We'll reduce the font size in the main_menu function.
2. Display the Number of Lines Completed
We'll introduce a lines_cleared counter to keep track of the number of lines cleared during the game and display it at the top left of the screen.
3. Increase Piece Fall Speed When Down Arrow is Held
To make the piece fall faster when the down arrow is held, we'll adjust the fall_speed dynamically based on whether the down key is pressed.
4. Fix the Width of the Last Column
It seems the last column might be incorrectly sized due to screen dimensions. We'll ensure the grid dimensions match the standard Tetris grid (10 columns by 20 rows) and adjust the screen size accordingly.
5. Standardize the Number of Columns
Standard Tetris has a grid of 10 columns and 20 rows. We'll modify the GRID_WIDTH to 10 and adjust SCREEN_WIDTH to accommodate both the grid and a side panel for displaying the next shape and score.
Updated Code with Changes
import pygame
import random
# Initialize Pygame
pygame.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
# Screen dimensions (grid + side panel)
SIDE_PANEL_WIDTH = 200
SCREEN_WIDTH = GRID_WIDTH * BLOCK_SIZE + SIDE_PANEL_WIDTH
SCREEN_HEIGHT = GRID_HEIGHT * BLOCK_SIZE
# 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
]
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 = [[(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 = []
shape = piece.shape[piece.rotation % len(piece.shape)]
for i, line in enumerate(shape):
row = list(line)
for j, column in enumerate(row):
if column == '0':
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] == (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):
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(text, size, color, surface):
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
))
def draw_grid(surface, grid):
for i in range(GRID_HEIGHT):
pygame.draw.line(surface, (128, 128, 128), (0, i * BLOCK_SIZE), (GRID_WIDTH * BLOCK_SIZE, i * BLOCK_SIZE))
for j in range(GRID_WIDTH):
pygame.draw.line(surface, (128, 128, 128), (j * BLOCK_SIZE, 0), (j * BLOCK_SIZE, GRID_HEIGHT * BLOCK_SIZE))
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:
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 = GRID_WIDTH * BLOCK_SIZE + 20 # Adjusted based on GRID_WIDTH
sy = 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 == '0':
pygame.draw.rect(surface, piece.color,
(sx + j * BLOCK_SIZE, sy + i * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)
surface.blit(label, (sx + 10, sy - 30))
def draw_window(surface, grid, lines_cleared):
surface.fill((0, 0, 0))
font = pygame.font.SysFont('comicsans', 60)
label = font.render('Tetris', 1, (255, 255, 255))
surface.blit(label, (SCREEN_WIDTH / 2 - label.get_width() / 2, 30))
# Display Lines Cleared at top left
font_small = pygame.font.SysFont('comicsans', 30)
label_lines = font_small.render(f'Lines: {lines_cleared}', 1, (255, 255, 255))
surface.blit(label_lines, (10, 10))
for i in range(len(grid)):
for j in range(len(grid[i])):
pygame.draw.rect(surface, grid[i][j],
(j * BLOCK_SIZE, i * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)
draw_grid(surface, grid)
pygame.draw.rect(surface, (255, 0, 0),
(0, 0, GRID_WIDTH * BLOCK_SIZE, GRID_HEIGHT * BLOCK_SIZE), 5)
def main():
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
fall_speed = 0.5 # Normal fall speed
fast_fall_speed = 0.05 # Faster fall speed when down is held
lines_cleared = 0 # Initialize lines cleared counter
while run:
grid = create_grid(locked_positions)
fall_time += clock.get_rawtime()
clock.tick()
keys = pygame.key.get_pressed()
if keys[pygame.K_DOWN]:
current_fall_speed = fast_fall_speed
else:
current_fall_speed = fall_speed
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
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 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
draw_window(win, grid, lines_cleared)
draw_next_shape(next_piece, win)
pygame.display.update()
if check_lost(locked_positions):
draw_text_middle("YOU LOST!", 60, (255, 255, 255), win) # Reduced font size
pygame.display.update()
pygame.time.delay(2000)
run = False
def main_menu():
run = True
while run:
win.fill((0, 0, 0))
draw_text_middle('Press Any Key To Play', 40, (255, 255, 255), win) # Reduced font size
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
main()
pygame.quit()
# Create the game window
win = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Tetris')
if __name__ == '__main__':
main_menu()
Explanation of Changes
-
Standardizing the Grid Dimensions
- GRID_WIDTH is set to
10 and GRID_HEIGHT to 20 to match the standard Tetris grid.
- SCREEN_WIDTH is calculated as
GRID_WIDTH * BLOCK_SIZE + SIDE_PANEL_WIDTH to include space for the side panel where the "Next Shape" and score will be displayed.
- SCREEN_HEIGHT remains
GRID_HEIGHT * BLOCK_SIZE for the grid.
-
Adjusting the Grid Creation
- In the
create_grid function, we ensure that locked positions are only added if they fall within the grid boundaries to prevent any drawing issues, especially with the last column.
-
Reducing Font Sizes
- In both
main_menu and game over screen ("YOU LOST!"), the font sizes have been reduced from 60 to 40 and 80 to 60, respectively, to prevent text overflow.
-
Displaying Lines Cleared
- Introduced a
lines_cleared variable in the main function to keep track of the number of lines cleared.
- Updated the
clear_rows function to return the number of lines cleared in a single operation, which is then added to lines_cleared.
- In the
draw_window function, the number of lines cleared is rendered at the top left corner.
-
Faster Fall When Down Arrow is Held
- Defined two fall speeds:
fall_speed for normal falling and fast_fall_speed for when the down arrow is held.
- In the game loop, checked if the down key is pressed using
pygame.key.get_pressed(). If it is, current_fall_speed is set to fast_fall_speed, making the piece fall faster.
-
Fixing the Last Column Width
- Ensured that the grid lines are drawn only within the grid area by modifying the
draw_grid function.
- Added a red border around the grid for better visualization.
-
Ensuring the Grid is Standard
- All grid-related calculations and drawings are now based on and , ensuring a standard Tetris experience.
Additional Recommendations
-
Score Tracking: You can enhance the game by adding more detailed scoring, such as points per line cleared and levels based on lines cleared.
-
Next Piece Display: Currently, only the next piece is displayed. Consider adding more information or animations to enhance the user experience.
-
Sound Effects and Music: Adding audio can greatly improve the gameplay experience.
-
Responsive Controls: Implement smooth movements and rotations by handling key presses more effectively, possibly with key repeat delays.
Feel free to further customize and enhance the game as per your preferences!