~facundo/enjuewemela/trunk

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
# This code is part of the 'enjuewemela' game
# License: GPLv3
# Main author: Facundo Batista
# Code, bug tracker, etc:
#   https://launchpad.net/enjuewemela/
#
"""Menus of the game."""

import random


class FakeBoard(object):
    """Fake representation of the board."""

    def __init__(self, board):
        self.board = board
        self.height = len(board) - 1

    def get_piece(self, pos_x, pos_y):
        """Return the piece of the x, y position."""
        return self.board[self.height - pos_y][pos_x]

    def __len__(self):
        return len(self.board)

    def __str__(self):
        return "\n".join(str(x) for x in self.board)


def _cross(results):
    """Cross the results to see if they're composed."""
    lenres = len(results)
    for i in range(lenres):
        for j in range(i + 1, lenres):
            match = set(results[i]) & set(results[j])
            if match:
                return match.pop()


def _check_array(array):
    """Checks a single row or col to see if there's a match."""
    piece_which = None
    piece_counter = None
    for piece in array:
        if piece == 13:
            # magic ball
            return True
        if piece == piece_which:
            piece_counter += 1
            if piece_counter == 3:
                return True
        else:
            piece_which = piece
            piece_counter = 1
    return False


def future_guess(board):
    """Guess which piece the user could move to have a match."""
    lenboard = len(board)
    rangesize = range(lenboard)

    # horizontal
    for y in rangesize:
        row = [board.get_piece(x, y) for x in rangesize]

        for x in rangesize:
            prv = row[x]
            if y > 0:
                row[x] = board.get_piece(x, y - 1)
                if _check_array(row):
                    return x, y - 1

            if y < lenboard - 1:
                row[x] = board.get_piece(x, y + 1)
                if _check_array(row):
                    return x, y + 1
            row[x] = prv

            if x > 0:
                row[x - 1], row[x] = row[x], row[x - 1]
                if _check_array(row):
                    return x, y
                row[x], row[x - 1] = row[x - 1], row[x]

            if x < lenboard - 1:
                row[x + 1], row[x] = row[x], row[x + 1]
                if _check_array(row):
                    return x, y
                row[x], row[x + 1] = row[x + 1], row[x]

    # vertical
    for x in rangesize:
        col = [board.get_piece(x, y) for y in rangesize]

        for y in rangesize:
            if y > 0:
                col[y - 1], col[y] = col[y], col[y - 1]
                if _check_array(col):
                    return x, y
                col[y], col[y - 1] = col[y - 1], col[y]

            if y < lenboard - 1:
                col[y + 1], col[y] = col[y], col[y + 1]
                if _check_array(col):
                    return x, y
                col[y], col[y + 1] = col[y + 1], col[y]

            prv = col[y]
            if x > 0:
                col[y] = board.get_piece(x - 1, y)
                if _check_array(col):
                    return x - 1, y

            if x < lenboard - 1:
                col[y] = board.get_piece(x + 1, y)
                if _check_array(col):
                    return x + 1, y
            col[y] = prv


def detect(board):
    """Tell in which positions there're matches."""
    rangesize = range(len(board))

    all_found = {}

    # horizontal
    piece_which = None
    piece_counter = None
    found_mark = None

    for y in rangesize:
        for x in rangesize:
            this_piece = board.get_piece(x, y)
            if this_piece == piece_which:
                piece_counter += 1
                if piece_counter == 3:
                    found_mark = (x - 2, y, this_piece, "hztl")
                    all_found[found_mark] = piece_counter
                elif piece_counter > 3:
                    all_found[found_mark] = piece_counter
            else:
                piece_counter = 1
                found_mark = None
                piece_which = this_piece

        # breaking line
        piece_counter = 1
        found_mark = None
        piece_which = None

    # vertical
    piece_which = None
    piece_counter = None
    found_mark = None

    for x in rangesize:
        for y in rangesize:
            this_piece = board.get_piece(x, y)
            if this_piece == piece_which:
                piece_counter += 1
                if piece_counter == 3:
                    found_mark = (x, y - 2, this_piece, "vtcl")
                    all_found[found_mark] = piece_counter
                elif piece_counter > 3:
                    all_found[found_mark] = piece_counter
            else:
                piece_counter = 1
                found_mark = None
                piece_which = this_piece

        # breaking line
        piece_counter = 1
        found_mark = None
        piece_which = None

    # process!
    processed = []
    for (x, y, piece, piece_type), length in all_found.items():
        result = []
        if piece_type == "hztl":
            for i in range(length):
                result.append((x + i, y, piece))
        else:
            for i in range(length):
                result.append((x, y + i, piece))
        processed.append(result)

    while True:
        matching = _cross(processed)
        if not matching:
            break

        match_no = []
        match_yes = []
        for p in processed:
            if matching in p:
                match_yes.append(p)
            else:
                match_no.append(p)

        processed = match_no
        flattened = set()
        for m in match_yes:
            for x in m:
                flattened.add(x)
        processed.append(flattened)

    final = []
    for proc in processed:
        final.append(tuple((x, y) for x, y, __ in list(proc)))
    return final


def _get_sane_piece(board, pos_x, pos_y):
    """Return a piece for pos x, y different from roundings."""
    rounding = set()
    if pos_x > 0:
        rounding.add(board[pos_y][pos_x - 1])
    if pos_x < 7:
        rounding.add(board[pos_y][pos_x + 1])

    if pos_y > 0:
        rounding.add(board[pos_y - 1][pos_x])
    if pos_y < 7:
        rounding.add(board[pos_y + 1][pos_x])

    all_sane = rounding ^ set(range(7))
    return random.choice(list(all_sane))


def generate_nonmatch_board(specials=None):
    """Return a board with no match."""
    def get_board():
        """Get a board."""
        board = []
        for __ in range(8):
            lin = [random.randint(0, 6) for __ in range(8)]
            board.append(lin)
        return board

    def set_specials(board, quant_explosives, quant_magic):
        """Set some specials in the board."""
        posics = [(x, y) for x in range(8) for y in range(8)]
        random.shuffle(posics)
        for _ in range(quant_explosives):
            pos_x, pos_y = posics.pop()
            board[pos_x][pos_y] += 7
        for _ in range(quant_magic):
            pos_x, pos_y = posics.pop()
            board[pos_x][pos_y] = 99
        return board

    board = get_board()

    while True:
        fb = FakeBoard(board)
        res = detect(fb)
        if res == []:
            # excelent! no match!
            if future_guess(fb):
                # yet better, we have a chance!
                if specials is not None:
                    set_specials(board, *specials)
                return board

        if res:
            # need to alter sligthly the random one to eliminate matches
            pos_x, pos_y = res[0][0]
            pos_y = 7 - pos_y  # remember that the board is upside down
            sane = _get_sane_piece(board, pos_x, pos_y)
            board[pos_y][pos_x] = sane
        else:
            # no match, but also no chances... get a new board
            board = get_board()


def get_around(slot):
    """Return the slots all around the given one.

    Normally they're eight, unless the given slot is next to
    a wall, or in a corner.
    """
    px, py = slot
    for dx in (-1, 0, 1):
        for dy in (-1, 0, 1):
            if dx or dy:   # skip both in 0
                nx = px + dx
                ny = py + dy
                if 0 <= nx <= 7 and 0 <= ny <= 7:
                    yield nx, ny


def get_center(match, hints=None):
    """Guess the center in a match."""
    len_m = len(match)

    # the matches of three or four elements
    if len_m == 3:
        return match[1]

    if len_m == 4:
        m1, m2 = match[1], match[2]
        if hints is not None:
            for h in hints:
                if h == m1 or h == m2:
                    return h
        return m1

    # five elements and linear: just in the middle
    if len_m == 5:
        linear_x = len(set(p[0] for p in match)) == 1
        linear_y = len(set(p[1] for p in match)) == 1
        if linear_x or linear_y:
            return match[2]

    # 5, 6, or 7 elements, can't be linear
    if 5 <= len_m <= 7:
        # it's an L, need to see the point where it turns
        xxx = [z[0] for z in match]
        for z in set(xxx):
            if xxx.count(z) >= 3:
                corner_x = z
                break
        else:
            raise ValueError("We had an L without good equals in X: %s", match)

        yyy = [z[1] for z in match]
        for z in set(yyy):
            if yyy.count(z) >= 3:
                corner_y = z
                break
        else:
            raise ValueError("We had an L without good equals in Y: %s", match)

        return (corner_x, corner_y)

    raise ValueError("Had a match with incorrect length: %s", match)


def generate_custom(board):
    """Return a board with specified layout."""
    # verify that all numbers are 0-6 (normal pieces),
    # 7-12 (explosives) or 13 (magic ball)
    for lin in board:
        for piece in lin:
            if not (0 <= piece <= 13):
                raise ValueError("Custom board has bad piece number: %r"
                                 % piece)

    # verify it doesn't has a match
    fb = FakeBoard(board)
    res = detect(fb)
    if res != []:
        raise ValueError("Custom board has matches: %s" % res)

    # all ok
    return board