-
Notifications
You must be signed in to change notification settings - Fork 0
/
wxgame2lib.py
1716 lines (1484 loc) · 56 KB
/
wxgame2lib.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" wxgame framework common lib
wxGameFramework
Copyright 2011,2013,1014 kasw <[email protected]>
wxpython을 사용해서 게임을 만들기위한 프레임웍과 테스트용 게임 3가지
기본적인 가정은
좌표계는 0~1.0 인 정사각형 실수 좌표계
collision은 원형: 현재 프레임의 위치만을 기준으로 검출한다.
모든? action은 frame 간의 시간차에 따라 보정 된다.
문제점은 frame간에 지나가 버린 경우 이동 루트상으론 collision 이 일어나야 하지만 검출 불가.
"""
Version = '2.5.0'
import time
import math
import random
import itertools
import zlib
try:
import simplejson as json
except:
import json
import sys
import Queue
import select
import multiprocessing
import cProfile as Profile
import pstats
import socket
import logging
import struct
from euclid import Vector2
# ======== general lib ============
def getLogger(level=logging.DEBUG, appname='noname'):
# create logger
logger = logging.getLogger(appname)
logger.setLevel(level)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(level)
# create formatter
#formatter = logging.Formatter("%(asctime)s:%(levelname)s: %(message)s")
formatter = logging.Formatter("%(levelname)s: %(message)s")
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)
return logger
Log = getLogger(level=logging.ERROR, appname='wxgame2lib')
# Log.critical('current loglevel is %s',
# logging.getLevelName(Log.getEffectiveLevel()))
if sys.version_info < (2, 7, 0):
Log.critical('python version 2.7.x or more need')
getSerial = itertools.count().next
def getFrameTime():
return time.time()
def random2pi(m=2):
return math.pi * m * (random.random() - 0.5)
def putParams2Queue(qobj, **kwds):
qobj.put(toGzJson(kwds))
def toGzJson(obj):
return zlib.compress(json.dumps(obj))
def toGzJsonParams(**kwds):
return zlib.compress(json.dumps(kwds))
def fromGzJson(data):
return json.loads(zlib.decompress(data))
class Storage(dict):
"""from gluon storage.py """
__slots__ = ()
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
__getitem__ = dict.get
__getattr__ = dict.get
__repr__ = lambda self: '<Storage %s>' % dict.__repr__(self)
# http://stackoverflow.com/questions/5247250/why-does-pickle-getstate-accept-as-a-return-value-the-very-instance-it-requi
__getstate__ = lambda self: None
__copy__ = lambda self: Storage(self)
def getlist(self, key):
value = self.get(key, [])
if value is None or isinstance(value, (list, tuple)):
return value
else:
return [value]
def getfirst(self, key, default=None):
values = self.getlist(key)
return values[0] if values else default
def getlast(self, key, default=None):
values = self.getlist(key)
return values[-1] if values else default
class Statistics(object):
def __init__(self, timeFn=None):
self.datadict = {
'min': None,
'max': None,
'avg': None,
'sum': 0,
'last': None,
'count': 0,
}
self.formatstr = '%(last)s(%(min)s~%(max)s), %(avg)s=%(sum)s/%(count)d'
self.timeFn = timeFn # FPS mode
if self.timeFn:
self.frames = []
def update(self, data):
data = float(data)
self.datadict['count'] += 1
self.datadict['sum'] += data
if self.datadict['last'] is not None:
self.datadict['min'] = min(self.datadict['min'], data)
self.datadict['max'] = max(self.datadict['max'], data)
self.datadict['avg'] = self.datadict[
'sum'] / self.datadict['count']
else:
self.datadict['min'] = data
self.datadict['max'] = data
self.datadict['avg'] = data
self.formatstr = '%(last).2f(%(min).2f~%(max).2f), %(avg).2f=%(sum).2f/%(count)d'
self.datadict['last'] = data
return self
def updateFPS(self):
if not self.timeFn:
raise AttributeError('Statistics not inited for FPS')
thistime = self.timeFn()
self.frames.append(thistime)
while(self.frames[-1] - self.frames[0] > 1):
del self.frames[0]
if len(self.frames) > 1:
fps = len(self.frames) / (self.frames[-1] - self.frames[0])
else:
fps = 0
self.update(fps)
return self.frames
def getStat(self):
return self.datadict
def __str__(self):
return self.formatstr % self.datadict
class FPSMixin(object):
""" frames per second or frame pacing system
framepacing to maxFPS
class workClass(FPSMixin):
def __init__(self):
self.FPSInit(time.time, 60)
self.registerRepeatFn( self.calledEvery1secFn , 1)
self.registerRepeatFn( self.calledEvery2secFn , 2)
while True:
self.FPSRun()
self.FPSYield()
def FPSMain(self): # called 60 / sec
# your code here
def calledEvery1secFn(self):
pass
def calledEvery2secFn(self):
pass
"""
def FPSInit(self, frameTimeFn, maxFPS):
self.repeatingcalldict = {}
self.frameinfo = Storage(
stat=Statistics(timeFn=frameTimeFn),
pause=False,
maxFPS=maxFPS,
frameTimeFn=frameTimeFn,
thisFrameTime=frameTimeFn(),
last_ms=0.1,
lastFPS=10.0,
remain_ms=1,
)
def registerRepeatFn(self, fn, dursec):
"""
function signature
def repeatFn(self,repeatinfo):
repeatinfo is {
"dursec" : dursec ,
"oldtime" : time.time() ,
"starttime" : time.time(),
"repeatcount":0 }
"""
self.repeatingcalldict[fn] = {
"dursec": dursec,
"oldtime": self.frameinfo.frameTimeFn(),
"starttime": self.frameinfo.frameTimeFn(),
"repeatcount": 0}
return self
def unRegisterRepeatFn(self, fn):
return self.repeatingcalldict.pop(fn, [])
def FPSRun(self):
self.frameinfo.thisFrameTime = self.frameinfo.frameTimeFn()
frames = self.frameinfo.stat.updateFPS()
self.frameinfo.last_ms = frames[
-1] - frames[-2] if len(frames) > 1 else 0.1
self.frameinfo.lastFPS = 1 / self.frameinfo.last_ms
if not self.frameinfo.pause:
self.FPSMain()
for fn, d in self.repeatingcalldict.iteritems():
if self.frameinfo.thisFrameTime - d["oldtime"] > d["dursec"]:
self.repeatingcalldict[fn][
"oldtime"] = self.frameinfo.thisFrameTime
self.repeatingcalldict[fn]["repeatcount"] += 1
fn(d)
nexttime = (self.frameinfo.frameTimeFn()
- self.frameinfo.thisFrameTime) * 1000
remain_ms = min(1000, 1000 / self.frameinfo.maxFPS - nexttime)
# remain_ms = min(
# 1000, max(self.frameinfo.last_ms * 800, 1000 / self.frameinfo.maxFPS)
# - nexttime)
if remain_ms < 1:
remain_ms = 0
self.frameinfo.remain_ms = remain_ms
def isFPSRunNeed(self):
return (self.frameinfo.frameTimeFn() - self.frameinfo.thisFrameTime) > 1.0 / self.frameinfo.maxFPS
def FPSYield(self):
if self.frameinfo.remain_ms > 0:
time.sleep(self.frameinfo.remain_ms / 1000.0)
def FPSMain(self):
""" overide this """
pass
class ProfileMixin(object):
def __init__(self, profile):
if profile:
self.begin = self._begin
self.end = self._end
else:
self.begin = self._dummy
self.end = self._dummy
def _dummy(self):
pass
def _begin(self):
self.profile = Profile.Profile()
self.profile.enable()
def _end(self):
self.profile.disable()
pstats.Stats(self.profile).strip_dirs().sort_stats(
'time').print_stats(20)
class SendRecvStatMixin(object):
def __init__(self):
self.sendstat = Statistics(timeFn=getFrameTime)
self.recvstat = Statistics(timeFn=getFrameTime)
def getStatInfo(self):
return 'send:{} recv:{}'.format(
self.sendstat, self.recvstat
)
def updateSendStat(self):
self.sendstat.updateFPS()
def updateRecvStat(self):
self.recvstat.updateFPS()
class I32sendrecv(SendRecvStatMixin):
"""
recv 32bit len packet to recvQueue
send 32bit len packet from sendQueue
"""
headerStruct = struct.Struct('!I')
headerLen = struct.calcsize('!I')
def __init__(self, sock):
self.recvQueue = Queue.Queue()
self.sendQueue = Queue.Queue()
self.sock = sock
self.readbuf = [] # memorybuf, toreadlen , buf state
self.writebuf = [] # memorybuf, towritelen
SendRecvStatMixin.__init__(self)
def __str__(self):
return '[{}:{}:{}:{}]'.format(
self.__class__.__name__,
self.sock,
self.readbuf,
self.writebuf,
)
def getStatInfo(self):
return 'send:{}:{} | recv:{}:{}'.format(
self.sendQueue.qsize(), self.sendstat,
self.recvQueue.qsize(), self.recvstat
)
def recv(self):
""" async recv
recv completed packet is put to recv packet
"""
if self.recvQueue.full():
return 'sleep' # recv queue full
if self.readbuf == []: # read header
self.readbuf = [
memoryview(bytearray(self.headerLen)),
self.headerLen,
'header'
]
nbytes = self.sock.recv_into(
self.readbuf[0][-self.readbuf[1]:], self.readbuf[1])
if nbytes == 0:
raise RuntimeError("socket connection broken")
self.readbuf[1] -= nbytes
if self.readbuf[1] == 0: # complete recv
if self.readbuf[2] == 'header':
bodylen = self.headerStruct.unpack(
self.readbuf[0].tobytes())[0]
self.readbuf = [
memoryview(bytearray(bodylen)),
bodylen,
'body'
]
elif self.readbuf[2] == 'body':
self.recvQueue.put(self.readbuf[0].tobytes())
self.readbuf = []
return 'complete'
else:
Log.error('invalid recv state %s', self.readbuf[2])
return 'unknown'
return 'cont'
def canSend(self):
return not self.sendQueue.empty() or len(self.writebuf) != 0
def send(self):
if self.sendQueue.empty() and len(self.writebuf) == 0:
return 'sleep' # send queue empty
if len(self.writebuf) == 0: # send new packet
tosenddata = self.sendQueue.get()
headerdata = self.headerStruct.pack(len(tosenddata))
self.writebuf = [
[memoryview(headerdata), 0],
[memoryview(tosenddata), 0]
]
wdata = self.writebuf[0]
sentlen = self.sock.send(wdata[0][wdata[1]:])
if sentlen == 0:
raise RuntimeError("socket connection broken")
wdata[1] += sentlen
if len(wdata[0]) == wdata[1]: # complete send
del self.writebuf[0]
if len(self.writebuf) == 0:
return 'complete'
return 'cont'
def sendrecv(self):
recvlist = [self]
sendlist = [self] if self.canSend() else []
inputready, outputready, exceptready = select.select(
recvlist, sendlist, [], 1.0 / 120)
for s in inputready:
if self.recv() == 'complete':
self.recvstat.updateFPS()
for s in outputready:
if self.send() == 'complete':
self.sendstat.updateFPS()
def fileno(self):
# for select
return self.sock.fileno()
class I32ClientProtocol(object):
headerStruct = struct.Struct('!I')
headerLen = struct.calcsize('!I')
def __init__(self, sock, recvcallback):
self.recvcallback = recvcallback
self.sendQueue = Queue.Queue()
self.sock = sock
self.safefileno = sock.fileno()
self.readbuf = [] # memorybuf, toreadlen , buf state
self.writebuf = [] # memorybuf, towritelen
def __str__(self):
return '[{}:{}:{}:{}]'.format(
self.__class__.__name__,
self.sock,
self.readbuf,
self.writebuf,
)
def setRecvCallback(self, recvcallback):
self.recvcallback = recvcallback
def recv(self):
""" async recv
recv completed packet is put to recv packet
"""
if self.readbuf == []: # read header
self.readbuf = [
memoryview(bytearray(self.headerLen)),
self.headerLen,
'header'
]
nbytes = self.sock.recv_into(
self.readbuf[0][-self.readbuf[1]:], self.readbuf[1])
if nbytes == 0:
return 'disconnected'
self.readbuf[1] -= nbytes
if self.readbuf[1] == 0: # complete recv
if self.readbuf[2] == 'header':
bodylen = self.headerStruct.unpack(
self.readbuf[0].tobytes())[0]
self.readbuf = [
memoryview(bytearray(bodylen)),
bodylen,
'body'
]
elif self.readbuf[2] == 'body':
self.recvcallback(self.readbuf[0].tobytes())
self.readbuf = []
return 'complete'
else:
Log.error('invalid recv state %s', self.readbuf[2])
return 'unknown'
return 'cont'
def canSend(self):
return not self.sendQueue.empty() or len(self.writebuf) != 0
def send(self):
if self.sendQueue.empty() and len(self.writebuf) == 0:
return 'sleep' # send queue empty
if len(self.writebuf) == 0: # send new packet
tosenddata = self.sendQueue.get()
headerdata = self.headerStruct.pack(len(tosenddata))
self.writebuf = [
[memoryview(headerdata), 0],
[memoryview(tosenddata), 0]
]
wdata = self.writebuf[0]
sentlen = self.sock.send(wdata[0][wdata[1]:])
if sentlen == 0:
raise RuntimeError("socket connection broken")
wdata[1] += sentlen
if len(wdata[0]) == wdata[1]: # complete send
del self.writebuf[0]
if len(self.writebuf) == 0:
return 'complete'
return 'cont'
def fileno(self):
return self.sock.fileno()
class ChannelPipe(object):
def __init__(self, reader, writer):
self.initedTime = time.time()
self.recvcount, self.sendcount = 0, 0
self.sendQueue = Queue.Queue()
self.reader, self.writer = reader, writer
self.canreadfn = self.reader.poll
self.readfn = self.reader.recv
self.writefn = self.writer.send
def __str__(self):
return '[{}:{}:{}:{}]'.format(
self.__class__.__name__,
self.reader,
self.writer,
self.getStatInfo(),
)
def getStatInfo(self):
t = time.time() - self.initedTime
return 'recv:{} {}/s send:{} {}/s'.format(
self.recvcount, self.recvcount / t,
self.sendcount, self.sendcount / t
)
def canReadFrom(self):
return self.canreadfn()
def readFrom(self):
self.recvcount += 1
return self.readfn()
def canSend(self):
return not self.sendQueue.empty()
def writeFromQueue(self):
if self.sendQueue.empty():
return 'sleep' # send queue empty
self.writeTo(self.sendQueue.get())
def writeTo(self, obj):
self.sendcount += 1
return self.writefn(obj)
def makeChannel():
reader1, writer1 = multiprocessing.Pipe(duplex=False)
reader2, writer2 = multiprocessing.Pipe(duplex=False)
return ChannelPipe(reader1, writer2), ChannelPipe(reader2, writer1)
# ================================
# for game
def updateDict(dest, src):
for k, v in src.iteritems():
if isinstance(v, dict) and not isinstance(v, Storage):
if k not in dest:
dest[k] = {}
updateDict(dest[k], v)
elif isinstance(v, Vector2):
dest[k] = v.copy()
elif isinstance(v, list) and not isinstance(v, GameObjectGroup):
dest[k] = v[:]
else:
dest[k] = v
class SpriteObj(Storage):
validFields = {
'ID': 0,
"enabled": True,
"visible": True,
"pos": Vector2(0.5, 0.5),
"objtype": None,
"collisionCricle": 0.01,
"secToLifeEnd": 10.0,
"createdTime": 0,
"expireFn": None,
"movefn": None,
"movevector": Vector2(0, 0),
"movelimit": 1.0,
"movefnargs": {
"accelvector": Vector2(0, 0),
"handstype": 0,
"targetobj": None,
"diffvector": Vector2(0, 0),
"anglespeed": 0.0,
},
"wallactionfn": None,
"bounceDamping": 1.,
"weight": 1,
"afterremovefn": None,
"afterremovefnarg": [],
"level": 0,
"group": None,
'lastAutoMoveTick': 0,
'autoMoveFns': [],
'fireTimeDict': {},
'difftick': 0,
'thistick': 0,
}
def __init__(self):
""" create obj
"""
Storage.__init__(self)
# initailize default field, value
# self.update(copy.deepcopy(self.validFields))
updateDict(self, self.validFields)
self.ID = getSerial()
self.createdTime = getFrameTime()
self.lastAutoMoveTick = self.createdTime
def __str__(self):
return '[{}:{}:{}: pos:{} mv:{}|{}]'.format(
self.__class__.__name__,
self.objtype,
self.ID,
self.pos,
self.movevector,
self.group
)
def __hash__(self):
return self.ID
"""
moving, bouncing sprite
모든 move fn은 movevector를 통해서 pos를 바꾼다.
movevector의 속도는 /sec 임.
즉 abs(movevector) == 1 이면 1초에 화면 왼쪽끝에서 오른쪽 끝가지 가는 속도임.
여러 개의 mvfn을 등록할수 있고 각 펑션은 mvector를 수정한다.
그 마직막 결과를 pos에 더한다.
movefn, move, check wall 순으로 일어남.
"""
def initialize(self, params={}):
updateDict(
self,
self.typeDefaultDict.get(params.get('objtype'), {})
)
updateDict(self, params)
self.registerAutoMoveFn(self.movefn, [])
self.registerAutoMoveFn(SpriteObj.Move_byMoveVector, [])
self.registerAutoMoveFn(self.wallactionfn, [])
return self
def registerAutoMoveFn(self, fn, args=[]):
if fn is not None:
self.autoMoveFns.append([fn, args])
return self
def lento(self, target):
return abs(target.pos - self.pos)
def lentopos(self, targetpos):
return abs(targetpos - self.pos)
def lentocenter(self):
return abs(Vector2(.5, .5) - self.pos)
def isCollision(self, target):
return self != target and self.lento(target) < target.collisionCricle + self.collisionCricle
def CheckWallCollision(self, collisionRange):
collisionWall = []
collisionLen = {
"Center": 0,
"Outer": self.collisionCricle,
"Inner": -self.collisionCricle
}[collisionRange]
if self.pos.x + collisionLen > 1.0:
collisionWall.append("Right")
elif self.pos.x - collisionLen < 0.0:
collisionWall.append("Left")
if self.pos.y + collisionLen > 1.0:
collisionWall.append("Bottom")
elif self.pos.y - collisionLen < 0.0:
collisionWall.append("Top")
return collisionWall
def getAge(self, tick):
return tick - self.createdTime
def AutoMoveByTime(self, thistick):
if not self.enabled:
return
self.difftick = (thistick - self.lastAutoMoveTick)
if self.difftick == 0:
return
self.thistick = thistick
if self.secToLifeEnd > 0 and self.createdTime + self.secToLifeEnd < thistick:
if self.expireFn:
self.expireFn(self)
self.enabled = False
return # to old too move
for fn, args in self.autoMoveFns:
fn(self)
self.lastAutoMoveTick = thistick
def Move_byMoveVector(self):
"""실제로 pos를 변경하는 함수."""
if abs(self.movevector) > self.movelimit:
self.movevector = self.movevector.normalized() * self.movelimit
self.pos += self.movevector * self.difftick
def WallAction_Bounce(self):
movevector = self.movevector
rtn = self.CheckWallCollision("Outer")
while rtn:
if "Right" in rtn:
self.pos = Vector2(
2.0 - self.collisionCricle * 2 - self.pos.x, self.pos.y)
movevector = movevector.negX()
elif "Left" in rtn:
self.pos = Vector2(
0.0 + self.collisionCricle * 2 - self.pos.x, self.pos.y)
movevector = movevector.negX()
if "Bottom" in rtn:
self.pos = Vector2(
self.pos.x, 2.0 - self.collisionCricle * 2 - self.pos.y)
movevector = movevector.negY()
elif "Top" in rtn:
self.pos = Vector2(
self.pos.x, 0.0 + self.collisionCricle * 2 - self.pos.y)
movevector = movevector.negY()
if rtn:
movevector *= self.bounceDamping
movevector = movevector.addAngle(random.random() - 0.5)
if abs(movevector) > 0.5:
movevector = movevector.normalized() / 0.5
self.movevector = movevector
rtn = self.CheckWallCollision("Outer")
def WallAction_Remove(self):
if self.CheckWallCollision("Inner"):
self.enabled = False
def WallAction_Wrap(self):
rtn = self.CheckWallCollision("Center")
if "Right" in rtn:
self.pos = Vector2(0.0, self.pos.y)
elif "Left" in rtn:
self.pos = Vector2(1.0, self.pos.y)
elif "Bottom" in rtn:
self.pos = Vector2(self.pos.x, 0.0)
elif "Top" in rtn:
self.pos = Vector2(self.pos.x, 1.0)
def WallAction_Wrap_Outer(self):
rtn = self.CheckWallCollision("Outer")
if "Right" in rtn:
self.pos = Vector2(0.0, self.pos.y)
elif "Left" in rtn:
self.pos = Vector2(1.0, self.pos.y)
elif "Bottom" in rtn:
self.pos = Vector2(self.pos.x, 0.0)
elif "Top" in rtn:
self.pos = Vector2(self.pos.x, 1.0)
def WallAction_Wrap_Inner(self):
rtn = self.CheckWallCollision("Inner")
if "Right" in rtn:
self.pos = Vector2(0.0, self.pos.y)
elif "Left" in rtn:
self.pos = Vector2(1.0, self.pos.y)
elif "Bottom" in rtn:
self.pos = Vector2(self.pos.x, 0.0)
elif "Top" in rtn:
self.pos = Vector2(self.pos.x, 1.0)
def WallAction_Stop(self):
if self.CheckWallCollision("Outer"):
self.movefn = SpriteObj.Move_NoAccel
def WallAction_None(self):
pass
def Move_Sin(self):
self.movevector = Vector2.rect(0.005, self.difftick * 10)
def Move_NoAccel(self):
pass
def Move_Circle(self):
self.movevector = (
self.pos.rotate(Vector2(0.5, 0.5), - self.difftick * self.movefnargs["anglespeed"]
) - self.pos) / self.difftick
def Move_Vector(self):
self.movevector += self.movefnargs["accelvector"]
def Move_SyncTarget(self):
if self.movefnargs["targetobj"] is None:
return
self.enabled = self.movefnargs["targetobj"].enabled
if not self.enabled:
return
self.movefnargs["diffvector"] = self.movefnargs["diffvector"].rotate(
Vector2(0, 0), self.movefnargs["anglespeed"] * self.difftick)
self.movevector = (self.movefnargs[
"targetobj"].pos - self.pos + self.movefnargs["diffvector"]) / self.difftick
def Move_FollowTarget(self):
if self.movefnargs["targetobj"] is None:
return
self.enabled = self.movefnargs["targetobj"].enabled
if not self.enabled:
return
self.accelToPos(self.movefnargs["targetobj"].pos)
mvlen = abs(self.movevector)
self.movevector += self.movefnargs["accelvector"] * self.difftick
self.movevector = self.movevector.normalized() * mvlen
def bounceToObj(self, target):
self.movevector = Vector2.rect(
abs(self.movevector) * self.bounceDamping,
(self.movevector.normalized() * self.collisionCricle +
(self.pos - target.pos).normalized() * target.collisionCricle).phase())
return self
def accelToPos(self, pos):
self.movefnargs["accelvector"] = Vector2.rect(abs(
self.movefnargs["accelvector"]), (pos - self.pos).phase())
def setAccelVector(self, vt):
self.movefnargs["accelvector"] = vt
return self
def clearAccelVector(self):
self.movefnargs["accelvector"] = Vector2(0, 0)
return self
def getAccelVector(self):
return self.movefnargs["accelvector"]
"""
obj type, level, groupingingo
check collsion and scrore object
"""
def getDelScore(self, factor=1):
" 피격 타격시 점수 계산 로직 "
" (1-math.sqrt(2)/2) ~ 1.0 사이의 값 * factor 를 리턴, 중앙으로 갈수록 점수가 작다. "
# return (self.lentopos(Vector2(0.5,0.5)) + (1-math.sqrt(2)/2))*factor
# return math.sqrt(1.0/(1-self.lentocenter()) -1)*factor
return (self.lentocenter() + 0.5) * factor
# return factor
def checkCollisionAppend(self, target, rtnobjs):
"""
두 object간에 collision(interaction) 하고
objtype이 collisionTarget에 속하면
rtnobjs에 append 한다.
"""
if self.isCollision(target):
if target.objtype in self.collisionTarget:
rtnobjs.setdefault(self, set()).add(target)
if self.objtype in target.collisionTarget:
rtnobjs.setdefault(target, set()).add(self)
typeDefaultDict = {
"circularbullet": {
"objtype": 'circularbullet',
'secToLifeEnd': 10.0,
'movelimit': 0.4,
'collisionCricle': 0.004,
'collisionTarget': ['bounceball', 'shield', 'supershield', 'bullet', 'circularbullet', 'superbullet', 'hommingbullet'],
'movefnargs': {"accelvector": Vector2(0, 0)},
'movefn': Move_Vector,
'wallactionfn': WallAction_Remove,
'shapefnargs': {'animationfps': 30},
},
"superbullet": {
"objtype": 'superbullet',
'secToLifeEnd': 10.0,
'movelimit': 0.6,
'collisionCricle': 0.032,
'collisionTarget': ['supershield', 'superbullet', 'hommingbullet'],
'movefnargs': {"accelvector": Vector2(0, 0)},
'movefn': Move_Vector,
'wallactionfn': WallAction_Remove,
'shapefnargs': {'animationfps': 30},
},
"hommingbullet": {
"objtype": 'hommingbullet',
'secToLifeEnd': 10.0,
'movelimit': 0.3,
'collisionCricle': 0.016,
'collisionTarget': ['supershield', 'superbullet', 'hommingbullet'],
'movefn': Move_FollowTarget,
'movefnargs': {"accelvector": Vector2(0.0, 0.0)},
'wallactionfn': WallAction_None,
'shapefnargs': {'animationfps': 30},
},
"bullet": {
"objtype": 'bullet',
'secToLifeEnd': 10.0,
'movelimit': 0.5,
'collisionCricle': 0.008,
'collisionTarget': ['bounceball', 'shield', 'supershield', 'bullet', 'circularbullet', 'superbullet', 'hommingbullet'],
'movefnargs': {"accelvector": Vector2(0, 0)},
'movefn': Move_Vector,
'wallactionfn': WallAction_Remove,
'shapefnargs': {'animationfps': 30},
},
"bounceball": {
"objtype": 'bounceball',
'secToLifeEnd': -1.0,
'movelimit': 0.3,
'collisionCricle': 0.016,
'collisionTarget': ['bounceball', 'shield', 'supershield', 'bullet', 'circularbullet', 'superbullet', 'hommingbullet'],
'bounceDamping': 1.0,
"level": 1,
'pos': Vector2(0.5, 0.5),
'movevector': Vector2(0, 0),
'movefn': Move_Vector,
'wallactionfn': WallAction_Bounce,
'movefnargs': {"accelvector": Vector2(0, 0)},
'fireTimeDict': {},
'shapefnargs': {'animationfps': 30},
},
"shield": {
"objtype": 'shield',
'secToLifeEnd': -1.0,
'collisionCricle': 0.008,
'collisionTarget': ['bounceball', 'shield', 'supershield', 'bullet', 'circularbullet', 'superbullet', 'hommingbullet'],
'movefn': Move_SyncTarget,
'wallactionfn': WallAction_None,
'shapefnargs': {'animationfps': 30},
},
"supershield": {
"objtype": 'supershield',
'secToLifeEnd': 10.0,
'collisionCricle': 0.011,
'collisionTarget': ['bounceball', 'shield', 'supershield', 'bullet', 'circularbullet', 'superbullet', 'hommingbullet'],
'movefn': Move_SyncTarget,
'wallactionfn': WallAction_None,
'shapefnargs': {'animationfps': 30},
},
"spriteexplosioneffect": {
"objtype": 'spriteexplosioneffect',
'secToLifeEnd': .25,
'collisionCricle': 0,
'collisionTarget': [],
'movefn': Move_Vector,
'wallactionfn': WallAction_Remove,
'movefnargs': {"accelvector": Vector2(0, 0)},
'shapefnargs': {'animationfps': 30},
},
"ballexplosioneffect": {
"objtype": 'ballexplosioneffect',
'secToLifeEnd': 0.5,
'collisionCricle': 0,
'collisionTarget': [],
'movefn': Move_Vector,
'wallactionfn': WallAction_Remove,
'movefnargs': {"accelvector": Vector2(0, 0)},
'shapefnargs': {'animationfps': 30},
},
"spawneffect": {
"objtype": 'spawneffect',
'secToLifeEnd': 0.5,
'collisionCricle': 0,
'collisionTarget': [],
'movevector': Vector2(0, 0),
'movefn': Move_Vector,
'wallactionfn': WallAction_Remove,
'movefnargs': {"accelvector": Vector2(0, 0)},
'shapefnargs': {'animationfps': 30},
},
"cloud": {
"objtype": 'cloud',
'movelimit': 0.2,
'secToLifeEnd': -1.0,
'collisionCricle': 0.05,
'collisionTarget': [],
'movevector': Vector2(0, 0),
'movefn': Move_Vector,
'wallactionfn': WallAction_Wrap_Inner,
'movefnargs': {"accelvector": Vector2(1, 0)},