Skip to content
TheChatArchiveThe Chat Archive
gpt-4-1106-preview· openaiHugging Face Suzhen/CodeChat

i have this original function that operates fine def processmove(move, gameboard):…

  1. User

    i have this original function that operates fine

    def process_move(move, game_board):

    global san_moves, sa_number, total_moves, history, user_turn, chat_window, valid_moves, llm_turn, board

    try:

    if llm_turn:
    
        result_label.config(text="It's not your turn to move.")
    
        return
    
    
    
    if move in game_board.legal_moves:
    
        game_board.push(move)
    
        fen_notation = game_board.fen()
    
        shredder_fen = chess.Board(fen_notation)
    
        result_label.config(text=f"FEN Notation: {fen_notation}")
    
        draw_board(game_board)
    
    
    
        if total_moves % 2 == 1:
    
            sa_number += 1
    
            san_moves += f"{sa_number}. {move} "
    
            total_moves += 1
    
            history = []
    
            move_list = re.findall(r'\((.*?)\)', str(valid_moves))
    
            chat_window.delete(1.0, tk.END)
    
            role = "user"
    
        else:
    
            san_moves += f"{move} "
    
            total_moves += 1
    
    
    
        print("SAN Moves:", san_moves)
    
    
    
        if move_list == ['']:
    
            message = "Checkmate."
    
            chat_window.insert(tk.END, f"\nCheckmate")
    
        else:
    
            message = f"Check out the state of this board\n\n {shredder_fen}. What should this tell me about the move I need to make. I can only choose moves from this list, {move_list}.\n\n I can only choose moves from this list, {move_list}. Help me pick the best move, and reply with one word, move."
    
            history.append({"role": role, "content": message})
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
            interact_with_llm(message)
    
            print("line 77")
    
    
    
        llm_turn = True
    
        last_assistant_message = next((item['content'] for item in reversed(history) if item['role'] == 'assistant'), None)
    
    
    
    
    
    
    
        if last_assistant_message:
    
            first_word = last_assistant_message.split()[0]
    
            llm_move = first_word.replace('.', '')
    
            print(llm_move)
    
            match = re.search(r'([a-hA-H])(\d)', llm_move)
    
            print(f"the match is {match}")
    
            if match:
    
                # Extract the entire matched substring
    
                llm_square_notation = match.group(0)
    
                print(f"the match is {llm_square_notation}")
    
                # Get attackers for the dynamically determined square
    
                attackers = board.attackers(chess.WHITE, chess.parse_square(llm_square_notation.lower()))
    
                print(attackers)
    
                update_game_board(llm_move)
    
                llm_turn = False
    
            else:
    
                print("Invalid move format.")
    

    except Exception as e:

    print(f"Error in LLM request: {e}")
    
    chat_window.insert(tk.END, "\nAssistant: Error in LLM request")
    

    except ValueError:

    result_label.config(text="Invalid move")
    

    i tried splitting the function into two functions, like this:

    def process_move(move, game_board):

    global san_moves, sa_number, total_moves, history, user_turn, chat_window, valid_moves, llm_turn, board

    try:

    if llm_turn:
    
        result_label.config(text="It's not your turn to move.")
    
        return
    
    
    
    if move in game_board.legal_moves:
    
        game_board.push(move)
    
        draw_board(game_board)
    
        sa_number += 1
    
        san_moves += f"{sa_number}. {move} "
    
        total_moves += 1
    
        move_list = re.findall(r'\((.*?)\)', str(valid_moves))
    
        print("SAN Moves:", san_moves)
    
    
    
        if move_list == ['']:
    
            message = "Checkmate."
    
            chat_window.insert(tk.END, f"\nCheckmate")
    
        else:
    
            llm_move_choice()
    

    except ValueError:

    result_label.config(text="Invalid move")
    

    def llm_move_choice():

    global san_moves, sa_number, total_moves, history, user_turn, chat_window, valid_moves, llm_turn, board

    chat_window.delete(1.0, tk.END)

    fen_notation = game_board.fen()

    shredder_fen = chess.Board(fen_notation)

    result_label.config(text=f"FEN Notation: {fen_notation}")

    history = []

    role = "user"

    move_list = re.findall(r'((.*?))', str(valid_moves))

    message = f"Check out the state of this board\n\n {shredder_fen}. What should this tell me about the move I need to make. I can only choose moves from this list, {move_list}.\n\n I can only choose moves from this list, {move_list}. Help me pick the best move, and reply with one word, move."

    history.append({"role": role, "content": message})

    interact_with_llm(message)

    print("line 78")

    last_assistant_message = next((item['content'] for item in reversed(history) if item['role'] == 'assistant'), None)

    if last_assistant_message:

    first_word = last_assistant_message.split()[0]
    
    llm_move = first_word.replace('.', '')
    
    print(f"llm_move from line 83 is {llm_move}")
    
    match = re.search(r'([a-hA-H])(\d)', llm_move)
    
    print(f"the match is {match}")
    
    if match:
    
        # Extract the entire matched substring
    
        llm_square_notation = match.group(0)
    
        print(f"the match is {llm_square_notation}")
    
        # Get attackers for the dynamically determined square
    
        attackers = board.attackers(chess.WHITE, chess.parse_square(llm_square_notation.lower()))
    
        print(attackers)
    
        update_game_board(llm_move)
    
        llm_turn = False
    
    else:
    
        print("Invalid move format.")
    

    except Exception as e:

    print(f"Error in LLM request: {e}")
    
    chat_window.insert(tk.END, "\nAssistant: Error in LLM request")
    

    except ValueError:

    result_label.config(text="Invalid move")
    
  2. Assistant

    It looks like you're trying to refactor a function process_move that reacts to a move in a chess game, interacting with a large language model (LLM) and updating the game state accordingly. Your refactoring approach involves splitting the original function into two: process_move and llm_move_choice. However, your llm_move_choice function seems to include code that should not raise a ValueError.

    The refactored code has a few issues; let's address those:

    1. The try and except blocks are misplaced. The except blocks should be closely associated with the code that can raise exceptions.
    2. The game_board parameter is not available in llm_move_choice. You should either pass it as an argument to the function or handle the board-related logic differently.
    3. Global variable declarations need to be placed at the top of each function where you are modifying them.
    4. It is not clear where interact_with_llm and update_game_board functions are defined. These need to be visible to your llm_move_choice function.

    Here's an updated version of your code:

    (First part, no change here except making sure the two functions are correctly called)

    def process_move(move, game_board):
        global san_moves, sa_number, total_moves, history, user_turn, chat_window, valid_moves, llm_turn, board
        
        try:
            if llm_turn:
                result_label.config(text="It's not your turn to move.")
                return
    
            if move in game_board.legal_moves:
                game_board.push(move)
                draw_board(game_board)
                
                # Update move number and history. Even if it's supposed to be the LLM's turn after this, increment the number
                sa_number += (total_moves % 2)
                if total_moves % 2 == 0:
                    san_moves += f"{sa_number}. {move} "
                else:
                    san_moves += f"{move} "
                total_moves += 1
    
                move_list = re.findall(r'\((.*?)\)', str(valid_moves))
                print("SAN Moves:", san_moves)
    
                if move_list == ['']:
                    message = "Checkmate."
                    chat_window.insert(tk.END, f"\nCheckmate")
                else:
                    llm_move_choice(game_board)  # Pass game_board as an argument
    
        except ValueError:
            result_label.config(text="Invalid move")
    

    (Second part, corrected with game_board as a parameter and proper handling of exceptions)

    def llm_move_choice(game_board):
        global san_moves, sa_number, total_moves, history, user_turn, chat_window, valid_moves, llm_turn, board
    
        chat_window.delete(1.0, tk.END)
        fen_notation = game_board.fen()
        shredder_fen = chess.Board(fen_notation)
        result_label.config(text=f"FEN Notation: {fen_notation}")
        
        history = []
        role = "user"  # This looks like a local variable; it does not need to be global unless it's used elsewhere
        move_list = re.findall(r'\((.*?)\)', str(valid_moves))
    
        message = "...\n\n"  # Your message here
        history.append({"role": role, "content": message})        
                
        try:
            interact_with_llm(message)
            print("line 78")
            llm_turn = False  # Assuming the LLM has successfully made a move
        except Exception as e:
            print(f"Error in LLM request: {e}")
            chat_window.insert(tk.END, "\nAssistant: Error in LLM request")
    

    Note that the handling of last_assistant_message, llm_move, and update_game_board code is removed from the llm_move_choice function. You'll need to consider how you want to handle these steps, likely after the call to llm_move_choice. They seem to involve parsing a response from an assistant and updating the game board, so those actions could be in a separate function entirely or still part of the process_move function depending on how you expect the control flow to work.

    Remember that in Python, it's crucial to pass arguments to functions correctly when refactoring code and to properly scope exception handlers for the code they're intended to catch errors in.