News:

Building a 3D Ray Tracer  By stevmjon

Main Menu

Filling array with diamond shape

Started by jimwon, November 12, 2009, 05:06:18 PM

Previous topic - Next topic

jimwon

OK - This is a maths type question rather than a programming thing....

If I have a 2D integer array with all elements within in set to 0, I can create a square of elements set to 1 within it starting at a central point and at any size by doing the following and adjusting PosX, PosY & Size:

Dim Array(100,100)

PosX=10
PosY=10
Size=5

For Y=PosY-Size To PosY+Size
   For X=PosX-Size To PosX+Size
      Array(X,Y)=1
   Next X
Next Y

This will create a square, but how do I create a diamond?

kevin

#1
 Something like this would do.

PlayBASIC Code: [Select]
   Height=100
Width=100

xpos=400
ypos=300

ChangeInX#=float(Width)/Height

x#=Width

for ylp= 0 to Height

line xpos-x#,ypos-ylp,xpos+x#,ypos-ylp
line xpos-x#,ypos+ylp,xpos+x#,ypos+ylp

x#=x#-ChangeInX#
next

Sync
waitkey



jimwon

Thanks! Here's my code using Kevins equations - this doesn't catch errors if you try to address outside the array dimensions, but I'll sort that out when I implement it into my program.

;Dim array
Dim Map(10,10)
;Scale of box size
SC=50
;Size of diamond shape
Size=3
;Height & Width of diamond shape
Height=Size
Width=Size
;Funky maths bit
ChangeInX#=Float(Width)/Height
X#=Width
;starting position of the diamond
PosX=5
PosY=5
;Do this as many times as the size variable dictates
For L=1 To Size
   ;reset x# to the current value of L
   X#=L
   ;do this as many times as L variabel
   For Y=0 To L
      ;fill the map array with value 1 at these co-ords
      Map(PosX-X#,PosY-Y)=1
      Map(PosX+X#,PosY-Y)=1
      Map(PosX-X#,PosY+Y)=1
      Map(PosX+X#,PosY+Y)=1
      ;alter the value of x#
      X#=X#-ChangeInX#
   Next Y
Next L
;draw the array to the screen sequentially
For Y=0 To 10
   For X=0 To 10
      If Map(X,Y)=0 Then BoxC X*SC,Y*SC,(X*SC)+SC,(Y*SC)+SC,0,RGB(255,255,255)
      If Map(X,Y)=1 Then BoxC X*SC,Y*SC,(X*SC)+SC,(Y*SC)+SC,0,RGB(255,0,0)
   Next X
Next Y
;display drawing
Sync
WaitKey

kevin


There's little too much work in the routine.   You can use the  ClearArrayCells command to fill rows of values in 2D arrays.   So all you  need to do is interpolate down the Y axis and calc the X values (the funky math bit).. This gives you the starting X cords (and the end cords).  Then you'd call ClearArrayCells to fill the cells.   For small rows there'd be really no benefit, but for bigger arrays, it'd be quicker.