/
planetarium.py
1249 lines (1076 loc) · 45.9 KB
/
planetarium.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
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import division
"""
Emily Newman's TP F15
Compatible with Python 2.7
Using Pygame and PyEphem libraries
Uses the Yale Bright Star Catalog, as well as PyEphem's star catalog
YBS available at http://mirrors.dotsrc.org/exherbo/YBS.edb
Used http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html
for distance of a point from a line
Icon images obtained from Google Images.
"""
import pygame
from framework import Framework
import ephem
import ephem.stars
import ephem.cities
import datetime, time
import math
import copy
import os
"""
TODO MASTER LIST:
-implement quiz
-all the extra stuff (video, readme, etc)
"""
# read/writeFile from the class notes on Basic File I/O
# http://www.cs.cmu.edu/~112/notes/notes-strings.html#basicFileIO
def readFile(filename, mode="rt"): # rt = "read text"
with open(filename, mode) as fin:
return fin.read()
def writeFile(filename, contents, mode="wt"): # wt = "write text"
with open(filename, mode) as fout:
fout.write(contents)
def pointInBox(point, boxCoords): #from my hw8a.py
(x, y) = point
(boxLeft, boxTop, boxRight, boxBot) = boxCoords
return boxLeft<=x<=boxRight and boxTop<=y<=boxBot
def pointInCircle(point, circlePos, r):
(x, y) = point
(cx, cy) = circlePos
return (x-cx)**2 + (y-cy)**2 <= r**2
class Star(object):
def __init__(self, name, body):
self.name = name
self.body = body #type == ephem.Body
self.screenPos = None
self.showInfo = False
self.r = 1
def __str__(self):
return self.name
def __eq__(self, other):
return isinstance(other, Star) and self.name == other.name
def __hash__(self):
return hash(self.name)
def changeInfo(self):
self.showInfo = not self.showInfo
def calculate(self, ref, shift): #ref = city, shift = Planetarium.shift
self.body.compute(ref)
self.r = int(self.body.mag)
if self.body.alt < 0: #below horizon
self.screenPos = None
return #do nothing, screenPos remains None
phi = self.body.alt + math.pi/2
theta = 2*math.pi - self.body.az
#convert from spherical to cartesian xy coordinates
#constant sphere radius
x = math.sin(phi)*math.cos(theta)
y = math.sin(phi)*math.sin(theta)
#convert to draw-able coordinates
#stores them based on "big" screen, not "current" screen
self.screenPos = (shift * (x + 1), shift * (-y + 1))
def displayPos(self, left, up):
if self.screenPos == None: return None
(x,y) = self.screenPos
return (int(x - left), int(y - up))
class Line(object):
def __init__(self, startStar, screenPos, endStar=None):
self.screenPos = screenPos
(left, up) = screenPos
self.star1 = startStar
(self.dispX1, self.dispY1) = self.star1.displayPos(left, up)
(self.x1, self.y1) = self.star1.screenPos
self.star2 = endStar
(self.x2, self.y2) = self.star1.screenPos
(self.dispX2, self.dispY2) = (self.dispX1, self.dispY1)
self.color = (255, 255, 255) #white
self.width = 2
def __hash__(self):
if self.star2 != None:
return hash(self.star1.name) + hash(self.star2.name)
else:
return hash(self.star1.name) + hash("None")
def __repr__(self):
if self.star2 != None:
return self.star1.name+"|"+self.star2.name
else:
return self.star1.name+"|"+"None"
def __eq__(self, other):
return (isinstance(other, Line) and (other.star1 == self.star1
and other.star2 == self.star2) or (other.star1 == self.star2
and other.star2 == self.star1))
def onClick(self, x, y):
#point distance from a line equation
(x1, y1, x2, y2) = (self.dispX1, self.dispY1, self.dispX2, self.dispY2)
d = abs((x2-x1)*(y1-y) - (x1-x)*(y2-y1))
denom = math.sqrt((x2-x1)**2 + (y2-y1)**2)
if denom != 0: d /= denom
return d <= 3*self.width
def setEnd(self, star, ref):
(left, up) = ref
self.star2 = star
(self.x2, self.y2) = self.star2.screenPos
(self.dispX2, self.dispY2) = self.star2.displayPos(left, up)
def updateLine(self, ref):
(left, up) = ref
(self.dispX1, self.dispY1) = self.star1.displayPos(left, up)
(self.dispX2, self.dispY2) = self.star2.displayPos(left, up)
def updateEndPoint(self, x, y):
#only used temporarily for aesthetic purposes
self.dispX2 = x
self.dispY2 = y
def displayPoints(self, ref):
(left, up) = ref
if self.star2 == None:
return (self.star1.displayPos(left,up), (self.dispX2, self.dispY2))
else:
return (self.star1.displayPos(left, up),
self.star2.displayPos(left, up))
def draw(self, screen, ref):
(start, end) = self.displayPoints(ref)
pygame.draw.line(screen, self.color, start, end, self.width)
class Hint(object):
def __init__(self, x, y, text, width, height):
self.x = x
self.y = y
self.text = text
self.show = False
self.textcolor = (0, 0, 0) #black
self.bgcolor = (242, 189, 46) #yellowish
self.width = width
self.height = height
self.text2 = "Click here to go back."
def display(self, value=True):
self.show = value
def onClick(self, x, y):
if (pointInBox((x,y), (self.x, self.y, self.x+self.width,
self.y+self.height))):
self.show = False
return True
return False
def draw(self, screen, font):
if self.show:
pygame.draw.rect(screen, self.bgcolor,
pygame.Rect(self.x, self.y, self.width, self.height))
text = font.render(self.text, 1, self.textcolor)
screen.blit(text, (self.x+self.width//2-font.size(self.text)[0]//2,
self.y+self.height//3-font.size(self.text)[1]//2))
text2 = font.render(self.text2, 1, self.textcolor)
screen.blit(text2, (self.x+self.width//2-font.size(self.text2)[0]//2,
self.y+self.height*2//3-font.size(self.text2)[1]//2))
def setText(self, text):
self.text = text
class Button(object):
def __init__(self, name, x, y, color, width=25, height=15):
# x and y are upper left corner
self.name = name
self.x = x
self.y = y
self.width = width
self.height = height
self.BLACK = (0, 0, 0)
self.color = color
def onClick(self, x, y):
return pointInBox((x,y), (self.x, self.y,
self.x+self.width, self.y+self.height))
def draw(self, screen, font):
#todo use images instead of pygame drawing?
pygame.draw.rect(screen, self.BLACK, pygame.Rect(self.x, self.y,
self.width, self.height), 1)
screen.fill(self.color, pygame.Rect(self.x, self.y,
self.width, self.height))
class HintButton(Button):
def __init__(self, name, x, y, color, width=50, height=50):
super(HintButton, self).__init__(name, x, y, color, width, height)
self.icon = pygame.image.load(os.path.join('icons', self.name+'.png'))
def draw(self, screen, font):
screen.blit(self.icon, (self.x, self.y))
class ModeButton(Button):
def __init__(self, name, x, y, color, width=25, height=15):
super(ModeButton, self).__init__(name, x, y, color, width, height)
def draw(self, screen, font):
word = self.name[0].upper() + self.name[1:]
if (self.width, self.height) == (25, 15): #defaults
(self.width, self.height) = font.size(word)
super(ModeButton, self).draw(screen, font)
text = font.render(word, 1, self.BLACK)
screen.blit(text, (self.x, self.y))
def onClick(self, x, y):
if pointInBox((x,y), (self.x, self.y, self.x+self.width,
self.y+self.height)):
return self.name
return None
class TimeButton(Button):
def __init__(self, name, x, y, color, width=25, height=15):
super(TimeButton, self).__init__(name, x, y, color, width, height)
#set max time val
self.minTime = 0
if self.name == "year":
self.minTime = 100
self.maxTime = 3000
self.width += 15
elif self.name == "month":
self.minTime = 1
self.maxTime = 12
elif self.name == "day":
self.minTime = 1
self.maxTime = 31 #to be controlled in Planetarium
elif self.name == "hour":
self.maxTime = 23
else: #minute
self.maxTime = 59
self.timeVal = 0
self.YELLOW = (255, 255, 0)
self.WHITE = (255, 255, 255)
def up(self):
if self.minTime <= self.timeVal+1 <= self.maxTime:
self.timeVal += 1
def down(self):
if self.minTime <= self.timeVal-1 <= self.maxTime:
self.timeVal -= 1
def getTime(self):
return self.timeVal
def setTimeVal(self, val):
self.timeVal = val
def onClick(self, x, y):
if pointInBox((x,y), (self.x, self.y, self.x+self.width,
self.y+self.height)):
return self
def draw(self, screen, font):
super(TimeButton, self).draw(screen, font)
text = font.render(str(self.timeVal), 1, self.BLACK)
screen.blit(text, (self.x, self.y))
name = self.name[0].upper() + self.name[1:]
text = font.render(name, 1, self.WHITE)
screen.blit(text, (self.x+self.width//2-font.size(name)[0]//2,
self.y-font.size(name)[1]-5))
class NowButton(Button):
def draw(self, screen, font):
word = self.name[0].upper() + self.name[1:]
super(NowButton, self).draw(screen, font)
text = font.render(word, 1, self.BLACK)
screen.blit(text, (self.x, self.y))
def onClick(self, x, y):
if pointInBox((x,y), (self.x, self.y, self.x+self.width,
self.y+self.height)):
return datetime.datetime.now()
class ToggleButton(Button):
def __init__(self, name, x, y, color, width=25, height=15):
super(ToggleButton, self).__init__(name, x, y, color, width, height)
self.toggle = False
self.offColor = color #red
self.onColor = (0, 204, 0) #green
self.width += 5
def onClick(self, x, y):
if pointInBox((x,y), (self.x, self.y, self.x+self.width,
self.y+self.height)):
self.toggle = not self.toggle
return self.toggle
def draw(self, screen, font):
if self.toggle:
word = "ON"
self.color = self.onColor
else:
word = "OFF"
self.color = self.offColor
super(ToggleButton, self).draw(screen, font)
text = font.render(word, 1, self.BLACK)
screen.blit(text, (self.x, self.y))
class ListButton(Button):
def __init__(self, name, x, y, color, data, width=25, height=15):
super(ListButton, self).__init__(name, x, y, color, width, height)
self.data = data #stores strings
self.selectedWord = self.data[0]
self.index = 0
def selectItem(self, item):
self.selectedWord = item
index = self.data.find(item)
def down(self):
self.index = (self.index+1)%len(self.data)
self.selectedWord = self.data[self.index]
return self.data[self.index]
def up(self):
if self.index - 1 < 0:
self.index = len(self.data) - (self.index + 1)
else:
self.index -= 1
self.selectedWord = self.data[self.index]
return self.data[self.index]
def getItem(self):
return self.data[self.index]
def onClick(self, x, y):
if pointInBox((x,y), (self.x, self.y, self.x+self.width,
self.y+self.height)):
return self
def draw(self, screen, font):
(self.width, self.height) = font.size("OOOOOOOOOOOOOO")
super(ListButton, self).draw(screen, font)
text = font.render(self.selectedWord, 1, self.BLACK)
screen.blit(text, (self.x, self.y))
class DrawButton(Button):
def __init__(self, name, x, y, color, width=25, height=15):
super(DrawButton, self).__init__(name, x, y, color, width, height)
self.icon = pygame.image.load(os.path.join('icons', name+'.png'))
def drawSelected(self, screen):
pygame.draw.rect(screen, self.color,
pygame.Rect(self.x, self.y, self.width, self.height))
def draw(self, screen, font):
screen.blit(self.icon, (self.x, self.y))
def onClick(self, x, y):
if pointInBox((x,y), (self.x, self.y, self.x+self.width,
self.y+self.height)):
return self
class Planetarium(Framework):
def __init__(self, width=1000, height=666, fps=50, title="PyPlanetarium"):
super(Planetarium, self).__init__(width, height, fps, title)
self.initBasics()
self.initColors()
self.initButtons()
self.initOptionsMode()
self.inRealTime = False
self.mode = "splash"
#draw mode initializing
self.initDrawMode()
self.updateOptionButtons()
self.justClicked = False
(self.mouseStartX, self.mouseStartY) = (None, None)
self.infostar = None
self.infopos = None
self.lastMode = None
self.initSplash()
self.initHelp()
self.initQuiz()
################################# INIT FUNCTIONS ##############################
def initBasics(self):
self.title = "PyPlanetarium"
self.bgColor = self.BLACK
self.shift = 1400 #changes with zooming
#full screen width and height is self.shift*2 at any time
self.margin = 10
self.minZoom = 500
self.maxZoom = 10000
self.shiftChange = 10
(self.MIN_ALT, self.MAX_ALT) = (0, math.pi/2)
(self.MIN_AZ, self.MAX_AZ) = (0, 2*math.pi) #radians
# upper left corner of screen in terms of sky
# starts w/ center of screen being (0,0) of sky
self.screenPos = (self.shift-self.width//2, self.shift-self.height//2)
self.date = datetime.datetime.now() #always Datetime form
self.starList = [ ]
self.cities = [city for city in ephem.cities._city_data]
self.cities.sort()
self.initPittsburgh()
self.city = self.pgh
self.cityName = "Pittsburgh"
self.initStars()
#read in more stars!
yaleCatalog = self.readInDB("ybs.edb")
self.starList += yaleCatalog #using Yale's Bright Star catalog
def initColors(self):
self.LIGHT_BLUE = (114, 164, 255)
self.RED = (208, 9, 9)
self.GREEN2 = (0, 204, 0)
self.PINK = (255, 102, 255)
self.YELLOW = (255, 255, 0)
def initQuiz(self):
self.hint = Hint(self.width//2-175, self.height//2-65, "", 370, 120)
self.correctMsg = "Correct!"
size = 50
self.quizButtons = [
HintButton("hint", self.width-size, self.height-size, self.YELLOW,
size, size)
]
self.constindex = 0
self.quizzes = ["bigdipper", "littledipper"]
self.const = self.quizzes[0]
def initSplash(self):
self.splashScreen = pygame.image.load(os.path.join("screens",
"splash.png"))
self.splashButtons = [
ModeButton("GO", self.width//2, self.height*7//8, self.GREEN2,
self.bigFont.size("GO")[0], self.bigFont.size("GO")[1])
]
self.inFastTime = True
def initButtons(self):
self.buttons = [
ModeButton("draw", self.width-self.font.size("draw")[0], 0,
self.LIGHT_BLUE),
ModeButton("options",self.width-self.font.size("draw")[0]
-self.font.size("options")[0]-10, 0, self.LIGHT_BLUE)
]
def initHelp(self):
self.helpScreen = pygame.image.load(os.path.join("screens", "help.png"))
self.helpButtons = [
ModeButton("return", self.width//2-self.font.size("return")[0]//2,
self.height*7//8, self.LIGHT_BLUE)
]
def initOptionsMode(self):
#splitting the screen into 9ths width wise, 8ths height wise
self.optionsButtons = [
TimeButton("year", self.width*5//18, self.height*3//8, self.WHITE),
TimeButton("month", self.width*4//9, self.height*3//8, self.WHITE),
TimeButton("day", self.width*5//9, self.height*3//8, self.WHITE),
TimeButton("hour", self.width*6//9, self.height*3//8, self.WHITE),
TimeButton("minute", self.width*7//9, self.height*3//8, self.WHITE),
NowButton("now", self.width*8//9, self.height*3//8, self.PINK, 33),
ListButton("city", self.width//2-self.font.size("OOOOOOOOOOOOOO")[0]//2,
self.height*4//8, self.LIGHT_BLUE, self.cities),
ToggleButton("realtime", self.width//2-self.font.size("OFF")[0]//2,
self.height*5//8, self.RED),
ModeButton("return", self.width//2-self.font.size("Return")[0]//2,
self.height*6//8, self.GREEN2),
ModeButton("quit", self.width//2-self.font.size("Quit")[0]//2,
self.height*7//8, self.RED )
]
self.selectedButton = None
def initDrawMode(self):
size = 50
self.drawModeButtons = [
ModeButton("quiz", 0, 0, self.PINK),
ModeButton("help", self.width-self.font.size("Options")[0]-
self.font.size("Draw")[0]-60, 0, self.LIGHT_BLUE),
DrawButton("erase", 0, self.height//8, self.YELLOW, size, size),
DrawButton("undo", 0, self.height*2//8, self.YELLOW, size, size),
DrawButton("redo", 0, self.height*3//8, self.YELLOW, size, size),
DrawButton("clear", 0, self.height*4//8, self.YELLOW, size, size),
DrawButton("save", 0, self.height*5//8, self.YELLOW, size, size),
DrawButton("loadfile", 0, self.height*6//8,self.YELLOW, size, size),
DrawButton("savefile", 0, self.height*7//8, self.YELLOW, size, size)
]
self.onLine = False
self.lines = [ ]
self.undidLines = [ ]
self.undidActions = [ ]
self.erasedLines = [ ]
self.lastAction = "draw"
self.selectedDrawButton = None
self.drawMode = "draw"
self.actions = [ ]
self.iconSize = 50
def initStars(self): #FLAG
for star in ephem.stars.db.split("\n"):
starName = star.split(",")[0]
if starName == "": continue #not a star
self.starList.append(Star(starName, ephem.star(starName)))
def initPittsburgh(self):
self.pgh = ephem.Observer()
self.pgh.lat = "40:26:26.3"
self.pgh.long = "-79:59:45.20"
self.pgh.date = ephem.Date(self.date)
self.cities.insert(0, "Pittsburgh")
########################## LOAD FROM FILE FUNCTIONS ###########################
def readInDB(self, path):
#returns list of Star objects from all stars in DB
db = readFile(path)
starList = [ ]
for line in db.splitlines():
if line.startswith("#") or line == "": continue
line = line.strip()
body = ephem.readdb(line)
if body.name == "Benetnasch": continue #duplicate of Alkaid
starList.append(Star(body.name, body))
return starList
def unpackFile(self, source="savedata.txt", folder=""):
directory = os.getcwd()
if folder == "": pass
else:
directory = os.path.join(directory, folder)
lines = [ ]
actions = [ ]
if source not in os.listdir(directory):
return 1
#TODO:popup saying "not available, chk filename savedata.txt"
info = readFile(os.path.join(directory, source)).splitlines()
date = None
screenPos = None
shift = None
for index in xrange(len(info)):
action = info[index]
if action == "": continue
if index == 0: #datetime
date = datetime.datetime.strptime(action, "%Y %m %d %H %M")
continue
elif index == 1: #screenPos and shift
action = action.split(".")
screenPos = (int(action[0]), int(action[1]))
shift = int(action[2])
city = action[3]
if city == "Pittsburgh": city = self.pgh
else: city = ephem.city(city)
city.date = date
continue
action = action.split(".")
typeof = action[0]
line = action[1]
line = line.split("|")
(star1Name, star2Name) = (line[0], line[1])
(star1, star2) = (None, None)
for star in self.starList:
if star.name == star1Name:
star1 = star
elif star.name == star2Name:
star2 = star
star1.calculate(city, shift)
star2.calculate(city, shift)
newLine = Line(star1, screenPos)
newLine.setEnd(star2, screenPos)
lines += [ newLine ]
actions += [ (typeof, lines[-1]) ]
self.date = date
self.screenPos = screenPos
self.shift = shift
self.lines = copy.copy(lines)
self.actions = copy.copy(actions)
def loadConstellation(self, const):
self.const = const
folder = "const" #where all constellations are
self.unpackFile(const+".txt", folder)
self.constLines = copy.copy(self.lines)
#create set of stars in constellation
self.constStars = set()
for line in self.constLines:
self.constStars.add(line.star1)
self.constStars.add(line.star2)
self.lines = [ ]
self.actions = [ ]
################################ UPDATE FUNCTIONS #############################
def calculateStars(self):
for star in self.starList:
star.calculate(self.city, self.shift)
def updateScreenPos(self, shiftChange, x=0, y=0):
(oldX, oldY) = self.screenPos
if shiftChange == 0:
self.screenPos = (x+oldX, y+oldY)
else:
oldShift = self.shift
self.shift += shiftChange
self.screenPos=(oldX*self.shift/oldShift, oldY*self.shift/oldShift)
def updateDate(self):
yr = self.date.year
mon = self.date.month
day = self.date.day
hr = self.date.hour
mi = self.date.minute
for button in self.optionsButtons:
if button.name == "year":
yr = button.getTime()
elif button.name == "month":
mon = button.getTime()
elif button.name == "day":
day = button.getTime()
elif button.name == "hour":
hr = button.getTime()
elif button.name == "minute":
mi = button.getTime()
self.date = self.date.replace(yr, mon, day, hr, mi)
def updateCity(self):
self.city.date = ephem.Date(self.date)
# self.city.epoch = self.city.date
def updateOptionButtons(self):
for button in self.optionsButtons:
if button.name == "year":
button.setTimeVal(self.date.year)
elif button.name == "month":
button.setTimeVal(self.date.month)
elif button.name == "day":
button.setTimeVal(self.date.day)
elif button.name == "hour":
button.setTimeVal(self.date.hour)
elif button.name == "minute":
button.setTimeVal(self.date.minute)
def resetTimeButtonColors(self):
for button in self.optionsButtons:
if isinstance(button, TimeButton) or isinstance(button, ListButton):
button.color = self.WHITE
if self.selectedButton != None:
self.selectedButton.color = self.YELLOW
def resetDrawMode(self):
self.date = datetime.datetime.now()
self.city = self.pgh
self.screenPos = (self.shift-self.width//2, self.shift-self.height//2)
############################### quiz functions ##############################
def checkAnswer(self):
lines = set(self.lines) #gets rid of duplicates
constLines = set(self.constLines)
stars = set()
for line in self.lines:
stars.add(line.star1)
stars.add(line.star2)
diff = len(self.constStars) - len(stars)
linediff = len(constLines) - len(lines)
if diff > 0 or (diff==0 and stars!=self.constStars):
#not enough stars! find missing star
missingStars = self.constStars - stars
#get stars in constellation but not in drawing
hintStar = missingStars.pop()
hinttext = "Hint: You are missing " + str(hintStar)
elif diff < 0: #too many stars! find the extra star
extraStars = stars - self.constStars
#get stars in drawing that arent in constellation
hintStar = extraStars.pop()
hinttext = "Hint: "+str(hintStar)+" does not belong!"
elif linediff < 0 or (linediff==0 and lines!=constLines):
#too many lines/lines where they shouldn't belong
wrongLines = lines - constLines
#get the lines in drawing not in constellations
hintLine = wrongLines.pop()
hinttext = ("Hint: " +hintLine.star1.name+" and "+
hintLine.star2.name+" shouldn't be connected!")
elif linediff > 0:
#not enough lines! find the missing line
missingLines = constLines - lines
hintLine = missingLines.pop()
star1, star2 = hintLine.star1, hintLine.star2
hinttext = ("Hint: " +str(star1)+" and "+str(star2)+" should be"
+" connected!")
else:
hinttext = self.correctMsg
return hinttext
########################### CHECK FUNCTIONS ##############################
def checkDrawButtons(self, x, y):
for button in self.drawModeButtons:
#undo, redo, erase, clear, save
if button.onClick(x, y) == None: continue
self.selectedDrawButton = button
if isinstance(button, ModeButton):
self.lastMode = self.mode
if self.mode == "draw" and button.name == "quiz":
self.loadConstellation(self.quizzes[0])
self.mode = button.name
elif self.mode == "quiz" and button.name == "quiz":
self.mode = "draw"
else:
self.mode = button.name
elif button.name == "erase":
if self.drawMode == "draw":
self.drawMode = "erase"
else:
self.drawMode = "draw"
self.selectedDrawButton = None
return 1
elif button.name == "undo":
if self.actions != [ ]:
toUndo = self.actions.pop()
self.undidActions.append(toUndo)
(action, line) = toUndo
if action == "erase":
self.lines.append(line)
elif action == "draw":
self.lines.remove(line)
return 1
elif button.name == "redo":
if self.undidActions != [ ]:
toRedo = self.undidActions.pop()
self.actions.append(toRedo)
(action, line) = toRedo
if action == "erase":
self.lines.remove(line)
elif action == "draw":
self.lines.append(line)
return 1
elif button.name == "clear":
self.lines = [ ]
self.actions = [ ]
elif button.name == "save":
pygame.image.save(self.screen, "screenshot.jpg")
return 1
elif button.name == "savefile":
(left, up) = self.screenPos
data = (self.date.strftime("%Y %m %d %H %M")+"\n"+str(int(left))
+"."+str(int(up))+"."+str(self.shift)+"." +
self.cityName + "\n")
for action in self.actions:
(typeof, line) = action
data += typeof + "."+ str(line)+"\n"
writeFile("savedata.txt", data)
print "File saved successfully to savedata.txt!" #TODO popup?
elif button.name == "loadfile":
try:
lines = self.unpackFile()
if lines == 1:
print ("File not found! Make sure it is named "+
"savedata.txt")
#TODO: file not loaded popup?
#TODO: popup saying loaded correctly?
except:
print "Not a valid file!"
def checkLines(self, x, y):
if self.drawMode == "erase":
erasedLine = None
for line in self.lines: #FLAG error here
if line.onClick(x, y):
erasedLine = line
self.lastAction = "erase"
if erasedLine != None:
self.actions.append(("erase", erasedLine))
self.erasedLines.append(erasedLine)
self.lines.remove(erasedLine)
erasedLine = None
def checkStarsDrawMode(self, x, y):
(left, up) = self.screenPos
if self.drawMode == "draw":
for star in self.starList:
if star.displayPos(left,up) == None: continue #not on screen
(cx, cy) = star.displayPos(left,up)
(width, height) = self.smallFont.size(star.name)
if pointInCircle((x,y), (cx, cy), star.r):
self.selectedDrawButton = None
if self.onLine == False:
self.lines.append(Line(star, self.screenPos))
self.onLine = True
else: #is on a line
if star != self.lines[-1].star1 and self.lines!=[]:
self.lines[-1].setEnd(star, self.screenPos)
self.actions.append(("draw", self.lines[-1]))
elif self.lines!=[]:
self.lines.pop(-1)
self.onLine = False
return 1
check = self.checkStarLabelsDrawMode(x, y)
if check == 1: return 1
if self.onLine and self.selectedDrawButton==None:
if self.lines != [ ]: self.lines.pop()
self.onLine = False
return 1
def checkStarLabelsDrawMode(self, x, y):
(left, up) = self.screenPos
if self.drawMode == "draw":
for star in self.starList:
if star.displayPos(left,up) == None: continue #not on screen
(cx, cy) = star.displayPos(left,up)
(width, height) = self.smallFont.size(star.name)
if pointInBox((x,y),(cx, cy, cx+width, cy+height)):
self.selectedDrawButton = None
if self.onLine == False:
self.lines.append(Line(star, self.screenPos))
self.onLine = True
return 1
else: #is on a line
if star != self.lines[-1].star1:
self.lines[-1].setEnd(star, self.screenPos)
self.actions.append(("draw", self.lines[-1]))
else:
self.lines.pop(-1)
self.onLine = False
return 1
def optionsMousePressed(self, x, y):
(left, up) = self.screenPos
for button in self.optionsButtons:
if super(type(button), button).onClick(x,y):
val = button.onClick(x, y)
if button.name == "realtime":
self.inRealTime = val
elif isinstance(button, NowButton):
self.date = val
self.updateOptionButtons()
elif isinstance(button, ModeButton):
if val == "return":
self.mode = self.lastMode
else:
self.mode = val
else:
self.selectedButton = val
def checkStars(self, x, y):
(left, up) = self.screenPos
for star in self.starList:
if star.displayPos(left,up) == None: continue #not on screen
(cx, cy) = star.displayPos(left,up)
(width, height) = self.smallFont.size(star.name)
if (pointInCircle((x,y), (cx, cy), star.r)
or pointInBox((x,y), (cx, cy, cx+width, cy+height))):
self.infostar = star
return #ensures only one star info shown
self.infostar = None
def checkNavButtons(self, x, y):
(left, up) = self.screenPos
for button in self.buttons:
name = button.onClick(x, y)
if name != None and self.mode != name:
self.lastMode = self.mode
self.mode = name
if self.mode == "draw":
self.inRealTime = False
self.infostar = None
elif self.mode == "options":
self.updateOptionButtons()
return
elif name != None and self.mode == name:
self.mode = "main"
button.color = self.LIGHT_BLUE
return
def legalScreenPos(self, x, y):
return (0-self.margin <= x <= self.shift*2-self.width+2*self.margin
and 0-self.margin <= y <= self.shift*2-self.height+2*self.margin)
def checkSplashButtons(self, x, y):
for button in self.splashButtons:
if super(type(button), button).onClick(x, y):
if isinstance(button, ModeButton) and button.name == "GO":
self.mode = "main"
self.inFastTime = False
def checkHelpButtons(self, x, y):
for button in self.helpButtons:
if super(type(button), button).onClick(x, y):
if isinstance(button, ModeButton) and button.name == "return":
self.mode = self.lastMode
def checkQuizButtons(self, x, y):
for button in self.quizButtons:
if super(type(button), button).onClick(x, y):
if isinstance(button, HintButton) and button.name == "hint":
#if box is check: click again to move to next const
result = self.checkAnswer()
self.hint.setText(result)
self.hint.display()
def checkHint(self, x, y):
clicked = self.hint.onClick(x, y)
if (clicked and (self.hint.text == "Correct!" or
self.hint.text == "You have completed the quiz!")):
self.constindex+=1
self.hint.text = ""
if self.constindex == len(self.quizzes):
self.hint.setText("You have completed the quiz!")
self.lines = [ ]
self.hint.display(True)
elif self.constindex > len(self.quizzes):
self.hint.setText("")
self.mode = "draw"
self.infostar = None
self.resetDrawMode()
else:
self.loadConstellation(self.quizzes[self.constindex])
################################# BASE FUNCTIONS ##############################
def mousePressed(self, x, y):
#Splash screen
if self.mode == "splash":
self.checkSplashButtons(x, y)
elif self.mode == "help":
self.checkHelpButtons(x, y)
#Options screen:
elif self.mode == "options":
self.optionsMousePressed(x, y)
#In main screen:
#check all buttons
elif self.mode == "draw" or self.mode == "quiz":
if self.mode == "quiz":
self.checkHint(x, y)
self.checkQuizButtons(x, y)
check = self.checkDrawButtons(x, y)
if check == 1: return
#check the nav buttons
check = self.checkNavButtons(x, y)
if check == 1: return
check = self.checkStarsDrawMode(x, y)
if check==1: return
self.checkLines(x, y)
elif self.mode == "main":
#check all buttons
check = self.checkNavButtons(x, y)