Game Development Reference
In-Depth Information
In this example, we'll put the concept of rectangles to work by drawing chessboard. The first thing
about a chessboard is that it has squares of alternating color and is generally 8×8 squares in size.
local _W, _H = love.graphics.getWidth(), love.graphics.getHeight()
local smaller = math.min(_W, _H)
local tileSize = math.floor(smaller/10) -- To allow for spacing above and below
function love.load()
love.graphics.setColor(0,0,0,255)
love.graphics.setBackgroundColor(255,255,255)
end
local mode = 1
for i = 1, 8 do
for j = 1, 8 do
if mode ==1 then
theMode = "fill"
else
theMode = "line"
end
mode = 1 - mode
love.graphics.rectangle(theMode, j*tileSize, i*tileSize, tileSize, tileSize)
end
mode = 1 - mode
end
end
function love.draw()
drawBoard()
end
The code is quite straightforward; we are just toggling
fill
and
line
by simply using the fact that
1 - 1 = 0 and 1 - 0 = 1, so
1 - mode
will help us toggle the number held in mode between 0 and 1.
Then, using an
if
statement, we set
theMode
to
fill
if the value of
mode
is 1 or
line
if the value of
mode
is 0. Because we are dealing with an even number of squares, at the end of the inner loop, the
value of
mode
will again be what we started with, so we do a toggle once again. That way, the next
line will start with the alternate mode, hence the alternating pattern. To see what would happen if we
did not do that, comment out
mode = 1 - mode
after the rectangle function and see what the code
renders.
Circles
The syntax for the function to draw a circle is
love.graphics.circle(mode, x, y, radius, segments)
mode
, as before, is either
fill
or
line
,
x
and
y
are the center points, and
radius
is the size of the
circle. The default number of segments is 10, which draws a jagged circle, good for debugging or
for systems that have low resources. For smooth good quality circles, the number of segments
recommended are 100.