~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
#!/usr/bin/env python

# Copyright 2011-2012 Facundo Batista
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# For further info, check  https://launchpad.net/enjuewemela

"""Replay a game from a log."""

import operator
import re
import time

from cocos import scene, layer, actions
from pyglet.window import key as keyboard

import games

from gems import gems


RE_ADD = ("(\d+-\d+-\d+ \d+:\d+:\d+),(\d+)  PieceHolder        "
          "DEBUG    set piece: ([\w-]+) in \((\d+), (\d+)\)\n")
RE_DEL = ("(\d+-\d+-\d+ \d+:\d+:\d+),(\d+)  PieceHolder        "
          "DEBUG    remove piece from \((\d+), (\d+)\): ([\w-]+)\n")
RE_SWITCH = ("(\d+-\d+-\d+ \d+:\d+:\d+),(\d+)  PieceHolder        DEBUG    "
             "switch piece from \((\d+), (\d+)\) to \((\d+), (\d+)\)\n")
RE_START = ("(\d+-\d+-\d+ \d+:\d+:\d+),(\d+)  PieceManager       INFO     "
            "Game start\n")

FH_FORMAT = "%Y-%m-%d %H:%M:%S"


class Operation(object):
    def __init__(self, **kwargs):
        keys = 'name tstamp piece x y xf yf xt yt'.split()
        self.__dict__.update(dict.fromkeys(keys))
        self.__dict__.update(kwargs)

    def __str__(self):
        data = ", ".join("%s=%s" % x for x in sorted(self.__dict__.items()))
        return "<Operation: %s>" % (data,)


def _file_parser(logfilename):
    """Parse log and yield data."""
    loginfo = []
    for line in open(logfilename):
        m = re.match(RE_START, line)
        if m:
            # game start, reset all and start again
            loginfo = []
            continue

        m = re.match(RE_ADD, line)
        if m:
            fh, ms, piece, x, y = m.groups()
            tstamp = time.mktime(time.strptime(fh, FH_FORMAT))
            tstamp += int(ms) / 1000.0
            x, y = int(x), int(y)
            o = Operation(name='add', tstamp=tstamp, piece=piece, x=x, y=y)
            loginfo.append(o)
            continue

        m = re.match(RE_DEL, line)
        if m:
            fh, ms, x, y, piece = m.groups()
            tstamp = time.mktime(time.strptime(fh, FH_FORMAT))
            tstamp += int(ms) / 1000.0
            x, y = int(x), int(y)
            o = Operation(name='del', tstamp=tstamp, piece=piece, x=x, y=y)
            loginfo.append(o)
            continue

        m = re.match(RE_SWITCH, line)
        if m:
            fh, ms, xf, yf, xt, yt = m.groups()
            tstamp = time.mktime(time.strptime(fh, FH_FORMAT))
            tstamp += int(ms) / 1000.0
            xf, yf, xt, yt = int(xf), int(yf), int(xt), int(yt)
            o = Operation(name='switch', tstamp=tstamp,
                          xf=xf, yf=yf, xt=xt, yt=yt)
            loginfo.append(o)
            continue
    return loginfo


class LogInfo(object):
    """Handles the log info."""
    def __init__(self, logfilename):
        self.loginfo = _file_parser(logfilename)
        self._pointer = None

    def next(self):
        """Return next log info."""
        if self._pointer is None:
            self._pointer = 0
        else:
            self._pointer += 1
        if self._pointer >= len(self.loginfo):
            return None
        return self.loginfo[self._pointer]

    def rewind(self):
        """Go back in one."""
        if self._pointer > 0:
            self._pointer -= 1


class Replayer(layer.Layer):
    """The replayer."""

    is_event_handler = True

    def __init__(self, board, loginfo):
        self.board = board
        self.loginfo = loginfo
        self.placed = {}
        self.pending_falls = []
        self.history = []
        self.histptr = None
        super(Replayer, self).__init__()

    def _fall(self, to_fill):
        """Make a piece fall."""
        # get other pieces in the column
        to_move = []
        pos_x, pos_y = to_fill
        while True:
            pos_y += 1
            piece = self.placed.get((pos_x, pos_y))
            if piece is None:
                break
            to_move.append(piece)

        # we have the list of pieces to move, from down up, let's move them
        pos_x, pos_y = to_fill
        for piece in to_move:
            gem = self.placed.pop((pos_x, pos_y + 1))
            new_coords = self.board.get_slot_center(pos_x, pos_y)
            gem.position = new_coords
            self.placed[(pos_x, pos_y)] = gem
            pos_y += 1

    def _rush(self):
        """Show changes that happened almost at the same time."""
        if self.pending_falls:
            to_fill = self.pending_falls.pop()
            self._fall(to_fill)
            return

        prvtstamp = None
        while True:
            op = self.loginfo.next()
            if op is None:
                # FIXME: decir que TERMINO en la pantalla
                print "Hit END"
                break
            if prvtstamp is None:
                prvtstamp = op.tstamp
            if op.tstamp - prvtstamp > .2:
                self.loginfo.rewind()
                break

            # FIXME: mostrar nro de linea del log en la pantalla
            if op.name == 'add':
                real_coords = self.board.get_slot_center(op.x, op.y)
                gem = gems.by_name(op.piece)
                gem.position = real_coords
                self.board.add(gem)
                self.placed[(op.x, op.y)] = gem
            elif op.name == 'del':
                gem = self.placed.pop((op.x, op.y))
                gem.do(
                    actions.FadeOut(.1) + actions.FadeIn(.1) +
                    actions.FadeOut(.1) + actions.FadeIn(.1) +
                    actions.CallFunc(self.board.remove, gem)
                )
                self.pending_falls.append((op.x, op.y))
            elif op.name == 'switch':
                gemf = self.placed[(op.xf, op.yf)]
                gemt = self.placed[(op.xt, op.yt)]
                self.placed[(op.xf, op.yf)] = gemt
                self.placed[(op.xt, op.yt)] = gemf

                def _setpos(gem, position):
                    """Set the position."""
                    gem.position = position

                gemf.do(
                    actions.FadeOut(.1) + actions.FadeIn(.1) +
                    actions.FadeOut(.1) + actions.FadeIn(.1) +
                    actions.CallFunc(_setpos, gemf, gemt.position)
                )
                gemt.do(
                    actions.FadeOut(.1) + actions.FadeIn(.1) +
                    actions.FadeOut(.1) + actions.FadeIn(.1) +
                    actions.CallFunc(_setpos, gemt, gemf.position)
                )
                break

            prvtstamp = op.tstamp

        # reorder pending falls to let them attack in order, and assure
        # all are valid (maybe it was re-filled with an explosive or something)
        self.pending_falls.sort(key=operator.itemgetter(1))
        self.pending_falls = [x for x in self.pending_falls
                              if x not in self.placed]

    def _copy_placed(self):
        """Copy the placed dict, but using gem name and not object."""
        d = {}
        for pos, gem in self.placed.iteritems():
            d[pos] = str(gem)
        return d

    def start(self):
        """Go."""
        self.histptr = 0
        self._rush()
        new_placed = self._copy_placed()
        self.history.append(new_placed)

    def _go_forward(self):
        """Move forward."""
        self.histptr += 1
        if self.histptr == len(self.history):
            self._rush()
            new_placed = self._copy_placed()
            self.history.append(new_placed)
        else:
            self._reshow(self.history[self.histptr])

    def _go_back(self):
        """Move back."""
        if self.histptr is None or self.histptr == 0:
            # FIXME: mostrar esto en pantalla
            print "Hit BEGIN"
            return
        self.histptr -= 1
        self._reshow(self.history[self.histptr])

    def _reshow(self, new_image):
        """Clean and show a scenario from scratch."""
        for gem in self.placed.itervalues():
            self.board.remove(gem)
        self.placed = {}
        for (x, y), gem_name in new_image.items():
            real_coords = self.board.get_slot_center(x, y)
            gem = gems.by_name(gem_name)
            gem.position = real_coords
            self.board.add(gem)
            self.placed[(x, y)] = gem

    def on_key_press(self, key, modifiers):
        """Receive a key press event."""
        if key in (keyboard.SPACE, keyboard.RIGHT, keyboard.DOWN):
            self._go_forward()
        elif key in (keyboard.LEFT, keyboard.UP):
            self._go_back()


def go(logfilename):
    """Main entry point."""
    loginfo = LogInfo(logfilename)

    sc = scene.Scene()
    board = games.Board()
    sc.add(board, z=0)

    r = Replayer(board, loginfo)
    sc.add(r, z=0)
    r.start()

    return sc