~e93b5ae3/+junk/github-import-readonly

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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable-msg=r0201
"""
    4digits - A guess-the-number game, aka Bulls and Cows
    Copyright (c) 2004-2011 Yongzhi Pan <http://fourdigits.sourceforge.net>

    4digits is a guess-the-number puzzle game. You are given eight times
    to guess a four-digit number. One digit is marked A if its value and
    position are both correct, and marked B if only its value is correct.
    You win the game when you get 4A0B. Good luck!

    4digits 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.

    4digits 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 4digits; if not, write to the Free Software Foundation,
    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
"""

import os
import cPickle
import random
import pango
import sys
import time
import webbrowser

try:
    import pygtk
    pygtk.require('2.0')
    import gtk
    import gtk.glade
except ImportError:
    print _('python-gtk2 is required to run 4digits.')
    print _('No python-gtk2 was found on your system.')
    sys.exit(1)

__version__ = '1.0'
__appdata_dir__ = os.path.join(os.path.expanduser('~'), '.4digits')
__config_path__ = os.path.join(__appdata_dir__, 'prefs.pickle')
__prefs__ = {
        'show toolbar': True,
        'show hint table': False,
        'auto fill hints': False
        }

# The first is the current directory, so you do not have to install 
# 4digits to play it. The second is the installation directory.
__gladefiles__ = [os.path.join(os.path.dirname(__file__), '4digits.glade'),
    os.path.normpath(os.path.join(
    os.path.dirname(__file__), '../share/4digits/4digits.glade'))]
__helpfiles__ = [os.path.join(os.path.dirname(__file__), 'doc', 'index.html'),
    os.path.normpath(os.path.join(
    os.path.dirname(__file__), '../share/doc/4digits/index.html'))]
__score_filename__ = os.path.join(__appdata_dir__, '4digits.4digits.scores')

# For future gettext support. I cannot figure out i18n now.
# I wish someone could help me with it.
try: 
    _()
except NameError:
    def _(arg):
        """Mark translatable strings."""
        return arg

def load_glade(dialog = None):
    """Try to load dialog from the different possible glade files."""
    for gladefile in __gladefiles__:
        try:
            return gtk.glade.XML(gladefile, dialog) 
        except RuntimeError:
            continue # Just ignore the error, the next file will be tested
    # Still here
    print "Gladefile not found! Checked paths were:"
    print __gladefiles__
    sys.exit(2)
    

class MainWindow(object):
    """The main game window."""
    def __init__(self):
        """GUI initialization."""
        self.widget_tree = load_glade()
        self.toolbar = self.widget_tree.get_widget('toolbar')
        self.view_toolbar = self.widget_tree.get_widget('view_toolbar')
        self.hint_table = self.widget_tree.get_widget('hint_table')
        self.hint_hseparator = self.widget_tree.get_widget(
                'hint_hseparator')
        self.view_hint_table = self.widget_tree.get_widget(
                'view_hint_table')
        self.auto_fill_hints = self.widget_tree.get_widget(
                'view_auto_fill_hints')

        # Input box
        self.entry = self.widget_tree.get_widget('entry')
        self.entry.grab_focus()
        fontsize = self.entry.get_pango_context().\
                get_font_description().get_size()/pango.SCALE
        self.entry.modify_font(pango.FontDescription(str(int(fontsize*3))))

        self.ok_button = self.widget_tree.get_widget('ok_button')
        for widget in ('g0', 'g1', 'g2', 'g3', 'g4', 'g5', 'g6', 'g7',
                'r0', 'r1', 'r2', 'r3', 'r4', 'r5', 'r6', 'r7'):
            setattr(self, widget, self.widget_tree.get_widget(widget))
        self.info_label = self.widget_tree.get_widget('info_label')
        self.time_label = self.widget_tree.get_widget('time_label')
        self.score_view = self.widget_tree.get_widget('score_view')

        self.cb_hint = [] # container for check boxes in the hint table
        self.label_hint = []
        self.build_hint_table()

        # parse preferences
        self.read_preferences_file()
        if __prefs__['show toolbar']:
            self.toolbar.show()
            self.view_toolbar.set_active(True)
        else:
            self.toolbar.hide()
            self.view_toolbar.set_active(False)
        if __prefs__['show hint table']:
            self.hint_table.show_all()
            self.hint_hseparator.show()
            self.view_hint_table.set_active(True)
        else:
            self.hint_table.hide_all()
            self.hint_hseparator.hide()
            self.view_hint_table.set_active(False)
        if __prefs__['auto fill hints']:
            self.auto_fill_hints.set_active(True)
        else:
            self.auto_fill_hints.set_active(False)
        
        # connect signals and callbacks
        dic = {'on_main_window_destroy': self.terminate_program,
                'on_quit_activate': self.terminate_program,
                'on_ok_clicked': self.on_entry_activate,
                'on_new_game_activate': self.on_new_game_activate,
                'on_view_toolbar_toggled': self.on_view_toolbar_toggled,
                'on_view_hint_table_toggled'
                : self.on_view_hint_table_toggled,
                'on_view_auto_fill_hints_toggled'
                : self.on_view_auto_fill_hints_toggled,
                'on_entry_activate': self.on_entry_activate,
                'on_entry_changed': self.on_entry_changed,
                'on_help_activate' : self.on_help_activate,
                'on_about_activate' : self.on_about_activate,
                'on_score_activate': self.on_score_activate}
        self.widget_tree.signal_autoconnect(dic)
        # new game initialization
        self.game = NewRound()

    def read_preferences_file(self):
        """Read preferences data from disk.
        Copied from Comix.
        """
        if os.path.isfile(__config_path__):
            try:
                config = open(__config_path__)
                old___prefs__ = cPickle.load(config)
                config.close()
            except Exception:
                print 'Corrupted preferences file \
                "%s", deleting...' % __config_path__
                os.remove(__config_path__)
            else:
                for key in old___prefs__:
                    if key in __prefs__:
                        __prefs__[key] = old___prefs__[key]

    def write_preferences_file(self):
        """Write preference data to disk.
        Copied from Comix.
        """
        config = open(__config_path__, 'w')
        cPickle.dump(__prefs__, config, cPickle.HIGHEST_PROTOCOL)
        config.close()

    def build_hint_table(self):
        """Create the controls for the hint table."""
        hint_table = self.widget_tree.get_widget('hint_table')
        for name in (0, 40):
            table = gtk.Table(rows=11, columns=6)
            hint_table.pack_start(table)

            # Create row labels
            for row in range(0, 10):
                label = gtk.CheckButton(str(row))
                table.attach(label, 0, 1, row+1, row+2)
                label.connect('toggled', self.change_row, row+name)
                self.label_hint.append(label)

            for col in range(1, 5):
                # Create column labels
                #label = gtk.Label(str(col))
                #table.attach(label, col, col+1, 0, 1)
                # Create Checkboxes
                for row in range(0, 10):
                    checkbutton = gtk.CheckButton()
                    table.attach(checkbutton, col, col+1, row+1, row+2)
                    self.cb_hint.append(checkbutton)

            if name == 0: # First table
                hint_table.pack_start(gtk.VSeparator())
        self.init_hint_table()

    def change_row(self, widget, row):
        """Toggle a rows state."""
        enable = widget.get_active()
        for col in range(0, 4):
            self.cb_hint[10 * col + row].set_sensitive(enable)

    def init_hint_table(self):
        """Reset all controls in the hinttable to their default state."""
        for i in range(0, 40):
            self.cb_hint[i].set_active(True)
            self.cb_hint[i+40].set_active(False)
            self.cb_hint[i+40].set_sensitive(False)
        self.cb_hint[0].set_active(False)
        for row in range(0, 10):
            self.label_hint[row].set_active(True)
            self.label_hint[row+10].set_active(False)
    
    #         1    2    3    4                   1    2    3    4
    #  0/0    00   10   20   30          0/10    40   50   60   70
    #  1/1    01   11   21   31          1/11    41   51   61   71
    #  2/2    02   12   22   32          2/12    42   52   62   72
    # ...

    def get_checkbox(self, row, col, tablenr=0):
        """Get the checkbox at the specified position."""
        return self.cb_hint[tablenr * 40 + col * 10 + row]

    def get_label(self, row, tablenr=0):
        """Get the label at the specified position."""
        return self.label_hint[tablenr*10 + row]

    def on_entry_activate(self, widget):
        """when input is accepted."""
        bulls, cows = 0, 0
        number = ''
        # check input
        if self.game.guess < 8:
            number = self.entry.get_text()
            if number == '':
                self.process_error(_('Must input something.'))
                return False
            elif number[0] == '0':
                self.process_error(_('First digit cannot be zero.'))
                return False
            try:
                number = repr(int(number))
            except ValueError:
                self.process_error(_('Must input a number.'))
                return False
            if len(number) < 4:
                self.process_error(_('Must input four digits.'))
                return False
            elif len(set(number)) < 4:
                self.process_error(_('Four digits must be unique.'))
                return False
            elif number in self.game.guesses:
                self.process_error(_("You've already guessed it."))
                return False
            self.game.guesses.append(number)
            # process input
            for i in xrange(4):
                for j in xrange(4):
                    if self.game.answer[i] == int(number[j]):
                        if i == j:
                            bulls += 1
                        else:
                            cows += 1
            guess_label = getattr(self, 'g' + repr(self.game.guess))
            result_label = getattr(self, 'r' + repr(self.game.guess))
            guess_label.set_text(number)
            result_label.set_text('%dA%dB' % (bulls, cows))

            if self.auto_fill_hints.get_active():
                self.fill_hints(number, bulls, cows)
            
            # win
            if bulls == 4:
                self.info_label.set_text(_('You win! :)'))
                self.get_time_taken_till_now()
                self.time_label.set_text(_('Used %.1f s.') % 
                    self.game.time_taken)
                self.ok_button.set_sensitive(False)
                self.entry.set_sensitive(False)
                if self.is_high_score(self.game.time_taken):
                    new_score_rank = self.write_score(self.game.time_taken)
                    self.show_score(new_score_rank)
            # lose
            elif self.game.guess == 7:
                answer = ''
                for i in xrange(4):
                    answer += repr(self.game.answer[i])
                self.info_label.set_text(_('Haha, you lose. It is %s.') % 
                    answer)
                self.get_time_taken_till_now()
                self.time_label.set_text(_('Wasted %.1f s.') % 
                    self.game.time_taken)
                self.ok_button.set_sensitive(False)
                self.entry.set_sensitive(False)
        self.game.guess += 1
        self.entry.grab_focus()

    def clear_row(self, row):
        """Clear a complete row."""
        self.get_label(row, 0).set_active(False)
        for col in range(0, 4):
            self.get_checkbox(row, col, 0).set_active(False)
            self.get_checkbox(row, col, 1).set_active(False)

    def fill_hints(self, number, bulls, cows):
        """Auto filling some obvious cases in the hint table."""
        number = [int(x) for x in number]
        if bulls == 0 and cows == 0:
            for digit in number:
                self.clear_row(digit)
            return

        if bulls+cows == 4:
            for digit in range(0, 10):
                if digit in number:
                    self.get_label(digit, 0).set_active(True)
                    self.get_label(digit, 1).set_active(True)
                else:
                    self.clear_row(digit)

        if bulls == 0: # Only cows
            for digit_pos in range(0, 4):
                self.get_checkbox(number[digit_pos], digit_pos, 
                    0).set_active(False)
                self.get_checkbox(number[digit_pos], digit_pos, 
                    1).set_active(False)

        if cows == 0: # Only bulls
        # Only digits which are either in the right place or completely wrong
            for digit_pos in range(0, 4):
                for pos2 in range(0, 4):
                    if pos2 == digit_pos:
                        continue
                    # uncheck impossible boxes in first column
                    self.get_checkbox(number[digit_pos], pos2, 
                        0).set_active(False)

    def on_entry_changed(self, widget):
        """Start timer as soon as the user enters the first digit."""
        self.info_label.set_text('')
        if self.game.on_entry_cb_first_called == True:
            self.time_label.set_text(_('Timer started...'))
            self.game.time_start = time.time()
            self.game.on_entry_cb_first_called = False
  
    def on_view_toolbar_toggled(self, widget):
        """Toggle toolbar visibility."""
        if self.toolbar.get_property('visible'):
            self.toolbar.hide()
            __prefs__['show toolbar'] = False
        else:
            self.toolbar.show()
            __prefs__['show toolbar'] = True

    def on_view_hint_table_toggled(self, widget):
        """Toggle hint table visibility."""
        if self.hint_table.get_property('visible'):
            self.hint_table.hide_all()
            self.hint_hseparator.hide()
            __prefs__['show hint table'] = False
        else:
            self.hint_table.show_all()
            self.hint_hseparator.show()
            __prefs__['show hint table'] = True
    
    def on_view_auto_fill_hints_toggled(self, widget):
        """Toggle auto filling of hint table."""
        if self.auto_fill_hints.get_active():
            __prefs__['auto fill hints'] = True
        else:
            __prefs__['auto fill hints'] = False

    @classmethod
    def on_help_activate(cls, widget):
        """Show help."""
        for helpfile in __helpfiles__:
            try:
                file(helpfile)
            except IOError:
                continue
            webbrowser.open(helpfile)

    @classmethod
    def on_about_activate(cls, widget):
        """Show about dialog."""
        about = AboutDialog().about_dialog
        about.run()
        about.destroy()
    
    @classmethod
    def on_score_activate(cls, new_score_rank):
        """Show high scores."""
        score_dialog = ScoreDialog()
        dlg = score_dialog.score_dialog
        score_view = score_dialog.score_view
        sv_selection = score_view.get_selection()
        sv_selection.set_mode(gtk.SELECTION_NONE)
        column = gtk.TreeViewColumn(
                _('Name'), gtk.CellRendererText(), text = 0)
        score_view.append_column(column)
        column = gtk.TreeViewColumn(
                _('Score'), gtk.CellRendererText(), text = 1)
        score_view.append_column(column)
        column = gtk.TreeViewColumn(
                _('Date'), gtk.CellRendererText(), text = 2)
        score_view.append_column(column)
        dlg.scoreList = gtk.ListStore(str, str, str)
        score_view.set_model(dlg.scoreList)

        try:
            scores = [line.split(' ', 6) 
                    for line in file(__score_filename__, 'r')]
        except IOError:
            scores = []

        for line in scores:
            score_tup = line[0], line[1], ' '.join(line[2:]).rstrip('\n')
            dlg.scoreList.append(score_tup)
        # high light the current high score entry
        try:
            sv_selection.set_mode(gtk.SELECTION_SINGLE)
            sv_selection.select_path(new_score_rank)
        except TypeError:
            sv_selection.set_mode(gtk.SELECTION_NONE)

        dlg.run()
        dlg.destroy()

    def on_new_game_activate(self, widget):
        """New game initialization."""
        self.game = NewRound()
        self.ok_button.set_sensitive(True)
        self.entry.set_sensitive(True)
        self.entry.grab_focus()
        # won't start the timer when you just start a new game
        self.game.on_entry_cb_first_called = False
        self.entry.set_text('')
        self.game.on_entry_cb_first_called = True
        self.info_label.set_text(_('Ready'))
        self.time_label.set_text('')

        for i in xrange(8):
            getattr(self, 'g' + repr(i)).set_text('')
            getattr(self, 'r' + repr(i)).set_text('')
        
        self.init_hint_table()

    def process_error(self, msg):
        """Show error message in statusbar."""
        self.info_label.set_text(msg)
        self.entry.grab_focus()

    def get_time_taken_till_now(self):
        """Get time since start of the game."""
        self.game.time_end = time.time()
        self.game.time_taken = self.game.time_end - self.game.time_start
        self.game.time_taken = round(self.game.time_taken, 1)

    @classmethod
    def is_high_score(cls, time_taken):
        """Is this time a highscore."""
        try:
            scores = [line.split(' ', 6) 
                    for line in file(__score_filename__, 'r')]
        except IOError:
            return True # List does not exist yet
        if len(scores) < 10:
            return True
        scores = sorted(scores, key = lambda x: float(x[1][:-1]))
        if time_taken < float(scores[-1][1][:-1]):
            return True
        else:
            return False

    @classmethod
    def write_score(cls, time_taken):
        """Write highscore file."""
        date = time.strftime("%a %b %d %H:%M:%S %Y") 
        new_score = "%s %ss %s\n" % (
                os.getenv('USERNAME'), time_taken, date)
        try:
            saved_scores = open(__score_filename__, 'r').readlines()
        except IOError:
            saved_scores = [] 
        saved_scores.append(new_score)
        scores = [line.split(' ', 6) for line in saved_scores]
        scores = sorted(scores, key = lambda x: float(x[1][:-1]))
        scores = scores[:10]

        # find the index of the new score
        new_score = new_score.split(' ', 6)
        new_score_rank = scores.index(new_score)
        try:
            scorefile = open(__score_filename__, 'w')
        except IOError:
            # Most likely the directory does not exist
            new_dir = os.path.dirname(__score_filename__)
            os.mkdir(new_dir)
            scorefile = open(__score_filename__, 'w') # Try again
        for score in scores:
            scorefile.write(' '.join(score))
        scorefile.close()
        return new_score_rank

    def show_score(self, new_score_rank):
        """Show highscore dialog."""
        self.on_score_activate(new_score_rank)
    
    def terminate_program(self, widget):
        """Run clean-up tasks and exit.
        Copied from comix.        
        """
        self.write_preferences_file()
        gtk.main_quit()


class AboutDialog(object):
    """The about dialog."""
    def __init__(self):
        self.widget_tree = load_glade('about_dialog')
        self.about_dialog = self.widget_tree.get_widget("about_dialog")
        gtk.about_dialog_set_url_hook(
                lambda about_dialog, url: webbrowser.open(url))
        self.about_dialog.set_website(
                'http://fourdigits.sourceforge.net')
        self.about_dialog.set_website_label(
                'http://fourdigits.sourceforge.net')


class ScoreDialog(object):
    """The score dialog."""
    def __init__(self):
        self.widget_tree = load_glade('score_dialog')
        self.score_dialog = self.widget_tree.get_widget('score_dialog')
        self.score_view = self.widget_tree.get_widget('score_view')


class NewRound(object):
    """Contains data in one round of the game."""
    def __init__(self):
        while True:
            self.answer = random.sample(range(10), 4)
            if self.answer[0] != 0: # first digit cannot be zero
                break
        #print self.answer
        if self.answer == [4, 6, 1, 9]:
            gtk.MessageDialog(message_format
                    ='4619: You are the luckiest guy on the planet!').show()
        self.guess = 0
        self.guesses = []
        self.time_start = 0
        self.time_end = 0
        self.time_taken = 0
        self.on_entry_cb_first_called = True

if __name__ == "__main__":
    MainWindow()
    gtk.main()