Untitled

mail@pastecode.io avatar
unknown
plain_text
19 days ago
41 kB
2
Indexable
Never
-- Initialization function on game load
function onLoad()
    createCivilizationButtons()
    createStartButton()
    createRandomCivilizationButton()
   -- checkObjectPosition("dda33b")
end

function checkObjectPosition(guid)
    local obj = getObjectFromGUID(guid)
    if obj then
        local position = obj.getPosition()
        broadcastToAll("Position de l'objet avec GUID " .. guid .. ": x=" .. position.x .. ", y=" .. position.y .. ", z=" .. position.z, {1, 1, 1})
        log("Position de l'objet avec GUID " .. guid .. ": x=" .. position.x .. ", y=" .. position.y .. ", z=" .. position.z)
    else
        broadcastToAll("Objet avec GUID " .. guid .. " non trouvé.", {1, 0, 0})
        log("Objet avec GUID " .. guid .. " non trouvé.")
    end
end

-- Define the 12 Civilizations, their Face A and Face B rulers with updated deck GUIDs
local civilizations = {
    ["ROYAUME DE FRANCE"] = {faceA = "Roi François Ier", faceB = "Roi Henri IV", civGUID = "878f6c", ship = "0d7664", deck = "51a678"},
    ["ROYAUME D'ANGLETERRE"] = {faceA = "Reine Elisabeth Ire", faceB = "Roi Henri VIII", civGUID = "0ca55d", ship = "1bc684", deck = "48cee3"},
    ["ROYAUME D'ÉCOSSE"] = {faceA = "Reine Marie Stuart", faceB = "Roi Jacques VI", civGUID = "81bf69", ship = "312a93", deck = "617c85"},
    ["ROYAUME DE PORTUGAL"] = {faceA = "Roi Manuel Ier", faceB = "Roi Jean III Le Pieux", civGUID = "d4f7e8", ship = "4b53ee", deck = "2ea990"},
    ["MONARCHIE ESPAGNOLE"] = {faceA = "Roi Philippe II", faceB = "Roi Ferdinand V Le Catholique", civGUID = "af2bac", ship = "2fcdcb", deck = "680f3d"},
    ["GRAND-DUCHÉ DE TOSCANE"] = {faceA = "Grand-duc Côme Ier de Toscane", faceB = "Grand-duc François Ier de Médicis", civGUID = "d3c468", ship = "81f996", deck = "427e57"},
    ["SAINT-EMPIRE"] = {faceA = "Empereur Charles Quint", faceB = "Empereur Ferdinand Ier", civGUID = "2f7beb", ship = "54d918", deck = "03c3bb"},
    ["TSARAT DE RUSSIE"] = {faceA = "Tsar Ivan IV le Terrible", faceB = "Tsar Fiodor Ier", civGUID = "1e5cd9", ship = "f9960d", deck = "404c94"},
    ["EMPIRE OTTOMAN"] = {faceA = "Sultan Soliman Ier le Magnifique", faceB = "Sultan Sélim II", civGUID = "96e604", ship = "026646", deck = "b067d9"},
    ["EMPIRE MOGHOL"] = {faceA = "Empereur Akbar le Grand", faceB = "Empereur Humayun", civGUID = "8a7afa", ship = "ae98eb", deck = "331364"},
    ["DYNASTIE MING"] = {faceA = "Empereur Jiajing", faceB = "Empereur Wanli", civGUID = "fd0891", ship = "2650b7", deck = "3f84a0"},
    ["SHOGUNAT DU NIPPON"] = {faceA = "Daimyo Oda Nobunaga", faceB = "Shogun Ashikaga Yoshiteru", civGUID = "687240", ship = "e21296", deck = "610e8c"}
}

-- Create buttons for civilization selection (Face A and B)
function createCivilizationButtons()
    local civZones = {'de439d', '7f9575', '0aedbd', 'f366a6', '7da3cb', 'ccc956', 'fdff38', 'd5327c', '65c7ca', 'acae12', 'b5cd2d', '3563c9'}
    for i, civZoneGUID in ipairs(civZones) do
        local obj = getObjectFromGUID(civZoneGUID)
        if obj then
            obj.createButton({
                click_function = "chooseFaceA", 
                function_owner = self,
                label          = "A",
                position       = {0.25, -0.5, 0.6},
                rotation       = {0, 180, 0},
                width          = 70, 
                height         = 70, 
                font_size      = 50, 
                color          = {0.2, 0.6, 1}, 
                font_color     = {1, 1, 1}
            })
            obj.createButton({
                click_function = "chooseFaceB", 
                function_owner = self,
                label          = "B",
                position       = {-0.25, -0.5, 0.6},
                rotation       = {0, 180, 0},
                width          = 70, 
                height         = 70, 
                font_size      = 50, 
                color          = {1, 0.5, 0.2},  
                font_color     = {1, 1, 1}
            })
        end
    end
end

-- Create "Démarrer" and "Choisir aléatoirement" buttons
function createStartButton()
    local buttonGUID = "c0c649"
    local obj = getObjectFromGUID(buttonGUID)
    if obj then
        obj.createButton({
            click_function = "startGame",
            function_owner = self,
            label          = "Démarrer",
            position       = {0, -0.5, 0},
            rotation       = {0, 180, 0},
            width          = 750,
            height         = 350,
            font_size      = 50,
            color          = {1, 0, 0},
            font_color     = {1, 1, 1},
            tooltip        = "Cliquez pour démarrer la partie"
        })
    end
end

function createRandomCivilizationButton()
    local buttonGUID = "c0c649"
    local obj = getObjectFromGUID(buttonGUID)
    if obj then
        obj.createButton({
            click_function = "chooseRandomCivilization",
            function_owner = self,
            label          = "Choisir aléatoirement",
            position       = {0, -0.5, 1},
            rotation       = {0, 180, 0},
            width          = 750,
            height         = 350,
            font_size      = 50,
            color          = {1, 1, 1},
            font_color     = {0, 0, 0},
            tooltip        = "Cliquez pour choisir une civilisation aléatoire"
        })
    end
end

-- Handle selection of Face A for a specific civilization
function chooseFaceA(obj, player_color)
    print("chooseFaceA triggered")
    print("Object GUID:", obj.getGUID())  -- Verify if the obj is valid
    print("Player color:", player_color)  -- Verify the player's color

    -- Call the test function to get the scripting zone GUID
    local zoneGUID = testCivilizationZone(obj, player_color)
    log("Scripting Zone GUID for Face A: " .. tostring(zoneGUID))

    -- Assign the civilization after testing
    assignCivilization(obj, "A", player_color)
end

-- Handle selection of Face B for a specific civilization
function chooseFaceB(obj, player_color)
    print("chooseFaceB triggered")
    print("Object GUID:", obj.getGUID())
    print("Player color:", player_color)

    -- Call the test function to get the scripting zone GUID
    local zoneGUID = testCivilizationZone(obj, player_color)
    log("Scripting Zone GUID for Face B: " .. tostring(zoneGUID))

    -- Assign the civilization after testing
    assignCivilization(obj, "B", player_color)
end


-- Randomly assign a civilization and face (A or B) when the "Choisir aléatoirement" button is clicked
function chooseRandomCivilization(obj, player_color)
    local availableCivs = {}
    
    -- Gather available civilizations
    for civName, data in pairs(civilizations) do
        local civCard = getObjectFromGUID(data.civGUID)
        if civCard and civCard.getPosition().y < 5 then -- Check if civilization is already assigned
            table.insert(availableCivs, civName)
        end
    end

    -- Check if there are any available civilizations
    if #availableCivs > 0 then
        local randomCiv = availableCivs[math.random(1, #availableCivs)]
        local randomFace = math.random() > 0.5 and "A" or "B"

        -- Assign the civilization and move cards for the selected civilization
        assignCivilization(getObjectFromGUID(civilizations[randomCiv].civGUID), randomFace, player_color)
        moveCivilizationToPlayer(randomCiv, player_color)

        -- Broadcast the chosen civilization
        broadcastToAll(player_color .. " a choisi " .. randomCiv .. " avec " .. 
            (randomFace == "A" and civilizations[randomCiv].faceA or civilizations[randomCiv].faceB) .. " (Face " .. randomFace .. ")", {1, 1, 1})

        -- Flip the civilization card if Face B is chosen
        if randomFace == "B" then
            local civilizationCard = getObjectFromGUID(civilizations[randomCiv].civGUID)
            if civilizationCard then
                Wait.time(function()
                    if not civilizationCard.is_face_down then
                        civilizationCard.flip()
                    end
                end, 1)  -- Delay the flip to ensure the card is placed before flipping
            end
        end

        -- Now, verify and move the sixth card after 3 seconds for smoothness
        Wait.time(function()
            local zoneGUID = getScriptingZoneGUID(randomCiv)
            verifyScriptingZoneContents(zoneGUID, player_color)  -- Use the same function as for buttons A and B
        end, 3)

    else
        -- If no civilizations are available, broadcast an error message
        broadcastToAll("Toutes les civilisations ont déjà été attribuées.", {1, 0, 0})
    end
end

-- Helper function to map civilization name to its scripting zone GUID
function getScriptingZoneGUID(civName)
    local scriptZoneToCiv = {
        ["ROYAUME DE FRANCE"] = "de439d",
        ["MONARCHIE ESPAGNOLE"] = "7f9575",
        ["ROYAUME DE PORTUGAL"] = "0aedbd",
        ["SAINT-EMPIRE"] = "f366a6",
        ["EMPIRE OTTOMAN"] = "7da3cb",
        ["DYNASTIE MING"] = "ccc956",
        ["ROYAUME D'ÉCOSSE"] = "fdff38",
        ["ROYAUME D'ANGLETERRE"] = "d5327c",
        ["GRAND-DUCHÉ DE TOSCANE"] = "65c7ca",
        ["TSARAT DE RUSSIE"] = "acae12",
        ["EMPIRE MOGHOL"] = "b5cd2d",
        ["SHOGUNAT DU NIPPON"] = "3563c9"
    }
    
    return scriptZoneToCiv[civName]
end




-- Function to assign civilization and move the decks
function assignCivilization(obj, face, player_color)
    log("assignCivilization triggered for face: " .. face .. " and player_color: " .. player_color)
    
    local scriptZoneToCiv = {
        ['de439d'] = "ROYAUME DE FRANCE",
        ['7f9575'] = "MONARCHIE ESPAGNOLE",
        ['0aedbd'] = "ROYAUME DE PORTUGAL",
        ['f366a6'] = "SAINT-EMPIRE",
        ['7da3cb'] = "EMPIRE OTTOMAN",
        ['ccc956'] = "DYNASTIE MING",
        ['fdff38'] = "ROYAUME D'ÉCOSSE",
        ['d5327c'] = "ROYAUME D'ANGLETERRE",
        ['65c7ca'] = "GRAND-DUCHÉ DE TOSCANE",
        ['acae12'] = "TSARAT DE RUSSIE",
        ['b5cd2d'] = "EMPIRE MOGHOL",
        ['3563c9'] = "SHOGUNAT DU NIPPON"
    }

    local zoneGUID = obj.getGUID()
    local civName = scriptZoneToCiv[zoneGUID]

    if civName then
        log("Civilization assigned: " .. civName)
        local ruler = face == "A" and civilizations[civName].faceA or civilizations[civName].faceB
        broadcastToAll(player_color .. " a choisi " .. civName .. " avec " .. ruler .. " (Face " .. face .. ")", {1, 1, 1})
        moveCivilizationToPlayer(civName, player_color)

        local civilizationCard = getObjectFromGUID(civilizations[civName].civGUID)
        if face == "B" and civilizationCard then
            Wait.time(function()
                if not civilizationCard.is_face_down then
                    civilizationCard.flip()
                end
            end, 1)
        end
    else
        log("Error: Civilization not found for GUID: " .. zoneGUID)
    end
end

-- Move the civilization's cards to the player's zones, now placing the deck cards in the corresponding slots
function moveCivilizationToPlayer(civName, player_color)
    local playerZones = {
        Red = {
            civilizationZone = "ffebbf", 
            deckZone = "504b03", 
            mainDeck = "b17dca", 
            civilizationSlots = {"dddf31", "eea4f2", "a75979", "a30a04", "0eeae0", "98d254"}
        },
        Blue = {
            civilizationZone = "4be444", 
            deckZone = "ef512f", 
            mainDeck = "99bc2d", 
            civilizationSlots = {"d259e1", "d86d08", "56108f", "158f5a", "052dba", "514f3d"}
        }
    }

    local data = civilizations[civName]
    local playerZone = playerZones[player_color]

    -- Move the civilization card to the player's designated civilization zone
    local civilizationCard = getObjectFromGUID(data.civGUID)
    if civilizationCard then
        civilizationCard.setPositionSmooth(getObjectFromGUID(playerZone.civilizationZone).getPosition())
    else
        log("Error: Civilization card not found for " .. civName)
    end

    -- Move the ship card to the player's main deck
    local shipCard = getObjectFromGUID(data.ship)
    if shipCard then
        shipCard.flip()
        local mainDeck = getObjectFromGUID(playerZone.mainDeck)
        if mainDeck then
            mainDeck.putObject(shipCard)
        else
            broadcastToAll("Error: Main deck not found for " .. player_color, {1, 0, 0})
        end
    else
        log("Error: Ship card not found for " .. civName)
    end

    -- Move the civilization deck to the player's deck zone and spread it across the civilization slots
    local civDeck = getObjectFromGUID(data.deck)
    if civDeck then
        -- Ensure the deck has at least 6 cards
        local objectsInDeck = civDeck.getObjects()
        if #objectsInDeck < 6 then
            broadcastToAll("Error: Civilization deck for " .. civName .. " has fewer than 6 cards.", {1, 0, 0})
            log("Error: Civilization deck for " .. civName .. " has fewer than 6 cards.")
            return
        end

        -- Loop through the first 5 cards and place them in the player's civilization slots 1 to 5
        for i = 1, 5 do
            Wait.time(function()
                local card = civDeck.takeObject({
                    index = 0,  -- Always take the top card
                    smooth = false,
                    callback_function = function(obj)
                        obj.setPositionSmooth(getObjectFromGUID(playerZone.civilizationSlots[i]).getPosition())
                        log("Placed card " .. i .. " in civilization slot " .. i .. " for " .. player_color)
                    end
                })
            end, i * 0.5)  -- Add a 0.5-second delay between each card placement for smoothness
        end
    else
        broadcastToAll("Error: Civilization deck not found for " .. civName, {1, 0, 0})
        log("Error: Civilization deck not found for " .. civName)
    end
end

-- Function to test and get the GUID of the clicked civilization's scripting zone
function testCivilizationZone(obj, player_color)
    -- Map the civilization names to their scripting zone GUIDs
    local scriptZoneToCiv = {
        ['de439d'] = "ROYAUME DE FRANCE",
        ['7f9575'] = "MONARCHIE ESPAGNOLE",
        ['0aedbd'] = "ROYAUME DE PORTUGAL",
        ['f366a6'] = "SAINT-EMPIRE",
        ['7da3cb'] = "EMPIRE OTTOMAN",
        ['ccc956'] = "DYNASTIE MING",
        ['fdff38'] = "ROYAUME D'ÉCOSSE",
        ['d5327c'] = "ROYAUME D'ANGLETERRE",
        ['65c7ca'] = "GRAND-DUCHÉ DE TOSCANE",
        ['acae12'] = "TSARAT DE RUSSIE",
        ['b5cd2d'] = "EMPIRE MOGHOL",
        ['3563c9'] = "SHOGUNAT DU NIPPON"
    }

    -- Get the clicked object's GUID (civilization card or zone)
    local zoneGUID = obj.getGUID()

    -- Find the corresponding civilization for the clicked zone GUID
    local civName = scriptZoneToCiv[zoneGUID]
    
    -- Log and return the GUID of the scripting zone for this civilization
    if civName then
        log("Civilization clicked: " .. civName)
        log("Scripting Zone GUID: " .. zoneGUID)
        
        -- Wait for 5 seconds, then verify the contents of the zone
Wait.time(function()
    log("3 seconds elapsed, now checking the contents of the zone for player " .. player_color)
    verifyScriptingZoneContents(zoneGUID, player_color)
end, 3)
        
        return zoneGUID
    else
        log("Error: Civilization not found for GUID: " .. zoneGUID)
        return nil
    end
end

-- Function to verify the contents of a scripting zone and move the identified card to the player's civilization slot 6
function verifyScriptingZoneContents(zoneGUID, player_color)
    -- Civilization slots based on player color
    local playerCivilizationSlots = {
        Red = "98d254", -- Slot 6 for Red player
        Blue = "514f3d" -- Slot 6 for Blue player
    }

    -- Get the object corresponding to the zone
    local zone = getObjectFromGUID(zoneGUID)

    -- Ensure the zone exists
    if zone then
        -- Retrieve all objects within the zone
        local objectsInZone = zone.getObjects()

        -- Log the number of objects found
        log("Number of objects in the zone: " .. #objectsInZone)

        -- Iterate through the objects and find the card
        for _, obj in ipairs(objectsInZone) do
            if obj and obj.tag == "Card" then
                local objName = obj.getName() or "Unknown Name" -- Handle case where getName() is nil
                local objGUID = obj.getGUID() or "Unknown GUID" -- Handle case where getGUID() is nil
                log("Card found: " .. objName .. " | GUID: " .. objGUID)

                -- Get the player's slot 6 based on player color
                local slotGUID = playerCivilizationSlots[player_color]
                
                -- Move the card to the player's civilization slot 6
                local slot = getObjectFromGUID(slotGUID)
                if slot then
                    obj.setPositionSmooth(slot.getPosition())
                    log("Moved card to civilization slot 6 for " .. player_color)
                else
                    log("Error: Slot GUID not found for player: " .. player_color)
                end
                
                break -- Stop after finding and moving the card
            else
                log("Ignored object: " .. (obj.getName() or "Unknown") .. " | Type: " .. (obj.tag or "Unknown"))
            end
        end
    else
        log("Error: Could not find zone with GUID: " .. zoneGUID)
    end
end


-- Start game setup when "Démarrer" is clicked
function startGame(obj, player_color)
    broadcastToAll("Que la partie commence !", {1, 1, 1})
    obj.clearButtons()

    -- Hide all civilization selection buttons after game starts
    for _, data in pairs(civilizations) do
        local civObject = getObjectFromGUID(data.civGUID)
        if civObject then
            civObject.clearButtons()
        end
    end

    -- Perform the game setup
    setupGame()
end

-- Function to set up the game after civilizations are chosen
function setupGame()
    shuffleGameDecks()
    setupMarkets()
    revealEventCard('dda33b', 'd74e3f')
    setupColonies()
    shuffleAndDealPlayerDecks()
    addConstantDeckButtons()
    addAssassinButtons()
    enableTurns()
    startPlayerTurn()
end

-- Shuffle decks and deal 5 cards to each player
function shuffleGameDecks()
    local deck_batiment = getObjectFromGUID('a9a1a6')
    local deck_personnage = getObjectFromGUID('5926ea')
    local deck_evenement = getObjectFromGUID('dda33b')
    local deck_colonieA = getObjectFromGUID('2156f1')
    local deck_colonieB = getObjectFromGUID('b2af7a')
    local deck_colonieC = getObjectFromGUID('29ca2a')
    local deck_colonieD = getObjectFromGUID('ade02c')

    if deck_batiment then deck_batiment.shuffle() end
    if deck_personnage then deck_personnage.shuffle() end
    if deck_evenement then deck_evenement.shuffle() end
    if deck_colonieA then deck_colonieA.shuffle() end
    if deck_colonieB then deck_colonieB.shuffle() end
    if deck_colonieC then deck_colonieC.shuffle() end
    if deck_colonieD then deck_colonieD.shuffle() end
end

-- Setup character and building markets
function setupMarkets()
    -- Character market without flipped cards
    setupMarket('5926ea', {'89def4', '2829a7', '591dfd'}, false)
    
    -- Building market without flipped cards
    setupMarket('a9a1a6', {'83f251', '93d9ea', '43bab5'}, false)
end

-- Function to set up the market by placing cards from the deck into the specified zones
function setupMarket(deckGUID, zoneGUIDs, shouldFlip)
    local deck = getObjectFromGUID(deckGUID)
    
    -- Check if the deck exists and has enough cards
    if deck then
        -- Loop through each zone and place the cards
        for i, zoneGUID in ipairs(zoneGUIDs) do
            local zone = getObjectFromGUID(zoneGUID)
            
            -- Ensure the zone exists before placing the card
            if zone then
                local card = deck.takeObject({
                    position = zone.getPosition(),
                    rotation = {0, 180, 0}, -- Adjust rotation if needed
                    smooth = true, -- Set to true for smooth movement
                })
            else
                log("Zone with GUID: " .. zoneGUID .. " not found!")
            end
        end
    else
        log("Deck with GUID: " .. deckGUID .. " not found!")
    end
end




-- Reveal an event card
function revealEventCard(eventDeckGUID, eventZoneGUID)
    local deck = getObjectFromGUID(eventDeckGUID)
    local zone = getObjectFromGUID(eventZoneGUID)
    local card = deck.takeObject({position = zone.getPosition(), smooth = false})
    card.flip()
end

-- Setup colony cards
function setupColonies()
    -- Adding a delay between the placement of each colony card for smoothness
    Wait.time(function() placeColonyCard('2156f1', 'db6451') end, 0.5)
    Wait.time(function() placeColonyCard('b2af7a', '321211') end, 1.0)
    Wait.time(function() placeColonyCard('29ca2a', '9befbe') end, 1.5)
    Wait.time(function() placeColonyCard('ade02c', '5f2959') end, 2.0)
end

function placeColonyCard(deckGUID, zoneGUID)
    local deck = getObjectFromGUID(deckGUID)
    local zone = getObjectFromGUID(zoneGUID)
    
    -- Take the card from the deck and move it smoothly to the zone's position
    local card = deck.takeObject({position = zone.getPosition(), smooth = true}) -- Smooth movement
    
    -- Flip the card randomly
    if math.random() > 0.5 then
        Wait.time(function() card.flip() end, 1.0) -- Flip after a slight delay
    end
end

-- Shuffle and deal player decks
function shuffleAndDealPlayerDecks()
    local redDeck = getObjectFromGUID('b17dca')
    local blueDeck = getObjectFromGUID('99bc2d')

    if redDeck then redDeck.shuffle() end
    if blueDeck then blueDeck.shuffle() end

    if redDeck then redDeck.deal(5, 'Red') end
    if blueDeck then blueDeck.deal(5, 'Blue') end
end

-- Enable turn-based system
function enableTurns()
    Turns.enable = true
    Turns.type = 1
    Turns.order = {"Red", "Blue"}
    Turns.skip_empty_hands = false
    Turns.reverse_order = false
end

-- Start the player's turn
function startPlayerTurn()
    local currentPlayer = Turns.turn_color
    broadcastToAll(currentPlayer .. " commence son tour!", {0.2, 0.8, 0.2})
end

-- Adjusted function to handle adding buttons with a delay and recheck for the building market
function onObjectEnterScriptingZone(zone, object)
    -- Handle for the Building Market slots
    if zone.getGUID() == '83f251' or zone.getGUID() == '93d9ea' or zone.getGUID() == '43bab5' then
        -- Add a delay before verifying and adding buttons to ensure the card is properly placed
        Wait.time(function()
            verifyAndAddButtons(zone, object, "Building")
        end, 0.5)
    end
    
    -- Handle for the Character Market slots
    if zone.getGUID() == '89def4' or zone.getGUID() == '2829a7' or zone.getGUID() == '591dfd' then
        -- Add a delay before verifying and adding buttons to ensure the card is properly placed
        Wait.time(function()
            verifyAndAddButtons(zone, object, "Character")
        end, 0.5)
    end
end

-- Function to verify the card presence and add buttons
function verifyAndAddButtons(zone, object, marketType)
    local objectsInZone = zone.getObjects()

    -- Ensure that the object is a card and is still in the zone before adding buttons
    for _, obj in ipairs(objectsInZone) do
        if obj == object and object.tag == "Card" then
            if marketType == "Building" then
                addAcquireDiscardButtons(object, "Building")
            elseif marketType == "Character" then
                if object.getDescription() == "HORS-LA-LOI" then
                    addServicePrimeButtons(object)
                else
                    addAcquireDiscardButtons(object, "Character")
                end
            end
        end
    end
end

-- Function to remove buttons when a card leaves the market slots
function onObjectLeaveScriptingZone(zone, object)
    -- Clear buttons when leaving Building Market slots
    if zone.getGUID() == '83f251' or zone.getGUID() == '93d9ea' or zone.getGUID() == '43bab5' then
        object.clearButtons()
    end
    
    -- Clear buttons when leaving Character Market slots
    if zone.getGUID() == '89def4' or zone.getGUID() == '2829a7' or zone.getGUID() == '591dfd' then
        object.clearButtons()
    end
end

-- Function for adding the "Acquérir" and "Défausser" buttons
function addAcquireDiscardButtons(object, marketType)
    local acquireFunc = (marketType == "Building") and "acquireBuilding" or "acquireCharacter"

    -- Create "Acquérir" button
    object.createButton({
        click_function = acquireFunc,
        function_owner = self,
        label = "Acquérir",
        position = {0.2, 0.3, 0.2},
        width = 420,  -- Smaller width
        height = 220, -- Smaller height
        font_size = 90, -- Smaller font size
        color = {0.2, 0.6, 1},
        font_color = {1, 1, 1},
        tooltip = "Acquérir cette carte"
    })
    
    -- Create "Défausser" button
    object.createButton({
        click_function = "discardMarketCard", -- Use unified discard function
        function_owner = self,
        label = "✖",  -- Cross symbol for discard
        position = {-0.4, 0.3, 0.2}, -- Adjusted side-by-side position
        width = 175,  -- Smaller width
        height = 175, -- Smaller height
        font_size = 100,  -- Cross symbol font size
        color = {1, 0, 0}, -- Red for discard
        font_color = {1, 1, 1},
        tooltip = "Défausser cette carte",
        parameters = {marketType} -- Pass the market type to the discard function
    })
end

-- Function to acquire a character card and send it to the player's discard pile
function acquireCharacter(obj, player_color)
    local playerDiscardZones = {Red = "9a7b71", Blue = "a1554c"}
    local discardZone = getObjectFromGUID(playerDiscardZones[player_color])
    
    -- Move card to the discard pile
    obj.setPositionSmooth(discardZone.getPosition())
    obj.clearButtons()

    -- Add a small delay before refilling the market
    Wait.time(function()
        refillMarket('5926ea', {'89def4', '2829a7', '591dfd'})
    end, 0.5)  -- Delay of 0.5 seconds to allow the acquisition to complete
end

-- Function to acquire a building card and send it to the construction zones
function acquireBuilding(obj, player_color)
    local playerConstructionZones = {
        Red = {"96b1a7", "971fb9", "26f9a5"},
        Blue = {"7cd574", "c7ac14", "3f4bf6"}
    }

    local constructionZones = playerConstructionZones[player_color]
    local placed = false

    if obj.tag == "Card" then
        for _, zoneGUID in ipairs(constructionZones) do
            local zoneObject = getObjectFromGUID(zoneGUID)
            if zoneObject then
                local zoneObjects = zoneObject.getObjects()
                local validObjects = {}
                
                -- Check for only cards or decks in the zone
                for _, zoneObj in ipairs(zoneObjects) do
                    if zoneObj.tag == "Card" or zoneObj.tag == "Deck" then
                        table.insert(validObjects, zoneObj)
                    end
                end

                -- Place the card if the zone is empty
                if #validObjects == 0 then
                    obj.setPositionSmooth(zoneObject.getPosition())
                    placed = true
                    obj.clearButtons()

                    -- Delay the refill to ensure acquisition completes
                    Wait.time(function()
                        refillMarket('a9a1a6', {'83f251', '93d9ea', '43bab5'})
                    end, 0.5)  -- Delay of 0.5 seconds
                    break
                end
            end
        end
    end

    if not placed then
        broadcastToColor("Your construction zones are full, please build before acquiring new buildings.", player_color, {1, 0, 0})
    end
end


-- Function to discard a card (building or character) to the common discard pile
function discardMarketCard(obj, player_color, marketType)
    local marketDiscardZone = getObjectFromGUID("46bb60") -- Common discard zone for all market cards
    obj.setPositionSmooth(marketDiscardZone.getPosition())
    obj.clearButtons()

    -- Trigger the appropriate market refill based on the market type
    if marketType == "Building" then
        refillMarket('a9a1a6', {'83f251', '93d9ea', '43bab5'}) -- Building market refill
    elseif marketType == "Character" then
        refillMarket('5926ea', {'89def4', '2829a7', '591dfd'}) -- Character market refill
    end
end


-- Adding the Acquérir button for constant decks

local constantDecks = {
    Characters = {
        ["Archer"] = "886dae",
        ["Fermier"] = "b73b60",
        ["Orfèvre"] = "bd19b9",
        ["Ouvrier"] = "a49c94"
    },
    Buildings = {
        ["Murailles"] = "d99388"
    }
}

-- Add buttons for character and building decks
function addConstantDeckButtons()
    for _, guid in pairs(constantDecks.Characters) do
        local obj = getObjectFromGUID(guid)
        if obj then
            addAcquireButtonConstantDeck(obj, "Character")
        end
    end
    
    for _, guid in pairs(constantDecks.Buildings) do
        local obj = getObjectFromGUID(guid)
        if obj then
            addAcquireButtonConstantDeck(obj, "Building")
        end
    end
end

-- Adding button specifically for constant decks (no need to remove it unless deck is empty)
function addAcquireButtonConstantDeck(object, deckType)
    local acquireFunc = (deckType == "Building") and "acquireBuildingFromConstantDeck" or "acquireCharacterFromConstantDeck"
    
    object.createButton({
        click_function = acquireFunc,
        function_owner = self,
        label = "Acquérir",
        position = {0, 0.3, 0.2},
        width = 420,  -- Smaller width
        height = 220, -- Smaller height
        font_size = 90, -- Smaller font size
        color = {0.2, 0.6, 1},
        font_color = {1, 1, 1},
        tooltip = "Acquérir cette carte"
    })
end

-- Function to acquire a card from a constant character deck
function acquireCharacterFromConstantDeck(obj, player_color)
    local playerDiscardZones = {Red = "9a7b71", Blue = "a1554c"}
    local discardZone = getObjectFromGUID(playerDiscardZones[player_color])

    if obj.getQuantity() > 1 then
        obj.takeObject({position = discardZone.getPosition(), smooth = true})
    else
        obj.setPositionSmooth(discardZone.getPosition())
        obj.clearButtons()  -- Clear buttons if no more cards remain in the deck
    end
end

-- Function to acquire a card from a constant building deck and send it to the player's construction zone
function acquireBuildingFromConstantDeck(obj, player_color)
    local playerConstructionZones = {Red = "96b1a7", Blue = "7cd574"}
    local constructionZone = getObjectFromGUID(playerConstructionZones[player_color])

    if obj.getQuantity() > 1 then
        obj.takeObject({position = constructionZone.getPosition(), smooth = true})
    else
        obj.setPositionSmooth(constructionZone.getPosition())
        obj.clearButtons()  -- Clear buttons if no more cards remain in the deck
    end
end

-- Function for adding Service and Prime buttons for HORS-LA-LOI cards
function addServicePrimeButtons(object)
    -- Add the Défausser button on the far left
    object.createButton({
        click_function = "discardCharacter",  -- Assuming discard function for HORS-LA-LOI remains the same
        function_owner = self,
        label = "✖",  -- Cross symbol for discard
        position = {-0.7, 0.3, 0.2}, -- Far left position
        width = 175,  -- Smaller width for discard button
        height = 175, -- Smaller height
        font_size = 100,  -- Cross symbol font size
        color = {1, 0, 0}, -- Red for discard
        font_color = {1, 1, 1},
        tooltip = "Défausser cette carte"
    })

    -- Add the Service button in the middle
    object.createButton({
        click_function = "serviceCard",  -- Assuming there is a service function
        function_owner = self,
        label = "Service",  -- Label for the service action
        position = {-0.15, 0.3, 0.2}, -- Middle position
        width = 350,  -- Width for the service button
        height = 220, -- Height for the service button
        font_size = 80,  -- Font size for the service button
        color = {0.5, 0.5, 0.5}, -- Grey for service
        font_color = {1, 1, 1},
        tooltip = "Demander un service"
    })

    -- Add the Prime button on the far right
    object.createButton({
        click_function = "primeCard",  -- Assuming there is a prime function
        function_owner = self,
        label = "Prime",  -- Label for the prime action
        position = {0.55, 0.3, 0.2}, -- Far right position
        width = 350,  -- Width for the prime button
        height = 220, -- Height for the prime button
        font_size = 80,  -- Font size for the prime button
        color = {1, 0.84, 0}, -- Gold color for prime
        font_color = {1, 1, 1},
        tooltip = "Recevoir la prime"
    })
end

-- Function to add "Prime" and "Service" buttons to the "Assassin" card during setup
function addAssassinButtons()
    local assassinCard = getObjectFromGUID("ec3efa")  -- GUID for Assassin card
    if assassinCard then
        -- Add the Service button
        assassinCard.createButton({
            click_function = "noopFunction",  -- No operation when clicked
            function_owner = self,
            label = "Service",
            position = {-0.15, 0.3, 0.2}, -- Middle position
            width = 350, 
            height = 220, 
            font_size = 80,  
            color = {0.5, 0.5, 0.5}, 
            font_color = {1, 1, 1},
            tooltip = "Demander un service"
        })

        -- Add the Prime button
        assassinCard.createButton({
            click_function = "noopFunction",  -- No operation when clicked
            function_owner = self,
            label = "Prime",
            position = {0.55, 0.3, 0.2}, -- Far right position
            width = 350,  
            height = 220, 
            font_size = 80,  
            color = {1, 0.84, 0}, 
            font_color = {1, 1, 1},
            tooltip = "Recevoir la prime"
        })
    end
end

-- No-op function for buttons that should not trigger any action
function noopFunction()
    -- Do nothing when clicked
end

function onPlayerTurn(player, previous_player)
    -- Announce the turn change
    if previous_player == nil then
        print(player.color .. " is the first player. It's now their turn.")
    else
        print(previous_player.color .. "'s turn is over. It's now " .. player.color .. "'s turn.")

        -- If there was a previous player, handle their end-of-turn actions
        if previous_player then
            if previous_player.color == "Red" then
                -- Move Red player's cards from their game zone to their discard pile
                moveObjectsToDiscard("8f5458", "9a7b71")

                -- Refill Red player's hand with 5 cards, handling empty deck if necessary
                drawCards("6c740a", "9a7b71", "Red", 5)
                
                -- Refill character and building markets for Red's turn ending
                refillMarket("Character")
                refillMarket("Building")

            elseif previous_player.color == "Blue" then
                -- Move Blue player's cards from their game zone to their discard pile
                moveObjectsToDiscard("d56a9d", "a1554c")

                -- Refill Blue player's hand with 5 cards, handling empty deck if necessary
                drawCards("9c8ab3", "a1554c", "Blue", 5)
                
                -- Refill character and building markets for Blue's turn ending
                refillMarket("Character")
                refillMarket("Building")
            end
        end
    end
end



-- Function to move cards from player's zone to discard
function moveObjectsToDiscard(zoneGUID, discardGUID)
    local zone = getObjectFromGUID(zoneGUID)
    local discardZone = getObjectFromGUID(discardGUID)

    if zone and discardZone then
        local objectsInZone = zone.getObjects()

        for _, obj in ipairs(objectsInZone) do
            if obj.tag == "Card" or obj.tag == "Deck" then
                obj.setPositionSmooth(discardZone.getPosition())
                obj.clearButtons() -- Clear any buttons on the cards
                log("Cartes déplacées")
            end
        end
    else
        log("Error: Zone or discard pile not found.")
    end
end

-- Function to draw cards from the deck, reshuffle discard pile if deck is empty
function drawCards(deckGUID, discardGUID, player_color, num_cards)
    local deck = getObjectFromGUID(deckGUID)
    local discardPile = getObjectFromGUID(discardGUID)
    
    -- Helper function to move discard pile to deck and reshuffle
    local function reshuffleFromDiscard()
        local objectsInDiscard = discardPile.getObjects()
        for _, obj in ipairs(objectsInDiscard) do
            obj.setPositionSmooth(deck.getPosition()) -- Move cards to deck zone
            if not obj.is_face_down then
                obj.flip() -- Ensure cards are face down
            end
        end
        Wait.time(function() deck.shuffle() end, 1) -- Shuffle after moving cards
    end

    -- Helper function to draw a card from the deck, handle remainder case
    local function drawCard(deckObj)
        local cardObj = deckObj.takeObject()
        if deckObj.remainder then
            deckObj = deckObj.remainder -- Update deckObj to the last remaining card
        end
        return {cardObj = cardObj, deckObj = deckObj}
    end

    if deck and discardPile then
        local objectsInDeck = deck.getObjects()
        local remaining_cards = num_cards -- Track how many more cards need to be drawn
        
        -- If the deck has fewer than the required number of cards
        if #objectsInDeck < remaining_cards then
            -- Draw all available cards from the deck first
            for i = 1, #objectsInDeck do
                drawCard(deck).cardObj.deal(1, player_color)
                remaining_cards = remaining_cards - 1
            end

            -- Reshuffle discard pile into deck
            reshuffleFromDiscard()

            -- Wait until reshuffling is complete before drawing the remaining cards
            Wait.time(function()
                -- Draw the remaining cards from the reshuffled deck
                for i = 1, remaining_cards do
                    drawCard(deck).cardObj.deal(1, player_color)
                end
            end, 1.5)  -- Adding a delay to ensure reshuffling is complete
        else
            -- If the deck has enough cards, simply draw the required number
            for i = 1, num_cards do
                drawCard(deck).cardObj.deal(1, player_color)
            end
        end
    else
        log("Error: Deck or discard pile not found for " .. player_color)
    end
end

-- Function to shift market cards to the right and refill from the deck
function refillMarket(deckGUID, slotGUIDs)
    local deck = getObjectFromGUID(deckGUID)

    -- Shift cards from right to left
    for i = #slotGUIDs, 2, -1 do
        local previousSlot = getObjectFromGUID(slotGUIDs[i-1])
        local currentSlot = getObjectFromGUID(slotGUIDs[i])
        local objectsInPrevSlot = previousSlot.getObjects()

        -- Ensure only cards are moved
        for _, obj in ipairs(objectsInPrevSlot) do
            if obj.tag == "Card" then
                obj.setPositionSmooth(currentSlot.getPosition())
                break -- Move only one card per slot
            end
        end
    end

    -- Finally, draw a new card into the first slot from the deck
    local firstSlot = getObjectFromGUID(slotGUIDs[1])
    if deck then
        local card = deck.takeObject({
            position = firstSlot.getPosition(),
            smooth = true
        })
        -- Flip the card after placing it
        if card and card.tag == "Card" then
            Wait.time(function()
                card.flip()
            end, 1.0)
        end
    end
end



Leave a Comment