using Random
using ProgressMeter
include("./utils.jl")

using Distributed
addpross(4)

@everywhere begin
    include("./mcts.jl")
end

@everywhere function playonce()
    game = Game()
    randomPlace(game, 2)
    playerX = MCTS()
    playerO = MCTS()
    chunk = Array{Array{Float32, 3}, Array{Float32, 1}, Integer}[]
    while iszero(game.winner)
        move, p = playerX(game, Clients)
        data = getAugmentation(game, p)
        append!(chunk, data)
        place(game, move)

        !iszero(game.winner) && break
        move, p = playerO(game, Clients)
        data = getAugmentation(game, p)
        append!(chunk, data)
        place(game, move)
    end
    @async closeClients(playerX.Clients)
    @async closeClients(playerO.Clients)
    for e in chunk
        @inbounds e[3] .*= game.winner
    end
    return chunk
end

function playNgames(N::Integer=64, bs::Integer=16)
    results = @showprogress pmap(1:N, batch_size=bs) do x
        playonce()
    end
    save_data(shuffle!(reduce(append!, results)))
    nothing
end
