-
Notifications
You must be signed in to change notification settings - Fork 2
/
dango.py
executable file
·593 lines (533 loc) · 21.1 KB
/
dango.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
#!/usr/bin/env python3
# from goban import Board
# from groups import *
# from goban import Board
# from nigiri import nigiri
# from game import *
from sys import argv, exit
import curses
from curses import wrapper
KOMI = 6.5
SIZE = 19
BLACK = -1
EMPTY = 0
WHITE = 1
MARGIN_X = 3
MARGIN_Y = 1
MESSAGE = (SIZE + 2, 2)
EMPTY = '·'
STONE = '●'
SPACE = ' '
VERSION = "0.4.2"
"""note that implementing curses will have breaking changes on API
this is also an opportunity to fix previous bad choices"""
def show_usage():
print("dango.py")
print("a goban for your terminal")
print("usage: python dango.py [options]")
print("Options:")
print(" -s, --size board size")
print(" -k, --komi game komi")
print(" -h, --help display this help message")
print(" -v, print version number.")
print(" -a, --about about dango")
print(" -c, --controls print version number.")
print(" -l, show licence.")
def flag_error():
print("One or more arguments are invalid.")
show_usage()
exit()
def logo():
print("""
dango
\033[0;30;43m 🮢 · · · · \033[0m
\033[0;30;43m · \033[0;31;43m●\033[0;30;43m · · · \033[0m
\033[0;30;43m · · \033[0;37;43m●\033[0;30;43m · · \033[0m
\033[0;30;43m · · · \033[0;32;43m●\033[0;30;43m · \033[0m
\033[0;30;43m · · · ·🮡 \033[0m
""")
# Check if flags present
i = 1
while i < len(argv):
arg = argv[i]
if arg == "-h" or arg == "--help":
show_usage()
exit()
elif arg == "-v":
print(f"version {VERSION}")
exit()
elif arg == "-a" or arg == "--about":
logo()
print(" issue or bug? \n @gsobell on github")
exit()
elif arg == "-l":
print("Under GPL3 licence.\n \
Full license distribuited \
with copy of software")
exit()
elif arg == "-c" or arg == "controls":
print("""Use vim or arrow keys to move,
space or enter to place a stone.
You can also use your mouse, double click to place a stone.
'p' to pass, 'u' to undo.""")
exit()
try:
if arg == "-s" or arg == "--pads":
SIZE = int(argv[i+1])
if SIZE < 1 or SIZE > 19:
raise ValueError
MESSAGE = (SIZE + 2, 2)
if arg == "-k" or arg == "--komi":
KOMI = float(argv[i+1])
if KOMI < 0:
raise ValueError
except ValueError:
flag_error()
i += 1
def curses_setup(stdscr):
stdscr.clear() # Clear the screen
curses.noecho() # Turn off echoing of keys
curses.cbreak() # Turn off normal tty line buffering
stdscr.keypad(True) # Enable keypad mode
curses.mousemask(True) # Enable mouse event reporting
curses.curs_set(0) # Hide cursor
curses.start_color() # Enable colors if supported
curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_YELLOW) # board B
curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_YELLOW) # board W
curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_GREEN) # select B
curses.init_pair(4, curses.COLOR_WHITE, curses.COLOR_GREEN) # select W
curses.init_pair(5, curses.COLOR_WHITE, curses.COLOR_BLACK) # background
curses.init_pair(6, curses.COLOR_BLACK, curses.COLOR_RED) # error
curses.init_pair(7, curses.COLOR_RED, curses.COLOR_YELLOW) # logo
curses.init_pair(8, curses.COLOR_GREEN, curses.COLOR_YELLOW) # logo
stdscr.bkgd(' ', curses.color_pair(5))
stdscr.refresh()
def place_piece(y, x, color, stones, moves, captures, stdscr):
"""recieves curses (y,x) and draws on board.
also handle group capture as needed."""
if color is WHITE:
stdscr.addstr(y, x, STONE + SPACE, curses.color_pair(2))
stones.white.append((y, x))
if color is BLACK:
stdscr.addstr(y, x, STONE + SPACE, curses.color_pair(1))
stones.black.append((y, x))
if (y, x) in stones.empty:
stones.empty.remove((y, x))
captured = stones.capture_check(y, x, color)
if captured:
for k in captured:
captures.append(k)
stones.remove(stdscr, k)
else:
captures.append(None)
moves.append((y, x))
stdscr.refresh()
def replace_piece(y, x, color, stones, moves, captures, stdscr):
"""Stone placement of `n`, where stones.black and stones.white
are not changed, and no capture is done"""
if color is WHITE:
stdscr.addstr(y, x, STONE + SPACE, curses.color_pair(2))
elif color is BLACK:
stdscr.addstr(y, x, STONE + SPACE, curses.color_pair(1))
elif color is EMPTY:
stdscr.addstr(y, x, EMPTY + SPACE, curses.color_pair(1))
stdscr.refresh()
class Stones:
def __init__(self):
"""Stones reflect (y,x) cordinates of curses board.
All methods must be cordinate offset agnostic."""
self.white = []
self.black = []
self.empty = [(y, x) for y in range(1, SIZE + 1)
for x in range(3, SIZE*2 + 2)] # updated if capture
self.total = set(self.empty) # immutable
def legal_placement(self, y, x, color, captures) -> bool:
if (y, x) in self.white or (y, x) in self.black:
return False
if self.capture_check(y, x, color):
if self.is_ko(y, x, color, captures):
return False
return True
return self.liberty_count(y, x, color)
def is_ko(self, y, x, color, captures) -> bool:
last_capture = captures[-1] if captures else None
if last_capture and len(last_capture) == 1 and (y, x) in last_capture:
return True
return False
def capture_check(self, y, x, color):
"""Checks if playing color at (y, x) captures neighbor
(any neighbor has one remaining liberty)"""
if color == WHITE:
same = self.white
other = self.black
else:
same = self.black
other = self.white
captured = []
stones = [k for k in self.adjacent(y, x) if k in other]
for stone in stones:
q = [k for k in self.adjacent(*stone) if k != (y, x)]
count = 0
visited = [(y, x), stone]
while q:
curr = q.pop()
visited.append(curr)
if curr in other:
q.extend([k for k in self.adjacent(*curr)
if k not in visited])
continue
elif curr in same:
continue
elif curr in self.empty:
count += 1
if not count:
captured.append([k for k in visited if k in other])
return captured if captured else None
def liberty_count(self, y, x, color) -> int:
"""True if group @color including @(y,x) has liberties"""
checked = [(y, x)]
count = 0
same = self.white if color == WHITE else self.black
q = self.adjacent(y, x)
while q:
curr = q.pop()
checked.append(curr)
if curr in self.empty:
count += 1
elif curr in same:
q.extend([k for k in
self.adjacent(curr[0], curr[1])
if k not in checked])
else:
continue
return count
def remove(self, stdscr, to_remove) -> None:
"""Removes group from board containing stone (y, x)"""
self.empty.extend(to_remove)
to_remove = set(to_remove)
self.white = list(set(self.white) - to_remove)
self.black = list(set(self.black) - to_remove)
for stone in to_remove:
stdscr.addstr(stone[0], stone[1], EMPTY, curses.color_pair(1))
def adjacent(self, y, x):
a = [(y + 1, x), (y - 1, x),
(y, x + 2), (y, x - 2)]
return list(set(a) & set(self.total))
def player_color(self, y, x, color):
if ((y, x) in self.white) or color == 1:
return self.white, self.black
elif ((y, x) in self.black) or color == -1:
return self.black, self.white
def draw_A1(stdscr):
for k in range(0, SIZE):
if k < 8: # A1 scheme does not have 'i' to avoid confusion
stdscr.addstr(0, k*2 + MARGIN_X, chr(65 + k), curses.color_pair(5))
stdscr.addstr(SIZE + 1, k*2 + MARGIN_X,
chr(65 + k), curses.color_pair(5))
if k >= 8:
stdscr.addstr(0, k*2 + MARGIN_X,
chr(65 + k + 1), curses.color_pair(5))
stdscr.addstr(SIZE + 1, k*2 + MARGIN_X,
chr(65 + k + 1), curses.color_pair(5))
for k in range(0, SIZE):
stdscr.addstr(k + 1, 0, f"{str(SIZE - k):>2}", curses.color_pair(5))
stdscr.addstr(k + 1, SIZE * 2 + MARGIN_X + 1,
f"{str(SIZE - k):<2}", curses.color_pair(5))
def draw_board(stdscr):
for j in range(1, SIZE + 1):
for k in range(1, SIZE + 1):
stdscr.addstr(j, k*2 + 1, EMPTY + SPACE, curses.color_pair(1))
def get_move(c, y, x, stdscr):
"""Given y, x, getch(), returns the new (y, x) or None if no change"""
if c == curses.KEY_LEFT or c == ord('h'):
x -= 2
if x > SIZE*2:
x = MARGIN_X
if x < MARGIN_X:
x = SIZE*2 + 1
elif c == curses.KEY_RIGHT or c == ord('l'):
x += 2
if x > SIZE*2 + 2:
x = MARGIN_X
if x < MARGIN_X:
x = SIZE*2 + 1
elif c == curses.KEY_UP or c == ord('k'):
y -= 1
if y > SIZE:
y = 1
if y < 1:
y = SIZE
elif c == curses.KEY_DOWN or c == ord('j'):
y += 1
if y > SIZE:
y = 1
if y < 1:
y = SIZE
else:
# stdscr.chgat(y, x, 2, curses.color_pair(6))
stdscr.addstr(SIZE + 1, 3, "Not a valid input key",
curses.color_pair(6))
return (y, x)
def draw_cursor(new_cursor, old_cursor, stones, stdscr):
"""Draws the new cursor, and returns old cursor to bg color"""
y, x = new_cursor
if old_cursor in stones.white:
stdscr.chgat(*old_cursor, 2, curses.color_pair(2))
else:
stdscr.chgat(*old_cursor, 2, curses.color_pair(1))
if (y, x) in stones.white:
stdscr.chgat(y, x, 2, curses.color_pair(4))
else:
stdscr.chgat(y, x, 2, curses.color_pair(3))
def yx_to_a1(y, x):
return int(x/2), 20 - y
def error_out(stdscr, message):
stdscr.addstr(*MESSAGE, message, curses.color_pair(6))
stdscr.refresh()
def standard_out(stdscr, message):
stdscr.addstr(*MESSAGE, message, curses.color_pair(5))
stdscr.refresh()
def clear_message(stdscr):
"""Clears the previous message"""
for k in range(curses.COLS - 1):
stdscr.addstr(MESSAGE[0], k, " ",
curses.color_pair(5)) # clear curr message
stdscr.refresh()
def play(stdscr):
moves = [] # moves (y,x), for undo. None if pass
captures = [] # list of stones removed, per move
n_toggle = 0
stones = Stones()
color = -1
draw_A1(stdscr)
draw_board(stdscr)
stdscr.getch()
update_to_play = True
y, x = 3, SIZE*2 - 3 # top right corner
while "game loop":
while "input loop":
old_cursor = y, x
c = stdscr.getch()
if c == 10 or c == ord(" "):
if stones.legal_placement(y, x, color, captures):
place_piece(y, x, color, stones, moves, captures, stdscr)
color *= -1
update_to_play = True
else:
error_out(stdscr, "Not a valid move")
break
elif c == curses.KEY_MOUSE:
click = curses.getmouse()
if (1 <= click[2] <= SIZE) and (MARGIN_X <=
click[1] +
click[1] % 2 - 1 <
SIZE * 2 + MARGIN_X):
x = click[1] + click[1] % 2 - 1
y = click[2]
if ((old_cursor[0] == y) and (x <=
old_cursor[1] <= x + 1)):
if stones.legal_placement(y, x, color, captures):
place_piece(y, x, color, stones,
moves, captures, stdscr)
color *= -1
else:
error_out(stdscr, "Not a valid move")
break
else:
error_out(stdscr, "Not a valid place to click")
elif c == ord(":"):
pass # vim style command in
elif c == ord("P") or c == ord("p"):
standard_out(stdscr, "Pass.")
moves.append(None)
captures.append(None)
color *= -1
elif c == ord("N") or c == ord("n"): # toggle kifu
if not moves:
break
if n_toggle:
for group in captures: # redraw captures first
if group:
for move in group:
replace_piece(move[0], move[1], EMPTY,
stones, moves, captures, stdscr)
for move in moves:
if (not move) or (move in stones.empty):
continue
if move in stones.white:
replace_piece(move[0], move[1], WHITE,
stones, moves, captures, stdscr)
if move in stones.black:
replace_piece(move[0], move[1], BLACK,
stones, moves, captures, stdscr)
n_toggle = 0
else:
i = 1
for move in moves:
if move in stones.black:
stdscr.addstr(move[0], move[1], str(i),
curses.color_pair(1))
elif move in stones.white:
stdscr.addstr(move[0], move[1], str(i),
curses.color_pair(2))
else: # captured stones
stdscr.addstr(move[0], move[1], str(i),
curses.color_pair(7))
i += 1
n_toggle = 1
elif c == ord("U") or c == ord("u"):
standard_out(stdscr, "Undo.")
if not moves:
error_out(stdscr, "No move to undo.")
break
undo = moves.pop()
replace = captures.pop()
if undo:
stones.empty.append(undo)
stdscr.addstr(undo[0], undo[1], EMPTY +
SPACE, curses.color_pair(1))
if undo in stones.white:
stones.white.remove(undo)
if replace:
for piece in replace:
place_piece(piece[0], piece[1], BLACK,
stones, moves, captures, stdscr)
elif undo in stones.black:
stones.black.remove(undo)
if replace:
for piece in replace:
place_piece(piece[0], piece[1], WHITE,
stones, moves, captures, stdscr)
else:
standard_out(stdscr, "Undo pass.")
color *= -1
elif c == ord("q"):
standard_out(
stdscr, "Would you like to exit? (Press 'q' again)")
if stdscr.getch() == ord("q"):
exit()
else:
y, x = get_move(c, y, x, stdscr)
draw_cursor((y, x), old_cursor, stones, stdscr)
# A1 = yx_to_a1(y, x)
# standard_out(stdscr, f"cords are: {A1}")
# standard_out(stdscr, f"click is: {click}")
# standard_out(stdscr, f"(y,x) is: {y, x}")
standard_out(
stdscr, f"{'White' if color == 1 else 'Black'} to play." +
((curses.COLS - 15) * ' ')) # clears old message
stdscr.refresh()
def menu(stdscr):
global SIZE
global KOMI
global MESSAGE
curses.curs_set(0) # Hide the cursor
stdscr.clear()
# Define menu items and their associated values
menu_items = [
"Start",
"Size",
"Komi",
"Players",
"Help",
"Exit"
]
screen_height, screen_width = stdscr.getmaxyx()
center_y = screen_height // 2
center_x = screen_width // 2
square_height = 9
square_width = square_height * 2
square_y = center_y - (square_height // 2)
square_x = center_x - (square_width // 2)
for y in range(square_y, square_y + square_height):
for x in range(square_x, square_x + square_width, 2):
stdscr.addstr(y, x, EMPTY + SPACE, curses.color_pair(1))
stdscr.addstr(square_y + 1, square_x + 10, "dango", curses.color_pair(1) | curses.A_BOLD)
stdscr.addstr(square_y + 2, square_x + 10, STONE, curses.color_pair(7))
stdscr.addstr(square_y + 3, square_x + 12, STONE, curses.color_pair(2))
stdscr.addstr(square_y + 4, square_x + 14, STONE, curses.color_pair(8))
menu_y = center_y - (len(menu_items) // 2)
for idx, item in enumerate(menu_items):
x = center_x + (square_width // 2) + 4
y = menu_y + idx
stdscr.addstr(y, x, f" {item}")
menu_len = len(menu_items)
max_len = len(max(menu_items, key=len))
selected_item = 0
selected_value = None
tally = 0
while True:
if tally == 3: # activate usage threshold
stdscr.addstr(square_y + 10, square_x, "Use up-down to select item,", curses.color_pair(0))
stdscr.addstr(square_y + 11, square_x, "left-right to change value, ", curses.color_pair(0))
stdscr.addstr(square_y + 12, square_x, "and space or enter to continue.", curses.color_pair(0))
tally = 0
stdscr.addstr(center_y + (len(menu_items) // 2) + 2, 0, " " * screen_width)
menu_values = [None, SIZE, KOMI, None, None, None] # refresh SIZE, KOMI
for idx, item in enumerate(menu_items):
x = center_x + (square_width // 2) + 4
y = menu_y + idx
if idx == selected_item:
if selected_item == 1 or selected_item == 2: # SIZE or KOMI
stdscr.addstr(y, x, " " * 5)
stdscr.addstr(y, x, f" {menu_values[selected_item]}", curses.A_BLINK | curses.A_BOLD)
stdscr.addstr(y, x - 2, ">")
stdscr.addstr(y, x + len(str(menu_values[selected_item])) + 3, "<")
else:
# stdscr.addstr(y, x, f" {item}")
stdscr.addstr(y, x - 2, ">")
stdscr.addstr(y, x, f" {item}", curses.color_pair(0) | curses.A_BOLD)
stdscr.addstr(y, x + len(item) + 3, "<")
else:
stdscr.addstr(y, x, f" {item} ")
stdscr.addstr(y, x - 2, " ")
stdscr.addstr(y, x + len(item) + 3, " ")
stdscr.refresh()
c = stdscr.getch()
if c == curses.KEY_UP:
selected_item = (selected_item - 1) % menu_len
selected_value = menu_values[selected_item]
elif c == curses.KEY_DOWN:
selected_item = (selected_item + 1) % menu_len
selected_value = menu_values[selected_item]
elif c == curses.KEY_LEFT:
if selected_item == 1:
SIZE = max(1, SIZE - 1)
if selected_item == 2:
KOMI = max(0, KOMI - 1)
elif c == curses.KEY_RIGHT:
if selected_item == 1:
SIZE += 1
if selected_item == 2:
KOMI += 0.5
elif c == 10 or c == ord(" "):
for y in range(square_y + 10, square_y + 13): # clear help/usage
stdscr.move(y, square_x)
stdscr.clrtoeol()
if selected_item == 0:
MESSAGE = (SIZE + 2, 2)
break
elif selected_item == menu_len -1 :
exit()
elif selected_item == 3:
stdscr.addstr(square_y + 10, square_x, "Only two-player is currently enabled.", curses.color_pair(0))
elif selected_item == 4:
stdscr.addstr(square_y + 10, square_x, "Run 'dango -h' for help.", curses.color_pair(0))
elif c == ord('q'):
exit()
else:
tally += 1
def main(stdscr):
curses_setup(stdscr)
menu(stdscr)
stdscr.clear()
play(stdscr)
if __name__ == "__main__":
try:
wrapper(main)
except KeyboardInterrupt:
print('Thank you for the game.')
except curses.error:
print("Terminal not large enough, resize and try again.")
# except:
# print("Something went wrong. Let us know, we'll try to fix it!")