Search code examples
gridluamoai

Moai grid with tile colors


I'm trying to create a grid for a game using the Moai SDK. Each tile in the grid should have the ability to be filled with a color.

So actually I have two questions:

  • What is the best way to build a grid using Moai
  • How can I fill each tile individually with a color

The grid

Thanks


Solution

  • What is the best way to build a grid using Moai

    Moai has an object for creating grids: MOAIGrid. Using the framework's jargon, you create a grid and give it a deck. Then you attach it to a prop and add the prop to a layer. (That layer also needs a viewport which is attached to a window.)

    How can I fill each tile individually with a color

    A Moai deck is an image or collection of images. If you wanted your tiles to be different colors then you would create a deck with images of the square in those colors.

    Example

    This code will create a 4x4 grid in a window:

    -- Open the window and create a viewport
    MOAISim.openWindow("Example", 512, 512)
    viewport = MOAIViewport.new()
    viewport:setSize(512, 512)
    viewport:setScale(512, 512)
    
    -- Create a layer
    layer = MOAILayer2D.new()
    layer:setViewport(viewport)
    MOAISim.pushRenderPass(layer)
    
    -- Create a 4x4 grid of 64x64px squares
    grid = MOAIGrid.new()
    grid:initGrid(4, 4, 64)
    grid:setRow(1, 1, 1, 1, 1)
    grid:setRow(2, 1, 1, 1, 1)
    grid:setRow(3, 1, 1, 1, 1)
    grid:setRow(4, 1, 1, 1, 1)
    
    -- Load the image file
    deck = MOAITileDeck2D.new()
    deck:setTexture("squares.png")
    deck:setSize(2, 2)
    
    -- Make a prop with that grid and image set
    prop = MOAIProp2D.new()
    prop:setDeck(deck)
    prop:setGrid(grid)
    prop:setLoc(-256, -256)
    
    -- Add it to the layer so it will be rendered
    layer:insertProp(prop)
    

    After that, if you want to change the color of a specific cell, use the setTile method to choose which item in the deck that cell uses.

    -- Change the color of cell 1,1 to the second item in the deck
    grid:setTile(1, 1, 2)