-
Notifications
You must be signed in to change notification settings - Fork 1
/
morris.py
576 lines (511 loc) · 22.5 KB
/
morris.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
__filename__ = "morris.py"
__author__ = "Bob Mottram"
__license__ = "AGPL3+"
__version__ = "1.0.0"
__maintainer__ = "Bob Mottram"
__email__ = "[email protected]"
__status__ = "Production"
__module_group__ = "Tabletop Games"
import os
VALID_MORRIS_BOARD_LOCATIONS = [
'a1', 'd1', 'g1',
'b2', 'd2', 'f2',
'c3', 'd3', 'e3',
'a4', 'b4', 'c4', 'e4', 'f4', 'g4',
'c5', 'd5', 'e5',
'b6', 'd6', 'f6',
'a7', 'd7', 'g7'
]
def get_morris_board_name(players: {}, id: int, rooms: {},
items: {}, items_db: {}) -> str:
"""Returns the name of the morris board if there is one in the room
This then corresponds to the subdirectory within morrisboards, where
icons exist
"""
rid = players[id]['room']
for _, itemobj in items.items():
if itemobj['room'] != rid:
continue
if items_db[itemobj['id']].get('morrisBoardName'):
return items_db[itemobj['id']]['morrisBoardName']
return None
def _morris_board_in_room(players: {}, id, rooms: {}, items: {},
items_db: {}) -> int:
"""Returns the item ID if there is a Morris board in the room
"""
rid = players[id]['room']
for item_id, itemobj in items.items():
if itemobj['room'] != rid:
continue
if 'morris' in items_db[itemobj['id']]['game'].lower():
return item_id
return None
def _no_of_mills(side: str, board: str) -> int:
"""Count the number of mills for the side
"""
if side == 'white':
piece = '●'
else:
piece = '○'
mills_ctr = 0
# vertical
if board[0] == piece and board[9] == piece and board[21] == piece:
mills_ctr += 1
if board[3] == piece and board[10] == piece and board[18] == piece:
mills_ctr += 1
if board[6] == piece and board[11] == piece and board[15] == piece:
mills_ctr += 1
if board[1] == piece and board[4] == piece and board[7] == piece:
mills_ctr += 1
if board[16] == piece and board[19] == piece and board[22] == piece:
mills_ctr += 1
if board[8] == piece and board[12] == piece and board[17] == piece:
mills_ctr += 1
if board[5] == piece and board[13] == piece and board[20] == piece:
mills_ctr += 1
if board[2] == piece and board[14] == piece and board[23] == piece:
mills_ctr += 1
# horizontal
if board[0] == piece and board[1] == piece and board[2] == piece:
mills_ctr += 1
if board[3] == piece and board[4] == piece and board[5] == piece:
mills_ctr += 1
if board[6] == piece and board[7] == piece and board[8] == piece:
mills_ctr += 1
if board[9] == piece and board[10] == piece and board[11] == piece:
mills_ctr += 1
if board[12] == piece and board[13] == piece and board[14] == piece:
mills_ctr += 1
if board[15] == piece and board[16] == piece and board[17] == piece:
mills_ctr += 1
if board[18] == piece and board[19] == piece and board[20] == piece:
mills_ctr += 1
if board[21] == piece and board[22] == piece and board[23] == piece:
mills_ctr += 1
return mills_ctr
def _morris_board_set(board: str, index: int, piece: str) -> str:
return board[:index] + piece + board[(index + 1):]
def morris_move(move_description: str,
players: {}, id, mud, rooms: {},
items: {}, items_db: {}) -> None:
game_item_id = _morris_board_in_room(players, id, rooms, items, items_db)
if not game_item_id:
mud.send_message(id, '\nThere are no Morris board here.\n')
return
if not items[game_item_id].get('gameState'):
items[game_item_id]['gameState'] = {}
turn = 'white'
if items[game_item_id]['gameState'].get('morrisTurn'):
turn = items[game_item_id]['gameState']['morrisTurn']
else:
items[game_item_id]['gameState']['morrisTurn'] = turn
white_counters = 9
if items[game_item_id]['gameState'].get('morrisWhite'):
white_counters = int(items[game_item_id]['gameState']['morrisWhite'])
black_counters = 9
if items[game_item_id]['gameState'].get('morrisBlack'):
black_counters = int(items[game_item_id]['gameState']['morrisBlack'])
if not items[game_item_id]['gameState'].get('millsWhite'):
items[game_item_id]['gameState']['millsWhite'] = 0
if not items[game_item_id]['gameState'].get('millsBlack'):
items[game_item_id]['gameState']['millsBlack'] = 0
if items[game_item_id]['gameState'].get('morris'):
board = items[game_item_id]['gameState']['morris']
else:
board = '·' * 24
items[game_item_id]['gameState']['morris'] = board
board_name = get_morris_board_name(players, id, rooms, items, items_db)
# check for a win
if white_counters == 0 and black_counters == 0:
if _morris_pieces('white', board) <= 2 or \
_morris_pieces('black', board) <= 2:
show_morris_board(board_name, players, id, mud, rooms,
items, items_db)
return
if _no_of_mills('black', board) > \
items[game_item_id]['gameState']['millsBlack']:
show_morris_board(board_name, players, id, mud, rooms, items, items_db)
return
if _no_of_mills('white', board) > \
items[game_item_id]['gameState']['millsWhite']:
show_morris_board(board_name, players, id, mud, rooms, items, items_db)
return
move_description = \
move_description.lower().replace('.', ' ').replace(',', ' ').strip()
words = move_description.split()
board_move = []
for wrd in words:
if len(wrd) == 2:
if wrd[1].isdigit():
if ord(wrd[0]) >= ord('a') and \
ord(wrd[0]) <= ord('g') and \
int(wrd[1]) >= 1 and \
int(wrd[1]) <= 7:
if wrd in VALID_MORRIS_BOARD_LOCATIONS:
board_move.append(wrd)
if len(wrd) == 4:
if wrd[1].isdigit() and wrd[3].isdigit():
if ord(wrd[0]) >= ord('a') and \
ord(wrd[0]) <= ord('g') and \
int(wrd[1]) >= 1 and \
int(wrd[1]) <= 7 and \
ord(wrd[2]) >= ord('a') and \
ord(wrd[2]) <= ord('g') and \
int(wrd[3]) >= 1 and \
int(wrd[4]) <= 7:
if wrd[:2] in VALID_MORRIS_BOARD_LOCATIONS and \
wrd[2:] in VALID_MORRIS_BOARD_LOCATIONS:
board_move.append(wrd[:2])
board_move.append(wrd[2:])
if len(board_move) == 0 or len(board_move) > 2:
mud.send_message(id, "\nThat's not a valid move.\n")
return
if len(board_move) == 1:
# single move to place a counter
index = 0
for loc in VALID_MORRIS_BOARD_LOCATIONS:
if loc == board_move[0]:
if board[index] == '·':
if turn == 'white':
if white_counters > 0:
board = _morris_board_set(board, index, '●')
white_counters -= 1
game_state = items[game_item_id]['gameState']
game_state['morrisWhite'] = white_counters
game_state['morris'] = board
game_state['morrisTurn'] = 'black'
else:
mud.send_message(id, '\nAll your counters ' +
'have been placed.\n')
else:
if black_counters > 0:
board = _morris_board_set(board, index, '○')
black_counters -= 1
game_state = items[game_item_id]['gameState']
game_state['morrisBlack'] = black_counters
game_state['morris'] = board
game_state['morrisTurn'] = 'white'
else:
mud.send_message(id, '\nAll your counters ' +
'have been placed.\n')
break
index += 1
else:
if turn == 'white' and white_counters > 0:
mud.send_message(id, '\nPlace your counters first before ' +
'moving any of them.\n')
return
elif turn == 'black' and black_counters > 0:
mud.send_message(id, '\nPlace your counters first before ' +
'moving any of them.\n')
return
# move a counter from one place to another
if board_move[0] == board_move[1]:
mud.send_message(id, '\nSpecify coordinates to move ' +
'from and to.\n')
return
if board_move[0][0] != board_move[1][0] and \
board_move[0][1] != board_move[1][1]:
mud.send_message(id, '\nYou can only move vertically ' +
'or horizontally.\n')
return
from_index = 0
for loc in VALID_MORRIS_BOARD_LOCATIONS:
if loc == board_move[0]:
if turn == 'white' and board[from_index] != '●':
mud.send_message(id, "\nThere isn't a counter at " +
loc + '\n')
return
if turn == 'black' and board[from_index] != '○':
mud.send_message(id, "\nThere isn't a counter at " +
loc + '\n')
return
break
from_index += 1
to_index = 0
for loc in VALID_MORRIS_BOARD_LOCATIONS:
if loc == board_move[1]:
if board[to_index] != '':
mud.send_message(id, "\nThere is already a counter at " +
loc + '\n')
return
if turn == 'white':
board = _morris_board_set(board, to_index, '●')
items[game_item_id]['gameState']['morrisTurn'] = 'black'
else:
board = _morris_board_set(board, to_index, '○')
items[game_item_id]['gameState']['morrisTurn'] = 'white'
board = _morris_board_set(board, from_index, '·')
items[game_item_id]['gameState']['morris'] = board
break
to_index += 1
show_morris_board(board_name, players, id, mud, rooms, items, items_db)
def _morris_pieces(side: str, board: str) -> int:
ctr = 0
if side == 'white':
for piece in board:
if piece == '●':
ctr += 1
else:
for piece in board:
if piece == '○':
ctr += 1
return ctr
def reset_morris_board(players: {}, id: int, mud, rooms: {},
items: {}, items_db: {}) -> None:
game_item_id = _morris_board_in_room(players, id, rooms, items, items_db)
if not game_item_id:
mud.send_message(id, '\nThere are no Morris board here.\n')
return
if not items[game_item_id].get('gameState'):
items[game_item_id]['gameState'] = {}
board_name = get_morris_board_name(players, id, rooms, items, items_db)
board = '·' * 24
items[game_item_id]['gameState']['morris'] = board
items[game_item_id]['gameState']['morrisWhite'] = 9
items[game_item_id]['gameState']['millsWhite'] = 0
items[game_item_id]['gameState']['morrisBlack'] = 9
items[game_item_id]['gameState']['millsBlack'] = 0
items[game_item_id]['gameState']['morrisTurn'] = 'white'
show_morris_board(board_name, players, id, mud, rooms, items, items_db)
def _board_location_indexes(board_name: str) -> {}:
"""Returns a dictionary containing board coordinates for each index
"""
locations_filename = 'morrisboards/' + board_name + '/locations.txt'
if not os.path.isfile(locations_filename):
print('No morris locations file: ' + locations_filename)
return None
index = 0
locations = {}
# read the locations file
try:
with open(locations_filename, "r", encoding='utf-8') as fp_loc:
lines = fp_loc.readlines()
for horizontal in lines:
if ' ' not in horizontal:
continue
coords = horizontal.strip().split(' ')
for locn in coords:
if ',' not in locn:
continue
x_co = locn.split(',')[0].strip()
y_co = locn.split(',')[1].strip()
if x_co.isdigit() and y_co.isdigit():
locations[index] = [int(x_co), int(y_co)]
index += 1
except OSError:
print('EX: _board_location_indexes ' + locations_filename)
if index != 24:
print('Invalid morris locations file: ' + locations_filename)
print('Indexes: ' + str(index))
print('locations: ' + str(locations))
return None
return locations
def _show_morris_board_as_html(board_name: str,
players: {}, id: int, mud, rooms: {},
items: {}, items_db: {}) -> None:
"""Shows the board as html for the web interface
"""
locations = _board_location_indexes(board_name)
if not locations:
mud.send_message(id, '\nSomething went wrong loading morris ' +
'board files.\n')
return
game_item_id = _morris_board_in_room(players, id, rooms, items, items_db)
if not game_item_id:
mud.send_message(id, '\nThere are no Morris board here.\n')
return
board_dir = 'morrisboards/' + board_name + '/'
if not items[game_item_id].get('gameState'):
items[game_item_id]['gameState'] = {}
if items[game_item_id]['gameState'].get('morris'):
board = items[game_item_id]['gameState']['morris']
else:
board = '·' * 24
items[game_item_id]['gameState']['morris'] = board
if not items[game_item_id]['gameState'].get('millsWhite'):
items[game_item_id]['gameState']['millsWhite'] = 0
if not items[game_item_id]['gameState'].get('millsBlack'):
items[game_item_id]['gameState']['millsBlack'] = 0
board_html = '<div class="parent">'
board_html += \
'<img class="morrisboard" src="' + board_dir + 'board.jpg" />'
counter_width = 8
counter_width_half = counter_width / 2
for i in range(24):
x_co = int(locations[i][0])
y_co = int(locations[i][1])
if board[i] == '○':
board_html += \
'<img src="' + board_dir + 'player1.png" ' \
'style="position:absolute;' + \
'width:' + str(counter_width) + '%;' + \
'left:' + \
str(int((x_co * 100 / 1024) - counter_width_half)) + '%;' + \
'top:' + \
str(int((y_co * 100 / 1024) - counter_width_half)) + '%;' + \
'" />'
elif board[i] == '●':
board_html += \
'<img src="' + board_dir + 'player2.png" ' \
'style="position:absolute;' + \
'width:' + str(counter_width) + '%;' + \
'left:' + \
str(int((x_co * 100 / 1024) - counter_width_half)) + '%;' + \
'top:' + \
str(int((y_co * 100 / 1024) - counter_width_half)) + '%;' + \
'" />'
board_html += '</div>\n'
mud.send_game_board(id, board_html)
white_counters = 9
if items[game_item_id]['gameState'].get('morrisWhite'):
white_counters = int(items[game_item_id]['gameState']['morrisWhite'])
black_counters = 9
if items[game_item_id]['gameState'].get('morrisBlack'):
black_counters = int(items[game_item_id]['gameState']['morrisBlack'])
if white_counters == 0 and black_counters == 0:
if _morris_pieces('white', board) <= 2:
mud.send_message(id, 'Black wins\n')
return
if _morris_pieces('black', board) <= 2:
mud.send_message(id, 'White wins\n')
return
if _no_of_mills('black', board) > \
items[game_item_id]['gameState']['millsBlack']:
mud.send_message(id, 'Black has a mill. Take a white counter.\n')
return
if _no_of_mills('white', board) > \
items[game_item_id]['gameState']['millsWhite']:
mud.send_message(id, 'White has a mill. Take a black counter.\n')
return
if not items[game_item_id]['gameState'].get('morrisTurn'):
items[game_item_id]['gameState']['morrisTurn'] = 'white'
mud.send_message(id, items[game_item_id]['gameState']['morrisTurn'] +
"'s move\n")
def show_morris_board(board_name: str,
players: {}, id: int, mud, rooms: {},
items: {}, items_db: {}) -> None:
"""Draws the morris board
"""
if mud.player_using_web_interface(id):
_show_morris_board_as_html(board_name, players, id, mud, rooms,
items, items_db)
return
game_item_id = _morris_board_in_room(players, id, rooms, items, items_db)
if not game_item_id:
mud.send_message(id, '\nThere are no Morris board here.\n')
return
if not items[game_item_id].get('gameState'):
items[game_item_id]['gameState'] = {}
if items[game_item_id]['gameState'].get('morris'):
board = items[game_item_id]['gameState']['morris']
else:
board = '·' * 24
items[game_item_id]['gameState']['morris'] = board
if not items[game_item_id]['gameState'].get('millsWhite'):
items[game_item_id]['gameState']['millsWhite'] = 0
if not items[game_item_id]['gameState'].get('millsBlack'):
items[game_item_id]['gameState']['millsBlack'] = 0
board_str = '\n'
board_str += ' 7 ' + board[21] + '─────' + board[22] + \
'─────' + board[23] + '\n'
board_str += ' 6 │ ' + board[18] + '───' + board[19] + \
'───' + board[20] + ' │\n'
board_str += ' 5 │ │ ' + board[15] + '─' + board[16] + \
'─' + board[17] + ' │ │\n'
board_str += ' 4 ' + board[9] + '-' + board[10] + '-' + \
board[11] + ' ' + board[12] + '-' + board[13] + '-' + \
board[14] + '\n'
board_str += ' 3 │ │ ' + board[6] + '─' + board[7] + \
'─' + board[8] + ' │ │\n'
board_str += ' 2 │ ' + board[3] + '───' + board[4] + \
'───' + board[5] + ' │\n'
board_str += ' 1 ' + board[0] + '─────' + board[1] + \
'─────' + board[2] + '\n'
board_str += ' a b c d e f g\n'
mud.send_game_board(id, board_str)
white_counters = 9
if items[game_item_id]['gameState'].get('morrisWhite'):
white_counters = int(items[game_item_id]['gameState']['morrisWhite'])
black_counters = 9
if items[game_item_id]['gameState'].get('morrisBlack'):
black_counters = int(items[game_item_id]['gameState']['morrisBlack'])
if white_counters == 0 and black_counters == 0:
if _morris_pieces('white', board) <= 2:
mud.send_message(id, 'Black wins\n')
return
if _morris_pieces('black', board) <= 2:
mud.send_message(id, 'White wins\n')
return
if _no_of_mills('black', board) > \
items[game_item_id]['gameState']['millsBlack']:
mud.send_message(id, 'Black has a mill. Take a white counter.\n')
return
if _no_of_mills('white', board) > \
items[game_item_id]['gameState']['millsWhite']:
mud.send_message(id, 'White has a mill. Take a black counter.\n')
return
if not items[game_item_id]['gameState'].get('morrisTurn'):
items[game_item_id]['gameState']['morrisTurn'] = 'white'
mud.send_message(id, items[game_item_id]['gameState']['morrisTurn'] +
"'s move\n")
def take_morris_counter(take_description: str,
players: {}, id: int, mud, rooms: {},
items: {}, items_db: {}) -> None:
"""Takes an opponent counter from the board
"""
game_item_id = _morris_board_in_room(players, id, rooms, items, items_db)
if not game_item_id:
mud.send_message(id, '\nThere are no Morris board here.\n')
return
board_name = get_morris_board_name(players, id, rooms, items, items_db)
if not items[game_item_id].get('gameState'):
items[game_item_id]['gameState'] = {}
if items[game_item_id]['gameState'].get('morris'):
board = items[game_item_id]['gameState']['morris']
else:
board = '·' * 24
items[game_item_id]['gameState']['morris'] = board
take_description = \
take_description.lower().replace('.', ' ').replace(',', ' ').strip()
words = take_description.split()
board_move = []
for wrd in words:
if len(wrd) != 2:
continue
if not wrd[1].isdigit():
continue
if ord(wrd[0]) >= ord('a') and ord(wrd[0]) <= ord('g') and \
int(wrd[1]) >= 1 and int(wrd[1]) <= 7:
if wrd in VALID_MORRIS_BOARD_LOCATIONS:
board_move.append(wrd)
if len(board_move) != 1:
mud.send_message(id, '\nSpecify the coordinate of the ' +
'counter to be taken.\n')
return
if _no_of_mills('black', board) > \
items[game_item_id]['gameState']['millsBlack']:
index = 0
for loc in VALID_MORRIS_BOARD_LOCATIONS:
if loc == board_move[0]:
if board[index] == '●':
items[game_item_id]['gameState']['millsBlack'] = \
_no_of_mills('black', board)
board = _morris_board_set(board, index, '·')
items[game_item_id]['gameState']['morris'] = board
show_morris_board(board_name,
players, id, mud, rooms, items, items_db)
index += 1
elif (_no_of_mills('white', board) >
items[game_item_id]['gameState']['millsWhite']):
index = 0
for loc in VALID_MORRIS_BOARD_LOCATIONS:
if loc == board_move[0]:
if board[index] == '○':
items[game_item_id]['gameState']['millsWhite'] = \
_no_of_mills('white', board)
board = _morris_board_set(board, index, '·')
items[game_item_id]['gameState']['morris'] = board
show_morris_board(board_name,
players, id, mud, rooms, items, items_db)
index += 1