@name negamax
@inputs 
@outputs 
@persist 
@trigger 



if (first()) {
    
    Game = table(
                array(0, 0, 0, 0, 0, 0, 0),
                array(0, 0, 0, 0, 0, 0, 0),
                array(0, 0, 0, 0, 0, 0, 0),
                array(0, 0, 0, 0, 0, 0, 0),
                array(0, 0, 0, 0, 0, 0, 0),
                array(0, 0, 0, 0, 0, 0, 0)
            )
    
    Eval = table(
            array(3, 4,  5, 7,   5, 4, 3),
            array(4, 6,  8, 10,  8, 6, 4),
            array(5, 8, 11, 13, 11, 8, 5),
            array(5, 8, 11, 13, 11, 8, 5),
            array(4, 6,  8, 10,  8, 6, 4),
            array(3, 4,  5,  7,  5, 4, 3)
        )
    
    BestCol = 0
    
    function number eval( G:table ) {
            local Sum = 128
            for (Row = 1, 6) {
                for (Col = 1, 7) {
                    if (G[Row, array][Col, number] != 0) {
                        Sum += Eval[Row, array][Col, number]    
                    }
                }
            }
            
            return Sum 
    }
    function number negamax( G:table, Depth, Turn ) {
        if (Depth == 0) { 
            return eval(G)*Turn
        }
        
        local Score = -10000
        local Best  = 0
        
        for (Column = 1, 7) {
            local Row = 6
            for (R = 1, Row) {
                if (G[R, array][Column, number] != 0) {
                    Row--
                    break    
                }
            }
            
            if (Row > 0) {
                G[Row - 1, array][Column, number] = Turn
                
                local Value = -negamax(G, Depth - 1, -Turn)
                if (Score < Value) {
                    Score = Value
                    Best = Column 
                }
                
                G[Row - 1, array][Column, number] = 0   
            }
        }
        
        BestCol = Best
    
        return Score  
    }
    
    for (Row = 1, 6) {
        print(Game[Row, array])    
    }


#print( negamax( Game, 2, -1 ) )
#print(BestCol)

}

