-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
355 lines (287 loc) · 10.9 KB
/
main.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
"""Setup, application and layout code"""
from __future__ import division
from ConfigParser import NoSectionError, NoOptionError
from functools import partial
import kivy
kivy.require('1.8.1')
from kivy.app import App
from kivy.clock import Clock
from kivy.config import Config as KivyConfig
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.anchorlayout import AnchorLayout
from kivy.properties import (
BooleanProperty,
NumericProperty,
ObjectProperty,
)
from kivy_grid_cells.constants import Colours
from kivy_p2life.constants import Colours as Players
from kivy_p2life.exceptions import NoPiecesObjectForPlayer
from kivy_p2life.events import propagate_events
from kivy_p2life.gol import life_animation
from kivy_p2life.utils import Player
class CustomLayoutMixin(object):
"""Base layout code relating to the game"""
app = ObjectProperty(None)
grid = ObjectProperty(None)
shapes = ObjectProperty(None)
end_turn_button = ObjectProperty(None)
interactions_enabled = BooleanProperty(True)
def __init__(self, *args, **kwargs):
self.register_event_type("on_drag_shape")
self.register_event_type("on_drop_shape")
super(CustomLayoutMixin, self).__init__(*args, **kwargs)
self._player = None
def on_drag_shape(self, evt):
return propagate_events(self, "on_drag_shape", evt)
def on_drop_shape(self, evt):
return propagate_events(self, "on_drop_shape", evt)
def disable_interaction(self):
self.interactions_enabled = False
if self.end_turn_button:
self.end_turn_button.text = "Waiting..."
def enable_interaction(self):
self.interactions_enabled = True
if self.end_turn_button:
self.end_turn_button.text = "End turn"
def set_turn(self, player):
other_colour = Player(player).next() # TODO something more clever?
if self.end_turn_button:
self.end_turn_button.color = Colours[other_colour]
self.end_turn_button.background_color = Colours[player]
self.player = player
self.grid.selected_state = player
new_pieces = max(self.app.minimum_pieces,
self.grid.get_new_pieces_for_player(player))
try:
self.grid.get_player_pieces().update_pieces(new_pieces)
except NoPiecesObjectForPlayer:
pass
def unset_winner(self):
# Override this method on a per-UI basis
pass
def set_winner(self, player, ui):
# Override this method on a per-UI basis
pass
def evolve(self, iterations, speed, callback=None):
""" Evolve the grid multiple times
:param iterations: Number of times to evolve
:type iterations int:
:param speed: Speed at which to evolve
:type speed int:
:param callback: Function to call after evolving
:type callback function:
>>> import mock
>>> from kivy.uix.widget import Widget
>>> Clock.schedule_once = lambda func, timeout: func()
>>> thing = type("Thing", (CustomLayoutMixin, Widget), {})()
>>> thing.grid = mock.Mock(cells=[[]])
>>> callback = mock.Mock()
>>> with mock.patch("kivy_p2life.gol.life_step") as life_step:
... thing.evolve(10, 0.001, callback)
>>> life_step.call_count
10
>>> callback.call_count
1
"""
anim = life_animation(self.grid.cells)
def _update(dt=None, remaining=0):
self.grid.cells = anim.next()
remaining -= 1
if remaining:
Clock.schedule_once(partial(_update, remaining=remaining),
timeout=(1 / speed))
elif callback is not None:
callback()
_update(remaining=iterations)
def end_turn_callback(self):
""" Finish ending the turn after iterating
Setup:
>>> import mock
>>> from kivy.uix.widget import Widget
>>> thing = type("Thing", (CustomLayoutMixin, Widget), {"set_turn": mock.Mock(), "set_winner": mock.Mock()})()
>>> thing.player = Players.WHITE
>>> thing.grid = mock.Mock()
>>> ui = thing.grid.get_player_ui.return_value
Normal turn:
>>> ui.had_maximum_score = False
>>> ui.has_maximum_score = True
>>> thing.interactions_enabled = False
>>> thing.end_turn_callback()
>>> thing.set_winner.call_count
0
>>> thing.interactions_enabled
True
>>> ui.had_maximum_score = True
>>> ui.has_maximum_score = False
>>> thing.interactions_enabled = False
>>> thing.end_turn_callback()
>>> thing.set_winner.call_count
0
>>> thing.interactions_enabled
True
Winning turn:
>>> ui.had_maximum_score = True
>>> ui.has_maximum_score = True
>>> thing.interactions_enabled = False
>>> thing.end_turn_callback()
>>> thing.set_winner.call_count
1
>>> thing.interactions_enabled
False
"""
self.set_turn(self.player.next())
ui = self.grid.get_player_ui(self.player)
if ui.had_maximum_score and ui.has_maximum_score:
self.set_winner(self.player, ui)
return
else:
self.enable_interaction()
def end_turn(self, *args):
""" Perform end turn tasks and evolve
Setup:
>>> import mock
>>> from kivy.uix.widget import Widget
>>> thing = type("Thing", (CustomLayoutMixin, Widget), {})()
>>> thing.player = Players.WHITE
>>> thing.app = mock.Mock()
>>> thing.grid = mock.Mock()
>>> thing.evolve = mock.Mock()
>>> ui = thing.grid.get_player_ui.return_value
Maximum score:
>>> ui.has_maximum_score = True
>>> thing.end_turn()
>>> ui.had_maximum_score
True
>>> thing.evolve.call_count
1
Not maximum score:
>>> ui.has_maximum_score = False
>>> thing.end_turn()
>>> ui.had_maximum_score
False
>>> thing.evolve.call_count
2
"""
self.disable_interaction()
ui = self.grid.get_player_ui(self.player)
if ui.has_maximum_score:
ui.had_maximum_score = True
else:
ui.had_maximum_score = False
self.evolve(self.app.iterations_per_turn, speed=self.app.speed,
callback=self.end_turn_callback)
@property
def player(self):
return self._player
@player.setter
def player(self, value):
self._player = Player(value)
def on_touch_down(self, evt):
""" Disable all touch events when evolution is in progress
>>> import mock
>>> from kivy.uix.widget import Widget
>>> Widget.on_touch_down = mock.Mock(return_value="superclass called")
>>> thing = type("Thing", (CustomLayoutMixin, Widget), {})()
>>> thing.on_touch_down(object())
'superclass called'
>>> thing.interactions_enabled = False
>>> thing.on_touch_down(object())
>>> thing.on_touch_down(mock.Mock(fid=0))
'superclass called'
"""
# TODO less hacky way to enable admin-reset
if self.interactions_enabled or (hasattr(evt, "fid") and evt.fid == 0):
return super(CustomLayoutMixin, self).on_touch_down(evt)
def on_touch_move(self, evt):
""" Disable all touch events when evolution is in progress
>>> import mock
>>> from kivy.uix.widget import Widget
>>> Widget.on_touch_move = mock.Mock(return_value="superclass called")
>>> thing = type("Thing", (CustomLayoutMixin, Widget), {})()
>>> thing.on_touch_move(object())
'superclass called'
>>> thing.interactions_enabled = False
>>> thing.on_touch_move(object())
>>> thing.on_touch_move(mock.Mock(fid=0))
"""
if self.interactions_enabled:
return super(CustomLayoutMixin, self).on_touch_move(evt)
class CustomBoxLayout(CustomLayoutMixin, BoxLayout):
"""Base layout for non-TUIO-mode"""
class CustomAnchorLayout(CustomLayoutMixin, AnchorLayout):
"""Base layout for TUIO-mode"""
def set_winner(self, player, ui):
ui.text = "You win!"
def unset_winner(self):
for ui in self.grid.player_uis:
ui.text = ""
class GameOfLifeApp(App):
"""Kivy application code"""
iterations_per_turn = NumericProperty()
speed = NumericProperty
def build_config(self, config):
config.setdefaults("game", {
"speed": 10,
"iterations_per_turn": 15,
"top_score": 100,
"minimum_pieces": 3,
})
config.setdefaults("grid", {
"rows": 30,
"cols": 30,
"cell_size": 15,
})
config.setdefaults("input", {
# 'touch' can be a finger or a mouse, depending on the platform
"touch": True,
"tuio": False,
})
def build(self):
config = self.config
# Input
if config.getboolean("input", "tuio"):
try:
KivyConfig.get("input", "tuiotouchscreen")
except (NoSectionError, NoOptionError):
KivyConfig.set('input', 'tuiotouchscreen', 'tuio,0.0.0.0:3333')
KivyConfig.write()
if config.getboolean("input", "touch"):
# Enable mouse interface
kv_filename = 'gameoflife-nontuio.kv'
else:
kv_filename = 'gameoflife-tuio.kv'
# Game
self.speed = config.getint("game", "speed")
self.iterations_per_turn = config.getint("game", "iterations_per_turn")
self.top_score = config.getint("game", "top_score")
self.minimum_pieces = config.getint("game", "minimum_pieces")
# Root widget
self.root = Builder.load_file(kv_filename)
self.root.app = self
# Grid
self.root.grid.rows = config.getint("grid", "rows")
self.root.grid.cols = config.getint("grid", "cols")
self.root.grid.cell_size = config.getint("grid", "cell_size")
def on_start(self):
self.root.grid.init_cells()
self.root.set_turn(Players.WHITE)
if self.root.end_turn_button:
self.root.end_turn_button.bind(on_press=self.root.end_turn)
Clock.schedule_once(self.after_start, timeout=1)
def after_start(self, *args):
if self.root.shapes:
for shape in self.root.shapes.children:
shape.setup()
def reset_ui(self):
for grid_index, unused in enumerate(self.root.grid.grids):
self.root.grid.clear_grid(grid_index)
self.root.unset_winner()
for player_pieces in self.root.grid.player_pieces:
player_pieces.update_pieces(-player_pieces.pieces)
self.root.set_turn(Players.WHITE)
self.root.enable_interaction()
if __name__ == '__main__':
# TODO set title, icon
GameOfLifeApp().run()