summaryrefslogtreecommitdiff
path: root/tictactoe.py
blob: e313a824fff9be7a8e36aa0b3942de78b9ddf7a2 (plain)
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
#!/usr/bin/env python
# coding=utf-8

"""
pyTicTacToe
Author : Guillaume "iXce" Seguin
Email  : guillaume@segu.in

 # Python Tic Tac Toe #

Copyright (C) 2007 Guillaume Seguin

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY 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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
"""

import pygtk
pygtk.require ('2.0')
import gtk
import gtk.glade

import random
import cairo
import pangocairo
from math import pi

def autoconnect (ob):
    '''Autoconnect every member from ob to its glade interface'''
    handlers = {}
    for i in dir (ob):
        handlers[i] = getattr (ob, i)
    ob.glade.signal_autoconnect (handlers);

def draw_rounded_rectangle (cr, x, y, width, height):
    radius = 30
    x0 = x + 10
    y0 = y + 10
    x1 = x + width - 10
    y1 = y + height - 10
    cr.new_path ()
    cr.arc (x0 + radius, y1 - radius, radius, pi / 2, pi)
    cr.line_to (x0, y0 + radius)
    cr.arc (x0 + radius, y0 + radius, radius, pi, 3 * pi / 2)
    cr.line_to (x1 - radius, y0)
    cr.arc (x1 - radius, y0 + radius, radius, 3 * pi / 2, 2 * pi)
    cr.line_to (x1, y1 - radius)
    cr.arc (x1 - radius, y1 - radius, radius, 0, pi / 2)
    cr.close_path ()

def prepare_text (cr, text):
    pcr = pangocairo.CairoContext (cr)
    layout = pcr.create_layout ()
    layout.set_markup (text)
    return pcr, layout

NO_WINNER   = -1
PLAYER_ID   = 1
COMPUTER_ID = 2

class gtkTicTacToe (gtk.DrawingArea):

    _parent      = None
    _surface     = None
    _map         = None
    _finished    = False

    def __init__ (self, side = 300, parent = None):
        '''Prepare widget'''
        super (gtkTicTacToe, self).__init__ ()
        self._parent = parent
        self.add_events (gtk.gdk.BUTTON_PRESS_MASK)
        self.connect ("expose_event", self.expose)
        self.connect ("button_press_event", self.button_press)
        self.set_size_request (side, side)
        self.new_game ()

    def new_game (self):
        '''Reset game'''
        self._map = [[0] * 3, [0] * 3, [0] * 3]
        self._finished = False
        if self._surface:
            self.redraw (queue = True)

    def empty_cells (self):
        '''Return the number of empty cells'''
        empty = filter (lambda x: not x, self._map[0])
        empty += filter (lambda x: not x, self._map[1])
        empty += filter (lambda x: not x, self._map[2])
        return len (empty)
        
    def check (self):
        '''Check if game is finished'''
        for i in range (3):
            xv = self._map[i][0]
            yv = self._map[0][i]
            if xv and self._map[i][1] == xv and self._map[i][2] == xv:
                return xv
            if yv and self._map[1][i] == yv and self._map[2][i] == yv:
                return yv
        diag1v = self._map[0][0]
        diag2v = self._map[0][2]
        if diag1v and self._map[1][1] == diag1v and self._map[2][2] == diag1v:
            return diag1v
        if diag2v and self._map[1][1] == diag2v and self._map[2][0] == diag2v:
            return diag2v
        if not self.empty_cells ():
            return NO_WINNER
        return False

    def computer_turn_random (self):
        '''Computer AI - yes, it's _very_ random'''
        cells = self.empty_cells ()
        cell = random.randint (1, cells)
        for j in range (3):
            for i in range (3):
                if not self._map[i][j]:
                    cell -= 1
                    if cell == 0:
                        self._map[i][j] = COMPUTER_ID
                        break
            if cell == 0:
                break

    def computer_turn_smart (self):
        '''Computer AI, much less random'''
        if not self._map[1][1]:
            self._map[1][1] = COMPUTER_ID
            return
        for i in range (3):
            xv1 = self._map[i][0]
            xv2 = self._map[i][1]
            yv1 = self._map[0][i]
            yv2 = self._map[1][i]
            if xv1 == COMPUTER_ID and xv1 == xv2 and not self._map[i][2]:
                self._map[i][2] = COMPUTER_ID
                return
            elif xv1 == COMPUTER_ID and self._map[i][2] == xv1 \
                 and not self._map[i][1]:
                self._map[i][1] = COMPUTER_ID
                return
            elif xv2 == COMPUTER_ID and self._map[i][2] == xv2 \
                 and not self._map[i][0]:
                self._map[i][0] = COMPUTER_ID
                return
            if yv1 == COMPUTER_ID and yv1 == yv2 and not self._map[2][i]:
                self._map[2][i] = COMPUTER_ID
                return
            elif yv1 == COMPUTER_ID and self._map[2][i] == yv1 \
                 and not self._map[1][i]:
                self._map[1][i] = COMPUTER_ID
                return
            elif yv2 == COMPUTER_ID and self._map[2][i] == yv2 \
                 and not self._map[0][i]:
                self._map[0][i] = COMPUTER_ID
                return
        for i in range (3):
            xv1 = self._map[i][0]
            xv2 = self._map[i][1]
            yv1 = self._map[0][i]
            yv2 = self._map[1][i]
            if xv1 == PLAYER_ID and xv1 == xv2 and not self._map[i][2]:
                self._map[i][2] = COMPUTER_ID
                return
            elif xv1 == PLAYER_ID and self._map[i][2] == xv1 \
                 and not self._map[i][1]:
                self._map[i][1] = COMPUTER_ID
                return
            elif xv2 == PLAYER_ID and self._map[i][2] == xv2 \
                 and not self._map[i][0]:
                self._map[i][0] = COMPUTER_ID
                return
            if yv1 == PLAYER_ID and yv1 == yv2 and not self._map[2][i]:
                self._map[2][i] = COMPUTER_ID
                return
            elif yv1 == PLAYER_ID and self._map[2][i] == yv1 \
                 and not self._map[1][i]:
                self._map[1][i] = COMPUTER_ID
                return
            elif yv2 == PLAYER_ID and self._map[2][i] == yv2 \
                 and not self._map[0][i]:
                self._map[0][i] = COMPUTER_ID
                return
        if not self._map[0][0]:
            self._map[0][0] = COMPUTER_ID
            return
        elif not self._map[0][2]:
            self._map[0][2] = COMPUTER_ID
            return
        elif not self._map[2][2]:
            self._map[2][2] = COMPUTER_ID
            return
        elif not self._map[2][0]:
            self._map[2][0] = COMPUTER_ID
            return
        cells = self.empty_cells ()
        cell = random.randint (1, cells)
        for j in range (3):
            for i in range (3):
                if not self._map[i][j]:
                    cell -= 1
                    if cell == 0:
                        self._map[i][j] = COMPUTER_ID
                        break
            if cell == 0:
                break

    def computer_turn (self):
        '''Computer plays!'''
        self.computer_turn_smart ()
        self.redraw (queue = True)

    def button_press (self, widget, event):
        '''Check if the cursor clicked an interesting area'''
        if self._finished:
            self.new_game ()
        alloc = self.get_allocation ()
        side = min (alloc.width, alloc.height)
        cell_side = int (float (side) / 3)
        i = (event.x - (event.x % cell_side)) / cell_side
        j = (event.y - (event.y % cell_side)) / cell_side
        i, j = int (i), int (j)
        if not self._map[i][j] and not self.check ():
            self._map[i][j] = PLAYER_ID
            self.redraw (queue = True)
            if not self.check ():
                self.computer_turn ()
        winner = self.check ()
        if winner:
            self._finished = True
            self.redraw (queue = True)
            if not self._parent:
                return
            if winner == PLAYER_ID:
                status = "You win"
            elif winner == COMPUTER_ID:
                status = "You fail"
            elif winner == NO_WINNER:
                status = "Draw!"
            self._parent.push_status (status)
            self._parent.open_message_dialog (status)

    def redraw (self, queue = False):
        '''Redraw internal surface'''
        alloc = self.get_allocation ()
        side = min (alloc.width, alloc.height)
        cell_side = int (float (side) / 3)
        self._surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, side, side)
        cr = cairo.Context (self._surface)
        # Draw background
        cr.set_source_rgb (1, 1, 1)
        cr.paint ()
        # Draw cells
        for i in range (3):
            for j in range (3):
                if not self._map[i][j]:
                    continue
                if self._map[i][j] == PLAYER_ID:
                    cr.set_source_rgb (0, 1, 0)
                else:
                    cr.set_source_rgb (1, 0, 0)
                cr.rectangle (cell_side * i, cell_side * j,
                              cell_side, cell_side)
                cr.fill ()
                cr.set_source_rgb (0, 0, 0)
                if self._map[i][j] == PLAYER_ID:
                    cr.move_to (cell_side * (i + 0.1), cell_side * (j + 0.1))
                    cr.line_to (cell_side * (i + 0.9),
                                cell_side * (j + 0.9))
                    cr.move_to (cell_side * (i + 0.9), cell_side * (j + 0.1))
                    cr.line_to (cell_side * (i + 0.1), cell_side * (j + 0.9))
                    cr.stroke ()
                else:
                    cr.arc (cell_side * (i + 0.5),
                            cell_side * (j + 0.5),
                            cell_side * 0.5 - 5,
                            0, 2 * pi)
                    cr.stroke ()
        # Draw borders
        cr.set_source_rgb (0, 0, 0)
        cr.move_to (cell_side, 0)
        cr.line_to (cell_side, side)
        cr.move_to (cell_side * 2, 0)
        cr.line_to (cell_side * 2, side)
        cr.move_to (0, cell_side)
        cr.line_to (side, cell_side)
        cr.move_to (0, cell_side * 2)
        cr.line_to (side, cell_side * 2)
        cr.stroke ()
        if self._finished:
            cr.set_source_rgba (0.8, 0.8, 0.8, 0.5)
            cr.paint ()
            cr.set_source_rgba (0.2, 0.2, 0.2, 0.6)
            draw_rounded_rectangle (cr, side * 0.1, side * 0.25,
                                    side * 0.8, side * 0.5)
            cr.fill ()
            cr.set_source_rgb (1, 1, 1)
            cr.move_to (side * 0.25, side * 0.43)
            text =  '<span font_desc="Sans 25"><b>Replay ?</b></span>'
            pcr, layout = prepare_text (cr, text)
            pcr.show_layout (layout)
        if queue:
            self.queue_draw ()

    def expose (self, widget, event):
        '''Expose event handler'''
        cr = self.window.cairo_create ()
        if not self._surface:
            self.redraw ()
        cr.set_source_surface (self._surface)
        cr.rectangle (event.area.x, event.area.y,
                      event.area.width, event.area.height)
        cr.clip ()
        cr.paint ()
        return False

class pyTicTacToe:

    glade           = None
    mainWindow	    = None
    aboutDialog	    = None
    mainFrame       = None
    statusBar       = None
    messageDialog   = None
    tictactoe       = None

    def __init__ (self):
        '''Initialize application'''
        self.glade = gtk.glade.XML (fname = "tictactoe.glade")
        self.mainWindow = self.glade.get_widget ("mainWindow")
        self.aboutDialog = self.glade.get_widget ("aboutDialog")
        self.mainFrame = self.glade.get_widget ("mainFrame")
        self.statusBar = self.glade.get_widget ("statusBar")
        self.messageDialog = self.glade.get_widget ("messageDialog")
        self.glade.get_widget ("toolBar").set_style (gtk.TOOLBAR_ICONS)
        autoconnect (self)
        self.tictactoe = gtkTicTacToe (parent = self)
        self.mainFrame.add (self.tictactoe)

    def new_game (self, *args):
        '''Starts a new game'''
        self.push_status ("")
        self.tictactoe.new_game ()

    def push_status (self, text):
        '''Update status bar message'''
        context = self.statusBar.get_context_id ("main")
        self.statusBar.pop (context)
        self.statusBar.push (context, text)

    def show (self):
        '''Show application'''
        self.mainWindow.show_all ()

    def gtk_main_quit (self, *args):
        '''Quit gtk main loop'''
        gtk.main_quit ()

    def show_about (self, *args):
        '''Show about dialog'''
        self.aboutDialog.show ()

    def close_about (self, *args):
        '''Hide about dialog'''
        self.aboutDialog.hide ()
        return True

    def open_message_dialog (self, text):
        '''Open the message dialog and set the message'''
        self.messageDialog.set_markup ("<b>%s</b>" % text)
        self.messageDialog.show ()

    def close_message_dialog (self, *args):
        '''Close message dialog'''
        self.messageDialog.hide ()
        return False

if __name__ == "__main__":
    game = pyTicTacToe ()
    game.show ()
    gtk.main ()