Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

An error occurred while executing the following Python script: Error: File…

  1. User

    An error occurred while executing the following Python script:

    Error: File "D:\Spatial\temp_scripts\temp_script_acdd4376afbd4691aa74ce28523699f8.py", line 1 display.update()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n\n if event.type == pygame.KEYDOWN:\n main(win)\n\n pygame.quit()\n\nif name == 'main':\n win = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))\n pygame.display.set_caption('Tetris')\n main_menu(win) # start game\n ^ SyntaxError: unexpected character after line continuation character

    Script: \nimport pygame\nimport random\n\n# Initialize Pygame\npygame.init()\n\n# Screen dimensions\nSCREEN_WIDTH = 300\nSCREEN_HEIGHT = 600\nBLOCK_SIZE = 30\n\n# Play area dimensions\nPLAY_WIDTH = 10 * BLOCK_SIZE # 300\nPLAY_HEIGHT = 20 * BLOCK_SIZE # 600\nTOP_LEFT_X = (SCREEN_WIDTH - PLAY_WIDTH) // 2\nTOP_LEFT_Y = SCREEN_HEIGHT - PLAY_HEIGHT\n\n# Define shapes\nS = [['.....',\n '.....',\n '..00.',\n '.00..',\n '.....'],\n ['.....',\n '..0..',\n '..00.',\n '...0.',\n '.....']]\n\nZ = [['.....',\n '.....',\n '.00..',\n '..00.',\n '.....'],\n ['.....',\n '..0..',\n '.00..',\n '.0...',\n '.....']]\n\nI = [['..0..',\n '..0..',\n '..0..',\n '..0..',\n '.....'],\n ['.....',\n '0000.',\n '.....',\n '.....',\n '.....']]\n\nO = [['.....',\n '.....',\n '.00..',\n '.00..',\n '.....']]\n\nJ = [['.....',\n '.0...',\n '.000.',\n '.....',\n '.....'],\n ['.....',\n '..00.',\n '..0..',\n '..0..',\n '.....'],\n ['.....',\n '.....',\n '.000.',\n '...0.',\n '.....'],\n ['.....',\n '..0..',\n '..0..',\n '.00..',\n '.....']]\n\nL = [['.....',\n '...0.',\n '.000.',\n '.....',\n '.....'],\n ['.....',\n '..0..',\n '..0..',\n '..00.',\n '.....'],\n ['.....',\n '.....',\n '.000.',\n '.0...',\n '.....'],\n ['.....',\n '.00..',\n '..0..',\n '..0..',\n '.....']]\n\nT = [['.....',\n '..0..',\n '.000.',\n '.....',\n '.....'],\n ['.....',\n '..0..',\n '..00.',\n '..0..',\n '.....'],\n ['.....',\n '.....',\n '.000.',\n '..0..',\n '.....'],\n ['.....',\n '..0..',\n '.00..',\n '..0..',\n '.....']]\n\n# List of shapes and their colors\nSHAPES = [S, Z, I, O, J, L, T]\nSHAPE_COLORS = [(0, 255, 0), # S - Green\n (255, 0, 0), # Z - Red\n (0, 255, 255), # I - Cyan\n (255, 255, 0), # O - Yellow\n (255, 165, 0), # J - Orange\n (0, 0, 255), # L - Blue\n (128, 0, 128)] # T - Purple\n\n# Define the Piece class\nclass Piece:\n def init(self, x, y, shape):\n self.x = x # Horizontal position on the grid\n self.y = y # Vertical position on the grid\n self.shape = shape\n self.color = SHAPE_COLORS[SHAPES.index(shape)]\n self.rotation = 0 # Number from 0-3\n\ndef create_grid(locked_positions={}):\n grid = [[(0,0,0) for _ in range(10)] for _ in range(20)]\n\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n if (j,i) in locked_positions:\n grid[i][j] = locked_positions[(j,i)]\n return grid\n\ndef convert_shape_format(shape):\n positions = []\n format = shape.shape[shape.rotation % len(shape.shape)]\n\n for i, line in enumerate(format):\n row = list(line)\n for j, column in enumerate(row):\n if column == '0':\n positions.append((shape.x + j - 2, shape.y + i - 4))\n\n return positions\n\ndef valid_space(shape, grid):\n accepted_positions = [[(j, i) for j in range(10) if grid[i][j] == (0,0,0)] for i in range(20)]\n accepted_positions = [j for sub in accepted_positions for j in sub]\n\n formatted = convert_shape_format(shape)\n\n for pos in formatted:\n if pos not in accepted_positions:\n if pos[1] >= 0:\n return False\n return True\n\ndef check_lost(positions):\n for pos in positions:\n x, y = pos\n if y < 1:\n return True\n return False\n\ndef get_shape():\n return Piece(5, 0, random.choice(SHAPES))\n\ndef draw_text_middle(surface, text, size, color):\n font = pygame.font.SysFont('comicsans', size, bold=True)\n label = font.render(text, 1, color)\n\n surface.blit(label, (TOP_LEFT_X + PLAY_WIDTH/2 - (label.get_width()/2),\n TOP_LEFT_Y + PLAY_HEIGHT/2 - label.get_height()/2))\n\ndef draw_grid(surface, grid):\n sx = TOP_LEFT_X\n sy = TOP_LEFT_Y\n for i in range(len(grid)):\n pygame.draw.line(surface, (128,128,128), (sx, sy + iBLOCK_SIZE), (sx+PLAY_WIDTH, sy + iBLOCK_SIZE))\n for j in range(len(grid[i])):\n pygame.draw.line(surface, (128,128,128), (sx + jBLOCK_SIZE, sy), (sx + jBLOCK_SIZE, sy + PLAY_HEIGHT))\n\ndef clear_rows(grid, locked):\n # Need to see if row is clear then shift every other row above down\n increment = 0\n for i in range(len(grid)-1, -1, -1):\n row = grid[i]\n if (0,0,0) not in row:\n increment += 1\n # Add positions to remove\n ind = i\n for j in range(len(row)):\n try:\n del locked[(j, i)]\n except:\n continue\n if increment > 0:\n # Shift every row above down\n for key in sorted(list(locked), key=lambda x: x[1])[::-1]:\n x, y = key\n if y < ind:\n newKey = (x, y + increment)\n locked[newKey] = locked.pop(key)\n return increment\n\ndef draw_next_shape(shape, surface):\n font = pygame.font.SysFont('comicsans', 30)\n label = font.render('Next Shape', 1, (255,255,255))\n\n sx = TOP_LEFT_X + PLAY_WIDTH + 50\n sy = TOP_LEFT_Y + PLAY_HEIGHT/2 - 100\n format = shape.shape[shape.rotation % len(shape.shape)]\n\n for i, line in enumerate(format):\n row = list(line)\n for j, column in enumerate(row):\n if column == '0':\n pygame.draw.rect(surface, shape.color, (sx + jBLOCK_SIZE, sy + iBLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)\n\n surface.blit(label, (sx + 10, sy - 30))\n\ndef update_score(nscore):\n score = max_score()\n\n with open('scores.txt', 'w') as f:\n if int(score) > nscore:\n f.write(str(score))\n else:\n f.write(str(nscore))\n\ndef max_score():\n try:\n with open('scores.txt', 'r') as f:\n lines = f.readlines()\n score = lines[0].strip()\n except:\n score = '0'\n return score\n\ndef draw_window(surface, grid, score=0, last_score=0):\n surface.fill((0,0,0))\n\n # Title\n font = pygame.font.SysFont('comicsans', 60)\n label = font.render('Tetris', 1, (255,255,255))\n\n surface.blit(label, (TOP_LEFT_X + PLAY_WIDTH / 2 - (label.get_width()/2), 30))\n\n # Current score\n font = pygame.font.SysFont('comicsans', 30)\n label = font.render('Score: ' + str(score), 1, (255,255,255))\n\n sx = TOP_LEFT_X - 200\n sy = TOP_LEFT_Y + 200\n\n surface.blit(label, (sx + 20, sy + 160))\n\n # High score\n label = font.render('High Score: ' + last_score, 1, (255,255,255))\n surface.blit(label, (sx + 20, sy + 200))\n\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n pygame.draw.rect(surface, grid[i][j],\n (TOP_LEFT_X + jBLOCK_SIZE, TOP_LEFT_Y + iBLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)\n\n # Draw grid and border\n draw_grid(surface, grid)\n pygame.draw.rect(surface, (255,0,0), (TOP_LEFT_X, TOP_LEFT_Y, PLAY_WIDTH, PLAY_HEIGHT), 5)\n\ndef main(win):\n last_score = max_score()\n\n locked_positions = {}\n grid = create_grid(locked_positions)\n\n change_piece = False\n run = True\n current_piece = get_shape()\n next_piece = get_shape()\n clock = pygame.time.Clock()\n fall_time = 0\n fall_speed = 0.5 # Seconds\n level_time = 0\n score = 0\n\n while run:\n grid = create_grid(locked_positions)\n fall_time += clock.get_rawtime()\n level_time += clock.get_rawtime()\n clock.tick()\n\n # Increase speed over time\n if level_time/1000 > 5:\n level_time = 0\n if fall_speed > 0.12:\n fall_speed -= 0.005\n\n # Handle piece falling\n if fall_time/1000 >= fall_speed:\n fall_time = 0\n current_piece.y +=1\n if not(valid_space(current_piece, grid)) and current_piece.y >0:\n current_piece.y -=1\n change_piece = True\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n pygame.display.quit()\n quit()\n\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n current_piece.x -=1\n if not(valid_space(current_piece, grid)):\n current_piece.x +=1\n elif event.key == pygame.K_RIGHT:\n current_piece.x +=1\n if not(valid_space(current_piece, grid)):\n current_piece.x -=1\n elif event.key == pygame.K_DOWN:\n current_piece.y +=1\n if not(valid_space(current_piece, grid)):\n current_piece.y -=1\n elif event.key == pygame.K_UP:\n current_piece.rotation = (current_piece.rotation +1) % len(current_piece.shape)\n if not(valid_space(current_piece, grid)):\n current_piece.rotation = (current_piece.rotation -1) % len(current_piece.shape)\n\n shape_pos = convert_shape_format(current_piece)\n\n # Add piece to the grid for drawing\n for i in range(len(shape_pos)):\n x, y = shape_pos[i]\n if y > -1:\n grid[y][x] = current_piece.color\n\n # Check if piece hit the ground\n if change_piece:\n for pos in shape_pos:\n locked_positions[(pos[0], pos[1])] = current_piece.color\n current_piece = next_piece\n next_piece = get_shape()\n change_piece = False\n # Clear rows\n cleared = clear_rows(grid, locked_positions)\n if cleared > 0:\n score += cleared * 10\n\n draw_window(win, grid, score, last_score)\n draw_next_shape(next_piece, win)\n pygame.display.update()\n\n # Check if user lost\n if check_lost(locked_positions):\n draw_text_middle(win, "YOU LOST!", 80, (255,255,255))\n pygame.display.update()\n pygame.time.delay(1500)\n run = False\n update_score(score)\n\ndef main_menu(win):\n run = True\n while run:\n win.fill((0,0,0))\n draw_text_middle(win, 'Press Any Key To Play', 60, (255,255,255))\n pygame.display.update()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n\n if event.type == pygame.KEYDOWN:\n main(win)\n\n pygame.quit()\n\nif name == 'main':\n win = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))\n pygame.display.set_caption('Tetris')\n main_menu(win) # start game\n

    Please suggest a fix for the error.

  2. Assistant

    The error you're encountering:

    SyntaxError: unexpected character after line continuation character
    

    indicates that Python is encountering an unexpected character immediately following a line continuation character (\). This typically happens when the code includes escape sequences like \n outside of string literals or if the code's formatting has been disrupted, causing Python to misinterpret the structure of the script.

    Probable Cause

    From the error message, it appears that the script is being read as a single continuous line with \n characters embedded within it, rather than being split into multiple properly formatted lines. This can happen if:

    1. Improper Formatting: The script contains literal \n characters intended to represent newlines, but they are not within string literals. Python interprets \n as an escape character sequence, which isn't valid outside of strings unless used correctly.

    2. Copy-Paste Issues: When copying the script from a source (like a website or document), the newlines might have been converted to \n characters unintentionally.

    3. Incorrect File Encoding or Handling: The file might have been saved or processed in a way that introduced \n literals instead of actual newline characters.

    How to Fix the Error

    1. Ensure Proper Line Breaks:

      • Open your Python script in a proper code editor (like VS Code, PyCharm, Sublime Text, or even Notepad++).
      • Verify that each statement starts on a new line and that there are no \n characters outside of string literals.
      • Remove any unnecessary \n characters that are not part of strings.
    2. Correct Indentation:

      • Python relies on indentation to define code blocks. Ensure that all blocks (loops, conditionals, function definitions, etc.) are correctly indented with spaces or tabs consistently.
    3. Review Line Continuations:

      • If you intended to use line continuations with \, ensure they are used correctly. Typically, line continuations are not necessary within parentheses (), brackets [], or braces {}.
    4. Reformat the Script:

      • If the entire script is on a single line with \n characters, you'll need to manually insert proper line breaks. Here's how you can do it:

    Example Correction

    Based on the error message, it seems like the first line of your script might incorrectly start with display.update()\n for event in pygame.event.get():\n .... Here's how to correct it:

    Incorrect Portion:

    display.update()\n        for event in pygame.event.get():\n            if event.type == pygame.QUIT:\n                run = False\n\n            if event.type == pygame.KEYDOWN:\n                main(win)\n\n    pygame.quit()\n\nif __name__ == '__main__':\n    win = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))\n    pygame.display.set_caption('Tetris')\n    main_menu(win)  # start game\n
    

    Corrected Portion:

    import pygame
    import random
    
    # [Rest of your code...]
    
    def main_menu(win):
        run = True
        while run:
            win.fill((0,0,0))
            draw_text_middle(win, 'Press Any Key To Play', 60, (255,255,255))
            pygame.display.update()
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    run = False
    
                if event.type == pygame.KEYDOWN:
                    main(win)
    
        pygame.quit()
    
    if __name__ == '__main__':
        win = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
        pygame.display.set_caption('Tetris')
        main_menu(win)  # start game
    

    Steps to Correct:

    1. Remove Literal \n Characters:

      • Ensure that \n is only used within string literals where you intend to represent a newline in a string (e.g., print("Line1\nLine2")).
      • Remove any \n that appear outside string literals.
    2. Insert Proper Line Breaks:

      • Break the code into multiple lines as shown in the corrected portion above.
      • Ensure that each block of code (like event handling within the while loop) is properly indented.
    3. Verify the Entire Script:

      • Go through the entire script to ensure there are no other instances of misplaced \n characters.
      • Ensure all functions, classes, and control structures are correctly defined and closed.

    Final Correct Script

    Here's the fully corrected and properly formatted script based on the code you provided:

    import pygame
    import random
    
    # Initialize Pygame
    pygame.init()
    
    # Screen dimensions
    SCREEN_WIDTH = 300
    SCREEN_HEIGHT = 600
    BLOCK_SIZE = 30
    
    # Play area dimensions
    PLAY_WIDTH = 10 * BLOCK_SIZE  # 300
    PLAY_HEIGHT = 20 * BLOCK_SIZE  # 600
    TOP_LEFT_X = (SCREEN_WIDTH - PLAY_WIDTH) // 2
    TOP_LEFT_Y = SCREEN_HEIGHT - PLAY_HEIGHT
    
    # Define shapes
    S = [['.....',
          '.....',
          '..00.',
          '.00..',
          '.....'],
         ['.....',
          '..0..',
          '..00.',
          '...0.',
          '.....']]
    
    Z = [['.....',
          '.....',
          '.00..',
          '..00.',
          '.....'],
         ['.....',
          '..0..',
          '.00..',
          '.0...',
          '.....']]
    
    I = [['..0..',
          '..0..',
          '..0..',
          '..0..',
          '.....'],
         ['.....',
          '0000.',
          '.....',
          '.....',
          '.....']]
    
    O = [['.....',
          '.....',
          '.00..',
          '.00..',
          '.....']]
    
    J = [['.....',
          '.0...',
          '.000.',
          '.....',
          '.....'],
         ['.....',
          '..00.',
          '..0..',
          '..0..',
          '.....'],
         ['.....',
          '.....',
          '.000.',
          '...0.',
          '.....'],
         ['.....',
          '..0..',
          '..0..',
          '.00..',
          '.....']]
    
    L = [['.....',
          '...0.',
          '.000.',
          '.....',
          '.....'],
         ['.....',
          '..0..',
          '..0..',
          '..00.',
          '.....'],
         ['.....',
          '.....',
          '.000.',
          '.0...',
          '.....'],
         ['.....',
          '.00..',
          '..0..',
          '..0..',
          '.....']]
    
    T = [['.....',
          '..0..',
          '.000.',
          '.....',
          '.....'],
         ['.....',
          '..0..',
          '..00.',
          '..0..',
          '.....'],
         ['.....',
          '.....',
          '.000.',
          '..0..',
          '.....'],
         ['.....',
          '..0..',
          '.00..',
          '..0..',
          '.....']]
    
    # List of shapes and their colors
    SHAPES = [S, Z, I, O, J, L, T]
    SHAPE_COLORS = [(0, 255, 0),    # S - Green
                    (255, 0, 0),    # Z - Red
                    (0, 255, 255),  # I - Cyan
                    (255, 255, 0),  # O - Yellow
                    (255, 165, 0),  # J - Orange
                    (0, 0, 255),    # L - Blue
                    (128, 0, 128)]  # T - Purple
    
    # Define the Piece class
    class Piece:
        def __init__(self, x, y, shape):
            self.x = x  # Horizontal position on the grid
            self.y = y  # Vertical position on the grid
            self.shape = shape
            self.color = SHAPE_COLORS[SHAPES.index(shape)]
            self.rotation = 0  # Number from 0-3
    
    def create_grid(locked_positions={}):
        grid = [[(0,0,0) for _ in range(10)] for _ in range(20)]
    
        for i in range(len(grid)):
            for j in range(len(grid[i])):
                if (j,i) in locked_positions:
                    grid[i][j] = locked_positions[(j,i)]
        return grid
    
    def convert_shape_format(shape):
        positions = []
        format = shape.shape[shape.rotation % len(shape.shape)]
    
        for i, line in enumerate(format):
            row = list(line)
            for j, column in enumerate(row):
                if column == '0':
                    positions.append((shape.x + j - 2, shape.y + i - 4))
    
        return positions
    
    def valid_space(shape, grid):
        accepted_positions = [[(j, i) for j in range(10) if grid[i][j] == (0,0,0)] for i in range(20)]
        accepted_positions = [j for sub in accepted_positions for j in sub]
    
        formatted = convert_shape_format(shape)
    
        for pos in formatted:
            if pos not in accepted_positions:
                if pos[1] >= 0:
                    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(5, 0, random.choice(SHAPES))
    
    def draw_text_middle(surface, text, size, color):
        font = pygame.font.SysFont('comicsans', size, bold=True)
        label = font.render(text, 1, color)
    
        surface.blit(label, (TOP_LEFT_X + PLAY_WIDTH/2 - (label.get_width()/2),
                             TOP_LEFT_Y + PLAY_HEIGHT/2 - label.get_height()/2))
    
    def draw_grid(surface, grid):
        sx = TOP_LEFT_X
        sy = TOP_LEFT_Y
        for i in range(len(grid)):
            pygame.draw.line(surface, (128,128,128), (sx, sy + i*BLOCK_SIZE), (sx+PLAY_WIDTH, sy + i*BLOCK_SIZE))
            for j in range(len(grid[i])):
                pygame.draw.line(surface, (128,128,128), (sx + j*BLOCK_SIZE, sy), (sx + j*BLOCK_SIZE, sy + PLAY_HEIGHT))
    
    def clear_rows(grid, locked):
        # Need to see if row is clear then shift every other row above down
        increment = 0
        ind = -1
        for i in range(len(grid)-1, -1, -1):
            row = grid[i]
            if (0,0,0) not in row:
                increment += 1
                # Add positions to remove
                ind = i
                for j in range(len(row)):
                    try:
                        del locked[(j, i)]
                    except:
                        continue
        if increment > 0:
            # Shift every row above down
            for key in sorted(list(locked), key=lambda x: x[1])[::-1]:
                x, y = key
                if y < ind:
                    newKey = (x, y + increment)
                    locked[newKey] = locked.pop(key)
        return increment
    
    def draw_next_shape(shape, surface):
        font = pygame.font.SysFont('comicsans', 30)
        label = font.render('Next Shape', 1, (255,255,255))
    
        sx = TOP_LEFT_X + PLAY_WIDTH + 50
        sy = TOP_LEFT_Y + PLAY_HEIGHT/2 - 100
        format = shape.shape[shape.rotation % len(shape.shape)]
    
        for i, line in enumerate(format):
            row = list(line)
            for j, column in enumerate(row):
                if column == '0':
                    pygame.draw.rect(surface, shape.color, (sx + j*BLOCK_SIZE, sy + i*BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)
    
        surface.blit(label, (sx + 10, sy - 30))
    
    def update_score(nscore):
        score = max_score()
    
        with open('scores.txt', 'w') as f:
            if int(score) > nscore:
                f.write(str(score))
            else:
                f.write(str(nscore))
    
    def max_score():
        try:
            with open('scores.txt', 'r') as f:
                lines = f.readlines()
                score = lines[0].strip()
        except:
            score = '0'
        return score
    
    def draw_window(surface, grid, score=0, last_score=0):
        surface.fill((0,0,0))
    
        # Title
        font = pygame.font.SysFont('comicsans', 60)
        label = font.render('Tetris', 1, (255,255,255))
    
        surface.blit(label, (TOP_LEFT_X + PLAY_WIDTH / 2 - (label.get_width()/2), 30))
    
        # Current score
        font = pygame.font.SysFont('comicsans', 30)
        label = font.render('Score: ' + str(score), 1, (255,255,255))
    
        sx = TOP_LEFT_X - 200
        sy = TOP_LEFT_Y + 200
    
        surface.blit(label, (sx + 20, sy + 160))
    
        # High score
        label = font.render('High Score: ' + last_score, 1, (255,255,255))
        surface.blit(label, (sx + 20, sy + 200))
    
        for i in range(len(grid)):
            for j in range(len(grid[i])):
                pygame.draw.rect(surface, grid[i][j],
                                 (TOP_LEFT_X + j*BLOCK_SIZE, TOP_LEFT_Y + i*BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)
    
        # Draw grid and border
        draw_grid(surface, grid)
        pygame.draw.rect(surface, (255,0,0), (TOP_LEFT_X, TOP_LEFT_Y, PLAY_WIDTH, PLAY_HEIGHT), 5)
    
    def main(win):
        last_score = max_score()
    
        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  # Seconds
        level_time = 0
        score = 0
    
        while run:
            grid = create_grid(locked_positions)
            fall_time += clock.get_rawtime()
            level_time += clock.get_rawtime()
            clock.tick()
    
            # Increase speed over time
            if level_time/1000 > 5:
                level_time = 0
                if fall_speed > 0.12:
                    fall_speed -= 0.005
    
            # Handle piece falling
            if fall_time/1000 >= 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 = (current_piece.rotation +1) % len(current_piece.shape)
                        if not(valid_space(current_piece, grid)):
                            current_piece.rotation = (current_piece.rotation -1) % len(current_piece.shape)
    
            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:
                    grid[y][x] = current_piece.color
    
            # Check if piece hit the ground
            if change_piece:
                for pos in shape_pos:
                    locked_positions[(pos[0], pos[1])] = current_piece.color
                current_piece = next_piece
                next_piece = get_shape()
                change_piece = False
                # Clear rows
                cleared = clear_rows(grid, locked_positions)
                if cleared > 0:
                    score += cleared * 10
    
            draw_window(win, grid, score, last_score)
            draw_next_shape(next_piece, win)
            pygame.display.update()
    
            # Check if user lost
            if check_lost(locked_positions):
                draw_text_middle(win, "YOU LOST!", 80, (255,255,255))
                pygame.display.update()
                pygame.time.delay(1500)
                run = False
                update_score(score)
    
    def main_menu(win):
        run = True
        while run:
            win.fill((0,0,0))
            draw_text_middle(win, 'Press Any Key To Play', 60, (255,255,255))
            pygame.display.update()
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    run = False
    
                if event.type == pygame.KEYDOWN:
                    main(win)
    
        pygame.quit()
    
    if __name__ == '__main__':
        win = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
        pygame.display.set_caption('Tetris')
        main_menu(win)  # start game
    

    Additional Recommendations

    1. Use a Code Editor: Always use a code editor that correctly handles Python syntax and displays errors in real-time. This can help catch formatting issues early.

    2. Consistent Indentation: Python is sensitive to indentation. Ensure you're using spaces or tabs consistently throughout your script. Mixing them can lead to unexpected errors.

    3. Version Compatibility: Ensure you're using a compatible version of Python and Pygame. The script should be compatible with Python 3.x and the latest stable release of Pygame.

    4. Run Incrementally: If you encounter errors, try running smaller sections of your code to isolate the problem. This can make debugging more manageable.

    5. Check for Hidden Characters: Sometimes, especially when copying code from certain sources, hidden characters or incorrect encoding can cause issues. Use a code editor that can reveal invisible characters or retype problematic sections manually.

    By carefully reviewing and formatting your script as shown above, the SyntaxError should be resolved, allowing your Tetris game to run correctly.