puzzle example

Here’s an example of a puzzle program. The puzzle picture can be changed to whatever you want, but the larger the picture the better. You can use the parameter slider to change the number of pieces per side. Drag a piece around the screen to place it where you want it. I don’t pop the pieces to a grid, so where you place the piece is where it stays. Any piece that you move will show on top of all the other pieces. To see the puzzle picture, triple tap the screen. Triple tap again to hide the puzzle picture.


displayMode(FULLSCREEN)
supportedOrientations(PORTRAIT)

function setup()
    spriteMode(CORNER)  
    parameter.integer("side",3,8,4,setup1)   -- change number of pieces per side
end

function setup1()
    mov=0
    show=false
    img=readImage("Cargo Bot:Startup Screen")   -- puzzle picture
    w=img.width/side -- image width divided by number of sides
    h=img.height/side    -- image height divided by number of sides
    imgs={} -- table of image pieces
    pos={}  -- pieces location
    n=1 -- starting piece
    for y=1,side do  -- sides high
        for x=1,side do  -- sides wide
            imgs[n]=img:copy(w*(x-1),h*(y-1),w,h)  -- create pieces
            pos[n]=vec2(math.random(100,WIDTH-100),math.random(100,HEIGHT-100))
            n=n+1   -- number for next piece
        end
    end
end

function draw()
    background(40,40,50)
    fill(255)
    for a,b in pairs(pos) do    -- draw pieces
        sprite(imgs[a],b.x,b.y)
    end
    if show then
        sprite(img,0,0)
    end
end

function touched(t)
    if t.state==BEGAN then  -- which piece is being touched
        if t.tapCount==3 then   -- show/hide original image
            show=not show   -- toggle show true/false
        end
        for z=#pos,1,-1 do
            if t.x>pos[z].x and t.x<pos[z].x+w and 
                    t.y>pos[z].y and t.y<pos[z].y+h then
                mov=z   -- piece number being moved
                dx=t.x-pos[z].x -- offset touch x distance
                dy=t.y-pos[z].y -- offset touch y distance
                pos[#pos+1]=pos[mov] -- move it last in table,
                imgs[#imgs+1]=imgs[mov] -- so its drawn last
                table.remove(pos,mov) -- remove old piece x,y position
                table.remove(imgs,mov) -- remove old piece image
                return
            end
        end
    end
    if t.state==MOVING then -- selected piece is moving
        if mov>0 then -- dont move unless a piece is selected
            pos[#pos]=vec2(t.x-dx,t.y-dy)   -- update x,y of moving piece
        end        
    end
    if t.state==ENDED then  -- done moving
        mov,dx,dy=0,0,0   -- clear values
    end
end