/
main.py
463 lines (388 loc) · 16 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
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
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.scatter import Scatter
from kivy.uix.button import Button
from kivy.properties import NumericProperty, ReferenceListProperty, BooleanProperty
from kivy.vector import Vector
from kivy.clock import Clock
from math import sqrt
from kivy.graphics import Line
from kivy.uix.floatlayout import FloatLayout
from kivy.graphics.instructions import InstructionGroup
from kivy.uix.settings import SettingsWithSidebar
from settingsjson import settings_json
from kivy.core.image import Image
from random import choice
import os
import math
class Planet(Widget):
'''
a planet class
'''
velocity_x = NumericProperty(0)
velocity_y = NumericProperty(0)
velocity = ReferenceListProperty(velocity_x, velocity_y)
red = NumericProperty(255)
green = NumericProperty(255)
blue = NumericProperty(255)
colour = ReferenceListProperty(red, green, blue)
fixed = BooleanProperty(False)
mass = NumericProperty(1)
density = NumericProperty(10)
showforcelimit = NumericProperty(5)
drawtrajectory = BooleanProperty(False)
def __init__(self, fixed, position, velocity, mass, density, colour,
**kwargs):
super(Planet, self).__init__(**kwargs)
self.fixed = fixed
self.mass = mass
self.center = (position[0],position[1])
self.velocity = velocity
self.density = density
self.colour = colour
self.showforcelimit = float(App.get_running_app().config.get('planetapp',
'showforcelimit'))
self.calc_size()
self.hillbodies = []
def move(self):
self.pos = Vector(*self.velocity) + self.pos
def calc_gravity(self, planet, gravity):
if not self.fixed:
dist_x = self.center_x - planet.center_x
dist_y = self.center_y - planet.center_y
dist = self.parent.calc_distance(self.center,planet.center)
force = (gravity * self.mass * planet.mass) / (dist**2)
force_x = force * (dist_x / dist)
force_y = force * (dist_y / dist)
self.calc_hillbodies(force, planet)
self.velocity_x -= force_x / self.mass
self.velocity_y -= force_y / self.mass
def calc_hillbodies(self, force, planet):
# typecasting problem while crosscompiling
foo = App.get_running_app().config.get('planetapp','showforcemode')
if foo == u'0':
return
if ((force / self.mass) > (self.showforcelimit * 0.0002)):
if not planet.fixed:
if not planet in self.hillbodies:
self.hillbodies.append(planet)
else:
if planet in self.hillbodies:
self.hillbodies.remove(planet)
for dude in self.canvas.children:
if 'InstructionGroup' in type(dude).__name__:
self.canvas.remove(dude)
shit = InstructionGroup()
for body in self.hillbodies:
shit.add(Line(points=(self.center_x,self.center_y,
body.center_x,body.center_y),
width=1,
group=str(self.uid)))
if len(self.hillbodies) > 0:
self.canvas.add(shit)
if self.drawtrajectory and not self.fixed:
shit2 = InstructionGroup()
sunpos = (self.parent.width/2,self.parent.height/2)
trajectory = self.parent.calc_trajectory((self.center_x,self.center_y),
self.velocity,
self.mass, sunpos,
self.parent.sunmass, 1,
1000)
shit2.add(Line(points=trajectory, width=1, group=str(self.uid)))
self.canvas.add(shit2)
else:
pass
def merge(self, planet):
impulse_x = (self.velocity_x * self.mass + planet.velocity_x * planet.mass)
impulse_y = (self.velocity_y * self.mass + planet.velocity_y * planet.mass)
self.mass += planet.mass
if not self.fixed:
self.velocity_x = impulse_x / self.mass
self.velocity_y = impulse_y / self.mass
if (self.red > 0.1) and not self.fixed:
self.red -= 0.1
self.hillbodies = []
def on_mass(self, instance, value):
self.calc_size()
def calc_size(self):
diameter = 2 * sqrt(self.density * self.mass / 3.14)
self.size = (diameter,diameter)
#def on_showtrajectory(self, instance, value):
# print value
class PlanetGame(Scatter):
zoom = NumericProperty(1)
gravity = NumericProperty(1)
planetmass = NumericProperty(1)
resetmass = NumericProperty(10)
sunmass = NumericProperty(1000)
showtrajectorymode = BooleanProperty(False)
def __init__(self, **kwargs):
super(PlanetGame, self).__init__(**kwargs)
self.textures = []
self.files = []
self.load_textures()
#self.planetcycle = cycle(self.children)
self.planetindex = 0
self.maxplanets = len(self.children)
self.showplanet = None
def i_am_dead(self, deadplanet):
for planet in self.children:
if deadplanet in planet.hillbodies:
planet.hillbodies.remove(deadplanet)
def on_children(self, instance, value):
#print 'jow'
self.maxplanets = len(value)
self.planetindex = 0
print self.maxplanets
#self.planetcycle = cycle(self.children)
def load_textures(self):
path = ('./textures/')
for file in os.listdir(path):
if file.endswith('.png'):
self.files.append(path + str(file))
for string in self.files:
self.textures.append(Image(string).texture)
def add_planet(self, fixed, position, velocity, mass=1,
density=5, colour=(1,1,1)):
new_planet = Planet(fixed, position, velocity, mass, density, colour)
if not fixed:
new_planet.canvas.children[1].texture = choice(self.textures)
self.add_widget(new_planet)
def update(self,dt):
for planet in self.children:
if planet.fixed:
planet.center = (self.width/2,self.height/2)
planet.move()
for planet2 in self.children:
if planet == planet2:
continue
planet.calc_gravity(planet2, self.gravity)
if not planet.collide_widget(planet2):
continue
if planet.mass < planet2.mass:
continue
planet.merge(planet2)
self.i_am_dead(planet2)
self.remove_widget(planet2)
def on_touch_down(self, touch):
touch.push()
touch.apply_transform_2d(self.to_local)
ud = touch.ud
ud['id'] = 'gametouch'
ud['firstpos'] = touch.pos
ud['group'] = g = str(touch.uid)
with self.canvas:
ud['lines'] = [
Line(points=(touch.x,touch.y,touch.x+1,touch.y+1),width=1,
group=g)]
touch.grab(self)
touch.pop()
def on_touch_move(self, touch):
if touch.grab_current is not self:
return
touch.push()
touch.apply_transform_2d(self.to_local)
ud = touch.ud
# typecasting-problems during cross-compiling
# leads to this ugly construction like in calc_hillbodies
foo = App.get_running_app().config.get('planetapp','showtrajectorymode')
trajectorylength = int(App.get_running_app().config.get('planetapp',
'trajectorylength'))
if foo == u'0':
ud['lines'][0].points = (ud['firstpos'][0],ud['firstpos'][1],
touch.x,touch.y)
else:
velocity = ((ud['firstpos'][0] - touch.x) / -50,
(ud['firstpos'][1] - touch.y) / - 50)
planetpos = (ud['firstpos'][0], ud['firstpos'][1])
sunpos = (self.width/2,self.height/2)
trajectory = self.calc_trajectory(planetpos, velocity,
self.planetmass, sunpos,
self.sunmass, 1,
trajectorylength)
ud['lines'][0].points = trajectory
touch.pop()
def calc_trajectory (self, coord_planet, speed_planet, weight_planet, coord_sun,
weight_sun, interval, count):
gamma = self.gravity
L = []
coords = coord_planet
speed = speed_planet
for i in range(count):
r = self.calc_distance(coords, coord_sun)
g = (-1 * gamma) * (weight_sun) / math.pow(r, 2.0)
gx = g * ((coords[0] - coord_sun[0]) / r)
gy = g * ((coords[1] - coord_sun[1]) / r)
speed = (speed[0] + (gx * interval), speed[1] + (gy * interval))
coords = (coords[0] + (speed[0] * interval),
coords[1] + (speed[1] * interval))
L.append(coords)
R = []
for item in L:
R.append(item[0])
R.append(item[1])
return tuple(R)
def calc_distance(self, tuple1, tuple2):
dist = math.sqrt(math.pow(tuple1[0] - tuple2[0], 2.0) +
math.pow(tuple1[1] - tuple2[1], 2.0))
if dist == 0:
dist = 0.000001
return dist
def on_touch_up(self, touch):
if touch.grab_current is not self:
return
touch.ungrab(self)
touch.push()
touch.apply_transform_2d(self.to_local)
ud = touch.ud
touchdownv = Vector(ud['firstpos'])
touchupv = Vector(touch.pos)
velocity = (touchupv - touchdownv) / 50
self.add_planet(False, ud['firstpos'], (velocity.x, velocity.y), self.planetmass)
self.canvas.remove_group(ud['group'])
touch.pop()
def on_zoom(self,instance,value):
self.scale = 1/value
def clear_planets(self):
L = []
for planet in self.children:
if planet.mass < self.resetmass:
L.append(planet)
if L:
for planet in L:
self.i_am_dead(planet)
self.clear_widgets(L)
def reset_game(self):
L = []
for planet in self.children:
L.append(planet)
if L:
self.clear_widgets(L)
sunmass = float(App.get_running_app().config.get('planetapp','defaultsunmass'))
self.sunmass = sunmass
self.gravity = float(App.get_running_app().config.get('planetapp','gravity'))
self.planetmass = float(App.get_running_app().config.get('planetapp','planetmass'))
self.resetmass = float(App.get_running_app().config.get('planetapp','resetmass'))
self.add_planet(True, (100,100), (0,0), float(sunmass), 10, (1,1,1))
def next_trajectory(self):
if self.showplanet:
for planet in self.children:
if planet == self.showplanet:
if planet.drawtrajectory:
planet.drawtrajectory = False
self.planetindex += 1
#print self.planetindex, self.maxplanets
if self.planetindex >= (self.maxplanets):
self.planetindex = 0
showplanet = self.children[self.planetindex]
#print showplanet
self.showplanet = showplanet
for planet in self.children:
if planet == showplanet:
if not planet.drawtrajectory:
planet.drawtrajectory = True
#print 'hallo'
class PlanetGameLayout(FloatLayout):
def on_touch_down(self, touch):
if self.children[0].collide_point(touch.x,touch.y):
self.children[0].on_touch_down(touch)
#print 'NextButton'
elif self.children[1].collide_point(touch.x,touch.y):
self.children[1].on_touch_down(touch)
#print 'SettingButton'
elif self.children[2].collide_point(touch.x,touch.y):
self.children[2].on_touch_down(touch)
#print 'ResetButton'
elif self.children[4].collide_point(touch.x,touch.y):
self.children[4].on_touch_down(touch)
#print 'Slider'
else:
self.children[3].on_touch_down(touch)
#print 'Game'
def on_touch_up(self, touch):
if self.children[0].collide_point(touch.x,touch.y):
self.children[0].on_touch_up(touch)
#print 'Button1'
elif self.children[1].collide_point(touch.x,touch.y):
self.children[1].on_touch_up(touch)
#print 'Button2'
elif self.children[2].collide_point(touch.x,touch.y):
self.children[2].on_touch_up(touch)
#print 'Button2'
elif self.children[4].collide_point(touch.x,touch.y):
self.children[4].on_touch_up(touch)
#print 'Slider'
else:
pass
#self.children[3].on_touch_up(touch)
#print 'Game'
def clear_planets(self,instance):
self.children[3].clear_planets()
def next_trajectory(self,instance):
self.children[3].next_trajectory()
def set_background(self, showbackground):
for dude in self.canvas.children:
if 'Rectangle' in type(dude).__name__:
if showbackground:
dude.size = self.size
else:
dude.size = (0,0)
def reset_game(self):
showbackground = App.get_running_app().config.get('planetapp','showbackground')
if showbackground == u'0':
self.set_background(False)
else:
self.set_background(True)
self.children[3].reset_game()
class SettingsButton(Button):
pass
class PlanetApp(App):
def build(self):
self.settings_cls = SettingsWithSidebar
game = PlanetGame(do_rotation=False,do_translation=False)
# Settings come in as unicode!
sunmass = float(App.get_running_app().config.get('planetapp','defaultsunmass'))
game.sunmass = sunmass
game.gravity = float(App.get_running_app().config.get('planetapp','gravity'))
game.planetmass = float(App.get_running_app().config.get('planetapp','planetmass'))
game.resetmass = float(App.get_running_app().config.get('planetapp','resetmass'))
game.add_planet(True, (100,100), (0,0), sunmass, 10, (1,1,1))
Clock.schedule_interval(game.update, 1.0 / 120.0)
self.root = PlanetGameLayout()
self.root.add_widget(game)
b = Button(text="Reset",size_hint=(.3,.05),pos_hint={'x':.7,'y':0})
b.bind(on_press=self.root.clear_planets)
self.root.add_widget(b)
b2 = SettingsButton(text="Settings",size_hint=(.3,.05),pos_hint={'x':.4,'y':0})
self.root.add_widget(b2)
b3 = Button(text="Next",size_hint=(.3,.05),pos_hint={'x':.1,'y':0})
b3.bind(on_press=self.root.next_trajectory)
self.root.add_widget(b3)
self.root.reset_game()
def build_config(self, config):
config.setdefaults('planetapp', {
'defaultsunmass': 1000,
'gravity' : 2,
'resetmass' : 50,
'showforcemode' : False,
'showforcelimit' : 5,
'showtrajectorymode' : False,
'trajectorylength' : 250,
'showbackground' : True,
'planetmass' : 10}),
'''
'boolexample': True,
'optionsexample': 'option2',
'stringexample': 'some_string',
'pathexample': '/some/path'})
'''
def build_settings(self, settings):
settings.add_json_panel('PlanetApp',
self.config,
data=settings_json)
def on_config_change(self, config, section,
key, value):
print config, section, key, value
self.root.reset_game()
if __name__ == '__main__':
PlanetApp().run()