Home Tutorials Download Beta Store Forum Documentation KnowledgeBase Wiki Blog

ShiVa3D

Return to Code Snippets

Copy/Paste Functions & Handlers - Copy/Paste Format Only Pls

Paste down any little snippets or request a new one.

Copy/Paste Functions & Handlers - Copy/Paste Format Only Pls

Postby gamescorpion » 23 Sep 2011, 11:22

Hi all, Okay so I decided to write this post using a similar idea that I have in the getting started section for n00bs, however this is specifically for CODE. If you have a function/handler that you believe would be helpful to all (and you are allowing others to use it royalty free, no copyright issues), then the idea here is to create a full listing of functions/handlers that a developer could just copy and paste right into ShiVa or some form of code that requires VERY LITTLE for the developer to do to get up and running.

Rather than each dev coding their own versions of the SAME function/handler, we could have a repository of these that all devs can just come to, copy and paste right into their program and they are good to go and save several hours of time.

FORMAT OF POSTS:

Function/Handler NAME: What is the name of the function/handler

TYPE: Function or Handler

Code Created By, Date and Version: Your Name (Out of respect for all coders, however the code would still be allowed to be used by all, everyone would just know that it was you that wrote it and it would be attached in the comment of your function/handler), The date you wrote the code and just give a version number, that way if you ever create an updated version of the code, other devs can refer to that version specifically

Code Description: Place a description of your function/handler here

Function/Handler INPUTS: What inputs and format of inputs does the function/handler take

Function/Handler OUTPUTS: What outputs can a user expect

REQUIREMENTS: This is any requirements the user will need in order for the function to run, such as a specific variable being created or a HUD component being created.

CODE: The code itself using the [ code ] BB code brackets please as this makes it easier for all users to read.

AND THATS pretty much it. Hope we can build a massive set of functions/handlers that all the devs can share and use amongst each other and speed up development time :)

Nav
PS: I will write the first post shortly...
Last edited by gamescorpion on 23 Sep 2011, 12:13, edited 2 times in total.
Game Scorpion Inc. http://www.gamescorpion.com
Armies of Riddle Collectible Card Game: http://www.ArmiesOfRiddle.com
User avatar
gamescorpion
Platinum Boarder
Platinum Boarder
 
Posts: 667
Location: Ontario, Canada

Re: Copy/Paste Functions & Handlers - Copy/Paste Format Only Pls

Postby gamescorpion » 23 Sep 2011, 11:46

Function/Handler NAME: onSaveXML ( sName )

TYPE: Handler

Code Created By, Date and Version: Game Scorpion Inc. - Sep-23-2011 - 1.0

Code Description: A handler that will save any variables you want to an XML file you specify. For example purposes I have included various variable types being saved. Please keep in mind that XML requires output to be in STRING format so everything MUST be converted properly on SAVE. The next function I will write after will be for loading and it will require us to convert the strings back to regular variables. Files are saved to the users documents directory.

Function/Handler INPUTS: sName -> The name of the file you want to save in XML format

Function/Handler OUTPUTS: none (It saves a file to the documents folder)

REQUIREMENTS: You need to have an XML variable in your main AI called hXML (Variable Type: XML, Init Value: Empty)

CODE:
Code: Select all
--------------------------------------------------------------------------------
--  Handler.......... : onSaveXML
--  Author........... : Game Scorpion Inc.
--  Description...... : Version 1.0
--------------------------------------------------------------------------------

--------------------------------------------------------------------------------
function intro_ai.onSaveXML ( sName )
--------------------------------------------------------------------------------
   
    -- Create a local variable that holds the current XML variable
    local hXMLVar = this.hXML ( )   
   
    -- Make sure the current XML variable is empty
    xml.empty ( hXMLVar )   
   
    -- Create another variable called hRoot to store the root element
    local hRoot = xml.getRootElement ( hXMLVar )   
   
    -- ======================
    -- BEGIN SAVING VARIABLES
    -- ======================
   
    -- REPLACE BELOW VARIABLES WITH WHATEVER VARAIBLES YOU WISH TO SAVE.  FOR EXAMPLE PURPOSES WE HAVE PROVIDED 10 SAMPLES.
    -- FORMAT IS xml.appendElementAttribute ( hRoot, "VAR_NAME", string.format ( "%s", ACTUAL_VARIABLE and ACTUAL_VARIABLE or "ZERO_VALUE_OR_EMPTY_STRING" ) )
   
    -- Example of ENVIRONMENT VARIABLES
    xml.appendElementAttribute ( hRoot, "nTotal", string.format ( "%s", application.getCurrentUserEnvironmentVariable ( "nTotal" ) and application.getCurrentUserEnvironmentVariable ( "nTotal" ) or "0" ) )
    xml.appendElementAttribute ( hRoot, "nDT", string.format ( "%s", application.getCurrentUserEnvironmentVariable ( "nDT" ) and application.getCurrentUserEnvironmentVariable ( "nDT" ) or "0" ) )

    -- Example of BOOLEAN VARIABLES
    xml.appendElementAttribute ( hRoot, "bDead", string.format ( "%s", application.getCurrentUserEnvironmentVariable ( "bDead" ) and "true" or "false" ) )
    xml.appendElementAttribute ( hRoot, "bAlive", string.format ( "%s", application.getCurrentUserEnvironmentVariable ( "bAlive" ) and "true" or "false" ) )

    -- Example of AI BOOLEAN VARIABLES
    xml.appendElementAttribute ( hRoot, "bActive", string.format ( "%s", this.bActive ( ) and "true" or "false" ) )
    xml.appendElementAttribute ( hRoot, "bButton0Down", string.format ( "%s", this.bButton0Down ( ) and "true" or "false" ) )

    -- Example of PLAYER POSITION
    local nX, nY, nZ = object.getBoundingSphereCenter ( application.getCurrentUserSceneTaggedObject ( "obj_player" ) )

    -- Example of NUMERIC VARIABLES
    xml.appendElementAttribute ( hRoot, "nPlayerPositionX", string.format ( "%s", nX and nX or "0" ) )
    xml.appendElementAttribute ( hRoot, "nPlayerPositionY", string.format ( "%s", nY and nY or "0" ) )
    xml.appendElementAttribute ( hRoot, "nPlayerPositionZ", string.format ( "%s", nZ and nZ or "0" ) )

    -- Example of STRING VARIABLES
    xml.appendElementAttribute ( hRoot, "sTest", string.format ( "%s", "HELLO" and "HELLO" or "" ) )

    -- ====================
    -- END SAVING VARIABLES
    -- ====================

    -- Do save file
    xml.send ( hXMLVar, "file://"..system.getDocumentsDirectory ( ).."/"..sName )
   
    -- HOW TO CALL HANDLER:
    -- user.sendEvent ( application.getCurrentUser ( ), "AI_MODEL_NAME", "onSaveXML", "YOUR_FILE_NAME.xml" )
   -- OUTPUTTED FILE CONTENTS WILL INCLUDE ALL THE ABOVE ITEMS
   
--------------------------------------------------------------------------------
end
--------------------------------------------------------------------------------
Game Scorpion Inc. http://www.gamescorpion.com
Armies of Riddle Collectible Card Game: http://www.ArmiesOfRiddle.com
User avatar
gamescorpion
Platinum Boarder
Platinum Boarder
 
Posts: 667
Location: Ontario, Canada

Re: Copy/Paste Functions & Handlers - Copy/Paste Format Only Pls

Postby gamescorpion » 23 Sep 2011, 12:11

Function/Handler NAME: onLoadXML ( sName )

TYPE: Handler

Code Created By, Date and Version: Game Scorpion Inc. - Sep-23-2011 - 1.0

Code Description: A handler that will load any variables you want from an XML file you specify. For example purposes I am using the previous save functions saved variables for loading. You must know what values you are loading from the file (like variable names). We will be reading files that are saved to the users documents directory.

Function/Handler INPUTS: sName -> The name of the file you want to load in XML format

Function/Handler OUTPUTS: none (It will load up the variables)

REQUIREMENTS: You need to have an XML variable in your main AI called hXML (Variable Type: XML, Init Value: Empty)

CODE:
Code: Select all
--------------------------------------------------------------------------------
--  Handler.......... : onLoadXML
--  Author........... : Game Scorpion Inc.
--  Description...... : Version 1.0
--------------------------------------------------------------------------------

--------------------------------------------------------------------------------
function intro_ai.onLoadXML ( sName )
--------------------------------------------------------------------------------
   
    -- Try and obtain the file sName and place the root node in this.hXML ( )
    xml.receive ( this.hXML ( ), "file://"..system.getDocumentsDirectory ( ).."/"..sName )
   
    -- Get the loading status -> 1 = SUCCESS, anything LESS THAN 0 is a FAILURE
    local nStatus = xml.getReceiveStatus ( this.hXML ( ) )

    -- Check status to see if we have a SUCCESSFUL LOAD
    if ( nStatus == 1 ) then
       
        -- Get the Root node of XML
        local hRoot = xml.getRootElement ( this.hXML ( ) )
       
        -- ===============================
        -- BEGIN LOADING OF VARIABLES HERE
        -- ===============================

        -- We will load the examples from our save function. 
        -- MAKE EDITS AND CHANGES TO anything below to suit the variables you wish to load
       
        -- Get a NUMBER value -> string.toNumber ( xml.getAttributeValue ( xml.getElementAttributeWithName ( hRoot, "NAME_OF_VARIABLE_FROM_XML_FILE" ) ) )
        application.setCurrentUserEnvironmentVariable ( "nTotal", string.toNumber ( xml.getAttributeValue ( xml.getElementAttributeWithName ( hRoot, "nTotal" ) ) ) )
        application.setCurrentUserEnvironmentVariable ( "nDT", string.toNumber ( xml.getAttributeValue ( xml.getElementAttributeWithName ( hRoot, "nDT" ) ) ) )
       
        -- Boolean Values require an IF/THEN check to convert to true/false
        if xml.getAttributeValue ( xml.getElementAttributeWithName ( hRoot, "bDead" ) ) == "true" then
            application.setCurrentUserEnvironmentVariable ( "bDead", true )
        else
            application.setCurrentUserEnvironmentVariable ( "bDead", false )
        end

        if xml.getAttributeValue ( xml.getElementAttributeWithName ( hRoot, "bAlive" ) ) == "true" then
            application.setCurrentUserEnvironmentVariable ( "bAlive", true )
        else
            application.setCurrentUserEnvironmentVariable ( "bAlive", false )
        end
       
        if xml.getAttributeValue ( xml.getElementAttributeWithName ( hRoot, "bActive" ) ) == "true" then
            this.bActive ( true )
        else
            this.bActive ( false )
        end

        if xml.getAttributeValue ( xml.getElementAttributeWithName ( hRoot, "bButton0Down" ) ) == "true" then
            this.bButton0Down ( true )
        else
            this.bButton0Down ( false )
        end

        application.setCurrentUserEnvironmentVariable ( "nPlayerPositionX", string.toNumber ( xml.getAttributeValue ( xml.getElementAttributeWithName ( hRoot, "nPlayerPositionX" ) ) ) )
        application.setCurrentUserEnvironmentVariable ( "nPlayerPositionY", string.toNumber ( xml.getAttributeValue ( xml.getElementAttributeWithName ( hRoot, "nPlayerPositionY" ) ) ) )
        application.setCurrentUserEnvironmentVariable ( "nPlayerPositionZ", string.toNumber ( xml.getAttributeValue ( xml.getElementAttributeWithName ( hRoot, "nPlayerPositionZ" ) ) ) )
       
        -- Text Values do not require any conversion and can be read by using -> xml.getAttributeValue ( xml.getElementAttributeWithName ( hRoot, "sNameOfXMLField" ) )
        application.setCurrentUserEnvironmentVariable ( "sTest", xml.getAttributeValue ( xml.getElementAttributeWithName ( hRoot, "sTest" ) ) )
   
        -- WE HAVE SUCCESSFULLY LOADED ALL VALUES FROM THE SAVE HANDLER EXAMPLE
        -- CHANGE/EDIT ANY OF THE ITEMS ABOVE AND LOAD UP YOUR OWN VARIABLES
   
        -- ========================
        -- END LOADING OF VARIABLES
        -- ========================
       
    else
        if ( nStatus < 0 ) then
            log.message ( "LOAD FAILED, FILE DOES NOT EXIST OR FILE ERROR" )
        end
    end

    -- HOW TO CALL HANDLER:
    -- user.sendEvent ( application.getCurrentUser ( ), "AI_MODEL_NAME", "onLoadXML", "YOUR_FILE_NAME.xml" )
   -- OUTPUTTED FILE CONTENTS WILL INCLUDE ALL THE ABOVE ITEMS
   
--------------------------------------------------------------------------------
end
--------------------------------------------------------------------------------
Game Scorpion Inc. http://www.gamescorpion.com
Armies of Riddle Collectible Card Game: http://www.ArmiesOfRiddle.com
User avatar
gamescorpion
Platinum Boarder
Platinum Boarder
 
Posts: 667
Location: Ontario, Canada

Re: Copy/Paste Functions & Handlers - Copy/Paste Format Only Pls

Postby gamescorpion » 01 Mar 2012, 21:33

Function/Handler NAME: GetDayOfWeek ( nYear, nMonth, nDay )

TYPE: Function

Code Created By, Date and Version: Game Scorpion Inc., with help from various sources as listed below - Mar-1-2012 - 1.0

SOURCES: Zellers Algorithim, Michael Keith's C program, and Wikipedia as well as Game Scorpion Inc. that created the ShiVa 3D version of the function

Code Description: This cool function will return the Day of the Week (Sun-0, Mon-1, Tue-2, Wed-3, Thu-4, Fri-5, Sat-6) for any given date input YYYY-MM-DD.

Function/Handler INPUTS: nYear -> The 4 digit year as either generated by ShiVa or inputted by user; nMonth -> The 2 digit month (where 0 = jan and 11 = dec); nDay -> The day of the month between 1-31 depending on the month.

Function/Handler OUTPUTS: nDayOfWeek -> 0 = Sunday, 1 = Monday, 2 = Tuesday, 3 = Wednesday, 4 = Thursday, 5 = Friday, 6 = Saturday

REQUIREMENTS: Create a function in your AI called GetDayofWeek and copy and paste this code into it.

CODE:

Code: Select all
--------------------------------------------------------------------------------
--  Function......... : GetDayOfWeek
--  Author........... : Game Scorpion Inc.
--  Description...... : Sources - Zellers Algorithim, Michael Keith's C program, and Wikipedia as well as Game Scorpion Inc. that created the ShiVa 3D version of the function
--------------------------------------------------------------------------------

--------------------------------------------------------------------------------
function MainAI.GetDayOfWeek ( nYear, nMonth, nDay )
--------------------------------------------------------------------------------
    -- Calculated using several sources: Zellers Algorithim, Michael Keith's C program, and Wikipedia
    -- Conversion over to ShiVa 3D By Game Scorpion Inc.

   -- Take the current day and subtract 1
    nDay = nDay - 1
   
    -- Set day of week to -1 so that if an error occurs, -1 is returned
    local nDayOfWeek = -1
   
    -- Determine month   
    if nMonth == 1 then
        nMonth = 13
        nYear = nYear - 1
    elseif ( nMonth == 2 ) then
        nMonth = 14
        nYear = nYear - 1   
    end
   
    -- Calculate the Month Factor being used
    local nMonthFactor = ( nMonth * 2 ) + math.floor ( ( ( nMonth + 1 ) * 3 ) / 5 )
       
    -- Calculate the 2 digit century EX. 2012 = 20; 1997 = 19
    local nYearOfTheCentury = math.floor ( nYear / 100 )

    -- Calculate the Year Factor (taking leap years into account)
    local nYearFactor = nYear + math.floor ( nYear / 4 ) - nYearOfTheCentury + math.floor ( nYear / 400 ) + 2
   
    -- Calculate base week INCLUDING decimals (float value)
    local nFloatWeek = nDay + nMonthFactor + nYearFactor
   
    -- Calculate the INTEGER value of the week
    local nWeekInt = math.floor ( nFloatWeek / 7 )
   
    -- Calculate day of week by subtracting the total days from the new calculated nWeekInt
    local nDayOfWeek = nFloatWeek - ( nWeekInt * 7 )
   
    -- Return the day of the week
    return nDayOfWeek


--------------------------------------------------------------------------------
end
--------------------------------------------------------------------------------

Game Scorpion Inc. http://www.gamescorpion.com
Armies of Riddle Collectible Card Game: http://www.ArmiesOfRiddle.com
User avatar
gamescorpion
Platinum Boarder
Platinum Boarder
 
Posts: 667
Location: Ontario, Canada

Re: Copy/Paste Functions & Handlers - Copy/Paste Format Only Pls

Postby broozar » 08 Mar 2012, 15:25

excellent topic.

everything Image
User avatar
broozar
Platinum Boarder
Platinum Boarder
 
Posts: 3570
Location: Berlin - Germany

Re: Copy/Paste Functions & Handlers - Copy/Paste Format Only Pls

Postby gamescorpion » 16 Apr 2012, 07:08

Function/Handler NAME: GetDayExt ( nDay )

TYPE: Function

Code Created By, Date and Version: Game Scorpion Inc. - Apr-16-2012 - 1.0

SOURCES: Game Scorpion Inc.

Code Description: This function will return the STRING ending for any calender day between 1 - 31. For example, 1 = 1st, 2 = 2nd, 3 = 3rd, etc.

Function/Handler INPUTS: nDay -> An integer value between 1 and 31

Function/Handler OUTPUTS: sExt -> The extension string (st, nd, rd, th)

REQUIREMENTS: Create a function in your AI called GetDayExt and copy and paste this code into it.

CODE:

Code: Select all
--------------------------------------------------------------------------------
--  Function......... : GetDayExt
--  Author........... : Game Scorpion Inc.
--  Description...... : V1.0
--------------------------------------------------------------------------------

--------------------------------------------------------------------------------
function MainAI.GetDayExt ( nDay )
--------------------------------------------------------------------------------
   
    local sExt = ""
   
    if nDay == 1 then
        sExt = "st"
    elseif ( nDay == 2 ) then
        sExt = "nd"
    elseif ( nDay == 3 ) then
        sExt = "rd"
    elseif ( nDay >= 4 and nDay <= 20 ) then
        sExt = "th"
    elseif ( nDay == 21 ) then
        sExt = "st"
    elseif ( nDay == 22 ) then
        sExt = "nd"
    elseif ( nDay == 23 ) then
        sExt = "rd"
    elseif ( nDay >= 24 and nDay <= 30 ) then
        sExt = "th"
    elseif ( nDay == 31 ) then
        sExt = "st"
    end
   
    return sExt
   
--------------------------------------------------------------------------------
end
--------------------------------------------------------------------------------

Game Scorpion Inc. http://www.gamescorpion.com
Armies of Riddle Collectible Card Game: http://www.ArmiesOfRiddle.com
User avatar
gamescorpion
Platinum Boarder
Platinum Boarder
 
Posts: 667
Location: Ontario, Canada

Re: Copy/Paste Functions & Handlers - Copy/Paste Format Only Pls

Postby gamescorpion » 16 Apr 2012, 08:39

Function/Handler NAME: RemoveChar ( sString, sChar )

TYPE: Function

Code Created By, Date and Version: Game Scorpion Inc. - Apr-16-2012 - 1.0

SOURCES: Game Scorpion Inc.

Code Description: This function will take in a string as well as a character you wish to remove from the string. This is very useful if you have a string you are trying to remove commas or other things from. Ex. BEFORE: Hello, World, How, Are, You? AFTER: Hello World How Are You?

Function/Handler INPUTS: sString -> The original string, sChar -> The character you wish to remove

Function/Handler OUTPUTS: sNewString -> The new string with the requested character missing from it.

REQUIREMENTS: Create a function in your AI called RemoveChar and copy and paste this code into it.

CODE:

Code: Select all
--------------------------------------------------------------------------------
--  Function......... : RemoveChar
--  Author........... : Game Scorpion Inc.
--  Description...... : V1.0
--------------------------------------------------------------------------------

--------------------------------------------------------------------------------
function MainAI.RemoveChar ( sString, sChar )
--------------------------------------------------------------------------------
   
    local sNewString = ""
    local nStringLen = string.getLength ( sString )
   
    for i = 0, nStringLen do
        local sCharTemp = string.getSubString ( sString, i, 1 )
        if sCharTemp ~= sChar then
            sNewString = sNewString..sCharTemp
        end
    end
   
    return sNewString
   
--------------------------------------------------------------------------------
end
--------------------------------------------------------------------------------

Game Scorpion Inc. http://www.gamescorpion.com
Armies of Riddle Collectible Card Game: http://www.ArmiesOfRiddle.com
User avatar
gamescorpion
Platinum Boarder
Platinum Boarder
 
Posts: 667
Location: Ontario, Canada

Re: Copy/Paste Functions & Handlers - Copy/Paste Format Only Pls

Postby gamescorpion » 18 Apr 2012, 08:52

Function/Handler NAME: HUDLog ( sText, nLocation )

TYPE: Function

Code Created By, Date and Version: Game Scorpion Inc. - Apr-18-2012 - 1.0

SOURCES: Game Scorpion Inc.

Code Description: This function is VERY useful. Its pretty much a VISUAL log that displays on the screen for 5 seconds rather than just a log in the log reporter. This is useful for testing on actual devices when you dont have access to a log reporter.

Function/Handler INPUTS: sText -> This is the text you wish to show in your log. You may even pass a boolean and you wont have any issues. nLocation -> This is just an extra OPTIONAL field that determines the location on the screen you wish for the log to appear. By default the location is in the center of the screen, however you may position it differently. nLocation 1 = Top Left, nLocation 2 = Top Right, nLocation 3 = Bottom Left and nLocation 4 = Bottom Right.

Function/Handler OUTPUTS: None

REQUIREMENTS: 1. Create two AI variables in your main AI => BOOLEAN bHudLog (Initial Value of false) AND NUMBER nHUDLogTimer (Initial Value of 0).

2. In your onEnterFrame copy and paste the following code:

Code: Select all
    -- ==================
    -- HUD LOG CODE START
    -- ==================
   
    local nFPS = 1/application.getAverageFrameTime ( )
    this.nHUDLogTimer ( this.nHUDLogTimer ( ) + 1 )
    if this.nHUDLogTimer ( ) >= nFPS * 5 and this.bHudLog ( ) then
        local hComponent = hud.getComponent ( this.getUser ( ), "lbl_hudlog" )
        hud.destroyComponent ( hComponent )
        this.bHudLog ( false )
        this.nHUDLogTimer ( 0 )
    end
   
    -- ================
    -- HUD LOG CODE END
    -- ================


3. Finally, create a function called HUDLog ( sText, nLocation ) and paste the following code into it:

CODE:

Code: Select all
--------------------------------------------------------------------------------
--  Function......... : HUDLog
--  Author........... : Game Scorpion Inc.
--  Description...... :
--------------------------------------------------------------------------------

--------------------------------------------------------------------------------
function MainAI.HUDLog ( sText, nLocation )
--------------------------------------------------------------------------------
   
    -- Create new HUD element
    local hComponent = nil
    if not hud.getComponent ( this.getUser ( ), "lbl_hudlog" ) then
        hComponent = hud.newComponent ( this.getUser ( ), hud.kComponentTypeLabel, "lbl_hudlog" )
    else
        hComponent = hud.getComponent ( this.getUser ( ), "lbl_hudlog" )
    end
   
    hud.setComponentActive ( hComponent, false )
    hud.setComponentVisible ( hComponent, false )
   
    -- Create temporary text
    local sFinalText = ""
   
    -- Check input text
    if sText == true then
        sFinalText = "true"
    elseif ( sText == false ) then
        sFinalText = "false"
    else
        sFinalText = ""..sText
    end

    hud.setComponentSize ( hComponent, 40, 10 )
    hud.setComponentBorderColor ( hComponent, 127, 127, 127, 255 )
    hud.setComponentBackgroundColor ( hComponent, 0, 0, 0, 180 )
    hud.setComponentShapeType ( hComponent, hud.kShapeTypeRoundRectangle )
    hud.setComponentShapeRoundRectangleCornerRadius ( hComponent, 10 )
    hud.setComponentForegroundColor ( hComponent, 127, 127, 127, 255 )
    hud.setComponentZOrder ( hComponent, 255 )
    hud.setLabelFont ( hComponent, "DefaultFont" )
    hud.setLabelText ( hComponent, sFinalText )

    if nLocation == nil or nLocation == "" or nLocation <= 0 then
        hud.setComponentPosition ( hComponent, 50, 50 )
    elseif ( nLocation == 1 ) then
        hud.setComponentPosition ( hComponent, 21, 94 )
    elseif ( nLocation == 2 ) then
        hud.setComponentPosition ( hComponent, 79, 94 )
    elseif ( nLocation == 3 ) then
        hud.setComponentPosition ( hComponent, 21, 6 )
    elseif ( nLocation >= 4 ) then
        hud.setComponentPosition ( hComponent, 79, 6 )
    end

    hud.setComponentActive ( hComponent, true )
    hud.setComponentVisible ( hComponent, true )
   
    this.bHudLog ( true )
   
--------------------------------------------------------------------------------
end
--------------------------------------------------------------------------------



4. TO CALL A HUD LOG Simply use the following example, you can call it from anywhere in your code and it will show up for 5 seconds each time you call it:

Code: Select all
-- Simple Text shown in center
this.HUDLog ( "Test" )

-- Simple Text shown in bottom right
this.HUDLog ( "Test", 4 )
Game Scorpion Inc. http://www.gamescorpion.com
Armies of Riddle Collectible Card Game: http://www.ArmiesOfRiddle.com
User avatar
gamescorpion
Platinum Boarder
Platinum Boarder
 
Posts: 667
Location: Ontario, Canada

Re: Copy/Paste Functions & Handlers - Copy/Paste Format Only Pls

Postby gamescorpion » 03 Dec 2012, 03:18

Function/Handler NAME: EvenSpace ( nTotalLength, nTotalComponents, nLengthOfComponents, nIndexOfComponentBeingRequested )

TYPE: Function

Code Created By, Date and Version: Game Scorpion Inc. - Dec-2-2012 - 1.0

SOURCES: Game Scorpion Inc.

Code Description: This function was created so I could easily space components out on my screen EVENLY without having to do the math every single time. For example, lets say you have a menu bar at the bottom with like 5 icons on it. Rather than figuring out the exact math to even it all out so it looks centered, this script will simply return the correct spacing for you. You can even just put specific buttons to load in different areas (Example: 5 buttons, but you just want button 2 and 4 to show up and it should all look evenly spaced).

Function/Handler INPUTS:

nTotalLength -> This is the total length of the screen. Usually 100 (as in 100%), but I have left it open incase you wish to change this in the future. You can use this same function to easily center and space out any components in ANY size, so if you wish to have a set of items within a component of size 80 then your nTotalLength would be 80 for example. The default value you should put is 100.

nTotalComponents -> This is the total number of components you have in the space. NOTE that the first number is actually 0, not 1, so For example if I have 5 buttons, then this value would be 4. If I have 10 components, then this value should be 9.

nLengthOfComponents -> This is the physical length/width of a single component. It is assumed that all the components share this value the same. For example if I wanted to space out the 5 components, I would assume they all had the same width of 8% for example or 100px. The opposite length can be varied, but the one being used here should be the same for every component.

nIndexOfComponentBeingRequested -> This is the component whose location you are requesting. If it's the first component, then this would be 0. If it's the 3rd component, then the value would be 2, etc.

Function/Handler OUTPUTS: Number value. It will be the STARTING position for the component that you have requested.

REQUIREMENTS:
1. Create a variable to hold the total number of components or you can just put this in manually.

2. Obtain the width of the first component (or the height) using the following code (Assume your HUD is called unique_instance_main_hud):

Code: Select all
        -- Assuming there is a component in your HUD called btn_0
        local hComponent = hud.getComponent ( this.getUser ( ), "unique_instance_main_hud.btn_0" )
        local nWidth, nHeight = hud.getComponentSize ( hComponent )


3. Anywhere in the code you want to space items out create a for loop starting at 0 and running to the number of items you have to space out:

CODE:

Code: Select all
        local nTotalComponents = 5
        local nNewStart = 0
        for i = 0, nTotalComponents do
           
            local hComponent = hud.getComponent ( this.getUser ( ), "unique_instance_main_hud.btn_"..i )
            local nLeft, nTop = hud.getComponentPosition ( hComponent )
            local nNewStart = this.EvenSpace ( 100, nTotalComponents, nWidth, i )
            hud.setComponentPosition ( hComponent, nNewStart, nTop )
           
        end



4. Now create a new function called EvenSpace (Click on AI Model Editor->Functions->Add Function) and replace the code with the following:
Code: Select all

--------------------------------------------------------------------------------
--  Function......... : EvenSpace
--  Author........... : Game Scorpion Inc.
--  Description...... : Evenly space out components on the screen
--------------------------------------------------------------------------------

--------------------------------------------------------------------------------
function MainAI.EvenSpace ( nTotalLength, nTotalComponents, nLengthOfComponents, nIndexOfComponentBeingRequested )
--------------------------------------------------------------------------------
   
    -- Inputs:
        -- Total Length = nTotalLength
        -- Number of Components = nTotalComponents
        -- Physical Width/Height of ONE component (Assume all are same size) = nLengthOfComponents
        -- The item who's position you want = nIndexOfComponentBeingRequested
       
    -- Outputs:
        -- The starting position of the component
       
    -- GOAL:
        -- The idea of this function is that you would put this function into a FOR loop for all components in the list
        -- and it will easily return an equally spaced set of components, hence the term EVEN SPACE

    nTotalComponents = nTotalComponents + 1
    local nDifference = nTotalLength - ( nTotalComponents * nLengthOfComponents )
    local nDistance = nDifference / ( nTotalComponents + 1 )
   
    return nDistance + ( nIndexOfComponentBeingRequested * ( nLengthOfComponents + nDistance ) )

--------------------------------------------------------------------------------
end
--------------------------------------------------------------------------------



5. Usage Example:

Lets say I have five buttons I want to space out evenly on the screen, the code would look like this (Assuming you have already installed the function as in step 4 above and that you have 5 buttons named btn_0, btn_1, btn_2, btn_3, btn_4) NOTE: Place this in the onInit to test:

Code: Select all

        -- Assuming there is a component in your HUD called btn_0
        local hComponent = hud.getComponent ( this.getUser ( ), "unique_instance_main_hud.btn_0" )
        local nWidth, nHeight = hud.getComponentSize ( hComponent )
        local nTotalComponents = 4
        local nNewStart = 0
        for i = 0, nTotalComponents do
           
            local hComponent = hud.getComponent ( this.getUser ( ), "unique_instance_main_hud.btn_"..i )
            local nLeft, nTop = hud.getComponentPosition ( hComponent )
            local nNewStart = this.EvenSpace ( 100, nTotalComponents, nWidth, i )
            hud.setComponentPosition ( hComponent, nNewStart, nTop )
           
        end



ENJOY and God Bless!

Nav
Game Scorpion Inc. http://www.gamescorpion.com
Armies of Riddle Collectible Card Game: http://www.ArmiesOfRiddle.com
User avatar
gamescorpion
Platinum Boarder
Platinum Boarder
 
Posts: 667
Location: Ontario, Canada

Re: Copy/Paste Functions & Handlers - Copy/Paste Format Only Pls

Postby capiright » 04 Dec 2012, 14:43

You know you can get the modulus
Code: Select all
local nExt = math.mod( nDay, 10)
local sExt = ""
if ( nExt == 1 )
then
    sExt = ""..nDay.."st"
--[rinse and repeat where else is "th"]
end
User avatar
capiright
Platinum Boarder
Platinum Boarder
 
Posts: 518

Re: Copy/Paste Functions & Handlers - Copy/Paste Format Only Pls

Postby Shaderman » 27 Apr 2014, 20:24

Function/Handler NAME: GetLeapYear ( nYear )

TYPE: Function

Code Created By, Date and Version: Shaderman - Apr-27-2014 - 1.0

Code Description: Check if a year is a leap year

Function/Handler INPUTS: nYear -> The year to check (i.e. 2014)

Function/Handler OUTPUTS: bool value. True if nYear is a leap year, otherwise false.

REQUIREMENTS: ShiVa :)

CODE:
Code: Select all
--------------------------------------------------------------------------------
function SmanDateTime.GetLeapYear ( nYear )
--------------------------------------------------------------------------------
   
    if ( math.mod ( nYear, 400 ) == 0 or math.mod ( nYear, 4 ) == 0 and math.mod ( nYear, 100 ) ~= 0 ) then
        return true
    else
        return false
    end
   
--------------------------------------------------------------------------------
end
--------------------------------------------------------------------------------
User avatar
Shaderman
Platinum Boarder
Platinum Boarder
 
Posts: 622
Location: Heidelberg, Germany

Re: Copy/Paste Functions & Handlers - Copy/Paste Format Only Pls

Postby Shaderman » 27 Apr 2014, 20:38

Function/Handler NAME: GetDayOfWeek ( nYear, nMonth, nDayOfMonth )

TYPE: Function

Code Created By, Date and Version: Shaderman - Apr-27-2014 - 1.0

Code Description: Get the day of week for a date, where nMonth is 0 based! Based on code from http://lua-users.org/wiki/DayOfWeekAndD ... nthExample

Function/Handler INPUTS: nYear, nMonth, nDayOfMonth -> The year, month and day to check (i.e. 2014, 4, 27)

Function/Handler OUTPUTS: number value. The number of the weekday, where 0 = Sunday, 1 = Monday...

REQUIREMENTS: ShiVa :)

CODE:
Code: Select all
--------------------------------------------------------------------------------
function SmanDateTime.GetDayOfWeek ( nYear, nMonth, nDayOfMonth )
--------------------------------------------------------------------------------
   
    --
    -- Based on code from http://lua-users.org/wiki/DayOfWeekAndDaysInMonthExample
    --
   
    nMonth = nMonth +1
    if ( nMonth == 1 ) then nMonth = 13; nYear = nYear -1  end
    if ( nMonth == 2 ) then nMonth = 14; nYear = nYear -1  end
   
    local   tmp1 = nDayOfMonth + ( nMonth * 2 ) + math.floor ( ( ( nMonth +1 ) *3) /5 ) + nYear + math.floor ( nYear / 4 ) - math.floor ( nYear / 100) + math.floor ( nYear / 400)+ 2
    local   tmp2 = math.floor ( tmp1 / 7 )
    return  tmp1 - ( tmp2 * 7 ) -1
   
--------------------------------------------------------------------------------
end
--------------------------------------------------------------------------------
User avatar
Shaderman
Platinum Boarder
Platinum Boarder
 
Posts: 622
Location: Heidelberg, Germany

Re: Copy/Paste Functions & Handlers - Copy/Paste Format Only Pls

Postby Shaderman » 27 Apr 2014, 20:43

Function/Handler NAME: GetDayOfYear ( nYear, nMonth, nDayOfMonth )

TYPE: Function

Code Created By, Date and Version: Shaderman - Apr-27-2014 - 1.0

Code Description: Get the day of year for a date, where nMonth is 0 based! Based on a formula from http://en.wikipedia.org/wiki/ISO%5Fweek ... given_date

Function/Handler INPUTS: nYear, nMonth, nDayOfMonth -> The year, month and day to check (i.e. 2014, 4, 27)

Function/Handler OUTPUTS: number value. The number of the day (i.e. 117 for 4/27/2014).

REQUIREMENTS: The GetLeapYear function.

CODE:
Code: Select all
--------------------------------------------------------------------------------
function SmanDateTime.GetDayOfYear ( nYear, nMonth, nDayOfMonth )
--------------------------------------------------------------------------------
   
    --
    -- Based on code from http://en.wikipedia.org/wiki/ISO%5Fweek%5Fdate#Calculating_the_week_number_of_a_given_date
    --
   
    if ( this.GetLeapYear ( nYear ) ) then
        local daysToAdd = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 }
        return daysToAdd[ nMonth +1 ] + nDayOfMonth
    else
        local daysToAdd = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }
        return daysToAdd[ nMonth +1 ] + nDayOfMonth
    end
   
--------------------------------------------------------------------------------
end
--------------------------------------------------------------------------------
User avatar
Shaderman
Platinum Boarder
Platinum Boarder
 
Posts: 622
Location: Heidelberg, Germany

Re: Copy/Paste Functions & Handlers - Copy/Paste Format Only Pls

Postby Shaderman » 27 Apr 2014, 20:47

Function/Handler NAME: GetWeekOfYear ( nYear, nMonth, nDayOfMonth )

TYPE: Function

Code Created By, Date and Version: Shaderman - Apr-27-2014 - 1.0

Code Description: Get the week of the year for a date, where nMonth is 0 based!

Function/Handler INPUTS: nYear, nMonth, nDayOfMonth -> The year, month and day to check (i.e. 2014, 4, 27)

Function/Handler OUTPUTS: number value. The number of the week (i.e. 17 for 4/27/2014).

REQUIREMENTS: The GetDayOfWeek and GetDayOfYear functions.

CODE:
Code: Select all
--------------------------------------------------------------------------------
function SmanDateTime.GetWeekOfYear ( nYear, nMonth, nDayOfMonth )
--------------------------------------------------------------------------------
   
    local nOrdinalDay   = this.GetDayOfYear ( nYear, nMonth, nDayOfMonth )
    local nDayOfWeek    = this.GetDayOfWeek ( nYear, nMonth, nDayOfMonth )
    nDayOfWeek          = nDayOfWeek > 0 and nDayOfWeek or 7 -- ShiVa returns 0 for Sunday, we need it to be 7 (1 for Monday to 7 for Sunday)
    return              math.trunc ( ( nOrdinalDay - nDayOfWeek + 10 ) / 7, 0 )
   
--------------------------------------------------------------------------------
end
--------------------------------------------------------------------------------
User avatar
Shaderman
Platinum Boarder
Platinum Boarder
 
Posts: 622
Location: Heidelberg, Germany


Return to Code Snippets