Compare commits

7 Commits

Author SHA1 Message Date
ScriptSorcerer 18d3d65ab4 Update README.md 2025-03-18 11:22:33 +01:00
IM23a-bachmannj2 340995910a animation somewhat added 2025-02-26 15:27:08 +01:00
IM23a-bachmannj2 2369c8b2da Leaderboard implemted +- 2025-02-04 10:57:54 +01:00
IM23a-bachmannj2 16c1ef8dd6 implemented xustom keybinds 2025-02-02 21:36:32 +01:00
IM23a-bachmannj2 fc31ab5912 start of Menu implementation 2025-02-02 09:16:50 +01:00
IM23a-bachmannj2 b8887598d4 implemented ghost tetrominos and made some optimisation (gamescore and visually) 2025-01-29 14:31:41 +01:00
IM23a-bachmannj2 9e419baedd reworked the code structure for better feature implementation 2025-01-28 18:40:20 +01:00
14 changed files with 745 additions and 284 deletions
BIN
View File
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

+172
View File
@@ -0,0 +1,172 @@
import pygame as pg
from game.settings import *
from game.game_manager import Grid
from game.util.util import *
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.ghost_tetromino = Tetrominos(cols, cell_size)
self.next_tetromino = Tetrominos(cols, cell_size)
self.hold_tetromino = None
self.hold_used = False
self.fall_timer = 0
self.move_timer = 0
self.move_interval = 100
self.playing = None
self.control_handler = settings.control_handler
def run(self):
"""Main game loop."""
self.playing = True
if not settings.gamestate:
self.game_grid = Grid(rows, cols, cell_size)
settings.game_score = 0
settings.gamestate = 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 == self.control_handler.controls['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 == self.control_handler.controls['Hold']:
self.handle_hold()
elif event.key == pg.K_ESCAPE: # Pause the game
self.playing = False
def update(self):
"""Update the game state."""
if self.game_grid.cleared_rows: # If an animation is running, wait before dropping pieces
return # Skip movement updates
current_time = pg.time.get_ticks()
fall_interval = get_fall_interval(settings.game_score)
keys = pg.key.get_pressed()
if keys[self.control_handler.controls['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[self.control_handler.controls['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
elif keys[self.control_handler.controls['Down']]:
fall_interval = 40
# 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
self.update_ghost_tetromino()
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.ghost_tetromino.draw_ghost_tetromino(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}', get_font(20), self.width - 150, 100, (255, 255, 255))
# Render surfaces
self.screen.blit(self.grid_surface, (settings.width // 2 - 150, 50))
self.game_grid.animate_line_clear(self.screen)
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 update_ghost_tetromino(self):
self.ghost_tetromino.shape = self.current_tetromino.shape
self.ghost_tetromino.x = self.current_tetromino.x
self.ghost_tetromino.y = self.current_tetromino.y
while not self.game_grid.check_collision(self.ghost_tetromino.shape, self.ghost_tetromino.x, self.ghost_tetromino.y + 1):
self.ghost_tetromino.y += 1
def show_game_over(self):
"""Handle game over screen."""
add_score("gamescore.json", settings.game_score)
settings.gamestate = False
self.playing = False
+115
View File
@@ -0,0 +1,115 @@
import pygame
from game.tetrominos import set_color
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.color = set_color()
self.grid = [[0 for j in range(self.cols)] for k in range(self.rows)]
self.cleared_rows = []
def draw_grid(self, surface):
for row in range(self.rows):
for col in range(self.cols):
cell_value = self.grid[row][col]
if cell_value == 0:
color = (0, 0, 0)
elif cell_value == 1:
color = self.color[0]
elif cell_value == 2:
color = self.color[1]
elif cell_value == 3:
color = self.color[2]
elif cell_value == 4:
color = self.color[3]
elif cell_value == 5:
color = self.color[4]
elif cell_value == 6:
color = self.color[5]
else:
color = self.color[6]
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] = tetromino.shape_number
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 store full rows for animation before clearing them."""
self.cleared_rows = [i for i, row in enumerate(self.grid) if all(cell != 0 for cell in row)]
if self.cleared_rows:
self.clearing_animation_timer = pygame.time.get_ticks() # Start animation timer
def animate_line_clear(self, screen):
"""Handles the visual effect when clearing rows."""
if not self.cleared_rows:
return
elapsed_time = pygame.time.get_ticks() - self.clearing_animation_timer
if elapsed_time < 500: # Animation lasts 500ms
fade_alpha = int(255 * (1 - elapsed_time / 500)) # Fading effect
if elapsed_time > 400:
fade_color = (0, 0, 0, fade_alpha) # White fading color
elif elapsed_time > 300:
fade_color = (100, 100, 100, fade_alpha)
elif elapsed_time > 200:
fade_color = (150, 150, 150, fade_alpha)
elif elapsed_time > 100:
fade_color = (200, 200, 200, fade_alpha)
else:
fade_color = (255, 255, 255, fade_alpha)
for row in self.cleared_rows:
for col in range(self.cols):
rect = pygame.Rect(col * self.cell_size + settings.width // 2 -150, row * self.cell_size +50, self.cell_size, self.cell_size)
pygame.draw.rect(screen, fade_color[:3], rect)
pygame.draw.rect(screen, (0, 0, 0), rect, 1)
else:
self.clear_rows() # Remove rows after animation is complete
def clear_rows(self):
"""Removes full rows after the animation finishes."""
new_grid = [row for i, row in enumerate(self.grid) if i not in self.cleared_rows]
cleared_count = len(self.cleared_rows)
# Add empty rows at the top
self.grid = [[0] * self.cols for _ in range(cleared_count)] + new_grid
score_table = {1: 100, 2: 300, 3: 500, 4: 800}
settings.game_score += score_table.get(len(self.cleared_rows), 0)
self.cleared_rows = [] # Reset after clearing
+176
View File
@@ -0,0 +1,176 @@
import pygame as pg
import game.settings as setting
from game.util.button import Button
from game.util.util import *
import sys
class StartMenu:
def __init__(self, screen, clock):
self.menu_running = None
self.screen = screen
self.clock = clock
self.screen_size = self.screen.get_size()
self.mouse_pos = pg.mouse.get_pos()
self.score = load_score("gamescore.json")
self.option = False
self.options_menu = OptionMenu(self.screen, self.clock)
def run(self):
self.menu_running = True
while self.menu_running:
self.clock.tick(60)
self.update()
self.draw()
return True
def update(self):
self.mouse_pos = pg.mouse.get_pos()
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()
if event.type == pg.MOUSEBUTTONDOWN:
if self.play.checkForInput(self.mouse_pos):
self.menu_running = False
if self.options.checkForInput(self.mouse_pos):
self.option = True
while self.option:
self.option = self.options_menu.run()
if self.quit.checkForInput(self.mouse_pos):
pg.quit()
sys.exit()
def draw(self):
self.screen.blit(get_background())
self.play = Button(image=None, pos=(setting.width // 2, setting.height // 3), text_input="Play", font=get_font(50), base_color=(255, 255, 255), hovering_color=(200, 200, 200))
self.play.changeColor(self.mouse_pos)
self.quit = Button(image=None, pos=(setting.width // 2, setting.height // 3 * 2), text_input="Quit", font=get_font(50), base_color=(255, 255, 255), hovering_color=(200, 200, 200))
self.quit.changeColor(self.mouse_pos)
self.options = Button(image=None, pos=(setting.width // 2, setting.height // 2), text_input="Options", font=get_font(50), base_color=(255, 255, 255), hovering_color=(200, 200, 200))
self.options.changeColor(self.mouse_pos)
draw_text(self.screen, "TETRIS", get_font(30), setting.width // 2, setting.height // 3 - 50, (255, 255, 255))
position = 0
count = 1
for item in self.score["score"]:
draw_text(self.screen, f"{count}: {item}", get_font(30), setting.width // 5, setting.height // 3 - 50 + position, (255, 255, 255))
position += 50
count += 1
self.score = load_score("gamescore.json")
self.play.update(self.screen)
self.options.update(self.screen)
self.quit.update(self.screen)
pg.display.update()
class GameMenu:
def __init__(self, screen, clock):
self.menu_running = None
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 setting.gamestate:
draw_text(self.screen, "Game Paused", get_font(50), setting.width // 2, setting.height // 2 - 50, (255, 255, 255))
draw_text(self.screen, "Press ESC to Resume", get_font(30), setting.width // 2, setting.height // 2 + 10, (200, 200, 200))
else:
draw_text(self.screen, "Game Over", get_font(50), setting.width // 2, setting.height // 2 - 50, (255, 0, 0))
draw_text(self.screen, "Press Enter to Restart", get_font(30), setting.width // 2, setting.height // 2 + 50, (200, 200, 200))
pg.display.update()
class OptionMenu:
def __init__(self, screen, clock):
self.menu_running = None
self.screen = screen
self.custom_screen = pygame.Surface((setting.width /2, setting.height /2))
self.clock = clock
self.control_handler = setting.control_handler
self.actions = setting.actions
def run(self):
self.menu_running = True
while self.menu_running:
self.clock.tick(60)
self.update()
self.draw()
return False
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_ESCAPE:
self.menu_running = False
if event.key == self.control_handler.controls['Left']:
self.actions['Left'] = True
if event.key == self.control_handler.controls['Right']:
self.actions['Right'] = True
if event.key == self.control_handler.controls['Up']:
self.actions['Up'] = True
if event.key == self.control_handler.controls['Down']:
self.actions['Down'] = True
if event.type == pygame.KEYUP:
if event.key == self.control_handler.controls['Left']:
self.actions['Left'] = False
if event.key == self.control_handler.controls['Right']:
self.actions['Right'] = False
if event.key == self.control_handler.controls['Up']:
self.actions['Up'] = False
if event.key == self.control_handler.controls['Down']:
self.actions['Down'] = False
self.control_handler.update(self.actions)
setting.actions = self.actions
def draw(self):
self.custom_screen.blit(get_background(), (0, 0))
self.control_handler.render(self.custom_screen)
self.screen.blit(pygame.transform.scale(self.custom_screen, (setting.width + 400, setting.height + 400)), (0, 0))
pg.display.update()
reset_keys(self.actions)
+23
View File
@@ -0,0 +1,23 @@
from game.util.control import Controls_Handler
from game.util.util import load_save
width, height = 0, 0
#grid surface
g_height, g_width = 600, 300
#score
game_score = 0
actions = {"Left": False, "Right": False, "Up": False, "Down": False, "Hold": False}
save = load_save()
control_handler = Controls_Handler(save)
rows = 20
cols = 10
cell_size = 30
fps = 60
gamestate = True
+14 -2
View File
@@ -30,7 +30,7 @@ class Tetrominos:
self.shape = self.SHAPES[self.shape_number - 1] self.shape = self.SHAPES[self.shape_number - 1]
self.colors = set_color() self.colors = set_color()
self.x = cols // 2 - len(self.shape[0]) // 2 # Center horizontally self.x = cols // 2 - len(self.shape[0]) // 2 # Center horizontally
self.y = 0 # Start at the top self.y = 0
@@ -80,4 +80,16 @@ class Tetrominos:
cell_size, cell_size,
cell_size cell_size
) )
pygame.draw.rect(surface, self.colors[self.shape_number - 1], cell_rect) # Red color for tetromino pygame.draw.rect(surface, self.colors[self.shape_number - 1], cell_rect)
def draw_ghost_tetromino(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:
x = (self.x + col_idx) * self.cell_size + 1
y = (self.y + row_idx) * self.cell_size + 1
rect = pygame.Rect(x, y, self.cell_size - 2, self.cell_size - 2)
pygame.draw.rect(screen, (61, 61, 61), rect)
pygame.draw.rect(screen, (255, 255, 255), rect, 1)
+29
View File
@@ -0,0 +1,29 @@
class Button():
def __init__(self, image, pos, text_input, font, base_color, hovering_color):
self.image = image
self.x_pos = pos[0]
self.y_pos = pos[1]
self.font = font
self.base_color, self.hovering_color = base_color, hovering_color
self.text_input = text_input
self.text = self.font.render(self.text_input, True, self.base_color)
if self.image is None:
self.image = self.text
self.rect = self.image.get_rect(center=(self.x_pos, self.y_pos))
self.text_rect = self.text.get_rect(center=(self.x_pos, self.y_pos))
def update(self, screen):
if self.image is not None:
screen.blit(self.image, self.rect)
screen.blit(self.text, self.text_rect)
def checkForInput(self, position):
if position[0] in range(self.rect.left, self.rect.right) and position[1] in range(self.rect.top, self.rect.bottom):
return True
return False
def changeColor(self, position):
if position[0] in range(self.rect.left, self.rect.right) and position[1] in range(self.rect.top, self.rect.bottom):
self.text = self.font.render(self.text_input, True, self.hovering_color)
else:
self.text = self.font.render(self.text_input, True, self.base_color)
+82
View File
@@ -0,0 +1,82 @@
import pygame, sys
from game.util.util import write_save, get_font
class Controls_Handler():
def __init__(self, save):
self.save_file = save
self.curr_block = save["current_profile"]
self.controls = self.save_file["controls"][str(self.curr_block)]
self.setup()
def update(self, actions):
if self.selected: self.set_new_control()
else: self.navigate_menu(actions)
def render(self, surface):
self.draw_text(surface, "Control Profile " + str(self.curr_block+1) , 20, pygame.Color((255, 255, 255)), 480 / 2, 270/8)
self.display_controls(surface, self.save_file["controls"][str(self.curr_block)])
if self.curr_block == self.save_file["current_profile"]: self.draw_text(surface, "*" , 20, pygame.Color((255, 255, 255)), 20, 20)
def navigate_menu(self, actions):
# Move the cursor up and down
if actions["Down"]: self.curr_index = (self.curr_index + 1) % (len(self.save_file["controls"][str(self.curr_block)]) + 1)
if actions["Up"]: self.curr_index = (self.curr_index - 1) % (len(self.save_file["controls"][str(self.curr_block)]) + 1)
# Switch between profiles
if actions["Left"]: self.curr_block = (self.curr_block -1) % len(self.save_file["controls"])
if actions["Right"]: self.curr_block = (self.curr_block +1) % len(self.save_file["controls"])
# Handle Selection
if pygame.key.get_pressed()[pygame.K_RETURN]:
if self.cursor_dict[self.curr_index] == "Set":
self.controls = self.save_file["controls"][str(self.curr_block)]
self.save_file["current_profile"] = self.curr_block
write_save(self.save_file)
else:
self.selected = True
def set_new_control(self):
selected_control = self.cursor_dict[self.curr_index]
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
done = True
pygame.quit()
sys.exit()
elif event.key not in self.save_file["controls"][str(self.curr_block)].values():
self.save_file["controls"][str(self.curr_block)][selected_control] = event.key
write_save(self.save_file)
self.selected = False
done = True
def display_controls(self,surface, controls):
color = (173, 2, 2) if self.selected else (207, 190, 41)
pygame.draw.rect(surface, color, (80 , 270/4 - 10 + (self.curr_index*30), 320, 20) )
i = 0
for control in controls:
self.draw_text(surface, control + ' - ' + pygame.key.name(controls[control]),20,
pygame.Color((255,255,255)), 480 / 2, 270/4 + i)
i += 30
self.draw_text(surface, "Set Current Profile",20, pygame.Color((255, 255, 255)), 480 / 2, 270/4 + i)
def setup(self):
self.selected = False
self.font = get_font(20)
self.cursor_dict = {}
self.curr_index = 0
i = 0
for control in self.controls:
self.cursor_dict[i] = control
i += 1
self.cursor_dict[i] = "Set"
def draw_text(self,surface, text, size, color, x, y):
text_surface = self.font.render(text, True, color, size)
text_surface.set_colorkey((0,0,0))
text_rect = text_surface.get_rect()
text_rect.center = (x, y)
surface.blit(text_surface, text_rect)
+103
View File
@@ -0,0 +1,103 @@
import pygame
import json, os
def get_fall_interval(score):
"""
Calculate the fall interval based on the current score.
"""
base_interval = 1000
decrease_per_1000_points = 50
min_interval = 100
interval = base_interval - (score // 400) * decrease_per_1000_points
return max(interval, min_interval)
def draw_text(surface, text, font, x, y, color):
"""Utility function to render text onto a surface."""
text_surface = font.render(text, True, color)
text_rect = text_surface.get_rect(center=(x, y))
surface.blit(text_surface, text_rect)
def get_font(size):
pygame.font.init()
return pygame.font.Font("assets/font.ttf", size)
def get_background():
return pygame.image.load('assets/menu_background.png')
#For the Leaderboard
def load_score(filename):
"""Load JSON data only if the file is not empty."""
if os.path.exists(filename) and os.path.getsize(filename) > 0:
with open(filename, "r") as file:
return json.load(file)
return {}
def add_score(filename, score):
"""Adds a new score only if it's in the top 5. Sorts scores in descending order."""
# Load existing data or create a new leaderboard
if os.path.exists(filename) and os.path.getsize(filename) > 0:
with open(filename, "r") as file:
try:
data = json.load(file)
except json.JSONDecodeError:
data = {"score": []} # Reset if JSON is corrupted
else:
data = {"score": []}
# Ensure "score" is a list
if "score" not in data or not isinstance(data["score"], list):
data["score"] = []
# Only add the score if there are less than 5 scores or it's higher than the lowest
if len(data["score"]) < 5 or score > min(data["score"]):
data["score"].append(score) # Add new score
data["score"] = sorted(data["score"], reverse=True)[:5] # Sort & keep top 5
# Save the updated leaderboard
with open(filename, "w") as file:
json.dump(data, file, indent=2)
# For keybinds (control.py)
def load_existing_save(savefile):
with open(os.path.join(savefile), 'r+') as file:
controls = json.load(file)
return controls
def write_save(data):
with open(os.path.join(os.getcwd(),'save.json'), 'w') as file:
json.dump(data, file)
def load_save():
try:
# Save is loaded
save = load_existing_save('save.json')
except:
# No save file, so create one
save = create_save()
write_save(save)
return save
def create_save():
new_save = {
"controls":{
"0" :{"Left": pygame.K_LEFT, "Right": pygame.K_RIGHT, "Up": pygame.K_UP, "Down": pygame.K_DOWN,
"Hold": pygame.K_c},
"1" :{"Left": pygame.K_LEFT, "Right": pygame.K_RIGHT, "Up": pygame.K_UP, "Down": pygame.K_DOWN,
"Hold": pygame.K_c}
},
"current_profile": 0
}
return new_save
def reset_keys(actions):
for action in actions:
actions[action] = False
return actions
-83
View File
@@ -1,83 +0,0 @@
import pygame
import settings
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)
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
+9
View File
@@ -0,0 +1,9 @@
{
"score": [
2200,
1100,
1100,
900,
600
]
}
+22 -173
View File
@@ -1,186 +1,35 @@
import pygame, sys import pygame
from settings import *
from game_manager import Grid, draw_text, get_fall_interval
from tetrominos import Tetrominos
import settings
def setup():
pygame.init()
global screen
screen = pygame.display.set_mode((width, height))
global clock
clock = pygame.time.Clock()
pygame.display.set_caption("Tetris")
icon_img = pygame.image.load('assets/icon.png')
pygame.display.set_icon(icon_img)
state_screen(game_state)
def state_screen(game_state):
"""Display the start screen."""
width = 300
screen = pygame.display.set_mode((width, height))
surface = pygame.Surface((WIDTH, HEIGHT))
surface.fill((0, 0, 0)) # Black background
if game_state:
# Draw text
draw_text(surface, "TETRIS", 50, WIDTH // 2, HEIGHT // 2 - 50, (255, 255, 255))
draw_text(surface, "Press ENTER to Start", 30, WIDTH // 2, HEIGHT // 2 + 50, (200, 200, 200))
else:
draw_text(surface, "Game Over", 50, WIDTH // 2, HEIGHT // 2 - 50, (255, 0, 0))
draw_text(surface, "Press Enter to Restart", 30, WIDTH // 2, HEIGHT // 2 + 50, (200, 200, 200))
# Display the surface
screen.blit(surface, (0, 0))
pygame.display.update()
# Wait for the player to press ENTER
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:
game_state = True
settings.game_score = 0
main()
return # Exit the start screen
def pause_menu(screen):
"""Render the pause menu."""
screen.fill((0, 0, 0)) # Black background
draw_text(screen, "Game Paused", 50, 450 // 2, HEIGHT // 2 - 50, (255, 255, 255))
draw_text(screen, "Press ESC to Resume", 30, 450 // 2, HEIGHT // 2 + 10, (200, 200, 200))
pygame.display.update()
from game.menu import StartMenu, GameMenu
from game.game import Game
import game.settings as setting
def main(): def main():
width = 450 running = True
screen = pygame.display.set_mode((width, height))
grid_surface = pygame.Surface((g_width, g_height)) pygame.init()
next_surface = pygame.Surface((150, 150)) screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
hold_surface = pygame.Surface((150, 150)) setting.width, setting.height = pygame.display.get_window_size()
clock = pygame.time.Clock()
# Create the grid and tetromino pygame.display.set_caption("Tetris")
game_grid = Grid(rows, cols, cell_size) icon_img = pygame.image.load('assets/icon.png')
current_tetromino = Tetrominos(cols, cell_size) pygame.display.set_icon(icon_img)
next_tetromino = Tetrominos(cols, cell_size)
hold_tetromino = None
hold_used = False # Flag to track if hold has been used for the current tetromino start_menu = StartMenu(screen, clock)
game_menu = GameMenu(screen, clock)
fall_timer = 0 game = Game(screen, clock)
move_timer = 0 while running:
move_interval = 100
while True: playing = start_menu.run()
screen.fill((138, 138, 138))
grid_surface.fill((87, 87, 87)) # Background color
current_time = pygame.time.get_ticks() while playing:
game.run()
fall_interval = get_fall_interval(settings.game_score) playing = game_menu.run()
for event in pygame.event.get(): if __name__ == "__main__":
if event.type == pygame.QUIT: main()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and settings.gamestate == "playing":
rotated_shape = [list(row) for row in zip(*current_tetromino.shape[::-1])]
if not game_grid.check_collision(rotated_shape, current_tetromino.x, current_tetromino.y):
current_tetromino.shape = rotated_shape # Apply rotation
elif event.key == pygame.K_SPACE and settings.gamestate == "playing":
current_tetromino.instant_drop(game_grid) # Perform instant drop
game_grid.add_tetromino(current_tetromino) # Lock tetromino in place
game_grid.check_full_row()
current_tetromino = next_tetromino
next_tetromino = Tetrominos(cols, cell_size)
hold_used = False # Reset hold flag when a new tetromino spawns
elif event.key == pygame.K_c and settings.gamestate == "playing":
if not hold_used:
if hold_tetromino is None:
hold_tetromino = current_tetromino
current_tetromino = next_tetromino
next_tetromino = Tetrominos(cols, cell_size)
else:
hold_tetromino, current_tetromino = current_tetromino, hold_tetromino
current_tetromino.x = cols // 2
current_tetromino.y = 0
hold_used = True
elif event.key == pygame.K_ESCAPE: # Pause the game
if settings.gamestate == "playing":
settings.gamestate = "paused"
elif settings.gamestate == "paused":
settings.gamestate = "playing"
if settings.gamestate == "playing":
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT]:
if current_time - move_timer > move_interval: # Ensure delay between movements
if not game_grid.check_collision(current_tetromino.shape, current_tetromino.x + 1, current_tetromino.y):
current_tetromino.move(1, 0) # Move right
move_timer = current_time # Reset timer
elif keys[pygame.K_LEFT]:
if current_time - move_timer > move_interval: # Ensure delay between movements
if not game_grid.check_collision(current_tetromino.shape, current_tetromino.x - 1, current_tetromino.y):
current_tetromino.move(-1, 0) # Move left
move_timer = current_time # Reset timer
# Handle automatic falling based on timer
if current_time - fall_timer > fall_interval:
if not game_grid.check_collision(current_tetromino.shape, current_tetromino.x, current_tetromino.y + 1):
current_tetromino.move(0, 1) # Move down
else:
# Collision detected, lock the tetromino in place
game_grid.add_tetromino(current_tetromino)
game_grid.check_full_row()
current_tetromino = next_tetromino
next_tetromino = Tetrominos(cols, cell_size) # Spawn a new tetromino
hold_used = False
# Check if game is over
if game_grid.check_collision(current_tetromino.shape, current_tetromino.x, current_tetromino.y):
game_state = False
state_screen(game_state)
fall_timer = current_time
# Draw the grid and tetromino
game_grid.draw_grid(grid_surface)
current_tetromino.draw(grid_surface)
# Draw the next and hold tetromino previews
next_surface.fill((0, 0, 0)) # Clear the next surface
next_tetromino.draw_next_tetromino(next_surface)
hold_surface.fill((0, 0, 0)) # Clear the hold surface
if hold_tetromino is not None:
hold_tetromino.draw_next_tetromino(hold_surface)
# Draw score
draw_text(screen, f'Score: {settings.game_score}', 30, width - 75, 100, (255, 255, 255))
# Render the surfaces
screen.blit(grid_surface)
screen.blit(next_surface, (width - 150, 200))
screen.blit(hold_surface, (width - 150, 400))
pygame.display.update()
clock.tick(fps)
elif settings.gamestate == "paused":
pause_menu(screen)
if __name__ == '__main__':
setup()
-26
View File
@@ -1,26 +0,0 @@
# Variables
#screen size
global height, width
height, width = 600, 300
#grid surface
g_height, g_width = 600, 300
#start surface size
HEIGHT, WIDTH = 600, 300
#state of the game
game_state = True
#score
game_score = 0
rows = 20
cols = 10
cell_size = 30
fps = 60
global gamestate # Add game state variable
gamestate = "playing"