/
maximetro.py
executable file
·920 lines (728 loc) · 28.9 KB
/
maximetro.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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2014, Benni Baermann http://bennibaermann.de/
# COPYING: See LICENSE. This program is Free Software under AGPL
import pygame
from pygame.locals import *
import Vec2D
from Vec2D import *
import random
##################################################################
# configuration section
##################################################################
DEBUG = False
ANIMALS = False
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
BLUE = ( 0, 0, 255)
GREEN = ( 0, 255, 0)
RED = (255, 0, 0)
MAGENTA = (255, 0, 255)
CYAN = ( 0, 255, 255)
YELLOW = (255, 255, 0)
SHAPES = ('circle','triangle','square')
OTHERSTATIONS = ('circle','triangle')
MAINSTATION = 'square'
MAXSTATIONS = 20
COLORS = [YELLOW,MAGENTA,CYAN,GREEN,BLUE,RED]
#COLORS = [CYAN,GREEN,BLUE,RED]
LINES = list(COLORS)
COLORNAMES = ['red','blue','green','cyan','magenta','yellow']
PASSENGERSIZE = 7
CARCAPACITY = 3
CARWITH = PASSENGERSIZE + 3 # actually half of it
CARLENGTH = 13 + PASSENGERSIZE * CARCAPACITY # actually half of it
CARSPEED = 3
STATIONSIZE = 17
STATIONTHICKNESS = 5
STATIONDISTANCE = CARLENGTH * 4
MAXSTATIONTRACKS = 5
STATIONTRACKDIST = 0 # TODO: minimal distance between tracks and center of station
PROBABILITY_START = .001
#PROBABILITY_DIFF = .000001
PROBABILITY_DIFF = 0
MAXWAITING = 5
DOUBLE_TRACKS = False # more than one track between same stations allowed?
CROSSING = False # crossing tracks allowed?
COLLISION = False # set False if Cars should stop if other car is in range
MIN_ANGLE = 0 # TODO: minimal angle between tracks
RIGHT_OFFSET = int(MAXWAITING * STATIONSIZE)
#RIGHT_OFFSET = 200
MAX_Y = 800
MAX_X = MAX_Y + RIGHT_OFFSET
FPS = 30
################################################################
# global variables
################################################################
score = 0
count = 0
gameover = False
screen = pygame.display.set_mode((MAX_X, MAX_Y))
# semaphore = [] # sorage for cars with possible COLLISION
stations = []
lines = []
################################################################
# global functions
################################################################
def init_game():
""" should be called at game (re)start """
global lines, stations, gameover, LINES, score #, semaphores
gameover = False
stations = []
lines = []
# semaphore = []
LINES = list(COLORS)
init_city()
score = 0
def intersect( track,start,end ):
"""Calculates the intersection of line P1-P2 with P3-P4."""
x1, y1 = track.startpos
x2, y2 = track.endpos
x3, y3 = start
x4, y4 = end
try:
# code from https://twitter.com/mekkablue
try:
slope12 = ( float(y2) - float(y1) ) / ( float(x2) - float(x1) )
except:
slope12 = None
try:
slope34 = ( float(y4) - float(y3) ) / ( float(x4) - float(x3) )
except:
slope34 = None
if slope12 == slope34:
return False
elif slope12 is None:
# first line is vertical
x = x1
y = slope34 * ( x - x3 ) + y3
elif slope34 is None:
# second line is vertical
x = x3
y = slope12 * ( x - x1 ) + y1
else:
x = ( slope12 * x1 - y1 - slope34 * x3 + y3 ) / ( slope12 - slope34 )
y = slope12 * ( x - x1 ) + y1
# only true if intersection is between track.startpos and track.endpos
x12_range = [x1,x2]
y12_range = [y1,y2]
x34_range = [x3,x4]
y34_range = [y3,y4]
x12_range.sort()
y12_range.sort()
x34_range.sort()
y34_range.sort()
if x12_range[0] < x < x12_range[1] and \
y12_range[0] < y < y12_range[1] and \
x34_range[0] < x < x34_range[1] and \
y34_range[0] < y < y34_range[1]:
return True
else:
return False
except Exception as e:
print (str(e))
return False
def intersect_any(start,end):
"""returns True if any intersection with existing tracks"""
for l in lines:
for t in l.tracks:
if intersect(t,start,end):
return True
return False
def rotate_poly(pol,angle):
"""rotate polygon pol around (0,0) with angle and returns turned one"""
# rotate car
turnedpol = []
for p in pol:
v = Vec2d(p)
turnedpol.append(v.rotated(angle))
return turnedpol
def move_poly(poly,pos):
"""return a moved polygon shiftet with pos"""
ret = []
for p in poly:
ret.append([p[0] + pos[0], p[1] + pos[1]])
return ret
def draw_image(image,pos,size,color,angle=0):
image = pygame.image.load(image)
image = pygame.transform.rotate(image,360-angle)
w,h = image.get_size()
pos = (pos[0]-w/2,pos[1]-h/2)
screen.blit(image,pos)
def draw_triangle(pos,size,color,angle=0):
"""draws an equilateral triangle in the outer circle at pos with size in color"""
b = size / 2
x = (size*size - b*b) ** .5
triangle = ((0,-size),(x,b),(-x,b))
if angle:
triangle = rotate_poly(triangle,angle)
poly = move_poly(triangle,pos)
pygame.draw.polygon(screen,color,poly,0)
def draw_square(pos,size,color,angle=0):
"""draw square at pos with size in color"""
square = ((-size,-size),(-size,size),(size,size),(size,-size))
if angle:
square = rotate_poly(square,angle)
rect = move_poly(square,pos)
pygame.draw.polygon(screen,color,rect,0)
def init_city():
"""we set some Stations in place."""
print ("Setting main station...")
stations.append(Station((int((MAX_X-RIGHT_OFFSET)/2), int (MAX_Y/2)),\
"square"))
print ("Setting stations...")
for i in range(0,MAXSTATIONS):
# TODO: make sure that any shape can be reached
foundpos = False
failed = 0
while not foundpos and failed < 10:
newstationpos = (random.randint(0 + 2 * STATIONSIZE,
MAX_X - 2 * STATIONSIZE - RIGHT_OFFSET),
random.randint(0 + 2 * STATIONSIZE,
MAX_Y - 2 * STATIONSIZE))
print ("trying position ", newstationpos)
foundpos = True
for s in stations:
if is_in_range(newstationpos,s.pos,STATIONDISTANCE):
foundpos = False
print ("... is to near to ", s.pos)
if foundpos:
print( "position ok!")
s = Station(newstationpos)
stations.append(s)
else:
failed += 1
def center_text(pos,string,color=BLACK,size=12):
"""TODO BUGGY: prints string centered at pos"""
font = pygame.font.Font(pygame.font.get_default_font(),size)
text = font.render(string, False, color)
rect = text.get_rect()
pos = list(pos)
pos[0] -= int(rect.width/2)
pos[1] -= int(rect.height/2)
screen.blit(text, pos)
def text(pos,string,color=BLACK,size=12):
"""prints string in default font at pos"""
font = pygame.font.Font(pygame.font.get_default_font(),size)
text = font.render(string, False, color)
screen.blit(text, pos)
def draw_interface():
"""draw the user interface"""
count = 0
for l in lines:
rect = pygame.Rect(MAX_X-RIGHT_OFFSET,count*50,RIGHT_OFFSET,50)
pygame.draw.rect(screen,l.color,rect)
pygame.draw.rect(screen,BLACK,rect,1)
center_text((MAX_X-int(RIGHT_OFFSET*.75),count*50+25),"-",BLACK,30)
center_text((MAX_X-int(RIGHT_OFFSET*.25),count*50+25),"+",BLACK,30)
count += 1
pygame.draw.line(screen,BLACK,(MAX_X-RIGHT_OFFSET,0),
(MAX_X-RIGHT_OFFSET,MAX_Y))
pygame.draw.line(screen,BLACK,(int(MAX_X-RIGHT_OFFSET/2),0),
(int(MAX_X-RIGHT_OFFSET/2),count*50-1))
text((MAX_X-RIGHT_OFFSET+10,MAX_Y-20),"SCORE: " + str(score))
def is_in_range(pos1,pos2,dist=STATIONSIZE):
"""returns true if pos1 and pos2 are not more than dist pixels apart"""
if pos1[0] < pos2[0] - dist:
return False
if pos1[0] > pos2[0] + dist:
return False
if pos1[1] < pos2[1] - dist:
return False
if pos1[1] > pos2[1] + dist:
return False
return True
def is_station_pos(pos):
"""returns center of station if at pos is a station."""
for s in stations:
if is_in_range(pos,s.pos):
return s.pos
return False
def get_station(pos):
"""returns station at position"""
return next(s for s in stations if s.pos == is_station_pos(pos))
def update():
"""updates (position of) all user independent objects"""
for l in lines:
l.update()
for s in stations:
s.update()
def is_track(start,end):
"""returns True if there is any track betwen start and end"""
for l in lines:
for t in l.tracks:
if t.startpos == start and t.endpos == end:
return True
return False
def for_all_cars(function):
None
################################################################
# classes
################################################################
class Semaphore(object):
'''Blocks a station or (part of) a track for use with other cars'''
def __init__(self):
self.used = False
self.queue = []
def block(self,car):
if DEBUG:
print("block Semaphore")
self.queue.append(car)
self.used = True
def free(self):
if DEBUG:
print("free Semaphore")
l = len(self.queue)
if l:
# print l
self.queue.pop()
if not self.queue:
self.used = False
class Car(object):
"""A railcar. Each Line holds at least one"""
def __init__(self,track):
self.track = track
self.pos = track.startpos
self.direction = 1
self.counter = 0
self.poly = ((-CARWITH,-CARLENGTH),(-CARWITH,CARLENGTH),
(CARWITH,CARLENGTH),(CARWITH,-CARLENGTH))
self.passengers = []
self.angle = 0
self.has_semaphore = False
# self.waiting = False
def move(self):
"""returns the moved polygon to self.pos with angle of self.track"""
ret = []
pol = self.poly
# determine angle of track
# TODO: should calculated only once
start = self.track.startpos
end = self.track.endpos
v = Vec2d(start[0]-end[0],start[1]-end[1])
self.angle = v.get_angle() + 90
# rotate car
turnedpol = rotate_poly(pol,self.angle)
# move to self.pos
ret = move_poly(turnedpol,self.pos)
return ret
def car_in_range(self, alternative_position=None):
"""returns a list with cars in range CARLENGTH * 3 from pos"""
ret = []
for l in lines:
for t in l.tracks:
for c in t.cars:
if c != self:
if alternative_position:
# we test not with the position of the car, but with another
if(is_in_range(c.pos,alternative_position,CARLENGTH*3)):
ret.append(c)
else:
if is_in_range(c.pos,self.pos,CARLENGTH*3):
ret.append(c)
return ret
def want_move(self):
"""collision detection is handled here"""
if COLLISION == True:
# there is no moving restriction if collision-detection is off
return True
else:
#calculate distance from start
if self.direction > 0:
start = self.track.startpos
end = self.track.endpos
else:
start = self.track.endpos
end = self.track.startpos
dist = ( (start[0]-self.pos[0])**2 + (start[1]-self.pos[1])**2 ) ** .5
# stay at center of track unless we have a free station
if dist < self.track.length() / 2:
return True
else:
sema = get_station(end).sem
if sema.used and not self.has_semaphore:
return False
elif not self.has_semaphore:
sema.block(self)
self.has_semaphore = True
return True
else:
return True
def draw(self):
"""draw the car."""
moved = self.move()
#if self.waiting and DEBUG:
# pygame.draw.polygon(screen,BLACK,moved,0)
#else:
pygame.draw.polygon(screen,self.track.color,moved,0)
if DEBUG:
None
#future_pos = self.track.get_newpos(self.pos,self.counter,self.direction,CARLENGTH/CARSPEED * 3)
#pygame.draw.circle(screen,self.track.color,future_pos,CARLENGTH*3,2)
#if self in semaphore:
# pygame.draw.circle(screen,WHITE,self.pos,10)
#
# drawing of passengers
# TODO: stil buggy for some values of CARCAPACITY
offset = CARCAPACITY/2 + 1
for p in self.passengers:
offset -= 1
p.draw(self.pos,offset,self.angle)
class Track(object):
"""A railtrack between stations."""
def __init__(self,start,end,color,line,withcar=1):
"""constructor should only be called, if LINES[] is not empty"""
# self.pos_in_line = pil
self.line = line
self.color = color
self.startpos = start
self.endpos = end
self.cars = []
if withcar:
self.cars.append(Car(self))
def draw(self):
pygame.draw.line(screen,self.color,self.startpos,self.endpos,5)
for c in self.cars:
c.draw()
def length(self):
"""returns the length of the track"""
#TODO: calculate only once if track changes
start = self.startpos
end = self.endpos
return ( (start[0]-end[0])**2 + (start[1]-end[1])**2 ) ** .5
def get_newpos(self,pos,count,direction=1,i=1):
""" calculates new position of a car in i iterations"""
count += (i - 1)
start = self.startpos
end = self.endpos
ret = [0,0]
length = self.length()
xdiff = (start[0] - end[0]) / length * CARSPEED * -1
ydiff = (start[1] - end[1]) / length * CARSPEED * -1
if direction > 0:
ret[0] = int(xdiff * count) + start[0]
ret[1] = int(ydiff * count) + start[1]
else:
ret[0] = end[0] - int(xdiff * count)
ret[1] = end[1] - int(ydiff * count)
return ret
def is_end(self,pos):
"""returns True if pos is not on track"""
start = self.startpos
end = self.endpos
x_range = [start[0],end[0]]
y_range = [start[1],end[1]]
x_range.sort()
y_range.sort()
if (x_range[0] <= pos[0] <= x_range[1] and
y_range[0] <= pos[1] <= y_range[1]):
return False
return True
def add_car(self,car):
car.track = self
self.cars.append(car)
class Line(object):
"""A line contains multiple tracks between stations"""
def __init__(self,start,end):
self.color = LINES[-1]
# self.colorname = COLORNAMES[-1]
self.tracks = []
self.tracks.append(Track(start,end,self.color,self))
self.stations = [start,end]
def is_circle(self):
if self.tracks[0].startpos == self.tracks[-1].endpos:
return True
return False
def update(self):
for t in self.tracks:
if t.cars:
for c in t.cars:
if c.want_move():
self.update_car(t,c)
def update_car(self,track,car):
"""calculate new position of cars"""
global score # TODO: ugly
car.pos = track.get_newpos(car.pos,car.counter,car.direction)
if track.is_end(car.pos):
# moving passengers
station = get_station(car.pos)
platform = [] # just for intermediate memory
copy = list(car.passengers)
for p in copy:
if p.leave_at(station):
# p leaves the car
car.passengers.remove(p) # TODO: PERFORMANCE
p.car = None
if p.shape == station.shape:
score += 1
else:
# transition
platform.append(p)
copy = list(station.passengers)
for p in copy:
if len(car.passengers) < CARCAPACITY and p.enter(car):
# p enters the car
station.passengers.remove(p) # TODO: PERFORMANCE
car.passengers.append(p)
p.car = car
for p in platform:
station.passengers.append(p)
# which is next track?
pil = self.tracks.index(track)
next_pil = pil + car.direction
if next_pil < 0 or next_pil > len(self.tracks)-1:
if self.is_circle():
# this transforms from direction -1/1 to index -1/0
next_pil = (car.direction - 1) / 2
else:
car.direction *= -1
next_pil = pil
next_track = self.tracks[next_pil]
# move car to next track
track.cars.remove(car)
next_track.add_car(car)
car.counter = 0
car.has_semaphore = False
station.sem.free()
car.counter += 1
def draw(self):
for t in self.tracks:
t.draw()
def __contains__(self,shape):
"""returns True if Line contains stations with shape"""
for pos in self.stations:
station = get_station(pos)
if shape == station.shape:
return True
return False
def delete_track(self):
"""deletes the last track from the line"""
print ("delete track from line color: ", self.color)
track = self.tracks[-1]
l = len(self.tracks)
if track.cars and not l == 1:
print ("we can't delete tracks with cars (unless last one)")
else:
# TODO: if car is deleted, we should do something
# with the passengers...
self.tracks.pop()
if l == 1:
LINES.append(track.color)
class Passenger(object):
"""they want to travel to a station with shape self.shape!"""
def __init__(self,station):
self.station = station
shapes = list(SHAPES) # copy list
shapes.remove(station.shape)
self.shape = random.choice(shapes)
self.car = None
def draw(self,pos,offset=0,angle=0):
# generate vector in angle and length PASSENGERSIZE
v = Vec2d(PASSENGERSIZE*3,0)
v.rotate(angle+90)
# add vector for every offset to pos
v_pos = Vec2d(pos)
v_new = v_pos + v * offset
pos = (int(v_new.x),int(v_new.y))
if ANIMALS:
if self.shape == 'circle':
draw_image('ladybeetle.png',pos,PASSENGERSIZE-1,BLACK,angle)
elif self.shape == 'triangle':
draw_image('ant.png',pos,PASSENGERSIZE-1,BLACK,angle)
elif self.shape == 'square':
draw_image('blowfish.png',pos,PASSENGERSIZE-1,BLACK,angle)
else:
if self.shape == 'circle':
pygame.draw.circle(screen,BLACK,pos,PASSENGERSIZE)
elif self.shape == 'triangle':
draw_triangle(pos,PASSENGERSIZE+1,BLACK,angle)
elif self.shape == 'square':
draw_square(pos,PASSENGERSIZE-1,BLACK,angle)
def enter(self,car):
"""returns True if this passenger wants to enter this car"""
return True
def leave_at(self,station):
"""returns True if this passenger wants to leave the car at the station"""
if station.shape == self.shape:
return True
if self.car:
# TODO: we need some kind of recursive path finding here instead
# stupid passenger: sits in car if shape is on line
if self.shape in self.car.track.line:
return False
# stupid passenger: leaves if another line here
if len(station.get_lines()) > 1:
return True
return False
class Station(object):
"""a station"""
def __init__(self,pos,shape=''):
if not shape:
shape = random.choice(OTHERSTATIONS)
self.shape = shape
self.pos = pos
self.passengers = []
self.sem = Semaphore()
def add_passenger(self):
passengers.append(Passenger(self))
def draw(self):
size = 20
pos = self.pos
# TODO: calculate area of shapes to make it same size optical
# dont use this ugly constants anymore
innercolor = WHITE
if DEBUG and self.sem.used:
innercolor = BLACK
if self.shape == 'circle':
pygame.draw.circle(screen,BLACK,pos,STATIONSIZE)
pygame.draw.circle(screen,innercolor,pos,STATIONSIZE-STATIONTHICKNESS)
if self.shape == 'triangle':
draw_triangle(pos,STATIONSIZE+4,BLACK)
draw_triangle(pos,STATIONSIZE+4-STATIONTHICKNESS*2,innercolor)
if self.shape == 'square':
draw_square(pos,STATIONSIZE-3,BLACK)
draw_square(pos,STATIONSIZE-STATIONTHICKNESS-3,innercolor)
count = 0
for p in self.passengers:
p.draw((pos[0]+int(STATIONSIZE*1.5)+STATIONSIZE*count,pos[1]))
count += 1
def update(self):
global gameover
global count
if random.random() < PROBABILITY_START + count * PROBABILITY_DIFF:
if len(self.passengers) < MAXWAITING:
self.passengers.append(Passenger(self))
else:
gameover = True
def get_lines(self):
"""returns a list of lines connected to the station"""
#TODO PERFORMANCE: should be stored not calculated
ret = []
for l in lines:
for t in l.tracks:
start = get_station(t.startpos)
end = get_station(t.endpos)
if start == self or end == self:
if l not in ret:
ret.append(l)
return ret
def get_tracks(self):
"""returns a list of tracks connected to the station"""
#TODO PERFORMANCE: should be stored, not calculated
ret = []
for l in lines:
for t in l.tracks:
start = get_station(t.startpos)
end = get_station(t.endpos)
if start == self or end == self:
ret.append(t)
return ret
########################################################################
# main programm
########################################################################
def main():
global count
# Initialise stuff
init_game()
pygame.init()
pygame.display.set_caption('Maxi Metro')
clock = pygame.time.Clock()
pos = startpos = (0,0)
have_line = draw_status = False
line = None
# Event loop
while 1:
count += 1
# TODO: ugly code. we have to wrote some functions here
for event in pygame.event.get():
if event.type == QUIT:
return
elif event.type == MOUSEBUTTONDOWN:
if gameover:
init_game()
pos = startpos = (0,0)
have_line = draw_status = False
line = None
else:
draw_status = False
if have_line:
LINES.pop()
have_line = False
if LINES:
pos = event.pos
spos = is_station_pos(pos)
if spos and not draw_status:
startpos = spos
if len(get_station(startpos).get_tracks()) < MAXSTATIONTRACKS:
print ("start drawing from " ,pos, " moving to ", startpos)
draw_status = True
else:
print("no more tracks avaiable at this station")
else:
print ("NO MORE LINES AVAIABLE!")
# handling of clicks at the right side
if event.pos[0] >= MAX_X - RIGHT_OFFSET:
color = int (event.pos[1] / 50)
in_use = len(COLORS) - len(LINES)
if color < in_use:
if event.pos[0] < MAX_X - RIGHT_OFFSET / 2:
line = lines[color]
line.delete_track()
if not line.tracks:
del lines[color]
else:
print ("add track to line with color ", color)
draw_status = have_line = True
line = lines[color]
LINES.append(line.color)
startpos = line.tracks[-1].endpos
elif event.type == MOUSEMOTION and not gameover:
if not CROSSING and not intersect_any(startpos,event.pos):
# TODO: there is stil a bug in CROSSING = False in seldom cases
pos = event.pos
spos = is_station_pos(pos)
# TODO: there should be no station in the way
# (plus a little extrasize)
# or: minimum angle between tracks
if draw_status and spos and not is_in_range(pos,startpos):
if (not DOUBLE_TRACKS and not is_track(startpos,spos) and
not is_track(spos,startpos)):
if (MAXSTATIONTRACKS and
len(get_station(spos).get_tracks()) < MAXSTATIONTRACKS and
len(get_station(startpos).get_tracks()) < MAXSTATIONTRACKS):
print ("stop drawing at " , pos , " moving to " , spos)
if have_line:
print ("appending track to line...")
# startpos = spos
line.tracks.append(Track(startpos,spos,line.color,line,0))
line.stations.append(spos) # TODO: should not be double if circle
else:
print ("creating new line...")
line = Line(startpos, spos)
lines.append(line)
have_line = True
startpos = spos
else:
print("to many tracks at station!")
else:
print("no doubletracks allowed!")
screen.fill(WHITE)
draw_interface()
if not gameover:
if draw_status:
if (MAXSTATIONTRACKS and len(get_station(startpos).get_tracks()) < MAXSTATIONTRACKS):
pygame.draw.line(screen,LINES[-1],startpos,pos,5)
else:
draw_status = False
update()
for l in lines:
l.draw()
for s in stations:
s.draw()
if gameover:
center_text((int(MAX_X/2),int(MAX_Y/2)),"GAME OVER!",BLACK,52)
center_text((int(MAX_X/2),int(MAX_Y/2)),"GAME OVER!",RED,50)
center_text((int(MAX_X/2),int(MAX_Y/2)+100),"click to restart",BLACK,20)
pygame.display.update()
msElapsed = clock.tick(FPS) # TODO: Gamespeed should be FPS-independent
if __name__ == '__main__': main()