forked from eldstal/cardcinogen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcard.py
93 lines (71 loc) · 2.5 KB
/
card.py
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
#!/bin/env python3
import unittest
import os
import sys
import util
from PIL import Image
from layout import SimpleLayout, ComplexLayout
class CardTemplate:
""" Parsed version of a JSON card template """
def __init__(self, json, rootdir="."):
self.front_name = util.get_default(json, "front-image", "front.png")
self.hidden_name = util.get_default(json, "hidden-image", "hidden.png")
self.layouts = []
for j in util.get_default(json, "layouts", []):
self.type = util.get_default(j, "type", "simple")
if (self.type == "complex"):
self.layouts.append(ComplexLayout(j, rootdir))
else:
self.layouts.append(SimpleLayout(j, rootdir))
front_path = os.path.join(rootdir, self.front_name)
hidden_path = os.path.join(rootdir, self.hidden_name)
# Make sure we have valid images and they all have matching sizes
self.front = util.default_image(front_path, (372, 520))
self.hidden = util.default_image(hidden_path, self.front.size, self.front.size)
def make_card(self, textgen):
""" Generate a single card """
if (len(self.layouts) == 0):
sys.stderr.write("Warning: No layouts specified.")
return None
face = self.front.copy()
for l in self.layouts:
overlay = l.render(face.size, textgen)
if (overlay is None):
# This layout is done generating cards.
# This happens when, eventually, textgen runs out of card texts for a given layout.
continue
# We have a card! Return it and that's that.
face.paste(overlay, mask=overlay)
return face
# None of the layouts can generate any cards. We're done.
return None
#
# Unit tests
#
class TestCardStuff(unittest.TestCase):
def test_default(self):
tmpl_default = CardTemplate({})
self.assertEqual(tmpl_default.front_name, "front.png")
self.assertEqual(tmpl_default.hidden_name, "hidden.png")
self.assertEqual(tmpl_default.labels, [])
# Override all settings
dic = {
"front-image": "card-front.jpeg",
"hidden-image": "card-hidden.jpeg",
"layout": [
{
"x": 10
},
{
"y": 20
}
]
}
tmpl = CardTemplate(dic)
self.assertEqual(tmpl.front_name, dic["front-image"])
self.assertEqual(tmpl.hidden_name, dic["hidden-image"])
self.assertEqual(len(tmpl.labels), 2)
self.assertEqual(tmpl.labels[0].x, dic["layout"][0]["x"])
self.assertEqual(tmpl.labels[1].y, dic["layout"][1]["y"])
if __name__ == '__main__':
unittest.main()