-
Notifications
You must be signed in to change notification settings - Fork 11
/
wordsearch.py
187 lines (159 loc) · 5.09 KB
/
wordsearch.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
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
#!/usr/bin/env python
import random
# Directions are:
# +. left to right
# -. right to left
# .+ top to bottom
# .- bottom to top
def read_words(filename):
words = set()
fd = open(filename)
try:
for line in fd.readlines():
if "'" in line:
continue
line = line.strip().lower()
if len(line) > 3 and len(line) < 7:
words.add(line)
finally:
fd.close()
return words
all_words = read_words('/usr/share/dict/words')
explicit_words = ('fuck', 'cunt', 'piss', 'bloody', 'shit', 'boob')
for word in explicit_words:
all_words.add(word)
all_directions = ('+-', '+.', '++', '.+', '.-', '--', '-.', '-+')
styles = {
'easy': ('10x10', ('+.', '.+')),
'standard': ('15x15', ('+-', '+.', '++', '.+', '.-', '-.')),
'hard': ('20x20', all_directions),
}
dirconv = {
'-': -1,
'.': 0,
'+': 1,
}
letters = "abcdefghijklmnopqrstuvwxyz"
class Grid(object):
def __init__(self, wid, hgt):
self.wid = wid
self.hgt = hgt
self.data = ['.'] * (wid * hgt)
self.used = [' '] * (wid * hgt)
self.words = []
def to_text(self):
result = []
for row in xrange(self.hgt):
result.append(''.join(self.data[row * self.wid :
(row + 1) * self.wid]))
return '\n'.join(result)
def used_to_text(self):
result = []
for row in xrange(self.hgt):
result.append(''.join(self.used[row * self.wid :
(row + 1) * self.wid]))
return '\n'.join(result)
def to_pdf(self, filename):
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter, A4
pagesize = A4
paper = canvas.Canvas(filename, pagesize=pagesize)
margin = 50
printwid, printhgt = map(lambda x: x - margin * 2, pagesize)
gx = margin
gy = printhgt - margin
gdx = printwid / self.wid
gdy = printhgt / self.hgt
for y in xrange(self.hgt):
cy = gy - y * gdy
for x in xrange(self.wid):
cx = gx + x * gdx
p = x + self.wid * y
c = self.data[p]
paper.drawString(cx, cy, c)
paper.showPage()
paper.save()
def pick_word_pos(self, wordlen, directions):
xd, yd = random.choice(directions)
minx = (wordlen - 1, 0, 0)[xd + 1]
maxx = (self.wid - 1, self.wid - 1, self.wid - wordlen)[xd + 1]
miny = (wordlen - 1, 0, 0)[yd + 1]
maxy = (self.hgt - 1, self.hgt - 1, self.hgt - wordlen)[yd + 1]
x = random.randint(minx, maxx)
y = random.randint(miny, maxy)
return x, y, xd, yd
def write_word(self, word, ox, oy, xd, yd):
x, y = ox, oy
for c in word:
p = x + self.wid * y
e = self.data[p]
if e != '.' and e != c:
return False
x += xd
y += yd
x, y = ox, oy
for c in word:
p = x + self.wid * y
self.data[p] = c
self.used[p] = '.'
x += xd
y += yd
return True
def place_words(self, words, directions, tries=100):
# Sort words into descending order of length
words = list(words)
words.sort(key = lambda x: len(x), reverse = True)
for word in words:
wordlen = len(word)
while True:
x, y, xd, yd = self.pick_word_pos(wordlen, directions)
if self.write_word(word, x, y, xd, yd):
self.words.append((word, x, y, xd, yd))
break
tries -= 1
if tries <= 0:
return False
return True
def fill_in_letters(self):
for p in xrange(self.wid * self.hgt):
if self.data[p] == '.':
self.data[p] = random.choice(letters)
def remove_bad_words(self):
return True
def make_grid(stylep="standard", words=[], tries=100):
# Parse and validate the style parameter.
size, directions = styles.get(stylep, (stylep, all_directions))
size = size.split('x')
if len(size) != 2:
raise ValueError("Invalid style parameter: %s" % stylep)
try:
wid, hgt = map(int, size)
except ValueError:
raise ValueError("Invalid style parameter: %s" % stylep)
directions = [(dirconv[direction[0]], dirconv[direction[1]])
for direction in directions]
while True:
while True:
grid = Grid(wid, hgt)
if grid.place_words(words, directions):
break
tries -= 1
if tries <= 0:
return None
grid.fill_in_letters()
if grid.remove_bad_words():
return grid
tries -= 1
if tries <= 0:
return None
if __name__ == '__main__':
import sys
random.seed()
grid = make_grid(sys.argv[1], sys.argv[2:])
if grid is None:
print "Can't make a grid"
else:
print grid.to_text()
print
print grid.used_to_text()
grid.to_pdf("ws.pdf")