-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfindCameraPositions.py
More file actions
executable file
·1219 lines (976 loc) · 39.6 KB
/
findCameraPositions.py
File metadata and controls
executable file
·1219 lines (976 loc) · 39.6 KB
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
import csv, shutil, sys, os, copy, glob, pickle
sys.path.append('/usr/local/lib/python2.7/site-packages')
import random, math
import numpy as np
from Queue import PriorityQueue
playerAccelerations = ["./Longplay5/playerAccelerationTrack.csv"]
spriteAccelerations = ["./Longplay5/spriteAccelerationTrack.csv"]
spritesListings = ["./Longplay5/spriteDescripts.csv"]
cameraPositions = "./Longplay5/cameraPositions.csv"
startAndEndFrames =[[33368, 38847]]
#3: 512, 5300 #5: 33368, 38847
class EngineNode:
def __init__(self, myParent, engine, distanceToGoal=0):
#self.parent = myParent
self.engine = engine
self.distanceFromRoot = 0
self.distanceToGoal = distanceToGoal
if not myParent ==None:
self.distanceFromRoot = myParent.distanceFromRoot+1
def GetTotalDistance(self):
return self.distanceFromRoot+self.distanceToGoal
#simulated annealing/GA algorithm
#montecarlo
#A single engine. transforms rules (in the form of Conditions)
class Engine:
def __init__(self, parent):
self.currLevel = None#Map of curr level sprites
self.rules = []
self.controlRules = []
self.totalRules = []
self.parentEngine = None
if not parent == None:
self.currLevel = parent.currLevel#Map of curr level sprites
self.rules = list(parent.rules)
self.controlRules = list(parent.controlRules)
self.totalRules = list(self.rules+self.controlRules)
self.parentEngine = parent
def __eq__(self, other):
if isinstance(other, self.__class__):
if len(self.rules)==len(other.rules) and len(self.controlRules)==len(other.controlRules):
for index in range(0, len(self.rules)):
if not self.rules[index]==other.rules[index]:
return False
for index in range(0, len(self.controlRules)):
if not self.controlRules[index]==other.controlRules[index]:
return False
return True
else:
return False
else:
return False
def __ne__(self, other):
if isinstance(other, self.__class__):
return not self.__eq__(other)
else:
return True
def __hash__(self):
return hash(tuple(self.rules), tuple(self.controlRules), tuple(self.totalRules))
def RemoveRule(self, rule):
if rule in self.rules:
self.rules.remove(rule)
if rule in self.controlRules:
self.controlRules.remove(rule)
if rule in self.totalRules:
self.totalRules.remove(rule)
def ReplaceRule(self, oldRule, newRule, oldEngine):
if oldRule in oldEngine.rules:
ruleIndex = oldEngine.rules.index(oldRule)
if not ruleIndex == -1 and ruleIndex<len(self.rules):
self.rules[ruleIndex] = newRule
if oldRule in oldEngine.controlRules:
ruleIndex = oldEngine.controlRules.index(oldRule)
if not ruleIndex == -1 and ruleIndex<len(self.controlRules):
self.controlRules[ruleIndex] = newRule
ruleIndex = oldEngine.totalRules.index(oldRule)
if not ruleIndex == -1 and ruleIndex<len(self.totalRules ):
self.totalRules[ruleIndex] = newRule
def AddRule(self, newRule, prevFrame, goalFrame):
self.rules.append(newRule)
self.totalRules.append(newRule)
if isinstance(newRule.change[0], VelocityXCondition) or isinstance(newRule.change[0], VelocityYCondition):
rulesToUpdate = []
for rule in self.totalRules:
if rule.activated:
rulesToUpdate.append(rule)
frames = PhysicsPredict(prevFrame, self, goalFrame)
minFrame = None
minDist = float("inf")
for frame in frames:
frameDist = FrameDistance(frame, changeFrames[currIndex])
if frameDist<minDist:
minDist = frameDist
minFrame = frame
minConditions = minFrame.ReallyGetConditions()
minConditionsSet = set(minConditions)
framesPlus = Predict(prevFrame, self, goalFrame)
minFramePlus = None
minDistPlus = float("inf")
for frame in framesPlus:
frameDist = FrameDistance(frame, changeFrames[currIndex])
if frameDist<minDistPlus:
minDistPlus = frameDist
minFramePlus = frame
minConditionsPlus = minFramePlus.ReallyGetConditions()
minConditionsSetPlus = set(minConditionsPlus)
for rule in rulesToUpdate:
rule.activated = True
if isinstance(rule.change[0], VelocityXCondition) or isinstance(rule.change[0], VelocityYCondition):
#if this rule was activated last frame, make sure adding new rule won't break that
for precog in rule.preconditions:
precog.conditionList = list(minConditionsSet.intersection(precog.conditionList))
precog.changeConditions = list(minConditionsSet.intersection(precog.changeConditions))
else:
#if this rule was activated last frame, make sure adding this rule won't break that
for precog in rule.preconditions:
precog.conditionList = list(minConditionsSetPlus.intersection(precog.conditionList))
precog.changeConditions = list(minConditionsSetPlus.intersection(precog.changeConditions))
#The basic idea of a condition
class Condition(object):
def __init__(self, frameObject):
self.pastFrames = 0
self.frameObject = frameObject
self.isPlayerRule = False
def UpdatePastFrames(self):
self.pastFrames +=1
class VelocityXCondition(Condition):
def __init__(self, frameObject, velocityVal):
super(VelocityXCondition,self).__init__(frameObject)
self.spriteName = frameObject.name
self.velocityValue = velocityVal
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.spriteName==other.spriteName and self.pastFrames==other.pastFrames and self.velocityValue==other.velocityValue
else:
return False
def __ne__(self, other):
if isinstance(other, self.__class__):
return not self.__eq__(other)
else:
return True
def __hash__(self):
return hash(tuple([self.pastFrames, self.spriteName, self.velocityValue]))
def clone(self):
condition = VelocityXCondition(self.frameObject, self.velocityValue)
condition.pastFrames = self.pastFrames
condition.isPlayerRule = self.isPlayerRule
return condition
def __str__(self):
return "VelocityXCondition: "+str([self.spriteName, self.velocityValue])
class VelocityYCondition(Condition):
def __init__(self, frameObject, velocityVal):
super(VelocityYCondition,self).__init__(frameObject)
self.spriteName = frameObject.name
self.velocityValue = velocityVal
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.spriteName==other.spriteName and self.pastFrames==other.pastFrames and self.velocityValue==other.velocityValue
else:
return False
def __ne__(self, other):
if isinstance(other, self.__class__):
return not self.__eq__(other)
else:
return True
def __hash__(self):
return hash(tuple([self.pastFrames, self.spriteName, self.velocityValue]))
def clone(self):
condition = VelocityYCondition(self.frameObject, self.velocityValue)
condition.pastFrames = self.pastFrames
condition.isPlayerRule = self.isPlayerRule
return condition
def __str__(self):
return "VelocityYCondition: "+str([self.spriteName, self.velocityValue])
#Animation State and not exists
class AnimationCondition(Condition):
def __init__(self, frameObject, existsSpriteName):
super(AnimationCondition,self).__init__(frameObject)
self.spriteName = existsSpriteName
self.x = 0
self.y = 0
self.width = 0
self.height = 0
if not frameObject==None:
self.x = frameObject.x
self.y = frameObject.y
self.width = frameObject.width
self.height = frameObject.height
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.spriteName==other.spriteName and self.pastFrames==other.pastFrames and self.x==other.x and self.y==other.y
else:
return False
def __ne__(self, other):
if isinstance(other, self.__class__):
return not self.__eq__(other)
else:
return True
def __hash__(self):
return hash(tuple([self.pastFrames, self.spriteName, self.x, self.y]))
def clone(self):
condition = AnimationCondition(self.frameObject, self.spriteName)
condition.pastFrames = self.pastFrames
condition.isPlayerRule = self.isPlayerRule
return condition
def __str__(self):
return "AnimationCondition: "+str([self.spriteName, self.x, self.y, self.width, self.height])
#screen position of sprites
class SpatialCondition(Condition):
def __init__(self, frameObject, sprite1, spritePosition):
super(SpatialCondition,self).__init__(frameObject)
self.spriteName = sprite1
self.screenPosition = spritePosition
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.spriteName==other.spriteName and self.screenPosition==other.screenPosition and self.pastFrames==other.pastFrames
else:
return False
def __ne__(self, other):
if isinstance(other, self.__class__):
return not self.__eq__(other)
else:
return True
def __hash__(self):
return hash(tuple([self.pastFrames, self.spriteName, tuple(self.screenPosition)]))
def clone(self):
condition = SpatialCondition(self.frameObject, self.spriteName, self.screenPosition)
condition.pastFrames = self.pastFrames
condition.isPlayerRule = self.isPlayerRule
return condition
def __str__(self):
return "SpatialCondition: "+str([self.spriteName, self.screenPosition])
#relationships between sprites
class RelationshipConditionX(Condition):
def __init__(self, frameObject, sprite1, sprite2, connect1, connect2, relativeVectorVal):
super(RelationshipConditionX,self).__init__(frameObject)
self.spriteName = sprite1
self.sprite1Edge = connect1
self.sprite2Name = sprite2
self.sprite2Edge = connect2
self.relativeVectorVal = relativeVectorVal
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.sprite2Edge==other.sprite2Edge and self.sprite1Edge==other.sprite1Edge and self.sprite2Name==other.sprite2Name and self.spriteName==other.spriteName and self.pastFrames==other.pastFrames and self.relativeVectorVal == other.relativeVectorVal
else:
return False
def __ne__(self, other):
if isinstance(other, self.__class__):
return not self.__eq__(other)
else:
return True
def __hash__(self):
return hash(tuple([self.pastFrames, self.spriteName, self.sprite1Edge, self.sprite2Name, self.sprite2Edge, self.relativeVectorVal]))
def clone(self):
condition = RelationshipConditionX(self.frameObject, self.spriteName, self.sprite2Name, self.sprite1Edge, self.sprite2Edge, self.relativeVectorVal)
condition.pastFrames = self.pastFrames
condition.isPlayerRule = self.isPlayerRule
return condition
def __str__(self):
return "RelationshipConditionX: "+str([self.spriteName, self.sprite1Edge, self.sprite2Name, self.sprite2Edge, self.relativeVectorVal])
#relationships between sprites
class RelationshipConditionY(Condition):
def __init__(self, frameObject, sprite1, sprite2, connect1, connect2, relativeVectorVal):
super(RelationshipConditionY,self).__init__(frameObject)
self.spriteName = sprite1
self.sprite1Edge = connect1
self.sprite2Name = sprite2
self.sprite2Edge = connect2
self.relativeVectorVal = relativeVectorVal
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.sprite2Edge==other.sprite2Edge and self.sprite1Edge==other.sprite1Edge and self.sprite2Name==other.sprite2Name and self.spriteName==other.spriteName and self.pastFrames==other.pastFrames and self.relativeVectorVal == other.relativeVectorVal
else:
return False
def __ne__(self, other):
if isinstance(other, self.__class__):
return not self.__eq__(other)
else:
return True
def __hash__(self):
return hash(tuple([self.pastFrames, self.spriteName, self.sprite1Edge, self.sprite2Name, self.sprite2Edge, self.relativeVectorVal]))
def clone(self):
condition = RelationshipConditionY(self.frameObject, self.spriteName, self.sprite2Name, self.sprite1Edge, self.sprite2Edge, self.relativeVectorVal)
condition.pastFrames = self.pastFrames
condition.isPlayerRule = self.isPlayerRule
return condition
def __str__(self):
return "RelationshipConditionY: "+str([self.spriteName, self.sprite1Edge, self.sprite2Name, self.sprite2Edge, self.relativeVectorVal])
#Variable relationships
class VariableCondition(Condition):
def __init__(self, frameObject, variableName, variableValue):
super(VariableCondition,self).__init__(frameObject)
self.variableName = variableName
self.variableValue = variableValue
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.variableValue==other.variableValue and self.variableName==other.variableName and self.pastFrames==other.pastFrames
else:
return False
def __ne__(self, other):
if isinstance(other, self.__class__):
return not self.__eq__(other)
else:
return True
def __hash__(self):
return hash(tuple([self.pastFrames, self.variableName, self.variableValue]))
def clone(self):
condition = VariableCondition(self.frameObject, self.variableName, self.variableValue)
condition.pastFrames = self.pastFrames
condition.isPlayerRule = self.isPlayerRule
return condition
def __str__(self):
return "VariableCondition: "+str([self.variableName, self.variableValue])
class RulePrecondition:
def __init__(self, initialConditionList, changeFrameObj):
self.conditionList = list(initialConditionList)
self.changeConditions = []
self.frameObject = changeFrameObj
if not self.frameObject == None:
for condition in self.conditionList:
if self.frameObject==condition.frameObject:
self.changeConditions.append(condition)
def clone(self):
newConditionList = []
for condition in self.conditionList:
newConditionList.append(condition.clone())
cloned = RulePrecondition(newConditionList, self.frameObject)
for condition in self.changeConditions:
cloned.changeConditions.append(condition.clone())
return cloned
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.conditionList == other.conditionList and self.changeConditions==other.changeConditions
else:
return False
def __ne__(self, other):
if isinstance(other, self.__class__):
return not self.__eq__(other)
else:
return True
def __hash__(self):
return hash(tuple([hash(tuple(conditionList)), hash(tuple(self.changeConditions))]))
class Rule:
def __init__(self, initialPreconditions, changePair):
self.preconditions = initialPreconditions
self.change = changePair#pair of conditions that constitutes this rule, rest of conditions are explanation
self.framesUsed = []
self.activated = False
def clone(self):
preconditionCopy = []
for precog in self.preconditions:
preconditionCopy.append(precog.clone())
changePair = [self.change[0].clone(), self.change[1].clone()]
cloned =Rule(preconditionCopy, changePair)
cloned.framesUsed = self.framesUsed
cloned.activated = self.activated
return cloned
def isTriggered(self, conditions, printIt=False):
if printIt:
print " isTriggered Rule: "+str(self.change[0])+"->"+str(self.change[1])
for precog in self.preconditions:
activeVal = len(precog.conditionList)
for condition in precog.conditionList:
if condition in conditions:
#if printIt:
# print " isTriggered Condition match: "+str(condition)
activeVal-=1
else:
if printIt:
print " isTriggered Condition not-match: "+str(condition)
break
if activeVal==0:#Has all the right conditions, has to check if it matches
return precog
return None
def __str__(self):
return "Rule: "+str(self.change[0])+"->"+str(self.change[1])+"<"+str(self.activated)+">"
def Activate(self, precog, frame):
self.activated = True
#print "Hit Activate Rule: "+str(self)+" with precog change conditions: "+str(len(precog.changeConditions))
if not self.framesUsed:
self.framesUsed.append(frame.number)
newFrame = frame.clone()
#print "HIT ACTIVATE"
#How to activate based on conditions
frameObjectToChange = None
#print " Hit the else"
#print " Instance of Animation Condition: "+str(isinstance(self,AnimationCondition))
#print " Change 0 to 1: "+str([self.change[0].frameObject, self.change[1].frameObject])
if len(precog.changeConditions)==0 and self.change[0].frameObject==None and self.change[1].frameObject==None:
#Condition Change
if "camera" in self.change[0].variableName and not "change" in self.change[0].variableName:
newFrame.cameraX += self.change[1].variableValue-self.change[0].variableValue
else:
variableName = variableName[:-1*len("change")]#TODO; will this ever happen? Except for camera?
for condition in newFrame.conditions:
if isinstance(condition, VariableCondition):
if condition.name == variableName:
condition.variableValue += change[1].variableValue-change[0].variableValue
return newFrame
elif isinstance(self.change[0],AnimationCondition) and self.change[0].frameObject==None and self.change[1].frameObject!=None:
#Instantiate
#print "Instantiate: "+self.change[1].frameObject.name
newFrame.frameObjects.append(FrameObject(self.change[1].frameObject.name, self.change[1].frameObject.x, self.change[1].frameObject.y, self.change[1].frameObject.width, self.change[1].frameObject.height, 1.0, 0, 0))
return newFrame
else:
#Find frameObject based on precog
frameObjectsToChange = []
nameToMatch = self.change[0].frameObject.name
#print "Rule "+str(self)+" toMatch num: "+str(len(precog.changeConditions))
for frameObj in newFrame.frameObjects:
if frameObj.name==nameToMatch:
objConditions = frameObj.GetConditions(newFrame)
toMatch = len(precog.changeConditions)
for condition in precog.changeConditions:
if condition in objConditions:
toMatch-=1
if toMatch==0:
frameObjectsToChange.append(frameObj)
if self.change[0].isPlayerRule and not frame.player in frameObjectsToChange:
frameObjectsToChange.append(frame.player)
for frameObj in frameObjectsToChange:
#print "Rule "+str(self)+" activated on: "+str(frameObj)
#Changed so that this happens for each correct frameobject
#frameIndex = frame.frameObjects.index(frameObj)
#if frameIndex<len(newFrame.frameObjects):
#frameObjectToChange = newFrame.frameObjects[]
frameObjectToChange = frameObj
#Walk through all of the possible conditions for frameObjects and implement
if isinstance(self.change[0],AnimationCondition):
if self.change[1].spriteName=="None":
newFrame.frameObjects.remove(frameObjectToChange)
else:
frameObjectToChange.name = self.change[1].spriteName
frameObjectToChange.width = self.change[1].width
frameObjectToChange.height = self.change[1].height
elif isinstance(self.change[1], VelocityYCondition):
frameObjectToChange.velocity = [frameObjectToChange.velocity[0], self.change[1].velocityValue]
elif isinstance(self.change[1], VelocityXCondition):
frameObjectToChange.velocity = [self.change[1].velocityValue, frameObjectToChange.velocity[1]]
elif isinstance(self.change[0], SpatialCondition):
frameObjectToChange.x = self.change[1].screenPosition[0]
frameObjectToChange.x = self.change[1].screenPosition[1]
elif isinstance(self.change[0], RelationshipConditionX) or isinstance(self.change[0], RelationshipConditionY):
secondFrameObject = None
for frameObj in newFrame.frameObjects:
if frameObj.name == self.change[0].sprite2Name:
#check that the distance between the frameObj and secondFrameObj matches change[0]
minCondition = GetMinConnectionBetweenTwoSprites(frameObjectToChange, frameObj)
if minCondition== self.change[0]:
secondFrameObject = frameObj
break
if isinstance(self.change[0], RelationshipConditionX):
sprite1Edge = self.change[1].sprite1Edge
pointGotten = GetPoint(sprite1Edge, frameObjectToChange)
if pointGotten==None:
pointGotten = [0,0]
startX = (frameObjectToChange.x-pointGotten[0])
endX = self.change[0].relativeVectorVal*4
pointB = GetPoint(self.change[1].sprite2Edge, secondFrameObject)
if pointB==None:
pointB = [0,0]
frameObjectToChange.x = startX+ pointB[0]+endX
else:
pointGotten = GetPoint(self.change[1].sprite1Edge, frameObjectToChange)
if pointGotten==None:
pointGotten = [0,0]
pointB = GetPoint(self.change[1].sprite2Edge, secondFrameObject)
if pointB==None:
pointB = [0,0]
frameObjectToChange.y = (frameObjectToChange.y-pointGotten[1])+ pointB[1]+self.change[1].relativeVectorVal*4
#Variable conditions can't be change conditions except for Camera (which is already handled above)
return newFrame
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.change[0]== other.change[0] and self.change[1] == other.change[1] and self.preconditions==other.preconditions
else:
return False
def __ne__(self, other):
if isinstance(other, self.__class__):
return not self.__eq__(other)
else:
return True
def __hash__(self):
return hash(tuple([hash(self.change[0]), hash(self.change[1]), hash(tuple(self.preconditions))]))
def GetLine(lineName, frameObj):
if lineName=="North":
return frameObj.GetNorthLine()
elif lineName=="South":
return frameObj.GetSouthLine()
elif lineName=="East":
return frameObj.GetEastLine()
elif lineName=="West":
return frameObj.GetWestLine()
def GetPoint(lineName, frameObj):
if frameObj==None:
return [0,0]
if lineName=="North":
return frameObj.GetNorthPoint()
elif lineName=="South":
return frameObj.GetSouthPoint()
elif lineName=="East":
return frameObj.GetEastPoint()
elif lineName=="West":
return frameObj.GetWestPoint()
def spriteTranslate(spriteName):
backgroundSignifiers = ["S", "W", "B"]
#Remove all background signifiers
if spriteName[len(spriteName)-1] in backgroundSignifiers:
spriteName = spriteName[:len(spriteName)-1]
#TODO; remove this after animation stuff
numberSignifiers = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
for number in numberSignifiers:
if number in spriteName:
spriteName = spriteName[:spriteName.index(number)]
if "ario" in spriteName and not "ire" in spriteName:
spriteName = "mario"
return spriteName
def CheckHorizontalSides(side1, side2):
parallelMatches = [["North", "North"], ["North", "South"], ["South", "South"]]
for pairMatch in parallelMatches:
if (side1==pairMatch[0] and side2==pairMatch[1]) or (side1==pairMatch[1] and side2==pairMatch[0]):
return True
return False
def CheckVerticalSides(side1, side2):
parallelMatches = [["East", "East"], ["East", "West"], ["West", "West"]]
for pairMatch in parallelMatches:
if (side1==pairMatch[0] and side2==pairMatch[1]) or (side1==pairMatch[1] and side2==pairMatch[0]):
return True
return False
def parallelLineDistance(point1, point2, line1, line2):
uTop = (point2[0]-line1[0][0])*(line1[1][0]-line1[0][0])+(point2[1]-line1[0][1])*(line1[1][1]-line1[0][1])
vMag = math.pow(line1[1][0]-line1[0][0], 2)+math.pow(line1[1][1]-line1[0][1], 2)
u=0
if vMag>0:
u = uTop/vMag
x = line1[0][0]+ u*(line1[1][0]-line1[0][0])
y = line1[0][1]+u*(line1[1][1]-line1[0][1])
diffVector = [x-point2[0], y-point2[1]]
diffMag = math.sqrt(math.pow(diffVector[0], 2)+math.pow(diffVector[1], 2))
return diffMag
def dotProduct(line1, line2):
return line1[0]*line2[0]+line1[1]*line2[1]
def pointDistance(point1, point2):
return math.sqrt(math.pow(point1[0]-point2[0], 2)+math.pow(point1[1]-point2[1], 2))
def GetMinConnectionBetweenTwoSprites(sprite1, sprite2):
sides1 = ["North", "North", "South", "South", "East", "East", "West", "West", "Center"]
sides2 = ["North", "South", "South", "North", "East", "West", "West", "East", "Center"]
minConnection = None
minDist = float("inf")
minVector = [0,0]
for i in range(len(sides1)):
thisDist = float("inf")
thisVector = [0,0]
if i<len(sides1)-1:
p1 = GetPoint(sides1[i], sprite1)
p2 = GetPoint(sides2[i], sprite2)
v1 = GetLine(sides1[i], sprite1)
v2 = GetLine(sides2[i], sprite2)
thisDist = parallelLineDistance(p1, p2, v1, v2)
thisVector = [p1[0]-p2[0], p1[1]-p2[1]]
else:
p1 = (sprite1.x, sprite1.y)
p2 = (sprite2.x, sprite2.y)
thisDist = pointDistance(p1, p2)
thisVector = [p1[0]-p2[0], p1[1]-p2[1]]
intDivision = int(4)
thisDist = int(thisDist/intDivision)
thisVector[0] = int(thisVector[0]/intDivision)
thisVector[1] = int(thisVector[1]/intDivision)
if thisDist<minDist:
minVector = thisVector
minDist = thisDist
minConnection = [sprite1, sprite1.name, sprite2.name, sides1[i], sides2[i], minVector]
return minConnection
class FrameObject:
def __init__(self, name, positionX, positionY, width, height, confidence, velocityX, velocityY):
self.name = name
self.x = positionX #middle of sprite
self.y = positionY #middle of sprite
self.width = width
self.height = height
self.confidence = confidence
self.velocity = (velocityX,velocityY)
def clone(self):
newFrameObj = FrameObject(self.name, self.x, self.y, self.width, self.height, self.confidence, self.velocity[0], self.velocity[1])
return newFrameObj
#Get a list of the four cordinal points
def GetPoints(self):
pts = []
pts.append(self.GetWestPoint())#left
pts.append(self.GetEastPoint())#right
pts.append(self.GetNorthPoint())#top
pts.append(self.GetSouthPoint())#bottom
return pts
def GetNorthPoint(self):
return [self.x,self.y-self.height/2.0]
def GetSouthPoint(self):
return [self.x,self.y+self.height/2.0]
def GetEastPoint(self):
return [self.x+self.width/2.0,self.y]
def GetWestPoint(self):
return [self.x-self.width/2.0,self.y]
def GetNorthLine(self):
return [ (self.x-self.width/2.0, self.y-self.height/2.0), (self.x+self.width/2.0, self.y-self.height/2.0)]
def GetSouthLine(self):
return [ (self.x-self.width/2.0, self.y+self.height/2.0), (self.x+self.width/2.0, self.y+self.height/2.0)]
def GetEastLine(self):
return [ (self.x+self.width/2.0, self.y-self.height/2.0), (self.x+self.width/2.0, self.y+self.height/2.0)]
def GetWestLine(self):
return [ (self.x-self.width/2.0, self.y-self.height/2.0), (self.x-self.width/2.0, self.y+self.height/2.0)]
def __eq__(self, other):
if isinstance(other, FrameObject):
return self.name==other.name and self.x==other.x and self.y==other.y
return False
def __ne__(self, other):
if isinstance(other, self.__class__):
return not self.__eq__(other)
else:
return True
def __hash__(self):
return hash(tuple([self.name, self.x, self.y]))
def __str__(self):
return "FrameObject: "+str([self.name, self.x, self.y, self.width, self.height, self.velocity])
def GetConditions(self, frame):
conditions = []
conditions.append(AnimationCondition(self, self.name))
conditions.append(VelocityXCondition(self, self.velocity[0]))
conditions.append(VelocityYCondition(self, self.velocity[1]))
conditions.append(SpatialCondition(self, self.name, [self.x, self.y]))
for frameObj in frame.frameObjects:
if not frameObj==self:
minCondition = GetMinConnectionBetweenTwoSprites(self, frameObj)
minConditionX = RelationshipConditionX(minCondition[0], minCondition[1], minCondition[2], minCondition[3], minCondition[4], minCondition[5][0])
conditions.append(minConditionX)
minConditionY = RelationshipConditionY(minCondition[0], minCondition[1], minCondition[2], minCondition[3], minCondition[4], minCondition[5][1])
conditions.append(minConditionY)
return conditions
class Change:
def __init__(self, spriteName, prevCondition, postCondition):
self.spriteName = spriteName
self.prevCondition = prevCondition
self.postCondition = postCondition
class Frame:
def __init__(self, number):
self.cameraX = 0
self.number = number
self.frameObjects = []#List of FrameObject objects
self.spritesContained = []#List of string values for frameobjects that exist in this frame
self.frameScreen = {}
self.player = None
self.conditions = []
def ReallyGetConditions(self):
if len(self.conditions)==0:
self.GetFrameConditions()
return self.conditions
def __eq__(self, other):
if isinstance(other, FrameObject):
return self.cameraX==other.cameraX and tuple(self.ReallyGetConditions())==tuple(other.ReallyGetConditions())
return False
def __ne__(self, other):
if isinstance(other, self.__class__):
return not self.__eq__(other)
else:
return True
def __hash__(self):
return hash(self.cameraX, tuple(self.ReallyGetConditions()))
def SetCameraX(self, camX, prevX):
self.cameraX = camX
cameraMovement = camX-prevX
if cameraMovement>0:
for obj in self.frameObjects:
if not obj.velocity[0]==0:
obj.velocity = [obj.velocity[0]+cameraMovement, obj.velocity[1]]
def clone(self):
cloneFrame = Frame(self.number)
cloneFrame.cameraX = self.cameraX
for frameObj in self.frameObjects:
newFrameObj = frameObj.clone()
cloneFrame.frameObjects.append(newFrameObj)
if not newFrameObj.name in cloneFrame.spritesContained:
cloneFrame.spritesContained.append(newFrameObj.name)
if frameObj==self.player:
cloneFrame.player = newFrameObj
cloneFrame.conditions = []
return cloneFrame
def AddRow(self, row, isPlayer = False):
spriteName = spriteTranslate(row[2])
if spriteName=="None":
spriteName = spriteTranslate(row[1])
if len(row)<=7:
spriteName = spriteTranslate(row[1][:-4])
if not spriteName=="None":
if not spriteName in self.spritesContained:
self.spritesContained.append(spriteName)
frameObjectToAdd = None
if len(row)>7:
if isPlayer:
frameObjectToAdd=FrameObject(spriteName, float(row[3]), float(row[4]), float(row[5]), float(row[6]), float(row[11]), float(row[7]), float(row[8]) )
else:
#frameObjectToAdd=FrameObject(spriteName, float(row[3]), float(row[4]), float(row[6]), float(row[5]), float(row[11]), float(row[7]), float(row[8]) )
frameObjectToAdd=FrameObject(spriteName, float(row[3])-float(row[5])/2.0+float(row[6])/2.0, float(row[4])-float(row[6])/2.0+float(row[5])/2.0, float(row[6]), float(row[5]), float(row[11]), float(row[7]), float(row[8]) )
else:#Added allowance for static frames
frameObjectToAdd=FrameObject(spriteName, float(row[2])+float(row[4])/2, float(row[3])+float(row[5])/2, float(row[4]), float(row[5]), float(row[6]), 0, 0)
if not frameObjectToAdd in self.frameObjects:
self.frameObjects.append(frameObjectToAdd)
if isPlayer:
self.player = frameObjectToAdd
#calculates and returns self.conditions
def GetFrameConditions(self):
self.conditions = []
for frameObj in self.frameObjects:
if frameObj!=self.player:
for condition in frameObj.GetConditions(self):
self.conditions.append(condition)
#Player
if not self.player==None:
for condition in self.player.GetConditions(self):
condition.isPlayerRule = True
self.conditions.append(condition)
self.conditions.append(VariableCondition(None, "cameraPos", self.cameraX))
return self.conditions
#Determine if string is number
def IsNumber(s):
try:
float(s)
return True
except ValueError:
return False
def GetPointDistance(pnt1, pnt2):
xDiff = pnt1[0]-pnt2[0]
yDiff = pnt1[1]-pnt2[1]
return (abs(yDiff)+abs(xDiff))
def GetSpriteDistance(sprite1, sprite2):
spritePoints1 = sprite1.GetPoints()
spritePoints2 = sprite2.GetPoints()
minVal = float("inf")
for pnt1 in spritePoints1:
for pnt2 in spritePoints2:
thisVal = GetPointDistance(pnt1, pnt2)
if thisVal<minVal:
minVal = thisVal
return minVal
def FindMinimumSprite(sprite, spriteList):
minSprite = None
minDist = float("inf")
for sprite2 in spriteList:
if not sprite.name in sprite2.name:
spriteDist = GetSpriteDistance(sprite, sprite2)
if spriteDist<minDist:
minDist = spriteDist
minSprite = sprite2
return minSprite
def LinearDistance(x1, y1, x2, y2):
return abs(x1-x2)+abs(y1-y2)#math.sqrt(pow(x1-x2, 2) + pow(y1-y2, 2))
def CloseEnough(oneSprite, changeSprite, multiplier = 1.5):
return LinearDistance(oneSprite.x, oneSprite.y, changeSprite.x, changeSprite.y) <(max(oneSprite.width,oneSprite.height)*multiplier+max(changeSprite.width,changeSprite.height)*multiplier)
#Calcultes distance between frames (Hellman's metric)
def FrameDistance(frame1, frame2, doPrint =False):
if len(frame1.frameScreen.keys())==0:
frame1.frameScreen = CreateFrameDict(frame1.frameObjects, frame1.player)
if len(frame2.frameScreen.keys())==0:
frame2.frameScreen = CreateFrameDict(frame2.frameObjects, frame2.player)
sumDiff = 0
for x in range(0,16*26):
for y in range(0,14*26):
if frame1.frameScreen[x][y]!=frame2.frameScreen[x][y]:
if doPrint:
print " Frame Difference ("+str([x,y])+"): "+str([frame1.frameScreen[x][y], frame2.frameScreen[x][y]])
sumDiff+=1
return sumDiff
#Calcultes distance between frames (Hellman's metric)
def FrameDistancePercentage(frame1, frame2, changeX, changeY):
if len(frame1.frameScreen.keys())==0:
frame1.frameScreen = CreateFrameDict(frame1.frameObjects, frame1.player)
if len(frame2.frameScreen.keys())==0:
frame2.frameScreen = CreateFrameDict(frame2.frameObjects, frame2.player)
sumDiff = 0.0
numComparisons = 0.0
for x in range(0,256):
for y in range(0,224):
if (x+changeX)>0 and (x+changeX)<(256):
if (y+changeY)>0 and (y+changeY)<(224):
numComparisons+=1.0
if frame1.frameScreen[x+changeX][y+changeY]!=frame2.frameScreen[x][y]:
sumDiff+=1.0
finalVal = sumDiff/numComparisons
return finalVal
def CreateFrameDict(frameObjects, player):
frameScreen = {}
for x in range(0,256):
frameScreen[x] = {}
for y in range(0, 224):
frameScreen[x][y] =""
for frameObj in frameObjects:
if not frameObj.name == "None":
for x in range(int(frameObj.GetWestPoint()[0]), int(frameObj.GetEastPoint()[0])):
for y in range(int(frameObj.GetNorthPoint()[1]), int(frameObj.GetSouthPoint()[1])):
if x<256 and y<224 and x>=0 and y>=0:
frameScreen[x][y] = frameObj.name
return frameScreen
#Physics prep
def PhysicsPredict(frame, engine, currFrame):
newFrame = frame.clone()
for rule in engine.rules:
if isinstance(rule.change[1], VelocityXCondition):
precog = None#rule.isTriggered(newFrame.ReallyGetConditions())
precog=rule.isTriggered(newFrame.ReallyGetConditions())
if not precog == None:
newFrame = rule.Activate(precog, newFrame)
elif isinstance(rule.change[1], VelocityYCondition):