This repository has been archived by the owner on Dec 30, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathanonymine.py
executable file
·1666 lines (1483 loc) · 58.7 KB
/
anonymine.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
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# Copyright (c) Oskar Skog, 2016-2017
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# This software is provided by the copyright holders and contributors "as is"
# and any express or implied warranties, including, but not limited to, the
# implied warranties of merchantability and fitness for a particular purpose
# are disclaimed. In no event shall the copyright holder or contributors be
# liable for any direct, indirect, incidental, special, exemplary, or
# consequential damages (including, but not limited to, procurement of
# substitute goods or services; loss of use, data, or profits; or business
# interruption) however caused and on any theory of liability, whether in
# contract, strict liability, or tort (including negligence or otherwise)
# arising in any way out of the use of this software, even if advised of the
# possibility of such damage.
'''A minesweeper that can be solved without guessing
Copyright (c) Oskar Skog, 2016-2017
Released under the FreeBSD license.
A minesweeper that can be solved without guessing
=================================================
This script contains a curses based interface class, a command line
setup function, a line mode setup function and glue.
The engine is in a separate module (anonymine_engine).
The game support three different gametypes:
Moore neighbourhoods: each cell has eight neighbours.
Hexagonal cells: each cell has six neighbours.
Von Neumann neighbourhoods: each cell has four neighbours.
'''
import curses
import os
import sys
import errno
import locale
try:
import subprocess
except:
# Let piping to less(1) fail on Minix.
pass
# Allow module names to be changed later.
import anonymine_engine as game_engine
# argparse: Losing the ability to take command line options is no biggy.
# traceback: Not needed unless shit happens.
import traceback # Not required.
# argparse is new in 2.7 and 3.2.
try:
import argparse
except:
pass
# These two are still needed.
GAME_NAME = 'Anonymine'
GAME_FILENAME = GAME_NAME.lower().replace(' ', '-')
GAME_CRAPTEXT = """Anonymine version MAKEFILE_GAME_VERSION
Copyright (c) Oskar Skog, 2016-2017
Released under the Simplified BSD license (2 clause).
\n"""
class curses_game():
'''Class for interface object for `engine.play_game(interface)`.
This is a large part of the curses mode interface for Anonymine.
The "engine" is in the module `anonymine_engine` and could be used
by a different interface.
The engine is currently (as of version 0.0.13) responsible for
creating the "field", initialization of the field (filling it with
mines) and the main loop of a game.
anonymine_engine.game_engine(**params).play_game(interface)
`interface` is an object that needs to provide these methods:
input(self, field)
output(self, field)
anykey_cont(self)
It is recommended that you read the documentation for the engine
as well.
Coordinates
===========
The "cursor" marks the selected cell on the field. It is a
"field coordinate".
A "virtual coordinate" is a coordinate on an imaginary screen.
A virtual coordinate doesn't need to be in the "visible area".
A virtual coordinate can easily be generated from a field
coordinate.
The visible area are those virtual coordinates that exist on
the screen. The visible area can be moved with
`self.window_start`.
A "real coordinate" is a coordinate on the screen and can be
sent to the methods of `self.window`.
real[0] = virtual[0] - window_start[0]
real[1] = virtual[1] - window_start[1]
The screen is `self.window`, not the real one.
Externally used methods
=======================
interface = curses_game(cfgfile, gametype)
`cfgfile` is the path to the cursescfg configuration file
(the configuration file with the key bindings and
textics.)
`gametype` is either 'moore', 'hex' or 'neumann'.
NOTICE: `curses_game.__init__` will enter curses mode.
WARNING: `curses_game.__init__` MAY raise an exception
while in curses mode if something is wrong with the
configuration or if bad parameters are given.
interface.leave()
Leave curses mode.
interface.input(engine)
(This method is called by `engine.play_game`.)
Take command from user and act on `engine.field`.
interface.output(engine)
(This method is called by `engine.play_game`.)
Print the field (`engine.field`) to the screen.
Prints the flags left text, invokes `self.print_square` or
`self.print_hex`, and finally, `self.window.refresh`.
interface.anykey_cont()
(This method is called by `engine.play_game`.)
Pause until input from user.
"Press any key to continue..."
Attributes
==========
interface.window = curses.initscr()
The screen.
interface.cursor = (0, 0)
The *field* coordinate.
interface.window_start = [0, 0]
Needed for translating virtual coordinates into real
coordinates.
Internally used methods
=======================
char, attributes = self.curses_output_cfg(key)
"Parse" the configuration (cursescfg) and pick the most
appropriate mode for the property `key`. The color pair
is properly attached to `attributes`.
self.message(msg)
Print `msg` at the bottom of the screen while in curses
mode. Invokes `self.window.refresh`.
Used for printing the initialization message and by
`self.anykey_cont`.
self.travel(engine, direction)
Modify `self.cursor` to select a new cell in the
specified direction.
self.print_char(x, y, cfg, char=None)
Print a character at the virtual coordinate (x, y) using
the textics property `cfg`. `char` will override the
character specified in the textics directive.
self.move_visible_area(virtual_x,virtual_y,x_border,y_border)
Modify `self.window_start` so (virtual_x, virtual_y) is
visible on the screen, and not too close to any edge.
self.print_square(field)
Print Moore and Neumann fields and the "cursor" to the
screen. Does not invoke `self.window.refresh` and does
not print the flags left text.
self.print_hex(field)
Print hexagonal fields and the "cursor" to the screen.
Does not invoke `self.window.refresh` and does not print
the flags left text.
Constants
=========
self.travel_diffs
A dictionary of dictionaries to translate a direction
into DELTA-x and DELTA-y. Used by `self.travel`.
self.direction_keys
A dictionary of lists representing the valid directions
for a certain gametype. This allows square and hex
directions to share the same keys.
Used by `self.input`.
self.specials
The method `get` of the field object may return one of
these value or a normal number. (Normal numbers will be
printed using their digit as character and the textics
directive 'number'.)
This dictionary maps the special return values into
textics properties.
'''
# BUG: This is referenced from various lines in the class.
# More or less platform specific.
# Detected on:
# OS: Debian 8 (Linux 3.16) (x86-64)
# curses.version: 2.2
# Library: ncurses5.9
# Description:
# After forking, it appears, when the field is being initialized, the
# curses mode stops working.
# Solution:
# Define a program mode and temporarily reset to shell mode while
# initializing the field.
# The cursor can still not be hidden, so it will be moved to an
# unimportant place.
# The screen requires one complete redrawal of the screen, so that
# will also be done.
# NOTICE:
# FOR THE LOVE OF KEN, DO NOT REMOVE WORKAROUND!!
# NOTICE:
# DO NOT REMOVE.
# This is referenced from the source.
# Update 2016-07-17:
# The windows only needs to be redrawn on initialization, not on every
# click.
# Trying to leave and re-enter curses mode was no good.
# Update 2016-12-10 (pre 0.4.2):
# No need to temporarily reset to shell mode every time a cell is
# revealed. The issue was that game_status changed. Fixed in 0.3.11
def __init__(self, cfgfile, gametype):
'''Create interface object and enter curses mode.
`cfgfile` is the path to the cursescfg file.
`gametype` must be 'moore', 'hex' or 'neumann'.
WARNING: This does not leave curses mode on exceptions!
'''
# Constants
self.travel_diffs = {
'square': {
'up': (0, -1),
'right': (1, 0),
'down': (0, 1),
'left': (-1, 0),
'NE': (1, -1),
'SE': (1, 1),
'SW': (-1, 1),
'NW': (-1, -1),
},
'hex-even': {
'hex0': (0, -1), # 5 0
'hex1': (1, 0), # 4 1
'hex2': (0, 1), # 3 2
'hex3': (-1, 1),
'hex4': (-1, 0), # x - 1 and x on even
'hex5': (-1, -1), # rows.
},
'hex-odd': {
'hex0': (1, -1),
'hex1': (1, 0), # x and x + 1 on odd
'hex2': (1, 1), # rows.
'hex3': (0, 1),
'hex4': (-1, 0),
'hex5': (0, -1),
}
}
self.direction_keys = {
'hex': ['hex0', 'hex1', 'hex2', 'hex3', 'hex4', 'hex5'],
'square': ['up', 'NE', 'right', 'SE', 'down', 'SW', 'left', 'NW'],
}
self.specials = {
0: 'zero',
None: 'free',
'F': 'flag',
'X': 'mine',
}
# Initialize...
self.gametype = gametype
self.window_start = [0, 0] # Item assignment
self.cursor = (0, 0)
self.attention_mode = False
# Initialize curses.
self.window = curses.initscr()
curses.cbreak()
curses.noecho()
curses.meta(1)
self.window.keypad(True)
try:
self.old_cursor = curses.curs_set(0)
except:
pass
curses.def_prog_mode() # BUG: see comments above __init__
# Check that we have a reasonable size on the window.
height, width = self.window.getmaxyx()
def toosmall():
self.leave()
sys.stdout.flush()
output(sys.stderr,'\nSCREEN TOO SMALL\n')
sys.stderr.flush()
sys.exit(1)
if self.gametype == 'hex' and (width < 10 or height < 8):
toosmall()
if self.gametype != 'hex' and (width < 7 or height < 4):
toosmall()
# Read the configuration.
self.cfg = eval(open(cfgfile).read())
# Apply ord() automatically to the keys in 'curses-input'.
for key in self.cfg['curses-input']:
for index in range(len(self.cfg['curses-input'][key])):
value = self.cfg['curses-input'][key][index]
if isinstance(value, str):
self.cfg['curses-input'][key][index] = ord(value)
# Initialize the color pairs.
self.color_pairs = []
if curses.has_colors():
self.use_color = True
# TODO: Check that enough pairs are available.
curses.start_color()
for key in self.cfg['curses-output']:
value = self.cfg['curses-output'][key]
ch, foreground, background, attr = value
# Only add new pairs.
if (foreground, background) not in self.color_pairs:
self.color_pairs.append((foreground, background))
curses.init_pair(
len(self.color_pairs),
eval('curses.COLOR_' + foreground),
eval('curses.COLOR_' + background)
)
else:
self.use_color = False
# Initialize mouse
mask = curses.REPORT_MOUSE_POSITION|curses.ALL_MOUSE_EVENTS
self.old_mousemask = curses.mousemask(mask)
curses.mouseinterval(self.cfg['curses-mouse-input']['interval'])
def leave(self):
'''Leave curses mode.'''
curses.nocbreak()
curses.echo()
self.window.keypad(False)
try:
curses.curs_set(self.old_cursor)
except:
pass
curses.endwin()
def curses_output_cfg(self, key):
'''Retrieve textics directive from cursescfg.
char, attributes = self.curses_output_cfg(key)
`key` is the property in cursescfg ('curses-output').
`char` is a character and needs to be converted before passed
to a curses function.
`attributes` is an integer to be passed directly to a curses
function. Color is or'ed in.
Retrieve a textics directive from the configuration file
(cursescfg). This function is responsible to choose the
key with the correct property and best available mode.
Raises KeyError if the entry can't be found.
gametype Best available mode 2nd best worst
'moore': ':moore' ':square' ''
'hex': ':hex' ''
'neumann' ':neumann' ':square' ''
This function will automatically convert the directive line
into two directly useful parts:
`char`: The character to be printed or `None`.
`attributes`: The attributes to be used (curses).
The color pair is also or'ed in.
See also: the configuration file.
'''
cfg = self.cfg['curses-output']
# Choose gametype specific entries if available
if self.gametype == 'neumann':
if key + ':neumann' in cfg:
key += ':neumann'
elif key + ':square' in cfg:
key += ':square'
elif self.gametype == 'hex':
if key + ':hex' in cfg:
key += ':hex'
elif self.gametype == 'moore':
if key + ':moore' in cfg:
key += ':moore'
elif key + ':square' in cfg:
key += ':square'
# Translate the key into (char, attributes)
char, foreground, background, attributes = cfg[key]
if self.use_color:
attributes |= curses.color_pair(
self.color_pairs.index((foreground, background)) + 1
)
return char, attributes
def message(self, msg):
'''Print `msg` at the bottom of the screen while in curses mode.
Invokes `self.window.refresh`.
Used for printing the initialization message and by
`self.anykey_cont`.
'''
height, width = self.window.getmaxyx()
ign, attributes = self.curses_output_cfg('text')
text_width = width - 4 # Pretty margin on the left.
lines = len(msg)//text_width + 1
if lines <= height:
for line in range(lines):
self.window.addstr(
height - lines + line, 3,
msg[line*text_width:(line+1)*text_width],
attributes
)
else:
pass # A screen this small? Seriously?
self.window.refresh()
def anykey_cont(self):
'''Press any key to continue...
Wait for input from the user, discard the input.
(This method is called by `engine.play_game`.)
'''
self.message('Press the "any" key to continue...')
self.window.getch()
def output(self, engine):
'''This method is called by `engine.play_game`.
It erases the window, prints the flags left message if it would
fit on the screen, invokes the appropriate field printer and
refreshes the screen. (In that order.)
'''
# TODO: The background gets set ridiculously often.
# Set the appropriate background.
char, attributes = self.curses_output_cfg('background')
self.window.bkgdset(32, attributes) # 32 instead of `char`.
# BUG: window.bkgdset causes a nasty issue when the background
# character is not ' ' and color is unavailable.
# Print the screen.
self.window.erase()
# Screen could resized at any time.
self.height, self.width = self.window.getmaxyx()
chunks = []
if engine.game_status == 'pre-game':
chunks.append('Choose your starting point.')
if engine.game_status == 'play-game':
if engine.field.flags_left is not None:
chunks.append("Flags left: {0}".format(
engine.field.flags_left
))
msg = ' '.join(chunks)
if len(msg) + 4 <= self.width:
ign, attributes = self.curses_output_cfg('text')
self.window.addstr(self.height - 1, 3, msg, attributes)
# (Keeping the following outside the loop magically solves a resizing
# bug that traces back to an `addch` in `self.print_char`.)
# Lie to the field printer functions to preserve the text.
self.height -= 1
# Print the field.
if self.gametype == 'hex':
self.print_hex(engine.field)
else:
self.print_square(engine.field)
# Remember that self.height has already been decremented by one.
self.window.move(self.height, 0) # BUG: see comments above __init__
self.window.refresh()
def input(self, engine):
'''This method is called by `engine.play_game`.
It receives a character from the user and interprets it.
Invokes `self.travel` for the steering of the cursor.
It doesn't do any output except for printing the field
initialization message, and forcing the entire screen to be
redrawn on unrecognised input (to de-fuck-up the screen).
'''
if self.gametype == 'hex':
direction_keys = self.direction_keys['hex']
else:
direction_keys = self.direction_keys['square']
look_for = ['reveal', 'flag', 'toggle-attention'] + direction_keys
# Receive input from player.
ch = self.window.getch()
# Interpret.
command = None
if ch == curses.KEY_MOUSE:
_, x, y, _, buttons = curses.getmouse()
valid = True
if self.gametype == 'hex':
valid = self.mouse_travel_hex(x, y, engine.field)
else:
valid = self.mouse_travel_square(x, y, engine.field)
if valid:
for tmp_command in ('flag', 'reveal'):
for mask in self.cfg['curses-mouse-input'][tmp_command]:
if buttons & mask:
command = tmp_command
else:
continue
break
else:
# Keyboard input:
for key in look_for:
if ch in self.cfg['curses-input'][key]:
command = key
# Act.
if command == 'flag':
engine.flag(self.cursor)
elif command == 'reveal':
pre_game = engine.game_status == 'pre-game'
if pre_game:
self.message('Initializing field... This may take a while.')
curses.reset_shell_mode() # BUG: see comments above __init__
engine.reveal(self.cursor)
if pre_game:
curses.reset_prog_mode() # BUG: see comments above __init__
# Clear junk that gets on the screen from impatient players.
self.window.redrawwin()
elif command in direction_keys:
self.travel(engine.field, command)
elif command == 'toggle-attention':
self.attention_mode = not self.attention_mode
elif ch != curses.KEY_MOUSE:
# Don't do this all the time, that'd be a little wasteful.
self.window.redrawwin()
def travel(self, field, direction):
'''Move the cursor in the specified direction.
It will not move past an edge (or in an otherwise impossible
direction). This is why the `field` argument is required.
Valid directions when self.gametype == 'moore':
'up', 'NE', 'right', 'SE', 'down', 'SW', 'left', 'NW'
Valid directions when self.gametype == 'hex':
'hex0', 'hex1', 'hex2', 'hex3', 'hex4', 'hex5'
Valid directions when self.gametype == 'neumann':
'up', 'right', 'down', 'left'
The hexagonal directions are:
5 0
4 1
3 2
'''
x, y = self.cursor
# Find the appropriate dictionary of direction to DELTA-x and DELTA-y.
if self.gametype != 'hex':
key = 'square'
elif y % 2:
key = 'hex-odd'
else:
key = 'hex-even'
# Move in the specified direction.
x_diff, y_diff = self.travel_diffs[key][direction]
new = x + x_diff, y + y_diff
# Do nothing if it is impossible to move in the specified direction.
x, y = new
if x >= 0 and x < field.dimensions[0]:
if y >= 0 and y < field.dimensions[1]:
self.cursor = new
def move_visible_area(self, virtual_x, virtual_y, x_border, y_border):
'''Move the area that will be printed by `self.print_char`.
Move the visible area (as printed by `self.print_char`) by
modifying `self.window_start`, which is used for translating
virtual coordinates (a step between field coordinates and
screen coordinates.)
`virtual_x` and `virtual_y` is the virtual coordinate.
`x_border` is the minimal allowed border between the virtual
coordinate and the left or the right side of the screen.
`y_border` is the minimal allowed border between the virtual
coordinate and the top or the bottom of the screen.
'''
real_x = virtual_x - self.window_start[0]
real_y = virtual_y - self.window_start[1]
if real_x + x_border > self.width - 1:
self.window_start[0] = virtual_x - self.width + x_border + 1
if real_x - x_border < 0:
self.window_start[0] = virtual_x - x_border
if real_y + y_border > self.height - 1:
self.window_start[1] = virtual_y - self.height + y_border + 1
if real_y - y_border < 0:
self.window_start[1] = virtual_y - y_border
def print_char(self, x, y, cfg, char=None):
'''Print a character at a virtual coordinate with the right attributes.
Print a character at the virtual coordinate (`x`, `y`)
using the textics directive `cfg`.
`char` is used to override the default character of the
textics directive.
'''
real_x = x - self.window_start[0]
real_y = y - self.window_start[1]
# Verify that the coordinate is printable.
if 0 <= real_x < self.width:
if 0 <= real_y < self.height:
cfg_char, attributes = self.curses_output_cfg(cfg)
# curses_output_cfg may raise KeyError
if char is None:
char = cfg_char
self.window.addstr(real_y, real_x, char, attributes)
def print_digit(self, x, y, digit):
'''Print a digit at a virtual coordinate.
Introduced in 0.4.9 to allow digits to have different colors.
'''
try:
self.print_char(x, y, str(digit))
except KeyError:
self.print_char(x, y, 'number', str(digit))
def print_cell(self, x, y, field, cell):
'''
`x` and `y` is the virtual coordinate for the single character
to be printed.
`cell` is the cell from the field.
Introduced in 0.4.15 to reduce code duplication and apply the
attention mode to numbers with too many mines around them.
'''
value = field.get(cell)
if value not in self.specials:
if self.attention_mode:
flags = 0
for neighour in field.get_neighbours(cell):
if field.get(neighour) == 'F':
flags += 1
if flags > value:
self.print_char(x, y, 'attention', str(value))
return
self.print_digit(x, y, value)
else:
if value is None and self.attention_mode:
self.print_char(x, y, 'attention')
else:
self.print_char(x, y, self.specials[value])
def print_square(self, field):
'''Helper function for `self.output` for non-hexagonal gametypes.
Print a non-hexagonal field in the area
0 to self.width-1 by 0 to self.height-2.
Also prints the "cursor".
It does not print the flags left text.
It will invoke `self.move_visible_area` to keep the "cursor" on
the screen. It will use `self.print_char` to print characters
on the screen.
_______
| X X X |
| X(*)X |
| X X X |
-------
'''
# Move the visible area.
# Compute the virtual locations on the screen and real locations.
# Adjust the virtual coordinate of the visible area.
#
# Border = 1 cell.
x, y = self.cursor
self.move_visible_area(2*x+1, y, 3, 1)
# Print all cells in a field.
for cell in field.all_cells():
x, y = cell
# Print blank grid .
self.print_char(2*x, y, 'grid', ' ')
self.print_char(2*x+2, y, 'grid', ' ')
# Print the actual cell.
self.print_cell(2*x+1, y, field, cell)
# Print the "cursor".
x, y = self.cursor
self.print_char(2*x, y, 'cursor-l')
self.print_char(2*x+2, y, 'cursor-r')
def mouse_travel_square(self, x, y, field):
'''
'''
x += self.window_start[0]
y += self.window_start[1]
# Inverse transformation of x and y.
if not x % 2:
return False
x = (x-1) // 2
# Travel
if 0 <= x < field.dimensions[0] and 0 <= y < field.dimensions[1]:
self.cursor = (x, y)
return True
else:
return False
def print_hex(self, field):
r'''Helper function for `self.output` for the hexagonal gametype.
Print a hexagonal field in the area
0 to self.width-1 by 0 to self.height-2.
Also prints the "cursor".
It does not print the flags left text.
It will invoke `self.move_visible_area` to keep the "cursor" on
the screen. It will use `self.print_char` to print characters
on the screen.
0000000000111111111122222222223
0123456789012345678901234567890
00 / \ / \ / \ / \ / \ / \ / \
01 | X | X | X | X | X | X | X |
02 \ / \ / \ / \ / \ / \ / \ / \
03 | X | X | X | X | X | X | X |
04 / \ / \ / \ / \ / \ / \ / \ /
05 | X | X | X |(X)| X | X | X |
06 \ / \ / \ / \ / \ / \ / \ / \
07 | X | X | X | X | X | X | X |
08 \ / \ / \ / \ / \ / \ / \ /
'''
# Define functions that translates field coordinates into
# virtual screen coordinates.
def fx(x, y): return 2 * (2*x + 1 + (y % 2))
def fy(x, y): return 2*y + 1
# Move the visible area.
#
# Compute the virtual locations on the screen and real locations.
# Adjust the virtual coordinate of the visible area.
# Border = 1 cell.
x, y = self.cursor
self.move_visible_area(fx(x, y), fy(x, y), 6, 3)
# Print all cells in a field.
for cell in field.all_cells():
x = 2 * (2*cell[0] + 1 + (cell[1] % 2))
y = 2*cell[1] + 1
# Print blank grid.
# Roof:
self.print_char(x - 1, y - 1, 'grid', '/')
self.print_char(x, y - 1, 'grid', ' ')
self.print_char(x + 1, y - 1, 'grid', '\\')
# Left wall:
self.print_char(x - 2, y, 'grid', '|')
self.print_char(x - 1, y, 'grid', ' ')
# Right wall:
self.print_char(x + 2, y, 'grid', '|')
self.print_char(x + 1, y, 'grid', ' ')
# Floor:
self.print_char(x - 1, y + 1, 'grid', '\\')
self.print_char(x, y + 1, 'grid', ' ')
self.print_char(x + 1, y + 1, 'grid', '/')
# Print the actual cell.
self.print_cell(x, y, field, cell)
# Print the "cursor".
x, y = self.cursor
self.print_char(fx(x, y) - 1, fy(x, y), 'cursor-l')
self.print_char(fx(x, y) + 1, fy(x, y), 'cursor-r')
def mouse_travel_hex(self, x, y, field):
'''
'''
x += self.window_start[0]
y += self.window_start[1]
# Inverse transformation of x and y.
if x % 4 == 2 and y % 4 == 0 or x % 4 == 0 and y % 4 == 2:
y += 1 # Right above the target
if x % 4 == 2 and y % 4 == 2 or x % 4 == 0 and y % 4 == 0:
y -= 1 # Right below the target
if not y % 2:
return False # Misc place on horizontal border
if y % 4 == 3: # Unpush the pushed rows.
x -= 2
if not x % 4: # Vertical border
return False
y = y // 2
x = x // 4
# Travel
if 0 <= x < field.dimensions[0] and 0 <= y < field.dimensions[1]:
self.cursor = (x, y)
return True
else:
return False
def output(stream, content):
'''
Due to a bug syscalls may fail with EINTR after leaving curses mode.
Write `content` to `stream` and flush() without crashing.
Example:
output(sys.stdout, 'Hello world!\n')
The bug
=======
sys.stdin.readline() in `ask` dies with IOError and
errno=EINTR when the terminal gets resized after curses has
been de-initialized.
1: SIGWINCH is sent by the terminal when the screen has been
resized.
2: curses forgot to restore the signal handling of SIGWINCH
to the default of ignoring the signal.
NOTE: signal.getsignal(signal.SIGWINCH) incorrectly
returns signal.SIG_DFL. (Default is to be ignored.)
3: Python fails to handle EINTR when reading from stdin.
REFERENCES:
Issue 3949: https://bugs.python.org/issue3949
PEP 0457: https://www.python.org/dev/peps/pep-0475/
SIMULATION:
Function `bug1` in 'test.py'.
FIX #1 (caused new bug: Can't resize on later games/SIGWICH not reset):
Set signal handling of SIGWINCH to ignore.
SIGWINCH: Fixed by the solution.
SIGINT: Properly handled by Python. (Well tested.)
SIGTSTP: Default is STOP, seems to be at default.
Any other signal will probably not be caught and
IOError with errno=EINTR will therefore never be returned.
FIX #2 (0.2.17)
Accept that `IOError`s and `InterrputedError`s may be raised
by IO functions.
'''
def write():
stream.write(content)
def flush():
stream.flush()
for function in (write, flush):
i = 0
while True:
i += 1
try:
function()
except InterruptedError:
if i > 10**7:
raise
continue
except IOError as e:
if 'EINTR' in dir(errno):
if i > 10**7:
raise
if e.errno == errno.EINTR:
continue
raise
break
def convert_param(paramtype, s):
'''Convert user input (potentially incorrect text) to the proper type.
Convert the string `s` to the proper type.
Raises ValueError if `s` cannot be converted.
`paramtype` MUST be one of the recognised values:
'str': `s` is returned.
'yesno': "Yes" is True and "no" is False.
'dimension': An integer >= 4
'minecount': Two modes (automatic selection):
An integer >= 1 returned as an integer.
Or a percentage `str(float)+'%'` in
]0%, 100%[ returned as a float:
'gametype': Mapping with case-insensitive keys and
lower-case values:
'a', 'neumann' and '4' to 'neumann'
'b', 'hex', 'hexagonal' and '6' to 'hex'
'c', 'moore' and '8' to 'moore'
'reverse-minecount': `s` is an integer or a float and the
returned value is a string that can be
converted back to `s` with 'minecount'.
'''
if paramtype == 'str':
return s
elif paramtype == 'yesno':
if s.upper() in ('Y', 'YES'):
return True
elif s.upper() in ('N', 'NO'):
return False
else:
output(sys.stderr,'"Yes" or "no" please. (WITHOUT quotes.)\n')
raise ValueError
elif paramtype == 'dimension':
try:
value = int(s)
except ValueError:
# Easter egg.
#
# ~85.6% of English words contain 'a', 'c', 'm' or 'p'.
# All numbers under one thousand belongs to the ~14.4%.
#
# 194 of the numbers between 0 and 200 contain one or more of
# the letters 'n', 'f' and 'h'.
#
# But zero, two, six and twelve aren't included.
# So check for X and startswith('TW').
#
# Some special words may appear too, so let's remove them.
s = s.lower()
for word in ['and', 'percent', 'point', 'comma', 'decimal']:
s = s.replace(word, '')
S = s.upper()
if (
'A' not in S and 'C' not in S and 'M' not in S and
'P' not in S and ('N' in S or 'F' in S or 'H' in S
or 'X' in S or S.startswith('TW'))
):
output(sys.stderr, "Use digits.\n")
else:
output(sys.stderr,
'Invalid width or height;'
' "{0}" is not an integer.\n'.format(s)
)
raise ValueError
if value < 4:
output(sys.stderr, 'Lowest allowed width or height is 4.\n')
raise ValueError
return value
elif paramtype == 'minecount':
if len(s) == 0:
output(sys.stderr, 'No (empty) amount of mines specified.\n')
raise ValueError
if s[-1] == '%':
try:
value = float(s[:-1])/100
except ValueError:
output(sys.stderr,
"You can't have {0} percent of the cells to be mines;"
" {0} is not a number.\n".format(s)
)
raise ValueError
if value >= 1.0 or value <= 0.0:
output(sys.stderr,
'Percentage of the cells that will be mines'
' must be in ]0%, 100%[.\n'
)
raise ValueError
else:
try: