Fundamental concepts - going loopy

As I said earlier I’m a complete novice so apologies. My mind has not grasped many of the fundamental concepts of the code or of modern programming languages…bring back the vic20! Adventureland nice!

I’ve purchased the programming in lua 5.2 manual and have been skimming through that, along with the operating manual from the internet and have read some of the very helpful codea documentation provided by Ignatz.
I’m trying to understand the relationship between the setup function and the draw function. It is stated that the draw function is running approx 60 times a second which I assume means that it’s on perpetual loop, whilst when I’m reading about efficiencies in coding , things are mentioned such as load a sprite from documents via setup so it only occurs once (as if you load it up in draw then it’s attempting to do it 60 times a second) etc. But setup isn’t just occurring once is it? Because the parameter functions are defined there and can be freely manipulated and even receive information back from the draw function…or are these separately existing functions which are just being setup and called from setup before continuing to exist independently from the setup function?

Is there a correct way of conceptualising the relationship?

I’m trying to understand this as this conceptualisation informs how one would use loops correctly and efficiently. I’ve already been helped several times and am probably annoying everyone so I’m trying to pin point the underlying cause. (My stupidity is the obvious answer…and perhaps a couple years study of object oriented programming) At the moment I’m trying to get codea to generate a set of systematic images, and then store these in documents, the problem being to do this I have to use loops in the draw function…or do I? I can achieve my aim semi-automatically via a parameter in setup which can then be moved backwards and forwards via touch and each point of the parameter then saves an image, but how do I then suspend the parameter and get the computer to do it automatically as the semi automatic method jumps and misses images due to the sensitivity of the slide bar…where does the loop go…but most importantly why does it go where it goes?

-- TileConstructor


--# Main
--to convert the numbers 0 to 255 into binary 
--and store the binary code for each number in a table
--to generate a graphical image based on each binary code

function setup()
--   parameter.action("Get matrix",devtab)
--   parameter.integer("k",1,512,109)
--   parameter.action("Clear Output", function() output.clear() end )

 
    screen = image(WIDTH,HEIGHT)
    basetile=readImage("Documents:newtile")  --these are to be used in the draw function section
    shady=readImage("Documents:newshade")    -- ditto
    xcoord={0,41,82,0,41,82,0,41,82}         -- ditto
    ycoord={0,0,0,41,41,41,82,82,82}         -- ditto
    m={}                      
    for ident = 1, 512 do
    m[ident]={}               
        for y=1,9 do
            m[ident][y]=0     
        end
    binary(ident,ident-1,1)           
    end
end

--function devtab()

--   print("new matrix")
--   print(m[k][7],m[k][8],m[k][9])
--   print(m[k][4],m[k][5],m[k][6])
--   print(m[k][1],m[k][2],m[k][3])                              
--   end                                   

function binary(ident,rntot,i)    
                                  
    rntot,r=math.modf(rntot/2)    
    if r>0 then r=1 else r=0 end  
    m[ident][i]=r                 
    i = i + 1                     
    if rntot>0 then binary(ident,rntot,i) else return
    end
end

function draw()

setContext(screen)
spriteMode(CORNER)
sprite(basetile,0,0)
    for i = 1,9 do
if m[k][i]==1 then sprite(shady,xcoord[i],ycoord[i]) end
end
setContext()
sprite(screen)
capturedImage = screen:copy(0,0,124,124)
picturesave()
end    


function picturesave()
    str="tile"..k
    print (str)
    saveImage("Documents:"..str,capturedImage)
end

If you reinstate the parameters everythingvworks perfectly…however only semi automatically…I wish to loop through k, yet my attempts cause the program to crash, occasionally run but black out, or simply closes codea down.

I dont quiet get what you wish to do…?

Is it that you want it to save 512 images but you don’t know how you’d loop through them just once in order to save them…?

I think if you only need it once, that either you set the loop in the setup function (this only gets called once, idk about the parameters exactly but they are just objects that are created i think)
But since you want to draw something to the screen, you could just use a var to check if it has already been done or not, so it would be like

-- TileConstructor


--# Main
--to convert the numbers 0 to 255 into binary 
--and store the binary code for each number in a table
--to generate a graphical image based on each binary code

function setup()
--   parameter.action("Get matrix",devtab)
--   parameter.integer("k",1,512,109)
--   parameter.action("Clear Output", function() output.clear() end )
    finished = false


    screen = image(WIDTH,HEIGHT)
    basetile=readImage("Documents:newtile")  --these are to be used in the draw function section
    shady=readImage("Documents:newshade")    -- ditto
    xcoord={0,41,82,0,41,82,0,41,82}         -- ditto
    ycoord={0,0,0,41,41,41,82,82,82}         -- ditto
    m={}                      
    for ident = 1, 512 do
    m[ident]={}               
        for y=1,9 do
            m[ident][y]=0     
        end
    binary(ident,ident-1,1)           
    end
end

--function devtab()

--   print("new matrix")
--   print(m[k][7],m[k][8],m[k][9])
--   print(m[k][4],m[k][5],m[k][6])
--   print(m[k][1],m[k][2],m[k][3])                              
--   end                                   

function binary(ident,rntot,i)    

    rntot,r=math.modf(rntot/2)    
    if r>0 then r=1 else r=0 end  
    m[ident][i]=r                 
    i = i + 1                     
    if rntot>0 then binary(ident,rntot,i) else return
    end
end

function draw()

if not(finished) then
setContext(screen)
spriteMode(CORNER)
sprite(basetile,0,0)
for k = 1, 512 do
    for i = 1,9 do
if m[k][i]==1 then sprite(shady,xcoord[i],ycoord[i]) end
end
end
setContext()
sprite(screen)
capturedImage = screen:copy(0,0,124,124)
picturesave()
end
end


function picturesave()
    str="tile"..k
    print (str)
    saveImage("Documents:"..str,capturedImage)
end

@TheAbstractMan The setup() function runs once when the program starts. The draw() function runs 60 times or less per second depending on what the code in draw() is doing. If you’re not sure about setup(), put a print statement in setup() and it will only print once. I would help with what you’re doing, but I don’t understand what’s going on. Also, for anyone else that tries this code, it creates a bunch of images (512) in the Documents folder.

@TheAbstractMan does this have something to do with untiling tile sheets or so…?

Hi my main aim really is to attempt a project so that by doing so I familiarise myself with the coding language. I mentioned when I first signed up that the only experience I had of programming was zx spectrums and Vic 20s about thirty years ago so my mind set is very much based on that sequential main body, go to statements and data files style of programming. Obviously diving into codea is a bit of an eye opener and I’m trying to get my head around the underlying concepts of modern programming which are obviously essential to understanding how to implement and write code…what I find fascinating is how all of the things that I was wanting to implement back in yesteryear and couldn’t now seem very much a possibility with the architecture of the language.

Coupled with this - I’ve got a good friend who works in a design school at a local university and I’ve had many fascinating conversations with him regarding the importance of design in modern/postmodern culture. A beautiful example of this is Lead Wars I’m not sure if you’ve seen the game app but it’s completely retro and almost revolutionary in terms of gaming with respect to the almost identikit stuff being churned out…just simple and beautifully styled…I’ve also been blown away by the Room which is at the complete opposite end of the spectrum to Lead Wars and represents the ultimate in styled, polished sophisticated gaming…

Anyway…this Is going to be a long one…I guess I’m fundamentally a d&d freak and was looking at all of these brilliant new things - I just bought an iPad air for myself at Christmas and just find it amazing…so I’ve been marvelling at all of these wonders like the kid in the proverbial candy shop thinking…it’s much more fun making candy than eating it and so I had an inkling of a retro styled fusion d&d game with what I believe will be a really interesting user interface suitable to the iPads touch screen…blah de blah…so the upshot of all of this that the initial part of the game has two main parts to the screen…a hand drawn dungeon (at least in style) and the user interface(I’ll keep that as secret squirrel stuff for the moment) so I was looking at ways in which I could produce a variety of hand drawn dungeons and thought about simply making a load of 3x3 tiles based on literally a grid and a shaded square and use these. If you’re familiar with the dungeon and dragon maps of the early eighties you’ll get where I’m coming from.

So so far I have done an image resized program (it sounds grand but it’s literally about 5 or six lines of code) which has allowed me to take a photo of some graph paper and a shaded square and make them correct sizes for overlay.

The code posted above, generates all 3x3 possible combinations of a differently shaded in 3x3 grid 512 in total and then attempts to save them with a coded file name. Also I have all of the matrix representations as well so that means I can use these as an underlying coding map for the computer to move around etc. I know that I could have produced less and used symmetry transformations but I just thought what the hell may as well just do it like this to begin with. Of course I am also aware that the way in which I am proceeding may backfire and I’ll have to come at the game design from a different angle but doing always seems to teach more than thinking…

My next aim is to create a dungeon builder which will allow me to select tiles I wish, stitch them together and basically design anything that I want based on those tiles. And also to modify them with particular attributes…secret passages etc…as well as non visible stuff. So the stitched together map has both a visual representation and a coded representation.

If I get this far and it don’t see why not then I believe I will have gained some rudimentary understanding of using codea. Mainly due to you kind folks who have so far been amazingly accommodating.

This will then allow me to move into examining the development of the user interface or the overlaying of animation on top of the map, it depends how I’m feeing at that point.

This is all coupled with me trying to teach my 7 year old the importance of logical thinking and give him some insight into how computers work on a coding level as opposed to being able to point and click a mouse to the effect of accidentally placing a 4000 pound bid on eBay for a Lego assault walker which he managed to do about 3 years ago!

I suppose another reason for the tiles is I just like the mathematical simplicity of generating them again, an interesting concept for my 7 year old…and yes I only wanted them generated once to be saved and used in the next program.

What you are doing is the equivalent of buying a tennis racket for the first time and entering a tournament the next weekend. You need to build your skills before you attempt something of this size.

Also, your choice of project appears to create a problem for anyone trying to help you, if it creates 512 images in their documents folder!

I suggest you start really small, work through all the tutorials and examples you can find, and build up towards something like this.

Could I just ask @stevon8ter I hope I’m reading this correctly, the var that you’ve assigned is finished = false, in setup and this is mentioned in the draw function at the beginning using if not (finished) then…
There’s nothing else added is there? …sorry I haven 't ran this yet…I’m assuming it works but can’t understand how.
So the logical translation here is
If not false then do the following…what is being considered as false or not false? Is it the actual draw function itself as this condition leads off from it…sorry…and my thinking would want something additional to reset the condition…I’m inferring from your comments that the loop process would somehow change this conditional…but how? Sorry again, I don’t get it so I wouldn’t be able to reapply it in a different context.

@TheAbstractMan - I think you need to keep going over the tutorial material, because we just aren’t equipped to teach you Lua via forum messages. We all struggle at first, but if you persevere, you will start getting it.

Okay, I’ll take that one on the chin. Apologies.

@TheAbstractMan I indeed didn’t set the variable to true, I should’ve done that when the loop was done

Also, instead of saving all of them in documents, you could save them in variables… which is easyer for the user who’ll use your project

If you think about putting it on the app store, you could always tweek your code so that it actually saves them for 1 time, but those are sorrows for waaay later

as @Ignatz said, first try some easyer projects, it could take a while to learn everything. Once you know how most basic stuff work, you can try going farther, and farther every time

Thank you. Strangely. Sort of worked but didn’t. Then realised I had to pass the k variable through the savepicture function to avoid error messages relating to concatenation of global functions…now I have 512 perfectly labelled blank tiles with no shading…back to drawing board…perhaps shouldn’t pass the k variable but then error…hmmm…yet it works absolutely fine albeit missing the occasional image with the parameter slide bar…

Whey hey! Success, many thanks. The k loop command needs to be placed directly after the
If NOT conditional…why I’ll have to work that one out. But now fully working.

@TheAbstractMan Here is another version of what I think you were doing. I don’t have your sprites, so I had to use some default sprites. Instead of saving 512 images to the Documents folder, I put them in a table. You can scroll thru the table and see the different images by moving your finger up or down the screen. You can replace my sprites with yours.


function setup()
    tab={}
    rectMode(CORNER)
    spriteMode(CORNER)
    base=readImage("SpaceCute:Background")
    shady=readImage("SpaceCute:Icon")
    dy=0
    z=0
end

function draw()
    background(40, 40, 50)
    fill(255)
    if z<512 then
        tab[z]=image(123,123)
        setContext(tab[z])
        sprite(base,0,0,123,123)
        bin(z)
        setContext()
        text("creating image  "..z,WIDTH/2,HEIGHT/2)
        z=z+1
    else
        text("Slide finger up or down to show different image",WIDTH/2,HEIGHT/2+200)
        yy=math.floor(dy/10)
        text("image "..yy,WIDTH/2,HEIGHT/2+100)
        sprite(tab[yy],WIDTH/2-61,HEIGHT/2-61)
    end        
end

function bin(z)
    x,y=0,-1
    for a=8,0,-1 do
        y=y+1
        if y>2 then
            y=0
            x=x+1
        end
        if z>=2^a then
            z=z-2^a
            sprite(shady,y*41,x*41,41,41)
        end
    end
end

function touched(t)
    if t.state==MOVING then
        dy=dy+t.deltaY
        if dy>#tab*10 then
            dy=#tab*10
        elseif dy<0 then
            dy=0
        end
    end
end

That’s wonderful @dave1707. Just tried it and works a treat! And much more elegant than mine. Yeah, I took the advice and tabularised everything too! Many thanks, lots of food for thought there. Will study this… I like the way you’ve used the looping of the draw function to perform the iteration without using an iteration which was what was causing me all the problems…very clever…it makes perfect sense now thinking about it in that way…