Overlapping Rectangles

Post your FreeBASIC source, examples, tips and tricks here. Please don’t post code without including an explanation.
Post Reply
nimdays
Posts: 236
Joined: May 29, 2014 22:01
Location: West Java, Indonesia

Overlapping Rectangles

Post by nimdays »

There are 16 possibilities when 2 rectangles are overlapping each other

Code: Select all

const sw = 800,sh = 600,sd = 32

type rect
    as integer x,y,w,h
    as ulong bcolor
end type

function test_rect(rs as rect,rd as rect)as integer
    dim as integer l = rs.x - rd.x,t = rs.y - rd.y,tb,lr,tb1,lr1
    'src
    tb += cuint(t) <= rd.h
    tb += cuint(t + rs.h) <= rd.h
    lr += cuint(l) <= rd.w
    lr += cuint(l + rs.w) <= rd.w
    
    if tb <> 0 and lr <> 0 then return 1
    'dst    
    l = rd.x - rs.x
    t = rd.y - rs.y
    lr1 += cuint(l) <= rs.w
    lr1 += cuint(l + rd.w) <= rs.w
    tb1 += cuint(t) <= rs.h
    tb1 += cuint(t + rd.h) <= rs.h
    
    if tb1 <> 0 and lr1 <> 0 then return 1
    if tb <> 0 and lr1 <> 0 then return 1
    if lr <> 0 and tb1 <> 0 then return 1
    
    return 0
end function

sub draw_rect(ps as ulong ptr,r as rect)
    ps += r.y * sw + r.x
    screenlock()
    for y as integer = 0 to r.h-1
        for x as integer = 0 to r.w-1
            ps[x] = r.bcolor
        next x
        ps += sw
    next y
    screenunlock()
end sub

'''''''''''''''''''''''''''''''

screenres sw,sh,sd
dim as ulong ptr ps = screenptr()
dim as rect rd = (140,140,220,280,&hff),rs = (10,10,100,100,&hffff)
dim as integer count,l = 110 * 5

draw_rect(ps,rd)
for y as integer = 0 to 4
    for x as integer = 0 to 4
        if test_rect(rs,rd) then 
            rs.bcolor = &hffff00
            count += 1
        end if
        draw_rect(ps,rs)
        rs.x += 110
        rs.bcolor = &hffff
        windowtitle "count : " & count
        sleep 500
    next x
    rs.x = 10
    rs.y += 110
next y

cls
draw_rect(ps,rd)
rs.x = 10
rs.y = 10
rs.w = 100
rs.h = l
for x as integer = 0 to 4
    if test_rect(rs,rd) then 
        rs.bcolor = &hffff00
        count += 1
    end if
    draw_rect(ps,rs)
    rs.x += 110
    rs.bcolor = &hffff
    windowtitle "count : " & count
    sleep 500
next x

cls
draw_rect(ps,rd)
rs.x = 10
rs.y = 10
rs.w = l
rs.h = 100
for y as integer = 0 to 4
    if test_rect(rs,rd) then 
        rs.bcolor = &hffff00
        count += 1
    end if
    draw_rect(ps,rs)
    rs.y += 110
    rs.bcolor = &hffff
    windowtitle "count : " & count
    sleep 500
next y

cls
draw_rect(ps,rd)
rs.x = 10
rs.y = 10
rs.w = l
rs.h = l
if test_rect(rs,rd) then 
    rs.bcolor = &hffff00
    count += 1
end if
draw_rect(ps,rs)
windowtitle "count : " & count

sleep

Post Reply