summaryrefslogtreecommitdiff
path: root/robots/cursesviewer.py
blob: b37a06a00012628ac4f8d07d064e54434078f174 (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
from itertools import cycle

from blessings import Terminal

from robots.utils import rate_limit

class Box:
    V = '│'
    H = '─'
    TL = '┌'
    TR = '┐'
    BL = '└'
    BR = '┘'

class CursesViewer:
    def __init__(self, game):
        self.game = game

        self.terminal = Terminal()

        colours = cycle('red blue green yellow magenta cyan'.split())
        self.player_colours = dict(zip(
            game.players.keys(),
            colours,
        ))
        self.player_colours['*'] = 'white'

    def draw_board(self):
        print(self.terminal.clear, end='')

        robots = {}
        for player, info in self.game.players.items():
            for x, y in info['robots']:
                robots[x, y] = player

        width = len(self.game.board[0]) * 2
        print(Box.TL + Box.H * width + Box.TR)

        for y, row in enumerate(self.game.board):
            output = []
            for x, cell in enumerate(row):
                value = '  '

                background = self.player_colours.get(cell)

                robot_owner = robots.get((x, y))
                if robot_owner:
                    foreground = self.player_colours[robot_owner]
                    if foreground == background:
                        foreground = 'white'

                    func = getattr(self.terminal, foreground)
                    value = func('<>')

                if background:
                    func = getattr(self.terminal, 'on_' + background)
                    value = func(value)

                output.append(value)
            print(Box.V + ''.join(output) + Box.V)

        print(Box.BL + Box.H * width + Box.BR)

    def run(self):
        limiter = rate_limit(10)

        self.draw_board()
        while not self.game.finished:
            next(limiter)

            self.game.next()
            self.draw_board()

        winners = self.game.finished
        if winners is True:
            print('Game ended in a draw.')
        else:
            print('Game won by:', ', '.join(winners))