4 Matrix music DJ app
Type in the following code (without -- comments), save it and test it:
1 function love.load()
2 la, lg = love.audio, love.graphics
3 names = { "lead", "drums", "drumsb", "clap" }
4 instr = {{},{}} -- Table of instruments with...
5 for i = 1, 2 do -- two rows and...
6 for j = 1, #names do -- four columns
7 instr[i][j] = {}
8 instr[i][j].snd = la.newSource( names[j] .. i .. ".ogg" )
9 instr[i][j].snd:setLooping( true ) -- Endless looping on
10 instr[i][j].snd:setVolume( 0 ) -- Loudness to 0
11 instr[i][j].snd:play() -- Track playback starts
12 instr[i][j].color = { 60
*
j, love.math.random(200), 200 }
13 end
14 end
15 columns = #instr[1] -- 4 columns
16 rows = #instr -- 2 rows
17 width = lg.getWidth() -- Screen size
18 height = lg.getHeight()
19 fieldW = width / columns -- Touch field size
20 fieldH = height / rows
21 end
22
23 function love.draw()
24 for i, row in ipairs(instr) do -- i is the index, row is the value
25 for j, instrument in ipairs(row) do
26 lg.setColor(instrument.color) -- Instruments have own colors
27 lg.rectangle( "fill", (j-1)
*
fieldW, (i-1)
*
fieldH, fieldW, fieldH )
28 if instrument.snd:getVolume() == 1 then
29 lg.setColor( 255, 255, 255, 95 ) -- on/off state is displayed
30 lg.circle( "fill", (j-0.5)
*
fieldW, (i-0.5)
*
fieldH, fieldW
*
0.4 )
31 end
32 end
33 end
34 end
35
36 function love.mousepressed(x, y) -- Gets started by mouse/touch
37 whereW = math.ceil( x / fieldW ) -- Calculating column
38 whereH = math.ceil( y / fieldH ) -- Calculating row
39 if instr[whereH][whereW].snd:getVolume() == 1 then
40 instr[whereH][whereW].snd:setVolume(0) -- Loudness 0%
41 else
42 instr[whereH][whereW].snd:setVolume(1) -- Loudness 100%
43 end
44 end
The code makes intense use of tables/lists and for loops as well as calculations, which might need
a bit more time to be understood.
LÖVE Game Programming - 17.01.05 6/6 qubodup.itch.io/startgamedev