Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Random Pinball for the iPad with Codea
-- Random PinBall by Dave1707
function setup()
    displayMode(FULLSCREEN)
    
    -- define variables and tables
    cx=0
    cy=0
    limit=150   
    tab1={}
    tab2={}
    
    create()    -- set table values
    
    -- set pinball values
    circ1 = physics.body(CIRCLE,5)
    circ1.x=300
    circ1.y=HEIGHT-50
    circ1.gravityScale=.6
    circ1.restitution=1
    -- set line values   
    line1 = physics.body(EDGE,vec2(0,0),vec2(0,HEIGHT))
    line2 = physics.body(EDGE,vec2(WIDTH,0),vec2(WIDTH,HEIGHT))
    line3 = physics.body(EDGE,vec2(0,0),vec2(WIDTH,0))
    line4 = physics.body(EDGE,vec2(0,HEIGHT),vec2(WIDTH,HEIGHT))     
end
function create()
    -- set initial values for pins in tables 
    for x=1,limit do
        tab1[x] = physics.body(CIRCLE,10)  
        tab1[x].x = math.random(WIDTH)
        tab1[x].y = math.random(HEIGHT)
        tab1[x].type = STATIC
        tab2[x]=0    -- 0=pin not hit, 1=pin was hit
    end       
end
function collide(contact)
    -- check for collision 
    if contact.state == BEGAN then
        cx=contact.bodyA.x    -- x position of hit pin
        cy=contact.bodyA.y    -- y position of hit pin
        -- restart pinball when at bottom of screen
        if circ1.y < 20 then
            circ1.y = HEIGHT-50
            circ1.x = math.random(WIDTH)
        end
    end   
end
function draw()
    background(0, 0, 0) 
    -- draw pinball
    fill(255,0,0,255)
    ellipse(circ1.x,circ1.y,10,10)
    -- draw boundary lines    
    line(0,0,0,HEIGHT)  
    line(WIDTH,0,WIDTH,HEIGHT) 
    line(0,0,0,WIDTH)
    line(0,HEIGHT,WIDTH,HEIGHT)
    
    -- draw flashing pins or white pins each draw cycle
    for x=1,limit do
        -- check which pin was hit
        if cx == tab1[x].x and cy == tab1[x].y then
            tab2[x] = 1    -- set table for hit pin
            cx=0           -- clear values         
            cy=0
        end
        
        fill(255)                -- set color to white
        if tab2[x] > 0 then      -- pin was hit, set random color
            fill(math.random(255),math.random(255),math.random(255),255)
        end
        
        ellipse(tab1[x].x,tab1[x].y,20)    -- draw pins       
    end 
    -- draw credits    
    fill(0, 252, 0, 255) 
    text("Random PinBall by Dave1707",WIDTH/2,HEIGHT/2)   
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment