summaryrefslogtreecommitdiff
path: root/robots/game.py
blob: 9b5c339307b1fbaa9a3c8baa2f5606d8099237ef (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
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
from collections import defaultdict, deque
from contextlib import contextmanager
from copy import deepcopy
from random import random
import time
import traceback

from robots.constants import Action, City, DIRECTIONS, Energy, ENERGY_BY_ACTION
from robots.state import GameState
from robots.utils import iter_board

@contextmanager
def protected(value, name):
    value_copy = deepcopy(value)
    try:
        yield value_copy
    finally:
        if value_copy != value:
            raise RuntimeError('Protected value %s was modified.' % name)

def extract_spawn_points(map_):
    points = []

    for x, y, cell in iter_board(map_):
        try:
            n = int(cell)
        except ValueError:
            pass
        else:
            points.append((n, (x, y)))
            map_[y][x] = City.NORMAL

    points.sort()
    return [point for n, point in points]

class Game:
    def __init__(self, map_):
        self.bots = {}
        self.time = 0

        map_ = deepcopy(map_)
        self.spawn_points = deque(extract_spawn_points(map_))

        self.state = GameState(map_)

    def add_bot(self, bot, name=None):
        if name is None:
            name = bot.__name__

        if name in self.bots:
            raise KeyError(
                'There is already a bot named %r in this game!' %
                (name,)
            )

        self.bots[name] = bot

        # Place the initial robot for this player.
        x, y = self.spawn_points.popleft()
        self.state.robots_by_player[name] = [
            (x, y, Energy.INITIAL),
        ]

    @property
    def finished(self):
        target = self.state.n_cities_to_win

        winners = []
        roboteers = []

        n_allegiances_by_player = self.state.n_allegiances_by_player

        for name, robots in self.state.robots_by_player.items():
            n_cities = n_allegiances_by_player[name]
            if n_cities >= target:
                winners.append(name)

            if robots:
                roboteers.append(name)

        won = bool(winners)
        if len(roboteers) <= 1:
            won = True
            winners.extend(roboteers)

        return winners or won

    def call_bots(self):
        for whoami, bot in self.bots.items():
            try:
                with protected(self.state, 'state') as state:
                    result = bot(whoami, state)

                assert isinstance(result, (str, list, tuple)), \
                    'Bot did not return a str/list/tuple, got %r' % (result,)
                result = str(''.join(result))

                my_robots = self.state.robots_by_player[whoami]
                assert len(result) == len(my_robots), (
                    'Bot did not return an action for all robots '
                    '(%d actions != %d robots)' % (len(result), len(my_robots))
                )

                for action in result:
                    assert action in Action.all, (
                        'Got unexpected action %r' % (action,)
                    )

            except Exception:
                # TODO: log this exception
                traceback.print_exc()
                time.sleep(1)

            else:
                for bot, action in zip(my_robots, result):
                    yield whoami, bot, action

    def apply_actions(self, actions):
        robots_by_player = defaultdict(list)

        for whoami, bot, action in actions:
            x, y, energy = bot

            if energy < ENERGY_BY_ACTION[action]:
                action = Action.NOTHING

            if action == Action.PROMOTE:
                if self.state.allegiances.get((x, y)) != whoami:
                    self.state.allegiances[x, y] = whoami
                else:
                    action = Action.NOTHING

            elif action != Action.NOTHING:
                nx, ny = self.state.expected_position(x, y, action)

                if x == nx and y == ny:
                    action = Action.NOTHING
                x, y = nx, ny

            energy -= ENERGY_BY_ACTION[action]

            robots_by_player[whoami].append((x, y, energy))

        for name, robots in self.state.robots_by_player.items():
            robots[:] = robots_by_player[name]

    def factories_produce_robots(self):
        state_robots = self.state.robots

        for x, y in self.state.factories:
            if state_robots[(x, y)]:
                continue

            owner = self.state.allegiances.get((x, y))
            if owner is None:
                continue

            if random() < 0.2:
                self.state.robots_by_player[owner].append(
                    (x, y, Energy.INITIAL)
                )

    def robots_gain_energy(self):
        for robots in self.state.robots_by_player.values():
            robots[:] = [
                (x, y, min(Energy.MAXIMUM, energy + Energy.GAIN))
                for x, y, energy in robots
            ]

    def resolve_combats(self):
        to_remove = set()
        to_append = defaultdict(list)

        for (x, y), robots in self.state.robots.items():
            if len(robots) <= 1:
                # No combat here.
                continue

            to_remove.add((x, y))

            # each player's strength is the sum of their robots' energy
            strength_by_player = defaultdict(int)
            total = 0
            for player, energy in robots:
                strength_by_player[player] += energy
                total += energy

            winner_count = 0
            for player, strength in strength_by_player.items():
                # subtract the sum of the other players' strength
                strength -= total - strength
                # remove with strength players <= 0
                if strength > 0:
                    energy = min(strength, Energy.MAXIMUM)
                    to_append[player].append((x, y, energy))
                    winner_count += 1

            # we should end up with one player.
            # (and I wrote a proof of that, so something's seriously wrong if
            # this fails)
            assert winner_count <= 1

        for player, robots in self.state.robots_by_player.items():
            extra_robots = to_append[player]
            robots[:] = [
                (x, y, energy)
                for x, y, energy in robots
                if (x, y) not in to_remove
            ] + extra_robots

    def __iter__(self):
        while not self.finished:
            yield self.state
            self.next()
        yield self.state

    def next(self):
        # 1. You give commands you your robots.
        actions = self.call_bots()
        # 2. They perform the requested commands.
        self.apply_actions(actions)
        # 3. Factories produce new robots.
        self.factories_produce_robots()
        # 4. Combats are resolved.
        self.resolve_combats()
        # 5. Each robot gains energy, up to the maximum.
        self.robots_gain_energy()

        self.time += 1