reworked the code structure for better feature implementation
This commit is contained in:
+142
@@ -0,0 +1,142 @@
|
||||
import pygame as pg
|
||||
from game.settings import *
|
||||
from game.game_manager import Grid
|
||||
from game.util import draw_text, get_fall_interval
|
||||
from game.tetrominos import Tetrominos
|
||||
import game.settings as settings
|
||||
import sys
|
||||
|
||||
|
||||
class Game:
|
||||
def __init__(self, screen, clock):
|
||||
self.screen = screen
|
||||
self.clock = clock
|
||||
self.width, self.height = self.screen.get_size()
|
||||
|
||||
self.grid_surface = pg.Surface((g_width, g_height))
|
||||
|
||||
self.next_surface = pg.Surface((150, 150))
|
||||
self.hold_surface = pg.Surface((150, 150))
|
||||
|
||||
self.game_grid = Grid(rows, cols, cell_size)
|
||||
|
||||
self.current_tetromino = Tetrominos(cols, cell_size)
|
||||
self.next_tetromino = Tetrominos(cols, cell_size)
|
||||
self.hold_tetromino = None
|
||||
|
||||
self.hold_used = False # Flag to track if hold has been used for the current tetromino
|
||||
|
||||
self.fall_timer = 0
|
||||
self.move_timer = 0
|
||||
self.move_interval = 100
|
||||
|
||||
def run(self):
|
||||
"""Main game loop."""
|
||||
self.playing = True
|
||||
while self.playing:
|
||||
self.clock.tick(fps)
|
||||
self.handle_events()
|
||||
self.update()
|
||||
self.draw()
|
||||
|
||||
def handle_events(self):
|
||||
"""Handle user input and events."""
|
||||
for event in pg.event.get():
|
||||
if event.type == pg.QUIT:
|
||||
sys.exit()
|
||||
elif event.type == pg.KEYDOWN:
|
||||
if event.key == pg.K_UP:
|
||||
rotated_shape = [list(row) for row in zip(*self.current_tetromino.shape[::-1])]
|
||||
if not self.game_grid.check_collision(rotated_shape, self.current_tetromino.x, self.current_tetromino.y):
|
||||
self.current_tetromino.shape = rotated_shape # Apply rotation
|
||||
elif event.key == pg.K_SPACE:
|
||||
self.current_tetromino.instant_drop(self.game_grid) # Perform instant drop
|
||||
self.lock_tetromino()
|
||||
elif event.key == pg.K_c:
|
||||
self.handle_hold()
|
||||
elif event.key == pg.K_ESCAPE: # Pause the game
|
||||
self.playing = False
|
||||
|
||||
def update(self):
|
||||
"""Update the game state."""
|
||||
current_time = pg.time.get_ticks()
|
||||
fall_interval = get_fall_interval(settings.game_score)
|
||||
|
||||
keys = pg.key.get_pressed()
|
||||
|
||||
if keys[pg.K_RIGHT]:
|
||||
if current_time - self.move_timer > self.move_interval: # Ensure delay between movements
|
||||
if not self.game_grid.check_collision(self.current_tetromino.shape, self.current_tetromino.x + 1, self.current_tetromino.y):
|
||||
self.current_tetromino.move(1, 0) # Move right
|
||||
self.move_timer = current_time # Reset timer
|
||||
elif keys[pg.K_LEFT]:
|
||||
if current_time - self.move_timer > self.move_interval: # Ensure delay between movements
|
||||
if not self.game_grid.check_collision(self.current_tetromino.shape, self.current_tetromino.x - 1, self.current_tetromino.y):
|
||||
self.current_tetromino.move(-1, 0) # Move left
|
||||
self.move_timer = current_time # Reset timer
|
||||
|
||||
# Handle automatic falling based on timer
|
||||
if current_time - self.fall_timer > fall_interval:
|
||||
if not self.game_grid.check_collision(self.current_tetromino.shape, self.current_tetromino.x, self.current_tetromino.y + 1):
|
||||
self.current_tetromino.move(0, 1) # Move down
|
||||
else:
|
||||
self.lock_tetromino()
|
||||
|
||||
self.fall_timer = current_time
|
||||
|
||||
def draw(self):
|
||||
"""Render the game elements."""
|
||||
self.screen.fill((138, 138, 138))
|
||||
self.grid_surface.fill((87, 87, 87))
|
||||
|
||||
# Draw the grid and tetromino
|
||||
self.game_grid.draw_grid(self.grid_surface)
|
||||
self.current_tetromino.draw(self.grid_surface)
|
||||
|
||||
# Draw next and hold previews
|
||||
self.next_surface.fill((0, 0, 0))
|
||||
self.next_tetromino.draw_next_tetromino(self.next_surface)
|
||||
|
||||
self.hold_surface.fill((0, 0, 0))
|
||||
if self.hold_tetromino:
|
||||
self.hold_tetromino.draw_next_tetromino(self.hold_surface)
|
||||
|
||||
# Draw score
|
||||
draw_text(self.screen, f'Score: {settings.game_score}', 30, self.width - 75, 100, (255, 255, 255))
|
||||
|
||||
# Render surfaces
|
||||
self.screen.blit(self.grid_surface, (0, 0))
|
||||
self.screen.blit(self.next_surface, (self.width - 150, 200))
|
||||
self.screen.blit(self.hold_surface, (self.width - 150, 400))
|
||||
|
||||
pg.display.update()
|
||||
|
||||
def lock_tetromino(self):
|
||||
"""Lock the current tetromino in place and spawn a new one."""
|
||||
self.game_grid.add_tetromino(self.current_tetromino)
|
||||
self.game_grid.check_full_row()
|
||||
self.current_tetromino = self.next_tetromino
|
||||
self.next_tetromino = Tetrominos(cols, cell_size)
|
||||
self.hold_used = False
|
||||
|
||||
# Check for game over
|
||||
if self.game_grid.check_collision(self.current_tetromino.shape, self.current_tetromino.x, self.current_tetromino.y):
|
||||
self.show_game_over()
|
||||
|
||||
def handle_hold(self):
|
||||
"""Handle the hold tetromino functionality."""
|
||||
if not self.hold_used:
|
||||
if self.hold_tetromino is None:
|
||||
self.hold_tetromino = self.current_tetromino
|
||||
self.current_tetromino = self.next_tetromino
|
||||
self.next_tetromino = Tetrominos(cols, cell_size)
|
||||
else:
|
||||
self.hold_tetromino, self.current_tetromino = self.current_tetromino, self.hold_tetromino
|
||||
self.current_tetromino.x = cols // 2
|
||||
self.current_tetromino.y = 0
|
||||
self.hold_used = True
|
||||
|
||||
def show_game_over(self):
|
||||
"""Handle game over screen."""
|
||||
settings.gamestate = False
|
||||
self.playing = False
|
||||
@@ -0,0 +1,59 @@
|
||||
import pygame
|
||||
import game.settings as settings
|
||||
|
||||
class Grid():
|
||||
def __init__(self, rows, cols, cell_size):
|
||||
self.cell_size = cell_size
|
||||
self.rows = rows
|
||||
self.cols = cols
|
||||
self.grid = [[0 for j in range(self.cols)] for k in range(self.rows)]
|
||||
|
||||
def draw_grid(self, surface):
|
||||
for row in range(self.rows):
|
||||
for col in range(self.cols):
|
||||
cell_value = self.grid[row][col]
|
||||
color = (0, 0, 0) if cell_value == 0 else (255, 0, 0) # Black for empty, red for filled
|
||||
cell_rect = pygame.Rect(
|
||||
col * self.cell_size + 1,
|
||||
row * self.cell_size + 1,
|
||||
self.cell_size - 2,
|
||||
self.cell_size - 2
|
||||
)
|
||||
pygame.draw.rect(surface, color, cell_rect)
|
||||
|
||||
def add_tetromino(self, tetromino):
|
||||
"""Lock the tetromino into the grid."""
|
||||
for row_idx, row in enumerate(tetromino.shape):
|
||||
for col_idx, cell in enumerate(row):
|
||||
if cell: # Only lock non-empty cells
|
||||
grid_x = tetromino.x + col_idx
|
||||
grid_y = tetromino.y + row_idx
|
||||
if 0 <= grid_y < self.rows and 0 <= grid_x < self.cols:
|
||||
self.grid[grid_y][grid_x] = 1
|
||||
|
||||
def check_collision(self, shape, x, y):
|
||||
"""Check if the tetromino collides with the grid or boundaries."""
|
||||
for row_idx, row in enumerate(shape):
|
||||
for col_idx, cell in enumerate(row):
|
||||
if cell: # Only check cells that are part of the tetromino
|
||||
grid_x = x + col_idx
|
||||
grid_y = y + row_idx
|
||||
|
||||
# Check bounds
|
||||
if grid_x < 0 or grid_x >= self.cols or grid_y >= self.rows:
|
||||
return True
|
||||
|
||||
# Check if cell is already occupied
|
||||
if grid_y >= 0 and self.grid[grid_y][grid_x] != 0:
|
||||
return True
|
||||
|
||||
def check_full_row(self):
|
||||
"""Check for and clear any full rows."""
|
||||
new_grid = [row for row in self.grid if not all(cell == 1 for cell in row)]
|
||||
cleared_rows = len(self.grid) - len(new_grid)
|
||||
self.grid = [[0] * self.cols for _ in range(cleared_rows)] + new_grid
|
||||
|
||||
if cleared_rows >= 4:
|
||||
settings.game_score += 100 * cleared_rows * 2
|
||||
else:
|
||||
settings.game_score += 100 * cleared_rows
|
||||
@@ -0,0 +1,82 @@
|
||||
import pygame as pg
|
||||
from game.settings import *
|
||||
from game.util import draw_text
|
||||
import sys
|
||||
|
||||
|
||||
class StartMenu:
|
||||
|
||||
def __init__(self, screen, clock):
|
||||
self.screen = screen
|
||||
self.clock = clock
|
||||
self.screen_size = self.screen.get_size()
|
||||
|
||||
|
||||
def run(self):
|
||||
self.menu_running = True
|
||||
while self.menu_running:
|
||||
self.clock.tick(60)
|
||||
self.update()
|
||||
self.draw()
|
||||
return True
|
||||
|
||||
def update(self):
|
||||
|
||||
for event in pg.event.get():
|
||||
if event.type == pg.QUIT:
|
||||
pg.quit()
|
||||
sys.exit()
|
||||
if event.type == pg.KEYDOWN:
|
||||
if event.key == pg.K_RETURN:
|
||||
self.menu_running = False
|
||||
if event.key == pg.K_ESCAPE:
|
||||
pg.quit()
|
||||
sys.exit()
|
||||
|
||||
def draw(self):
|
||||
self.screen.fill((0, 0, 0))
|
||||
|
||||
draw_text(self.screen, "TETRIS", 50, width // 2, HEIGHT // 2 - 50, (255, 255, 255))
|
||||
draw_text(self.screen, "Press ENTER to Start", 30, width // 2, HEIGHT // 2 + 50, (200, 200, 200))
|
||||
pg.display.update()
|
||||
|
||||
|
||||
class GameMenu:
|
||||
def __init__(self, screen, clock):
|
||||
self.screen = screen
|
||||
self.clock = clock
|
||||
self.screen_size = self.screen.get_size()
|
||||
self.playing = True
|
||||
|
||||
def run(self):
|
||||
self.menu_running = True
|
||||
while self.menu_running:
|
||||
self.clock.tick(60)
|
||||
self.update()
|
||||
self.draw()
|
||||
return self.playing
|
||||
|
||||
def update(self):
|
||||
for event in pg.event.get():
|
||||
if event.type == pg.QUIT:
|
||||
pg.quit()
|
||||
sys.exit()
|
||||
if event.type == pg.KEYDOWN:
|
||||
if event.key == pg.K_RETURN:
|
||||
self.menu_running = False
|
||||
if event.key == pg.K_ESCAPE:
|
||||
self.playing = False
|
||||
self.menu_running = False
|
||||
|
||||
def draw(self):
|
||||
|
||||
self.screen.fill((0, 0, 0))
|
||||
|
||||
if gamestate:
|
||||
draw_text(self.screen, "Game Paused", 50, width // 2, HEIGHT // 2 - 50, (255, 255, 255))
|
||||
draw_text(self.screen, "Press ESC to Resume", 30, width // 2, HEIGHT // 2 + 10, (200, 200, 200))
|
||||
else:
|
||||
draw_text(self.screen, "Game Over", 50, WIDTH // 2, HEIGHT // 2 - 50, (255, 0, 0))
|
||||
draw_text(self.screen, "Press Enter to Restart", 30, WIDTH // 2, HEIGHT // 2 + 50, (200, 200, 200))
|
||||
|
||||
pg.display.update()
|
||||
@@ -0,0 +1,23 @@
|
||||
# Variables
|
||||
|
||||
#screen size
|
||||
global height, width
|
||||
height, width = 600, 450
|
||||
|
||||
#grid surface
|
||||
g_height, g_width = 600, 300
|
||||
|
||||
#start surface size
|
||||
HEIGHT, WIDTH = 600, 300
|
||||
|
||||
#score
|
||||
game_score = 0
|
||||
|
||||
rows = 20
|
||||
cols = 10
|
||||
cell_size = 30
|
||||
|
||||
fps = 60
|
||||
|
||||
global gamestate # Add game state variable
|
||||
gamestate = True
|
||||
@@ -0,0 +1,83 @@
|
||||
import random
|
||||
import pygame
|
||||
|
||||
def set_color():
|
||||
yellow = (255, 255, 0)
|
||||
violet = (204, 0, 204)
|
||||
green = (0, 153, 0)
|
||||
orange = (255, 153, 0)
|
||||
light_blue = (0, 255, 255)
|
||||
red = (255, 0, 0)
|
||||
blue = (0, 0, 255)
|
||||
colors = [yellow, violet, green, orange, light_blue, red, blue]
|
||||
return colors
|
||||
|
||||
|
||||
class Tetrominos:
|
||||
SHAPES = [
|
||||
[[1, 1, 1, 1]], # I-shape
|
||||
[[1, 1], [1, 1]], # O-shape
|
||||
[[0, 1, 0], [1, 1, 1]], # T-shape
|
||||
[[1, 0, 0], [1, 1, 1]], # L-shape
|
||||
[[0, 0, 1], [1, 1, 1]], # J-shape
|
||||
[[0, 1, 1], [1, 1, 0]], # S-shape
|
||||
[[1, 1, 0], [0, 1, 1]], # Z-shape
|
||||
]
|
||||
|
||||
def __init__(self, cols, cell_size):
|
||||
self.cell_size = cell_size
|
||||
self.shape_number = random.choice([1, 2, 3, 4, 5, 6, 7]) # Randomly pick a shape
|
||||
self.shape = self.SHAPES[self.shape_number - 1]
|
||||
self.colors = set_color()
|
||||
self.x = cols // 2 - len(self.shape[0]) // 2 # Center horizontally
|
||||
self.y = 0 # Start at the top
|
||||
|
||||
|
||||
|
||||
def draw(self, screen):
|
||||
"""Draw the tetromino on the screen."""
|
||||
for row_idx, row in enumerate(self.shape):
|
||||
for col_idx, cell in enumerate(row):
|
||||
if cell: # Draw only if the cell is part of the tetromino
|
||||
x = (self.x + col_idx) * self.cell_size + 1
|
||||
y = (self.y + row_idx) * self.cell_size + 1
|
||||
pygame.draw.rect(
|
||||
screen,
|
||||
self.colors[self.shape_number - 1],
|
||||
pygame.Rect(x, y, self.cell_size - 2, self.cell_size - 2)
|
||||
)
|
||||
|
||||
def rotate(self):
|
||||
"""Rotate the tetromino shape clockwise."""
|
||||
self.shape = [list(row) for row in zip(*self.shape[::-1])]
|
||||
|
||||
def move(self, dx, dy):
|
||||
"""Move the tetromino."""
|
||||
self.x += dx
|
||||
self.y += dy
|
||||
|
||||
def instant_drop(self, grid):
|
||||
"""Move the tetromino to the lowest possible position."""
|
||||
while not grid.check_collision(self.shape, self.x, self.y + 1):
|
||||
self.y += 1
|
||||
|
||||
def draw_next_tetromino(self, surface):
|
||||
"""
|
||||
Draw the next tetromino in the preview window.
|
||||
"""
|
||||
surface.fill((0, 0, 0))
|
||||
|
||||
cell_size = 30 # Smaller cell size for the preview
|
||||
x_offset = (surface.get_width() - len(self.shape[0]) * cell_size) // 2
|
||||
y_offset = (surface.get_height() - len(self.shape) * cell_size) // 2
|
||||
|
||||
for row_idx, row in enumerate(self.shape):
|
||||
for col_idx, cell in enumerate(row):
|
||||
if cell:
|
||||
cell_rect = pygame.Rect(
|
||||
x_offset + col_idx * cell_size,
|
||||
y_offset + row_idx * cell_size,
|
||||
cell_size,
|
||||
cell_size
|
||||
)
|
||||
pygame.draw.rect(surface, self.colors[self.shape_number - 1], cell_rect) # Red color for tetromino
|
||||
@@ -0,0 +1,23 @@
|
||||
import pygame
|
||||
|
||||
def get_fall_interval(score):
|
||||
"""
|
||||
Calculate the fall interval based on the current score.
|
||||
"""
|
||||
base_interval = 1000 # Base interval in milliseconds
|
||||
decrease_per_1000_points = 50 # Decrease in ms per 1000 points
|
||||
min_interval = 100 # Minimum interval in milliseconds
|
||||
|
||||
# Calculate the fall interval
|
||||
interval = base_interval - (score // 400) * decrease_per_1000_points
|
||||
|
||||
# Ensure the interval doesn't go below the minimum
|
||||
return max(interval, min_interval)
|
||||
|
||||
#game states
|
||||
def draw_text(surface, text, size, x, y, color):
|
||||
"""Utility function to render text onto a surface."""
|
||||
font = pygame.font.Font(None, size) # Use default font
|
||||
text_surface = font.render(text, True, color)
|
||||
text_rect = text_surface.get_rect(center=(x, y))
|
||||
surface.blit(text_surface, text_rect)
|
||||
Reference in New Issue
Block a user