×

Langue

Fermer
Atelier 801
  • Forums
  • Dev Tracker
  • Connexion
    • English Français
      Português do Brasil Español
      Türkçe Polski
      Magyar Română
      العربية Skandinavisk
      Nederlands Deutsch
      Bahasa Indonesia Русский
      中文 Filipino
      Lietuvių kalba 日本語
      Suomi עברית
      Italiano Česky
      Hrvatski Slovensky
      Български Latviešu
      Estonian
  • Langue
  • Forums
  • /
  • Transformice
  • /
  • Modules
  • /
  • [Script] txshop
[Script] txshop
Hydroper
« Citoyen »
1488325920000
    • Hydroper#0528
    • Profil
    • Derniers messages
    • Tribu
#1
  0
txshop

Essa é uma árvore de elementos para construir UIs.

P.S.: essa biblioteca é genérica. Qualquer UI que é possível com addImage() e textareas pode ser construída e manipulada com TxShop.

Como funciona?

txshop suporta 2 tipos de elementos.


    ✦ txshop.Image, txshop.TextArea


Recursos e exemplos


    ✦ Textarea básica

    Code Lua

    1
    2
    3
    txshop.TextArea(400, 200, 130, 70, {
    html = '<p align="center">Olá</p>'
    })

    (Textareas são posicionadas pelo ponto do centro.)

    Essa textarea não será imediatamente exibida; é necessário atualizá-la à cada mudança que é feita também.

    Para isso existe o método update():

    Code Lua

    1
    suaTextArea:update()

    e também existe o método updateHTML() para atualizar apenas os HTMLs relacionados à textarea, que é mais rápido.

    Code Lua

    1
    suaTextArea:updateHTML()

    http://img.atelier801.com/8824f074.png

    ✦ Definindo o jogador da textarea e clonando

    O exemplo acima exibe uma textarea simples para todos jogadores na sala porque o campo textArea.target está indefinido.

    Caso você não queira que um elemento não se relacione à múltiplos jogadores ao mesmo tempo, basta cloná-lo, e quando for trabalhar com o mesmo elemento em um jogador, faça ações no seu respectivo clone.

    Code Lua

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    local clone

    -- Maneira #1

    clone = textArea:build 'Jogador'

    -- Maneira #2

    clone = textArea:clone()
    clone.target = 'Jogador'

    -- (As duas maneiras são equivalentes.)

    -- Propriedade especial:

    print(clone.origin) -- o elemento que foi clonado

    -- ### Para achar um elemento filho (mostrado logo abaixo) clonado:

    print( textArea:findCloneOf(origin) )

    ✦ Filhos de textareas

    Textareas podem ter elementos filhos. Os elementos filhos são apenas afetados quando o parente é atualizado.

    Os elementos filhos são atualizados por ordem de adição. Ou seja, o último elemento adicionado como filho vai aparecer na frente de todos, dependendendo do campo filho.z.

    Code Lua

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    local parente =
    txshop.TextArea(400, 200, 130, 70)

    local filhoAzul =
    txshop.TextArea(400, 180, 40, 40, {
    background = 0xbb
    })

    local filhoVermelho =
    filhoAzul:clone()

    filhoVermelho.background = 0xbb0000

    -- faz `filhoAzul` ser atualizado por último
    -- (ou seja, aparece na frente de `filhoVermelho`)

    filhoVermelho.z = 1
    -- ou `filhoAzul.z = 2`

    parente:addChild(filhoAzul, filhoVermelho):update()
    http://img.atelier801.com/1ca4f074.png

    ✦ Borda de diferente tamanho e cores

    Code Lua

    1
    2
    3
    4
    txshop.TextArea(400, 200, 130, 70, {
    html = '<p align="center">Olá</p>'
    , border = { 4, 255, 0xffff00 }
    }):update()

    Pixel-à-pixel (podia ser melhor, mas esse foi o máximo que consegui):

    http://img.atelier801.com/0824f074.png

    ✦ Propriedades comuns de textarea

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    string        textArea.html
    number textArea.x
    number textArea.y
    number textArea.width
    number textArea.height
    number textArea.alpha
    number textArea.background
    number|table textArea.border
    boolean textArea.display (padrão = true)
    boolean textArea.fixed (padrão = true)

    ✦ Final: boolean elemento.inherit (padrão = true)

    Indica se a imagem/textarea herda as propriedades parente.alpha e parente.fixed.

    ✦ Removendo elemento

    Code Lua

    1
    2
    3
    4
    5
    6
    elemento:remove():update()

    -- ### Removendo filho?

    filho:remove():update()
    parente:removeChild(filho)

    ✦ Pegando o elemento parente do topo

    Code Lua

    1
    print( textArea:top() )


Código da biblioteca

    ✦ Código fonte: github.com/... (archive.org)


Algumas notas

    ✦ As textareas são exibidas no tamanho "exato" em pixels, arredondada pelos cantos por conta do próprio Transformice.
    ✦ Os callbacks não são facilitados, mas ainda é fácil de manuseá-los.

    Por exemplo...
    Code 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
    local janelas = {}

    local bemVindo = txshop.TextArea(400, 200, 200, 100, {
    html = 'Bem-vindo!'
    })

    local fechar = txshop.TextArea(480, 170, 23, 23, {
    html = '<a href="event:fechar"><p align="center">x'
    })

    bemVindo:addChild(fechar)

    -- Eventos

    function eventNewPlayer(jogador)
    janelas[jogador] = bemVindo:build(jogador):update()
    end

    function eventTextAreaCallback(id, jogador, link)
    if link == 'fechar' then
    janelas[jogador]:remove():update()

    -- Permite o elemento ser coletado pelo gc
    -- quando possível \/

    janelas[jogador] = nil
    end
    end

    function eventPlayerLeft(jogador)
    janelas[jogador] = nil
    end

    table.foreach(tfm.get.room.playerList, eventNewPlayer)

    ✦ As imagens não foram testadas ainda

Dernière modification le 1678104840000
Impressorahp
« Citoyen »
1488326040000
    • Impressorahp#2775
    • Profil
    • Derniers messages
    • Tribu
#2
  0
dificil de entender
Brenower
« Censeur »
1488328980000
    • Brenower#0000
    • Profil
    • Derniers messages
    • Tribu
#3
  0
o que isso faz mesmo?
qual utilidade?
Hydroper
« Citoyen »
1488329220000
    • Hydroper#0528
    • Profil
    • Derniers messages
    • Tribu
#4
  0
Brenower a dit :
o que isso faz mesmo?
qual utilidade?

A utilidade é descrita no tópico
Impressorahp
« Citoyen »
1488329280000
    • Impressorahp#2775
    • Profil
    • Derniers messages
    • Tribu
#5
  0
Profiver a dit :
Brenower a dit :
o que isso faz mesmo?
qual utilidade?

A utilidade é descrita no tópico

onde:/?
Hydroper
« Citoyen »
1488329460000
    • Hydroper#0528
    • Profil
    • Derniers messages
    • Tribu
#6
  0
Novohp a dit :
Profiver a dit :
Brenower a dit :
o que isso faz mesmo?
qual utilidade?

A utilidade é descrita no tópico

onde:/?

a dit :
A utilidade é como foi descrito acima: com essa biblioteca fica mais fácil de entender o que está sendo feito, porque utiliza tabelas para representar imagens e textareas.
Hydroper
« Citoyen »
1488329460000
    • Hydroper#0528
    • Profil
    • Derniers messages
    • Tribu
#7
  0
Aprendam à ler o tópico?
Brenower
« Censeur »
1488329760000
    • Brenower#0000
    • Profil
    • Derniers messages
    • Tribu
#8
  0
Aparentemente eu vou fazer o mesmo código para adicionar textArea
Thanos
« Citoyen »
1488330840000
    • Thanos#1306
    • Profil
    • Derniers messages
    • Tribu
#9
  0
Dsclp mas é quase impossível entender o que vc tenta dizer.
Hydroper
« Citoyen »
1488363900000
    • Hydroper#0528
    • Profil
    • Derniers messages
    • Tribu
#10
  0
Lynezx a dit :
Dsclp mas é quase impossível entender o que vc tenta dizer.

Atualizei um pouco, melhorou?
Lcemt
« Citoyen »
1488375300000
    • Lcemt#0000
    • Profil
    • Derniers messages
    • Tribu
#11
  0
não entendi
Hydroper
« Citoyen »
1488381960000
    • Hydroper#0528
    • Profil
    • Derniers messages
    • Tribu
#12
  0
Lcemt a dit :
não entendi

O que não entendeu -_-?
Hydroper
« Citoyen »
1489185600000
    • Hydroper#0528
    • Profil
    • Derniers messages
    • Tribu
#13
  0
Esboço de uma nova versão:

Aqui
Code 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
do

local environment = (_ENV or _G)

local next = environment.next
local type = environment.type
local error = environment.error
local ipairs = environment.ipairs
local tonumber = environment.tonumber
local tostring = environment.tostring
local getmetatable = environment.getmetatable
local setmetatable = environment.setmetatable

local insert = table.insert
local remove = table.remove

local addImage = tfm.exec.addImage
local removeImage = tfm.exec.removeImage

local addTextArea = ui.addTextArea
local removeTextArea = ui.removeTextArea
local updateTextArea = ui.updateTextArea

-- Helpers -----------

-- Helpers could assume everything as
-- correct in general.

local function extendfields(target, ...)
for i, copy in ipairs { ... } do
if type(copy) == 'table' then
for k, v in next, copy do
target[k] = v
end
end
end
return target
end

local function findindexof(value, t)
for i, value2 in ipairs(t) do
if value == value2 then
return i
end
end
end

-- ### Classing

local function createclass()
return setmetatable({ IMeta = {} }, {})
end

local function createinstanceof(class)
return setmetatable({}, class.IMeta)
end

local function getparentclassof(class)
return getmetatable(class).__index
end

local function instanceof(class, value)
value = getmetatable(value)
class = class.IMeta
while type(value) == 'table' do
if value == class then
return true
end
value = getmetatable(value.__index)
end
return false
end

local function setconstructorof(class, fn)
getmetatable(class).__call = fn
end

local function setparentclassof(class, parentClass)
getmetatable(class).__index = parentClass
local prototype = class.IMeta.__index
if prototype then
setmetatable(prototype, parentClass.IMeta)
end
end

local function setprototypeof(class, prototype)
class.IMeta.__index = prototype
local parentClass = getparentclassof(class)
if parentClass then
setmetatable(prototype, parentClass.IMeta)
end
end

local function super(class, ...)
return setmetatable(getparentclassof(class)(...), class.IMeta)
end

-- Main (display and utils) -----------

-- The element classes are defined below, so
-- both utilities and elements can access bo-
-- th of them.

-- A child element MUST NOT be equal to any
-- of its parent elements.

local Element, Area, Image

local function forEachParent(target, fn, asc)
if asc then
local plist = {}
local pos = 0

repeat
target = target.parent
pos = pos + 1
plist[pos] = target
until not instanceof(Element, target)

for i = pos, 1, -1 do
if fn(plist[i]) == false then
return
end
end
else
while true do
target = target.parent
if not instanceof(Element, target) or (fn(target) == false) then
return
end
end
end
end

-- Make sure an element isn't the same as
-- any of its parents, otherwise throw an ex-
-- ception.

local nonParentTestTarget

local function nonParentTest(parent)
if nonParentTestTarget == parent then
error 'detected parent element at infinite cycle'
end
end

local function assertNonParentElement(target)
nonParentTestTarget = target
forEachParent(target, nonParentTest)
nonParentTestTarget = nil
end

-- Clone an element and their children, then
-- return the result.

local function clone(target)
local cloned = extendfields({}, target)
local children = cloned.children

if type(children) == 'table' then
local pos = 1
local newChildren = {}

for _, child in ipairs(children) do

-- Ignore non-elements.

if instanceof(Element, target) then
assertNonParentElement(target)
newChildren[pos] = clone(child)
pos = pos + 1
end
end

cloned.children = newChildren
end

cloned.orig = target

return cloned
end

-- Get the root parent of an element.

local function getRoot(target)
while true do
local parent = target.parent
if instanceof(Element, parent) then
target = parent
else
break
end
end
return target
end

-- Main displayer.

local targetPlayer

local imageCounter

local textAreaNumber = 0

local upAlpha, upBackgroundColor, upDisplay, upFixedPos

local function update(target)
local targetPlayerInit = not targetPlayer

if targetPlayerInit then
targetPlayer = target.target
end

-- Garbages to be removed.

local removals = target._rems

if type(removals) == 'table' then
for id in next, removals do
removeTextArea(id)
end
target._rems = nil
end

local display = target.display
display = (display == nil) and
upDisplay -- undefined, use upper value.
or display

-- Decide whose kind the element is and
-- display it, if allowed.

if instanceof(Area, target) then
if display == false then
removeTextArea(Area._id, targetPlayer)
local borders = Area._bords
if type(borders) == 'table' then
for i = 1, 4 do
removeTextArea(borders[i], targetPlayer)
end
Area._bords = nil
end
else
local id = target._id

if type(id) ~= 'number' then
id = textAreaNumber
target._id = id
textAreaNumber = textAreaNumber + 1
end

-- Pixel bounds.

local px = tonumber(target.x) or 0
local py = tonumber(target.y) or 0
local pw = tonumber(target.width) or 0
local ph = tonumber(target.height) or 0

pw = (pw < 11) and 11 or pw
ph = (ph < 11) and 11 or ph

-- Area gets positioned from center.

px = px - (pw / 2)
py = py - (ph / 2)

local alpha = target.alpha
alpha = ((alpha == nil) and
upAlpha or alpha) or 1

local fixedPos = target.fixedPos
fixedPos = ((fixedPos == nil) and
upFixedPos or fixedPos) or true

local html = (html == nil) and '' or tostring(html)

local backgroundColor = tonumber(target.backgroundColor) or 1
backgroundColor = (backgroundColor < 1) and 1 or backgroundColor

-- Compatible bounds to represent the expected
-- area.

local cx = px + 5
local cy = py + 5
local cw = pw - 10
local ch = ph - 10

local borders = target.borders

if type(borders) == 'table' then
local i = 1

local ids = target._bords

if type(ids) ~= 'table' then
ids = {
textAreaNumber, textAreaNumber + 1, textAreaNumber + 2, textAreaNumber + 3
}
textAreaNumber = textAreaNumber + 4
target._bords = ids
end

-- Borders are structured as below:

-- { Border 1, ... }

-- (Where Border N :
-- unpack { borderSize, leftTopColor, rightBottomColor }
-- .)

-- The first border is the innermost one.

-- (Note: border text areas don't need to be positioned
-- from center here.)

local lx = cx
local ly = cy
local lw = cw
local lh = ch

while true do
local borderSize = borders[i]

if not borderSize then
break
end

i = i + 1

local leftTopColor = borders[i]
local rightBottomColor

if leftTopColor then
i = i + 1

local rightBottomColor = borders[i]

if rightBottomColor then
i = i + 1
end
end

borderSize = tonumber(borderSize) or 0

if borderSize > 0 then

leftTopColor = tonumber(leftTopColor) or 1
leftTopColor = (leftTopColor < 1) and 1 or leftTopColor
rightBottomColor = tonumber(rightBottomColor) or 1
rightBottomColor = (rightBottomColor < 1) and 1 or rightBottomColor

-- Avoid creating new tables for each border.

local mlen = (borderSize + borderSize)

for i = 4, 1, -1 do

-- Bellow `is1` local will mean whether
-- the side is left or right on horizontal context,
-- or, top or bottom on vertical context.

-- I know this won't be significant to performance,
-- but anyways.

local is1 = (i == 1)

local bx, by, bw, bh

if is1 or i == 3 then
bw = borderSize
bh = (lh + mlen)
bx = is1 and
--[=[ Left ]=]
(lx - (bw + 10)) or
--[=[ Right ]=]
(lx + (lw - 10))
by = (ly - borderSize)
else
is1 = (i == 2)
bw = (lw + mlen)
bh = borderSize
bx = (lx - borderSize)
by = is1 and
--[=[ Top ]=]
(ly - (bh + 10)) or
--[=[ Bottom ]=]
(ly + (lh - 10))
end

local id = ids[i]

if not id then
ids[id] = textAreaNumber
textAreaNumber = textAreaNumber + 1
end

local color = is1 and leftTopColor or rightBottomColor

addTextArea(id, html, targetPlayer, bx, by, bw, bh,
color, color, alpha, fixedPos)
end

lx = (lx - borderSize)
ly = (ly - borderSize)

lw = (lw + borderSize)
lh = (lh + borderSize)
end
end
end

addTextArea(id, html, targetPlayer, cx, cy, cw, ch,
backgroundColor, backgroundColor, alpha, fixedPos)

upAlpha = alpha
upBackgroundColor = upBackgroundColor
upFixedPos = fixedPos
end

upDisplay = display

elseif instanceof(Image, target) then

if display == false then
removeImage(target._id)

else
local counterInit = not imageCounter

if counterInit then
imageCounter = 1
end

target._id = addImage(tostring(target.src), '&'..imageCounter,
tonumber(target.x) or 0, tonumber(target.y) or 0, targetPlayer)

if counterInit then
imageCounter = nil
else
imageCounter = imageCounter + 1
end
end
end

local children = target.children

if type(children) == 'table' then
local zlist = {}
local len = 0

for _, child in ipairs(children) do
if instanceof(Element, child) then
len = len + 1

local z = tonumber(child.z)

if z then
z = (((z < 1) and 1) or
(z > len) and len) or z
insert(zlist, z, child)
else
zlist[len] = child
end
end
end

for i = 1, len do
update(zlist[i])
end
end

if targetPlayerInit then
targetPlayer = nil
upAlpha = nil
upDisplay = nil
upFixedPos = nil
end
end

-- Displayer similiar, but only updates HTML
-- of areas.

local function updateHTML(target)
local targetPlayerInit = not targetPlayer

if targetPlayerInit then
targetPlayer = target.target
end

local id = target._id

if type(id) ~= 'number' then
error 'cannot update HTML of a possible non-displayed area'
end

local html = target.html

updateTextArea(
id, (html == nil) and '' or tostring(html),
targetPlayer
)

local children = target.children

if type(children) == 'table' then
for _, child in ipairs(children) do
if instanceof(Area, child) then
assertNonParentElement(child)
updateHTML(child)
end
end
end

if targetPlayerInit then
targetPlayer = nil
end
end

Element = createclass()

local elementPrototype = {}

-- Remove a target element from its parent if
-- possible, and try unallowing its display.

function elementPrototype:remove()
if not instanceof(Element, self) then
error 'bad argument #0 to \'remove\' (Element expected)'
end

self.display = false

local parent = self.parent

if parent then
local id = self._id

if id then
local removals = parent._rems

if type(removals) == 'table' then
removals[id] = true
else
removals = { [id] = true }
parent._rems = removals
end
end

local children = parent.children

if type(children) == 'table' then
local index = findindexof(self, children)
if index then
remove(children, index)
end
end
end
end

function elementPrototype:update()
if not instanceof(Element, self) then
error 'bad argument #0 to \'update\' (Element expected)'
end
update(self)
end

setconstructorof(Element, createinstanceof)
setprototypeof(Element, elementPrototype)

-- `Area`

Area = createclass()

setparentclassof(Area, Element)

local function areaConstructor(_, x, y, width, height)
local area = createinstanceof(Area)
area.x = tonumber(x)
area.y = tonumber(y)
area.width = tonumber(width)
area.height = tonumber(height)
return area
end

setconstructorof(Area, areaConstructor)

local areaPrototype = {}

function areaPrototype:updateHTML()
if not instanceof(Area, self) then
error 'bad argument #0 to \'updateHTML\' (Area expected)'
end
updateHTML(self)
end

setprototypeof(Area, areaPrototype)

extendfields(ui, { Area = Area, Element = Element, Image = Image })
end
Bolodefchoco
« Sénateur »
1513792140000
    • Bolodefchoco#0095
    • Profil
    • Derniers messages
    • Tribu
#14
  0
Interessante, mas é uma implementação ineficiente. De qualquer forma, continua interessante
Bloom
« Héliaste »
1535320020000
    • Bloom#6766
    • Profil
    • Derniers messages
#15
  1
Parabéns
  • Forums
  • /
  • Transformice
  • /
  • Modules
  • /
  • [Script] txshop
© Atelier801 2018

Equipe Conditions Générales d'Utilisation Politique de Confidentialité Contact

Version 1.27