thewindmage420

Renis

Jan 14th, 2024 (edited)
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 26.13 KB | None | 0 0
  1. import pygame
  2. import sys
  3. import random
  4. import collections
  5.  
  6. # Initialize Pygame
  7. pygame.init()
  8. pygame.mixer.init()
  9.  
  10. # Constants
  11. pygame.display.set_caption("Renis")  # Set window title to "Renis"
  12. WINDOW_WIDTH = 300
  13. WINDOW_HEIGHT = 600
  14. BLOCK_SIZE = 30
  15.  
  16. GRID_WIDTH = WINDOW_WIDTH // BLOCK_SIZE
  17. GRID_HEIGHT = WINDOW_HEIGHT // BLOCK_SIZE
  18.  
  19. LEVEL_UP_SCORE = 1000  # Score needed to level up
  20. MIN_FALL_SPEED = 100   # Minimum fall speed in milliseconds
  21. FALL_SPEED_DECREMENT = 50  # Speed increase per level
  22.  
  23. SCORING_RULES = {
  24.     1: 100,
  25.     2: 300,
  26.     3: 600,
  27.     4: 1000,
  28. }
  29.  
  30. SCORE_INCREMENT = 100  # Kept for backward compatibility  # Score increase for each cleared line
  31.  
  32. # Colors
  33. WHITE = (255, 255, 255)
  34. BLUE = (0, 0, 255)
  35. BLACK = (0, 0, 0)
  36.  
  37. # Sounds
  38. #rotate_sound = pygame.mixer.Sound("rotate.wav")
  39. #lock_sound = pygame.mixer.Sound("lock.wav")
  40. #hold_sound = pygame.mixer.Sound("hold.wav")
  41. #clear_sound = pygame.mixer.Sound("clear.wav")
  42. #renis_clear_sound = pygame.mixer.Sound("renisclear.wav")
  43.  
  44.  
  45.  
  46. # Tetrimino shapes
  47. TETRIMINOS = {
  48.     'O': {'shape': [[1, 1],
  49.                     [1, 1]], 'color': (255, 255, 0)},  # Yellow
  50.     'I': {'shape': [[1, 1, 1, 1]], 'color': (0, 255, 255)},  # Cyan
  51.     'S': {'shape': [[0, 1, 1],
  52.                     [1, 1, 0]], 'color': (0, 255, 0)},  # Green
  53.     'Z': {'shape': [[1, 1, 0],
  54.                     [0, 1, 1]], 'color': (255, 0, 0)},  # Red
  55.     'L': {'shape': [[1, 1, 1],
  56.                     [1, 0, 0]], 'color': (255, 165, 0)},  # Orange
  57.     'J': {'shape': [[1, 1, 1],
  58.                     [0, 0, 1]], 'color': (0, 0, 255)},  # Blue
  59.     'T': {'shape': [[1, 1, 1],
  60.                     [0, 1, 0]], 'color': (128, 0, 128)},  # Purple
  61. }
  62.  
  63. # To keep track of the last three generated pieces
  64. last_three_pieces = collections.deque(maxlen=3)
  65.  
  66. # Initialize window
  67. window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
  68.  
  69.  
  70. def generate_tetrimino():
  71.     while True:
  72.         tetrimino_key = random.choice(list(TETRIMINOS.keys()))
  73.         # Check if the new key is not repeating more than 3 times
  74.         if last_three_pieces.count(tetrimino_key) < 3:
  75.             break
  76.     last_three_pieces.append(tetrimino_key)  # Add the new key to the queue
  77.    
  78.     tetrimino_shape = TETRIMINOS[tetrimino_key]['shape']
  79.     x_position = random.randint(0, GRID_WIDTH - len(tetrimino_shape[0]))
  80.     return {'shape': tetrimino_shape, 'position': (x_position, 0), 'color': TETRIMINOS[tetrimino_key]['color']}
  81.    
  82. def update_tetriminos(tetriminos):
  83.     for tetrimino in tetriminos:
  84.         x, y = tetrimino['position']
  85.         tetrimino['position'] = (x, y + 1)
  86.     tetriminos[:] = [t for t in tetriminos if t['position'][1] < GRID_HEIGHT]
  87.  
  88. def draw_tetriminos(tetriminos, surface):
  89.     for tetrimino in tetriminos:
  90.         shape, (x, y), color = tetrimino['shape'], tetrimino['position'], tetrimino['color']
  91.         draw_tetrimino(surface, shape, x * BLOCK_SIZE, y * BLOCK_SIZE, color)
  92.  
  93. def draw_title_and_instructions(surface):
  94.     title_font = pygame.font.SysFont(None, 72)
  95.     instr_font = pygame.font.SysFont(None, 36)
  96.  
  97.     title_text = title_font.render('Renis', True, WHITE)
  98.     instr_text = instr_font.render('Press any key to start', True, WHITE)
  99.  
  100.  
  101.     title_rect = title_text.get_rect(center=(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2 - 50))
  102.     instr_rect = instr_text.get_rect(center=(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2 + 50))
  103.  
  104.     surface.blit(title_text, title_rect)
  105.     surface.blit(instr_text, instr_rect)
  106.  
  107. def display_title_screen():
  108.     # Load and play the music
  109.     #pygame.mixer.music.load('title.mp3')
  110.     #pygame.mixer.music.play(-1)  # The -1 will make the music loop indefinitely    running = True
  111.  
  112.     tetriminos = []
  113.     last_generation_time = 0
  114.     generation_interval = 1000
  115.  
  116.     while True:
  117.         current_time = pygame.time.get_ticks()
  118.         window.fill(BLACK)
  119.  
  120.         if current_time - last_generation_time > generation_interval:
  121.             tetriminos.append(generate_tetrimino())
  122.             last_generation_time = current_time
  123.  
  124.         update_tetriminos(tetriminos)
  125.         draw_tetriminos(tetriminos, window)
  126.         draw_title_and_instructions(window)
  127.  
  128.         pygame.display.flip()
  129.  
  130.         for event in pygame.event.get():
  131.             if event.type == pygame.QUIT:
  132.                 pygame.quit()
  133.                 sys.exit()
  134.             elif event.type == pygame.KEYDOWN:
  135.                 return
  136.  
  137.         pygame.time.delay(100)
  138.  
  139.     window.fill(BLACK)  # Clearing the screen
  140.     title_font = pygame.font.SysFont(None, 72)  # Larger font for the title
  141.     instr_font = pygame.font.SysFont(None, 36)  # Smaller font for instructions
  142.  
  143.     title_text = title_font.render('Renis', True, WHITE)
  144.     instr_text = instr_font.render('Press any key to start', True, WHITE)
  145.  
  146.     title_rect = title_text.get_rect(center=(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2 - 50))
  147.     instr_rect = instr_text.get_rect(center=(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2 + 50))
  148.  
  149.     window.blit(title_text, title_rect)
  150.     window.blit(instr_text, instr_rect)
  151.  
  152.     pygame.display.flip()  # Update the display
  153.  
  154. def draw_transparent_block(surface, color, x, y, block_size, alpha=128):
  155.     block = pygame.Surface((block_size, block_size), pygame.SRCALPHA)  
  156.     block.fill(color)  
  157.     block.set_alpha(alpha)  
  158.     surface.blit(block, (x, y))
  159.  
  160. def draw_tetrimino(surface, shape, x, y, color, is_ghost=False, scale=1):
  161.     for i, row in enumerate(shape):
  162.         for j, block in enumerate(row):
  163.             if block:
  164.                 scaled_block_size = int(BLOCK_SIZE * scale)
  165.                 if is_ghost:
  166.                     draw_transparent_block(surface, color, x + j*scaled_block_size, y + i*scaled_block_size, scaled_block_size)
  167.                 else:
  168.                     pygame.draw.rect(surface, color, (x + j*scaled_block_size, y + i*scaled_block_size, scaled_block_size, scaled_block_size))
  169.                 pygame.draw.rect(surface, WHITE, (x + j*scaled_block_size, y + i*scaled_block_size, scaled_block_size, scaled_block_size), 1)  # Always draw white border
  170.  
  171. #ghost tetrimino
  172. def get_ghost_position(tetrimino, x, y, grid):
  173.     shape = tetrimino['shape']
  174.     ghost_y = y
  175.    
  176.     # TODO: Replace 'collision' with your actual collision check function
  177.     while not collision(shape, (x, ghost_y + 1), grid):  
  178.         ghost_y += 1
  179.        
  180.     return (x, ghost_y)
  181.  
  182. #collision
  183. def collision(shape, position, grid):
  184.     """
  185.    Check if the space is occupied by the tetrimino.
  186.    
  187.    :param shape: 2D list representing the tetrimino shape.
  188.    :param position: (x, y) position of the tetrimino.
  189.    :param grid: 2D list representing the game grid.
  190.    :return: Boolean value representing whether a collision occurred.
  191.    """
  192.     for i, row in enumerate(shape):
  193.         for j, cell in enumerate(row):
  194.             try:
  195.                 if cell and grid[i + position[1]][j + position[0]]:
  196.                     return True  # Collision detected
  197.             except IndexError:  # Trying to access out of bounds index
  198.                 return True
  199.     return False
  200.  
  201. # Rotate the tetrimino
  202. def rotate_tetrimino(tetrimino, grid, x, y):
  203.     shape = tetrimino['shape']
  204.    
  205.     rotated_shape = [
  206.         [shape[x][y] for x in reversed(range(len(shape)))]
  207.         for y in range(len(shape[0]))
  208.     ]
  209.    
  210.     rotated_tetrimino = {'shape': rotated_shape, 'color': tetrimino['color']}
  211.     x_move = 0
  212.     y_move = 0
  213.     original_y = y
  214.  
  215.     found_valid_position = False
  216.  
  217.     while y >= 0 and not found_valid_position:
  218.         for x_offset in [0, -1, 1]:
  219.             if is_valid_move(grid, rotated_tetrimino, x + x_offset, y):
  220.                 x_move = x_offset
  221.                 y_move = y - original_y
  222.                 found_valid_position = True
  223.                 break
  224.         y -= 1
  225.  
  226.     if not found_valid_position:
  227.         return tetrimino, 0, 0
  228.  
  229.     # Play rotation sound if the tetrimino was rotated
  230.     if (rotated_tetrimino, x_move, y_move) != (tetrimino, 0, 0):
  231.         #rotate_sound.play()
  232.  
  233.     return rotated_tetrimino, x_move, y_move
  234.    
  235. # Counter-clockwise rotation
  236. def rotate_tetrimino_ccw(tetrimino, grid, x, y):
  237.     shape = tetrimino['shape']
  238.    
  239.     rotated_shape = [
  240.         [shape[x][y] for x in range(len(shape))]
  241.         for y in reversed(range(len(shape[0])))
  242.     ]
  243.    
  244.     rotated_tetrimino = {'shape': rotated_shape, 'color': tetrimino['color']}
  245.     x_move, y_move = 0, 0
  246.  
  247.     if not is_valid_move(grid, rotated_tetrimino, x, y):
  248.         if is_valid_move(grid, rotated_tetrimino, x + 1, y):
  249.             x_move = 1
  250.         elif is_valid_move(grid, rotated_tetrimino, x - 1, y):
  251.             x_move = -1
  252.         elif is_valid_move(grid, rotated_tetrimino, x, y - 1):
  253.             y_move = -1
  254.         else:
  255.             return tetrimino, 0, 0
  256.  
  257.     # Play rotation sound if the tetrimino was rotated
  258.     if (rotated_tetrimino, x_move, y_move) != (tetrimino, 0, 0):
  259.         #rotate_sound.play()
  260.  
  261.     return rotated_tetrimino, x_move, y_move
  262.    
  263. #Drop the Tetrimino to the bottom
  264. def hard_drop(current_tetrimino, current_x, current_y, current_grid):
  265.     # Find how far the Tetrimino can drop
  266.     while is_valid_move(current_grid, current_tetrimino, current_x, current_y + 1):
  267.         current_y += 1
  268.     # Return final position without altering the grid
  269.     return current_x, current_y
  270.  
  271.  
  272. # Check if the new position/rotation is valid
  273. def is_valid_move(grid, tetrimino, x, y):
  274.     for i, row in enumerate(tetrimino['shape']):
  275.         for j, block in enumerate(row):
  276.             if block:
  277.                 if (x + j < 0 or x + j >= GRID_WIDTH or
  278.                     y + i >= GRID_HEIGHT or grid[y + i][x + j]):
  279.                     return False
  280.     return True
  281. # Merge the tetrimino into the grid and return the number of cleared lines
  282. def merge_tetrimino(grid, tetrimino, x, y):
  283.     cleared_lines = 0
  284.     for i, row in enumerate(tetrimino['shape']):
  285.         for j, block in enumerate(row):
  286.             if block:
  287.                 grid[y + i][x + j] = tetrimino['color']
  288.  
  289.     for i, row in enumerate(grid):
  290.         if all(row):
  291.             print(f"Clearing line {i}: {row}")  # Debug log
  292.             del grid[i]
  293.             grid.insert(0, [0] * GRID_WIDTH)
  294.             cleared_lines += 1
  295.  
  296.     # Play clear sound effects here
  297.     if cleared_lines == 4:  # If four lines are cleared, it's a Tetris!
  298.         #renis_clear_sound.play()
  299.     elif cleared_lines > 0:  # If 1 to 3 lines are cleared
  300.         #clear_sound.play()
  301.  
  302.     print(f"Cleared lines: {cleared_lines}")  # Debug log
  303.     return cleared_lines
  304.    
  305. # Main loop
  306. def wait_for_key_press():
  307.     while True:
  308.         for event in pygame.event.get():
  309.             if event.type == pygame.QUIT:
  310.                 pygame.quit()
  311.                 sys.exit()
  312.             elif event.type == pygame.KEYDOWN:
  313.                 return
  314.  
  315. def draw_text(surface, text, size, x, y, color):
  316.     pygame.font.init()  # You only need to call this once, so you might do it in the main part of your program
  317.     font = pygame.font.Font(None, size)  # Choose the font and size
  318.     text_surface = font.render(text, True, color)  # Create the text surface
  319.     text_rect = text_surface.get_rect()
  320.     text_rect.midtop = (x, y)
  321.     surface.blit(text_surface, text_rect)
  322.  
  323.  
  324. def display_game_over_screen(final_score):
  325.     # Load and play the music
  326.     #pygame.mixer.music.load('gameover.mp3')
  327.     #pygame.mixer.music.play(-1)  # The -1 will make the music loop indefinitely    running = True
  328.  
  329.     flying_tetriminos = []
  330.     for _ in range(5):
  331.         tetrimino_key = random.choice(list(TETRIMINOS.keys()))
  332.         tetrimino = TETRIMINOS[tetrimino_key]
  333.        
  334.         while True:
  335.             x = random.randint(0, WINDOW_WIDTH - len(tetrimino['shape'][0]) * BLOCK_SIZE)
  336.             y = random.randint(-WINDOW_HEIGHT, WINDOW_HEIGHT//2)
  337.            
  338.             is_too_close = False
  339.             for x_existing, y_existing, _ in flying_tetriminos:
  340.                 if abs(x - x_existing) < BLOCK_SIZE and abs(y - y_existing) < BLOCK_SIZE:
  341.                     is_too_close = True
  342.                     break
  343.            
  344.             if not is_too_close:
  345.                 break
  346.        
  347.         flying_tetriminos.append((x, y, tetrimino))
  348.    
  349.     clock = pygame.time.Clock()
  350.     elapsed_time = 0
  351.    
  352.     input_enabled = False  # Disable input initially
  353.     input_enable_time = pygame.time.get_ticks() + 2000  # Enable input after 2000 ms (2 seconds)
  354.  
  355.     while True:
  356.         window.fill(BLACK)
  357.         elapsed_time += clock.tick(60)
  358.  
  359.         if elapsed_time >= 500:
  360.             tetrimino_key = random.choice(list(TETRIMINOS.keys()))
  361.             tetrimino = TETRIMINOS[tetrimino_key]
  362.             x = random.randint(0, WINDOW_WIDTH - len(tetrimino['shape'][0]) * BLOCK_SIZE)
  363.             y = -len(tetrimino['shape']) * BLOCK_SIZE
  364.             flying_tetriminos.append((x, y, tetrimino))
  365.             elapsed_time = 0
  366.  
  367.         for i, (x, y, tetrimino) in enumerate(flying_tetriminos):
  368.             flying_tetriminos[i] = (x, y + 5, tetrimino)
  369.             draw_tetrimino(window, tetrimino['shape'], x, y, tetrimino['color'])
  370.        
  371.         flying_tetriminos = [(x, y, tetrimino) for x, y, tetrimino in flying_tetriminos if y < WINDOW_HEIGHT]
  372.        
  373.         font = pygame.font.SysFont(None, 70)
  374.         game_over_text = font.render('GAME OVER', True, WHITE)
  375.         text_x = WINDOW_WIDTH // 2 - game_over_text.get_width() // 2
  376.         text_y = WINDOW_HEIGHT // 2 - game_over_text.get_height() // 2 - 40
  377.         window.blit(game_over_text, (text_x, text_y))
  378.  
  379.         score_label_font = pygame.font.SysFont(None, 50)
  380.         score_label_text = score_label_font.render('Final Score:', True, WHITE)
  381.         score_label_x = WINDOW_WIDTH // 2 - score_label_text.get_width() // 2
  382.         score_label_y = WINDOW_HEIGHT // 2 - score_label_text.get_height() // 2
  383.         window.blit(score_label_text, (score_label_x, score_label_y))
  384.  
  385.         score_value_font = pygame.font.SysFont(None, 50)
  386.         score_value_text = score_value_font.render(str(final_score), True, WHITE)
  387.         score_value_x = WINDOW_WIDTH // 2 - score_value_text.get_width() // 2
  388.         score_value_y = score_label_y + score_label_text.get_height()
  389.         window.blit(score_value_text, (score_value_x, score_value_y))
  390.        
  391.         pygame.display.flip()
  392.        
  393.         # Enable input after a delay
  394.         if pygame.time.get_ticks() >= input_enable_time:
  395.             input_enabled = True
  396.  
  397.         for event in pygame.event.get():
  398.             if event.type == pygame.QUIT:
  399.                 pygame.quit()
  400.                 sys.exit()
  401.             elif event.type == pygame.KEYDOWN and input_enabled:
  402.                 # Check if the key is not the print screen key
  403.                 if event.key not in [pygame.K_PRINT, pygame.K_PRINTSCREEN]:
  404.                     return
  405.        
  406.         clock.tick(30)
  407.  
  408.     game_over_font = pygame.font.SysFont(None, 72)  
  409.     game_over_text = game_over_font.render("Game Over", True, WHITE)
  410.     window.blit(game_over_text, (WINDOW_WIDTH // 2 - game_over_text.get_width() // 2, WINDOW_HEIGHT // 2 - game_over_text.get_height() // 2))
  411.     pygame.display.update()
  412.  
  413.  
  414. def main_game():
  415.     global LOCK_DELAY
  416.     running = True
  417.     # Load and play the music
  418.     #pygame.mixer.music.load('renis.mp3')
  419.     #pygame.mixer.music.play(-1)  # The -1 will make the music loop indefinitely    
  420.     running = True
  421.     grid = [[0] * GRID_WIDTH for _ in range(GRID_HEIGHT)]
  422.  
  423.     next_tetriminos = [TETRIMINOS[random.choice(list(TETRIMINOS.keys()))] for _ in range(3)]
  424.     tetrimino = next_tetriminos.pop(0)
  425.     held_tetrimino = None
  426.     can_swap = True
  427.  
  428.     x, y = GRID_WIDTH // 2 - len(tetrimino['shape'][0]) // 2, 0
  429.     clock = pygame.time.Clock()
  430.    
  431.     level = 1  
  432.     level_up_score = 1000  
  433.     fall_speed = 500
  434.     LOCK_DELAY = 1.5
  435.    
  436.     fall_time = 0
  437.     fall_speed -= (level-1) * 50  
  438.     move_speed = 150  
  439.     fast_fall_speed = 50  
  440.     last_move_time = 0
  441.     last_fast_fall_time = 0
  442.    
  443.     score = 0
  444.    
  445.     lock_timer = 0  # Initialize lock timer
  446.  
  447.     while running:
  448.         window.fill(WHITE)
  449.         current_time = pygame.time.get_ticks()
  450.         keys = pygame.key.get_pressed()  
  451.  
  452.         for event in pygame.event.get():
  453.             if event.type == pygame.QUIT:
  454.                 pygame.quit()
  455.                 sys.exit()
  456.                 running = False
  457.             elif event.type == pygame.KEYDOWN:
  458.                 if event.key == pygame.K_x:
  459.                     # Clockwise rotation for UP and X keys
  460.                     rotated_tetrimino, x_move, y_move = rotate_tetrimino(tetrimino, grid, x, y)
  461.                     if is_valid_move(grid, rotated_tetrimino, x + x_move, y + y_move):
  462.                         tetrimino = rotated_tetrimino
  463.                         x += x_move
  464.                         y += y_move
  465.                         keys = pygame.key.get_pressed()
  466.                         lock_timer = 0  # Reset lock timer when Tetrimino moves down
  467.                 elif event.key == pygame.K_z:
  468.                     # Counter-clockwise rotation for Z key
  469.                     rotated_tetrimino, x_move, y_move = rotate_tetrimino_ccw(tetrimino, grid, x, y)
  470.                     if is_valid_move(grid, rotated_tetrimino, x + x_move, y + y_move):
  471.                         tetrimino = rotated_tetrimino
  472.                         x += x_move
  473.                         y += y_move
  474.                         keys = pygame.key.get_pressed()
  475.                         lock_timer = 0  # Reset lock timer when Tetrimino moves down            
  476.                 elif event.key == pygame.K_SPACE:
  477.                     # Hard drop: Find the final position without altering the grid
  478.                     final_x, final_y = hard_drop(tetrimino, x, y, grid)
  479.                                    
  480.                     # Merge and check for line clears
  481.                     cleared = merge_tetrimino(grid, tetrimino, final_x, final_y)
  482.                     #lock_sound.play()
  483.                                    
  484.                     # Update score
  485.                     score += SCORING_RULES[cleared] if cleared in SCORING_RULES else cleared * SCORE_INCREMENT
  486.                                    
  487.                     # Level up if needed
  488.                     if score >= level * level_up_score:
  489.                         print(f"Level Up: {level}")
  490.                         print(f"Fall Speed: {fall_speed}")
  491.                         level += 1
  492.                         level = min(level, 20) # Ensure the level does not exceed 20
  493.                        
  494.                         fall_speed = max(MIN_FALL_SPEED, fall_speed - FALL_SPEED_DECREMENT)
  495.                                                        
  496.                     # Generate new Tetrimino and check for game over
  497.                     tetrimino = next_tetriminos.pop(0)
  498.                     next_tetriminos.append(TETRIMINOS[random.choice(list(TETRIMINOS.keys()))])
  499.                     x, y = GRID_WIDTH // 2 - len(tetrimino['shape'][0]) // 2, 0
  500.                    
  501.                     # Allow swapping again
  502.                     can_swap = True
  503.                    
  504.                     if not is_valid_move(grid, tetrimino, x, y):
  505.                         running = False
  506.                 elif event.key == pygame.K_LSHIFT and can_swap:
  507.                     #hold_sound.play()
  508.                     print("Swapping...")
  509.                     if held_tetrimino:
  510.                         # Swap current and held Tetrimino
  511.                         tetrimino, held_tetrimino = held_tetrimino, tetrimino
  512.                         x, y = GRID_WIDTH // 2 - len(tetrimino['shape'][0]) // 2, 0
  513.                     else:
  514.                         # Hold the current Tetrimino and spawn a new one
  515.                         held_tetrimino = tetrimino
  516.                         tetrimino = next_tetriminos.pop(0)
  517.                         next_tetriminos.append(TETRIMINOS[random.choice(list(TETRIMINOS.keys()))])
  518.                         x, y = GRID_WIDTH // 2 - len(tetrimino['shape'][0]) // 2, 0
  519.                     can_swap = False  # Prevent further swaps until a Tetrimino is placed
  520.                     print("can_swap set to False")
  521.                 elif event.key == pygame.K_r:  # Check for R key press
  522.                     reset_game = True  # Set the flag to True to indicate game reset
  523.                     running = False  # Exit the game loop to end the function
  524.                
  525.         if (keys[pygame.K_LEFT] and
  526.             is_valid_move(grid, tetrimino, x-1, y) and
  527.             current_time - last_move_time > move_speed):
  528.             x -= 1
  529.             last_move_time = current_time
  530.             lock_timer = 0  # Reset lock timer when Tetrimino moves down
  531.  
  532.         elif (keys[pygame.K_RIGHT] and
  533.               is_valid_move(grid, tetrimino, x+1, y) and
  534.               current_time - last_move_time > move_speed):
  535.             x += 1
  536.             last_move_time = current_time
  537.             lock_timer = 0  # Reset lock timer when Tetrimino moves down
  538.  
  539.  
  540.         elif (keys[pygame.K_DOWN] and
  541.               is_valid_move(grid, tetrimino, x, y+1) and
  542.               current_time - last_fast_fall_time > fast_fall_speed):
  543.             y += 1
  544.             last_fast_fall_time = current_time
  545.        
  546.         # Draw the held Tetrimino
  547.         if held_tetrimino:
  548.             draw_x = 10  # Adjust x to start drawing from left side
  549.             draw_y = 80  # Adjust y to place it below Score and Level text
  550.             draw_tetrimino(window, held_tetrimino['shape'], draw_x, draw_y, held_tetrimino['color'], scale=0.5)
  551.        
  552.         # Draw the grid
  553.         for i, row in enumerate(grid):
  554.             for j, block in enumerate(row):
  555.                 if block:
  556.                     pygame.draw.rect(window, block, (j*BLOCK_SIZE, i*BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE))
  557.                     pygame.draw.rect(window, WHITE, (j*BLOCK_SIZE, i*BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 1)
  558.  
  559.         # Drawing the ghost Tetrimino
  560.         ghost_x, ghost_y = get_ghost_position(tetrimino, x, y, grid)
  561.         draw_tetrimino(window, tetrimino['shape'], ghost_x * BLOCK_SIZE, ghost_y * BLOCK_SIZE, tetrimino['color'], is_ghost=True)
  562.  
  563.         # Drawing the active Tetrimino
  564.         draw_tetrimino(window, tetrimino['shape'], x * BLOCK_SIZE, y * BLOCK_SIZE, tetrimino['color'], is_ghost=False)
  565.  
  566.         # Draw the score
  567.         font = pygame.font.SysFont(None, 36)
  568.         score_text = font.render(f'Score: {score}', True, BLACK)
  569.         window.blit(score_text, (10, 10))
  570.  
  571.         # Draw the level
  572.         level_text = font.render(f'Level: {level}', True, BLACK)
  573.         window.blit(level_text, (10, 40))
  574.  
  575.         # Draw the next Tetrimino from the queue
  576.         next_tetrimino = next_tetriminos[0]  
  577.         draw_x = GRID_WIDTH * BLOCK_SIZE - 2 * BLOCK_SIZE  
  578.         draw_y = 0  
  579.         draw_tetrimino(window, next_tetrimino['shape'], draw_x, draw_y, next_tetrimino['color'], scale=0.5, is_ghost=False)  
  580.        
  581.         # Update the display
  582.         pygame.display.flip()
  583.  
  584.         # Control the falling speed of the tetrimino
  585.         fall_time += clock.get_rawtime()
  586.         clock.tick()
  587.  
  588.         if fall_time > fall_speed:
  589.             if is_valid_move(grid, tetrimino, x, y+1):
  590.                 y += 1
  591.                 lock_timer = 0  # Reset lock timer when Tetrimino moves down
  592.             else:
  593.                 lock_timer += clock.get_rawtime()  # Increment lock timer
  594.                 print(f"Incrementing Lock Timer: {lock_timer}")  # Debug print
  595.                 if lock_timer >= LOCK_DELAY:  # Check if lock timer has reached threshold
  596.                     print("Locking Tetrimino")  # Debug print
  597.                     # Merge, check for line clears, generate new Tetrimino, etc.
  598.                     cleared = merge_tetrimino(grid, tetrimino, x, y)
  599.                     # PLAY LOCK SOUND HERE
  600.                     #lock_sound.play()
  601.                     print(f"Cleared Lines: {cleared}")  # Debugging: Check cleared lines value
  602.                     print(f"Score Before Update: {score}")  # Debugging: Check score before update
  603.                     score += SCORING_RULES[cleared] if cleared in SCORING_RULES else cleared * SCORE_INCREMENT
  604.                     print(f"Score After Update: {score}")  # Debugging: Check score after update                    
  605.                     if score >= level * level_up_score:
  606.                         level += 1
  607.                         level = min(level, 20) # Ensure the level does not exceed 20
  608.                         print(f"Level Up: {level}")
  609.                         print(f"Fall Speed: {fall_speed}")
  610.                         print(f"Lock Delay: {LOCK_DELAY}")
  611.                         fall_speed = max(MIN_FALL_SPEED, fall_speed - FALL_SPEED_DECREMENT)
  612.                        
  613.                     tetrimino = next_tetriminos.pop(0)
  614.                     next_tetriminos.append(TETRIMINOS[random.choice(list(TETRIMINOS.keys()))])
  615.  
  616.                     x, y = GRID_WIDTH // 2 - len(tetrimino['shape'][0]) // 2, 0
  617.                     if not is_valid_move(grid, tetrimino, x, y):
  618.                         running = False
  619.                     can_swap = True
  620.                     lock_timer = 0  # Reset lock timer after locking Tetrimino
  621.             fall_time = 0
  622.         final_score = score
  623.  
  624.         # Define a dictionary that maps levels to LOCK_DELAY values
  625.         lock_delay_map = {
  626.             1: 2.5,
  627.             2: 3,
  628.             3: 3,
  629.             4: 4,
  630.             5: 4,
  631.             6: 4,
  632.             7: 5,
  633.             8: 6,
  634.             9: 8,
  635.             10: 8,
  636.             11: 8,
  637.             12: 8,
  638.             13: 9,
  639.             14: 9,
  640.             15: 9,
  641.             16: 9,
  642.             17: 10,
  643.             18: 10,
  644.             19: 10,
  645.             20: 10
  646.         }
  647.  
  648.         # Get the LOCK_DELAY value using the level as a key, if it exists in the dictionary
  649.         LOCK_DELAY = lock_delay_map.get(level)
  650.        
  651.     #pygame.mixer.music.stop()
  652.     reset_game = False
  653.     return final_score, reset_game  # Return the status of the reset_game flag
  654.  
  655.  
  656. if __name__ == "__main__":
  657.     while True:
  658.         display_title_screen()
  659.         final_score, reset_game = main_game() # Assume main_game returns a tuple (reset_flag, score)
  660.         #if not reset_game:
  661.         display_game_over_screen(final_score)
  662.         # If reset_game is True, the loop will repeat, restarting the game
  663.  
Advertisement
Add Comment
Please, Sign In to add comment