-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimpleLoopLib.lua
executable file
·776 lines (628 loc) · 19.6 KB
/
simpleLoopLib.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
-- Created By Giles Allensby 17th August 2012 --
------------------------- Variables ----------------------
-- Screen Width
screenW = application:getLogicalWidth()
-- Screen Height
screenH = application:getLogicalHeight()
--Screen Center X
centerX = screenW/2
--Screen Center Y
centerY = screenH/2
-- Arrays (Tables)
display = {}
physics = {}
package = {}
transition = {}
storyboard = {}
-------------------------- Group Helper ----------------------------
displayGroup = gideros.class(Sprite)
function displayGroup:init(addToStage)
if addToStage == nil then addToStage = true; end
if addToStage then
stage:addChild(self)
end
self.group = true
end
function displayGroup:insert(sprite)
self:addChild(sprite)
end
--------------------- Color Conversion Functions -----------------------
local function decToHex(IN)
local B,K,OUT,I,D=16,"0123456789ABCDEF","",0
while IN>0 do
I=I+1
IN,D=math.floor(IN/B),math.fmod(IN,B)+1
OUT=string.sub(K,D,D)..OUT
end
if OUT == "" then
OUT = "00"
end
return OUT
end
function rgbToHex(c)
local output = decToHex(c.r) .. decToHex(c.g) .. decToHex(c.b);
return output
end
function rgbToColor(r, g, b)
local sum = r * 65536 + g * 256 + b
return sum
end
------------------------ Shape Functions --------------------------
function Shape:setReferencePoint(pos)
--self:setAnchorPoint(pos[1], pos[2])
end
function Shape:setFillColor(re,gr,bl)
self:setColorTransform(1,1,1)
self:setColorTransform(re/255,gr/255,bl/255)
end
function Shape:setPos(x,y)
self:setPosition(x,y)
end
function Shape:init()
self.width = self:getWidth()
self.height = self:getHeight()
end
--function Shape.width()
-- local wid = 100--self:getWidth()
-- return wid
--end
--function Shape.height()
-- local hei = self:getHeight()
-- return hei
--end
------------------------ Image Functions -------------------------
function Bitmap:setReferencePoint(pos)
self:setAnchorPoint(pos[1], pos[2])
end
function Bitmap:setFillColor(re,gr,bl)
self:setColorTransform(1,1,1)
self:setColorTransform(re/255,gr/255,bl/255)
end
function Bitmap:setPos(x,y)
self:setPosition(x,y)
end
function Bitmap:setScaleP(scale)
self:setScale(scale)
end
-------------------------- Display Functions ----------------------------
display.c = {0.5,0.5}
display.cr = {1,0.5}
display.cl = {0,0.5}
display.tl = {0,0}
display.tr = {1,0}
display.bl = {0,1}
display.br = {1,1}
display.contentWidth = application:getContentWidth()
display.contentHeight = application:getContentHeight()
display.HiddenStatusBar = ""
display.newRect = function(x,y,width,height)
local xPos = x or 0
local yPos = y or 0
local object = Shape.new()
object:setFillStyle(Shape.SOLID, 0xFFFFFF)
object:beginPath()
object:moveTo(0, 0)
object:lineTo(width, 0)
object:lineTo(width, height)
object:lineTo(0, height)
object:closePath()
object:endPath()
object:setPosition(xPos,yPos)
return object
end
display.newCircle = function(x, y, radius)
local circle = Shape.new()
local x = x or 0
local y = y or 0
local fillStyle = {Shape.SOLID, 0xFFFFFF, 1}
local xradius = radius
local yradius = radius
local sides = (xradius + yradius)/2
local startAngle = 0
local arcAngle = 1
circle:setFillStyle(unpack(fillStyle))
local angleStep = arcAngle / sides
circle:setPosition(x,y)
local xx = math.cos(startAngle*2*math.pi) * xradius
local yy = math.sin(startAngle*2*math.pi) * yradius
circle:beginPath()
circle:moveTo(xx, yy)
for i = 1,sides do
local angle = startAngle + i * angleStep
circle:lineTo(math.cos(angle*2*math.pi) * xradius,
math.sin(angle*2*math.pi) * yradius)
end
circle:endPath()
return circle
end
display.newElipse = function(x, y, radiusX, radiusY)
local circle = Shape.new()
local x = x or 0
local y = y or 0
local fillStyle = {Shape.SOLID, 0xFFFFFF, 1}
local xradius = radiusX
local yradius = radiusY
local sides = (xradius + yradius)/2
local startAngle = 0
local arcAngle = 1
circle:setFillStyle(unpack(fillStyle))
local angleStep = arcAngle / sides
circle:setPosition(x,y)
local xx = math.cos(startAngle*2*math.pi) * xradius
local yy = math.sin(startAngle*2*math.pi) * yradius
circle:beginPath()
circle:moveTo(xx, yy)
for i = 1,sides do
local angle = startAngle + i * angleStep
circle:lineTo(math.cos(angle*2*math.pi) * xradius,
math.sin(angle*2*math.pi) * yradius)
end
circle:endPath()
return circle
end
display.newImage = function(file, baseDir, x, y)
local xPos
local yPos
local baseDirLoc
if type(baseDir) ~= "number" then
xPos = x or 0
yPos = y or 0
baseDirLoc = baseDir or ""
else
xPos = baseDir or 0
yPos = x or 0
baseDirLoc = ""
end
local fileLoc
if baseDirLoc ~= "" and type(baseDirLoc) ~= "integer" then
fileLoc = baseDirLoc.."/"..file
else
fileLoc = file
end
local newImg = Bitmap.new(Texture.new(fileLoc))
newImg:setAnchorPoint(0.5, 0.5)
newImg:setPosition(xPos,yPos)
return newImg
end
display.newGroup = function()
local this = displayGroup:new()
return this
end
display.newText = function(text, x, y, font)
local this = TextField.new(font, text)
this:setPosition(x,y)
return this
end
-------------------------- Text Functions ----------------------------
function TextField:setTextColorRGB(field,r,g,b)
field:setTextColor(rgbToColor(r,g,b))
end
----------------- Do Nothing Corona Only Functions -------------------------
display.setStatusBar = function(style)
end
module = function(to, even)
end
-------------------------- Transition Functions ----------------------------
transition.to = function(tweens, params)
if tweens then
if #tweens > 0 then
local thisTween = {}
for i,v in ipairs(tweens) do
local time = params.time or 1000
time = time/1000
local repeatCount = params.repeatCount or 1
local reflect = params.reflect or false
local easing = params.ease or easing.linear
local delay = params.delay or 0
delay = delay/1000
local vals = {}
for k,v in pairs(params) do
if k~="delay" and k~="ease" and k~="reflect" and k~="repeatCount" and k~="time" then
vals[k] = v
end
end
thisTween[#thisTween+1]=GTween.new(v, time, vals, {delay = delay, ease=easing, repeatCount=repeatCount, reflect=reflect})
end
return thisTween
else
local time = params.time or 1000
time = time/1000
local repeatCount = params.repeatCount or 1
local reflect = params.reflect or false
local easing = params.ease or easing.linear
local delay = params.delay or 0
delay = delay/1000
local vals = {}
for k,v in pairs(params) do
if k~="delay" and k~="ease" and k~="reflect" and k~="repeatCount" and k~="time" then
vals[k] = v
end
end
--transition.to(tweens, params)
local thisTween = GTween.new(tweens, time, vals, {delay = delay, ease=easing, repeatCount = repeatCount, reflect = reflect})
return thisTween
end
end
end
local sceneTrans = {
SceneManager.moveFromLeft,
SceneManager.moveFromRight,
SceneManager.moveFromBottom,
SceneManager.moveFromTop,
SceneManager.moveFromLeftWithFade,
SceneManager.moveFromRightWithFade,
SceneManager.moveFromBottomWithFade,
SceneManager.moveFromTopWithFade,
SceneManager.overFromLeft,
SceneManager.overFromRight,
SceneManager.overFromBottom,
SceneManager.overFromTop,
SceneManager.overFromLeftWithFade,
SceneManager.overFromRightWithFade,
SceneManager.overFromBottomWithFade,
SceneManager.overFromTopWithFade,
SceneManager.fade,
SceneManager.crossFade,
SceneManager.flip,
SceneManager.flipWithFade,
SceneManager.flipWithShade,
}
local sceneHelp = {
"slideLeft",
"slideRight",
}
--------------------------- StoryBoard Functions ------------------------------
storyboard.gotoScene = function(toScene, trans, dura, ease)
local transd
for i=0, #sceneHelp do
if trans == sceneHelp[i] then
transd = sceneTrans[i]
end
end
ease = ease or easing.linear
sceneManager:changeScene(toScene, dura/1000, trans, ease)
end
storyboard.newScene = function()
local this = gideros.class(Sprite)
return(this)
end
function stage:insert(sprite)
self:addChild(sprite)
end
function Sprite:insert(sprite)
self:addChild(sprite)
end
--------------------------- Physics Functions ------------------------------
physics.addBody = function(b2world, object, args)
local bodyDef = {}
if args.type then
if args.type == "static" then
bodyDef.type = b2.STATIC_BODY
elseif args.type == "kinematic" then
bodyDef.type = b2.KINEMATIC_BODY
elseif args.type == "dynamic" then
bodyDef.type = b2.DYNAMIC_BODY
else
bodyDef.type = b2.DYNAMIC_BODY
end
end
bodyDef.density = args.density or 1.0
bodyDef.restitution = args.bounce or 0.0
if args.restitution then
bodyDef.restitution = args.restitution
end
bodyDef.friction = args.friction or 0.0
bodyDef.isSensor = args.isSensor or false
if args.width then
bodyDef.width = args.width
else
bodyDef.width = object:getWidth()
end
if args.height then
bodyDef.height = args.height
else
bodyDef.height = object:getHeight()
end
if args.radius then
bodyDef.radius = args.radius
end
local thisShape
local thisBody = b2world:createBody({type = bodyDef.type})
bodyDef.x = math.floor(object:getX() + bodyDef.width/2)
bodyDef.y = math.floor(object:getY() + bodyDef.height/2)
if args.radius then
bodyDef.width = object:getWidth()
bodyDef.height = object:getHeight()
bodyDef.x = math.floor(object:getX() + (bodyDef.width/2))
bodyDef.y = math.floor(object:getY() + (bodyDef.height/2))
thisShape = b2.CircleShape.new(0, 0, bodyDef.radius)
else
thisShape = b2.PolygonShape.new()
thisShape:setAsBox(bodyDef.width/2, bodyDef.height/2)
end
local thisFixture = thisBody:createFixture{shape = thisShape, density = bodyDef.density, restitution = bodyDef.restitution, friction = bodyDef.friction, isSensor = bodyDef.isSensor}
thisBody:setPosition(bodyDef.x, bodyDef.y)
object.image:setAnchorPoint(0.5, 0.5)
object:setPosition(bodyDef.x, bodyDef.y)
object.body = thisBody
object.fixture = thisFixture
end
local function updatePosition(object)
local body = object.body
local bodyX, bodyY = body:getPosition()
object:setPosition(bodyX, bodyY)
object:setRotation(body:getAngle() * 180 / math.pi)
end
function updatePhysicsObjects(physWorld)
physWorld:step(1/60, 8, 3) -- edit the step values if required. These are good defaults!
for i = 1, stage:getNumChildren() do
local sprite = stage:getChildAt(i)
-- determine if this is a sprite, or a group
if sprite.group == nil then
local body = sprite.body
-- if it's not a group, but HAS a body (ie, it's a physical object directly on the stage)
if body then
updatePosition(sprite)
else
end
elseif sprite.group == true then
-- if it IS a group, then iterate through the groups children
for j = 1, sprite:getNumChildren() do
local childSprite = sprite:getChildAt(j)
local body = childSprite.body
if body then
updatePosition(childSprite)
end
end
end
end
end
--------------------------- Animated Sprite Functions --------------------------------
function loadSprite(spriteName, startFrame, endFrame)
local inp = assert(io.open(spriteName..".txt"))
local data = inp:read("*all")
local lines = {}
local frames = {}
local i = 0
for word in string.gmatch(data, "(.-)\n") do
lines[i]=word
i = i + 1
end
local ii
for i = 0, #lines do
ii = 0
for word in string.gmatch(lines[i], "(.-),") do
if ii == 0 then
frames[i] = word
end
ii = ii + 1
end
end
local newSprite = Core.class(Sprite)
function newSprite:init()
local pack = TexturePack.new(spriteName..".txt", spriteName..".png")
self.anim = {}
ii = 0
for i=startFrame, endFrame do
self.anim[ii]=Bitmap.new(pack:getTextureRegion(frames[i]))
ii = ii+1
end
self.frame = 1
self:addChild(self.anim[1])
self.nframes = #self.anim
self.subframe = 0
self:addEventListener(Event.ENTER_FRAME, self.onEnterFrame, self)
end
function newSprite:onEnterFrame()
self.subframe = self.subframe + 1
if self.subframe > 1 then
self:removeChild(self.anim[self.frame])
self.frame = self.frame + 1
if self.frame > self.nframes then
self.frame = 1
end
self:addChild(self.anim[self.frame])
self.subframe = 0
end
end
local this = newSprite:new()
return this
end
--------------------------- Extra Functions --------------------------------
function tileImage(image,x,y,width,height)
local newImg = Bitmap.new(Texture.new(image))
local imgWid = newImg:getWidth()
local imgHei = newImg:getHeight()
local imagesAcross = math.ceil(width/imgWid)
local imagesDown = math.ceil(height/imgHei)
local img = {}
print(imagesAcross, imagesDown)
for i = 0, imagesDown-1 do
local yLoc = y+(i*imgHei)
for ii = 0, imagesAcross-1 do
local xLoc = x+(ii*imgWid)
img[ii+((i+1)*ii)] = display.newImage(image,"",xLoc,yLoc)
end
end
return img
end
--[[ ########## Extended Print ########## ]--
It's pointless to print out a table - instead you want the key/value
pairing of the table. This extended print does just that, as well as
ading a blank line between prints for easier reading. Lastly, this will
only print on the simulator. You shouldn't leave your prints in your final
app anyway, but if you do this should help improve performance.
]]
cache = {}
cache.print = print
print = function( ... )
local a = ...
if type(a) == "table" then
cache.print("\n Object is a Table \n Showing Data:\n")
for k,v in pairs(a) do cache.print("\tKey: "..tostring(k), "Value: ", tostring(v)) end
elseif #{...} > 1 then cache.print("\nOutput mutiple: ", ...)
elseif a == "fonts" then printFonts()
else cache.print("\nOutput "..type(a).." :: ", a or "") end
end
--[[ ########## Saving and Loading ########## ]--
This bit has been mostly barrowed from the Ansca documentation,
we simply made it easier to use.
You keep one table of information, with as many properties
as you like. Simply pass this table into to Save() and it
will be taken care of. To load it, just call Load() which
returns the table.
:: SAVING EXAMPLE ::
local myData = {}
myData.bestScore = 500
myData.volume = .8
Save(myData)
:: LOADING EXAMPLE ::
local myData = Load()
print(myData.bestScore) <== 500
print(myData.volume) <== .8
]]
local tonum = tonumber
local split = function(str, pat)
local t = {}
local fpat = "(.-)" .. (pat or " ")
local last_end = 1
local s, e, cap = str:find(fpat, 1)
while s do
if s ~= 1 or cap ~= "" then table.insert(t,cap) end
last_end = e+1
s, e, cap = str:find(fpat, last_end)
end
if last_end <= #str then
cap = str:sub(last_end)
table.insert(t,cap)
end
return t
end
string.split = split
Save = function(table, fileName)
if filename ~= nil then
filename = "|D|"..fileName
end
local filePath = fileName or "|D|data.txt"
local file = io.open( filePath, "w" )
for k,v in pairs( table or Data ) do
if type(v) == "table" then
for k2,v2 in pairs( v ) do
file:write( k .. ":" .. k2 .. "=" .. tostring(v2) .. "~" )
end
else
file:write( k .. "=" .. tostring(v) .. "~" )
end
end
io.close( file )
end
Load = function(fileName)
if filename ~= nil then
filename = "|D|"..fileName
end
local filePath = fileName or "|D|data.txt"
local file = io.open( filePath, "r" )
if file then
local dataStr = file:read( "*a" )
local datavars = split(dataStr, "~")
local dataTableNew = {}
for k,v in pairs(datavars) do
if string.find(tostring(v),":") then
local table = split(v, ":")
local pair = split(table[2], "=")
if pair[2] == "true" then pair[2] = true
elseif pair[2] == "false" then pair[2] = false
elseif tonum(pair[2]) then pair[2] = tonum(pair[2]) end
if not dataTableNew[tonum(table[1]) or table[1]] then dataTableNew[tonum(table[1]) or table[1]] = {} end
dataTableNew[tonum(table[1]) or table[1]][tonum(pair[1]) or pair[1]] = pair[2]
else
local pair = split(v, "=")
if pair[2] == "true" then pair[2] = true
elseif pair[2] == "false" then pair[2] = false
elseif tonum(pair[2]) then pair[2] = tonum(pair[2]) end
dataTableNew[tonum(pair[1]) or pair[1]] = pair[2]
end
end
io.close( file ) -- important!
if not fileName then
for k,v in pairs(dataTableNew) do Data[k] = v; setVar{k,v,true} end
end
return dataTableNew
else
print("No data to load yet.")
return false
end
end
Defaults = function(d)
for k,v in pairs(d) do
Data[k] = v
setVar{k,v,true}
end
end
Data = {}
--[[ ########## Global Information Handling ########## ]--
Some of you may choose not to use this set of functions because global
information is generally a bad idea. What I use this for is tracking data
across the entire app, that may need to be changes in any one of a myriad
different files. For me the trade off is worth it. In main.lua I register
whatever variables I will need to track, and many of those I retrieve on
applicationExit to save them for use on next launch. Other than saving data,
it's very helpful to use these to keep track of a score, or a volume leve,
whether or not to play SFX, etc.
This set of functions is left accessible via crawlspaceLib.registerVariable
because if you find yourself using them often you will want them localized.
As a side note, Crawl Space Library automatically registers a variable for
"volume" and "sfx", as these are going to be used in most projects.
:: USAGE ::
registerVar{ variableName, initialValue }
registerBulk({ name1, name2, name3, name4}, initialValue)
getVar(variableName)
setVar{variableName, value [, true]}
:: EXAMPLE 1 ::
registerVar{"sfx", true}
setVar{"sfx", false}
print(getVar("sfx")) <== prints false
:: EXAMPLE 2 ::
registerVar{"score", 0}
setVar{"score", 1}
setVar{"score", 2} -- Because "score" is a number, these add rather then set
print(getVar("score")) <== prints 3
setVar{"score", 0, true} -- Setting the last argument to true makes a number set rather than add
print(getVar("score")) <== prints 0
]]
registeredVariables = {}
registerVariable = function(...)
local var, var2 = ...; var = var2 or var
if var[2] == "true" then var[2] = true elseif var[2] == "false" then var[2] = false end
registeredVariables[var[1]] = var[2]
end
registerVar = registerVariable
registerBulk = function(...)
local var, var2 = ...; var = var2 or var
for i,v in ipairs(var[1]) do registerVariable{var[1][i], var[2]} end
end
registerBulk = registerBulk
retrieveVariable = function(...)
local name, name2 = ...; name = name2 or name
local var = registeredVariables[name]
if tonum(var) then var = tonum(var) end
return var
end
getVar = retrieveVariable
setVariable = function(...)
local new, new2 = ...; new = new2 or new
if type(new[2]) == "number" then
if not registeredVariables[new[1]] then
registeredVariables[new[1]] = new[2]
else
registeredVariables[new[1]] = registeredVariables[new[1]] + new[2]
if new[3] then registeredVariables[new[1]] = new[2] end
if Data[new[1]] then Data[new[1]] = registeredVariables[new[1]] end
end
else
if new[2] == "true" then new[2] = true elseif new[2] == "false" then new[2] = false end
registeredVariables[new[1]] = new[2]
if Data[new[1]] ~= nil then Data[new[1]] = registeredVariables[new[1]] end
end
end
setVar = setVariable