-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel.py
executable file
·329 lines (266 loc) · 9.51 KB
/
model.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Yield or Die! Train yourself to learn rules for right-of-way,
without spending lots of money for practice at driving school!
Copyright (C) 2021 Dan Gheorghe Haiduc (aka danuker)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from kivy.uix.widget import Widget
from kivy.uix.image import Image
from kivy.properties import NumericProperty, BooleanProperty
from kivy.core.audio import SoundLoader
from yield_resolver import must_yield, relative_position
from time import time
import random
import os
class StretchyImage(Image):
allow_stretch=BooleanProperty(True)
def signal_turn(source_road, target_road):
"""
Tell the signal
>>> signal_turn('left', 'behind')
'sig_right'
>>> signal_turn('left', 'ahead')
'sig_left'
>>> signal_turn('left', 'right')
'sig_no'
>>> signal_turn('right', 'behind')
'sig_left'
>>> signal_turn('right', 'ahead')
'sig_right'
>>> signal_turn('behind', 'ahead')
'sig_no'
>>> signal_turn('ahead', 'left')
'sig_right'
>>> signal_turn('behind', 'behind')
Traceback (most recent call last):
...
ValueError: U-turns not allowed.
"""
directions = ['behind', 'left', 'ahead', 'right']
signals = [None, 'sig_left', 'sig_no', 'sig_right']
source_i = directions.index(source_road)
target_i = directions.index(target_road)
sig_i = (target_i - source_i) % len(signals)
sig = signals[sig_i]
if sig:
return sig
else:
raise ValueError('U-turns not allowed.')
class Car(StretchyImage):
angle = NumericProperty(0)
images = {
'sig_no': 'pics/pngs/car.png',
'sig_left': 'pics/pngs/car_signal_left.png',
'sig_right': 'pics/pngs/car_signal_right.png'
}
def __init__(self, source_road, target_road, app, **kwargs):
StretchyImage.__init__(self, **kwargs)
self.source = self.images['sig_no']
self.app = app
self.intersection = self.app.game.intersection
# Strings that name the road
self.source_road = source_road
self.target_road = target_road
self.stop_time = float('inf')
self.signal = signal_turn(source_road, target_road)
def must_yield(self, other_cars, prios):
for other_car in other_cars:
rel = relative_position(
self.source_road, other_car.source_road
)
must_yield_now, reason = must_yield(
my_right_of_way=prios[self.source_road],
my_turn=self.signal,
other_right_of_way=prios[other_car.source_road],
other_turn=other_car.signal,
other_relative_position=rel
)
if must_yield_now:
return must_yield_now, reason
# We don't have to yield to anyone in the intersection
return False, \
"Other cars either won't cross your path,\nnor need to yield to you."
def blink(self, state):
if state:
self.source = self.images[self.signal]
else:
self.source = self.images['sig_no']
def update(self):
"""Place car on screen"""
if self.intersection.touch_start_y:
self.blink(True)
if self.stop_time == float('inf'):
self.stop_time = time()
return
else:
# Time the blink-lights
if int(time() * 2) % 2 == 0:
self.blink(True)
else:
self.blink(False)
center_x = self.intersection.width / 2
center_y = self.intersection.height / 2
speed = min(self.intersection.width, self.intersection.height)/100
now = min(self.stop_time, time())
dist_from_center = center_x - (now - self.intersection.time)*speed
lane = self.app.lane_width/2
car_coords = {
'left': [
center_x - dist_from_center,
center_y - lane
],
'right': [
center_x + dist_from_center,
center_y + lane
],
'behind': [
center_x + lane,
center_y - dist_from_center
],
'ahead': [
center_x - lane,
center_y + dist_from_center
]
}
self.center = car_coords[self.source_road]
angles = {
'left': -90, 'ahead': 180, 'right': 90, 'behind': 0,
}
self.angle = angles[self.source_road]
class PlayerCar(Car):
def __init__(self, source_road, target_road, app, **kwargs):
Car.__init__(self, source_road, target_road, app, **kwargs)
self.images = {
'sig_no': 'pics/pngs/player.png',
'sig_left': 'pics/pngs/player_signal_left.png',
'sig_right': 'pics/pngs/player_signal_right.png'
}
class Sign(Widget):
def __init__(self, app, name, facing, with_panel, **kwargs):
"""
app : app having intersection as "game" field
name : 'yield' or 'prio'
facing : 'left', 'right', 'ahead', or 'behind'
with_panel : True or False
"""
super(Sign).__init__(**kwargs)
self.app = app
self.intersection = self.app.game.intersection
self.name = name
self.facing = facing
self.with_panel = with_panel
if facing in ['left', 'right']:
facing = f"ahead-{facing}"
self.sign = StretchyImage(source=f'pics/pngs/sign-{name}-{facing}.png')
if self.facing == 'behind':
self.panel_pics = self.build_panel_map()
else:
self.panel_pics = [
StretchyImage(source=f'pics/pngs/panel-{facing}.png')
]
self.pole = StretchyImage(source='pics/pngs/pole.png')
if facing != 'behind':
self.app.game.add_widget(self.sign)
self.add_panel_map()
self.app.game.add_widget(self.pole)
if facing == 'behind':
self.app.game.add_widget(self.sign)
self.add_panel_map()
def build_panel_map(self):
panels = [
StretchyImage(source='pics/pngs/panel-blank.png'),
]
for road, has_prio in self.intersection.prios.items():
kind = 'prio' if has_prio else 'yield'
panels.append(
StretchyImage(source=f'pics/pngs/panel-{kind}{road}.png')
)
return panels
def add_panel_map(self):
if self.with_panel:
for pic in self.panel_pics:
self.app.game.add_widget(pic)
def update(self):
self._transform_sign_pic(self.pole)
self._transform_sign_pic(self.sign)
for pic in self.panel_pics:
self._transform_sign_pic(pic)
def _transform_sign_pic(self, img):
size = self.app.lane_width * 4
center_x = self.intersection.width / 2
center_y = self.intersection.height / 2
dist_from_center = self.app.lane_width*1.5
lane = self.app.lane_width*1.5
positions = {
'left': [
center_x - dist_from_center,
center_y - lane
],
'right': [
center_x + dist_from_center,
center_y + lane
],
'behind': [
center_x + lane,
center_y - dist_from_center
],
'ahead': [
center_x - lane,
center_y + dist_from_center
]
}
img.size = [size, size]
img.center = positions[self.facing]
def _oggs_from_dir(directory):
"""List all .ogg files in a directory"""
try:
return [s for s in os.listdir(directory) if s.endswith('.ogg')]
except FileNotFoundError:
# We currently don't have any sounds for 'stop', nor a directory
return []
class Audio:
def __init__(self):
# Load audio in memory (fast playback)
self.sounds = self._get_sounds()
def play_sound(self, sound_class):
"""
Play a random sound of the given class
"""
try:
sound = random.choice(self.sounds[sound_class])
sound.play()
except IndexError:
# We currently don't have any sounds for 'stop', nor a directory
pass
def play(self, moved: bool, correct: bool):
"""
Play the appropriate sound, considering whether player
is moving, and is correct in doing so
"""
sound_class = {
(True, True): 'drive',
(True, False): 'crash',
(False, True): 'stop',
(False, False): 'honk'
}
self.play_sound(sound_class[(moved, correct)])
def _get_sounds(self):
dirs = ('drive', 'crash', 'stop', 'honk')
choices = {}
for d in dirs:
choices[d] = tuple(
SoundLoader.load(os.path.join('sounds', d, s))
for s in _oggs_from_dir(os.path.join('sounds', d))
)
return choices