This repository has been archived by the owner on Jul 31, 2021. It is now read-only.
forked from roguelike2d/TekkenBot
-
Notifications
You must be signed in to change notification settings - Fork 4
/
TekkenGameState.py
1390 lines (1076 loc) · 57.1 KB
/
TekkenGameState.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
"""
This module's classes are responsible for reading and interpreting the memory of a Tekken7.exe proecess.
TekkenGameReader reads the memory of Tekken7.exe, extracts information about the state of the game, then saves a
'snapshot' of each frame.
Each GameSnapshot has 2 BotSnapshots, together encapsulating the information of both players and shared data for a single game frame.
TekkenGameState saves these snapshots and provides an api that abstracts away the difference
between questions that query one player (is player 1 currently attacking?), both players (what is the expected frame
advantage when player 2 emerges from block), or multiple game states over time (did player 1 just begin to block this
frame?, what was the last move player 2 did?).
"""
from collections import Counter
import ctypes as c
from ctypes import wintypes as w
import struct
import math
import ModuleEnumerator
import PIDSearcher
from MoveInfoEnums import *
from ConfigReader import ConfigReader, ReloadableConfig
from MoveDataReport import MoveDataReport
import MovelistParser
k32 = c.windll.kernel32
OpenProcess = k32.OpenProcess
OpenProcess.argtypes = [w.DWORD,w.BOOL,w.DWORD]
OpenProcess.restype = w.HANDLE
ReadProcessMemory = k32.ReadProcessMemory
ReadProcessMemory.argtypes = [w.HANDLE,w.LPCVOID,w.LPVOID,c.c_size_t,c.POINTER(c.c_size_t)]
ReadProcessMemory.restype = w.BOOL
GetLastError = k32.GetLastError
GetLastError.argtypes = None
GetLastError.restype = w.DWORD
CloseHandle = k32.CloseHandle
CloseHandle.argtypes = [w.HANDLE]
CloseHandle.restype = w.BOOL
class TekkenGameReader:
def __init__(self):
self.pid = -1
self.needReaquireGameState = True
self.needReacquireModule = True
self.flagToReacquireNames = True
self.module_address = 0
self.original_facing = None
self.opponent_name = None
self.is_player_player_one = None
self.c = ReloadableConfig('memory_address', parse_nums=True)
self.player_data_pointer_offset = self.c['MemoryAddressOffsets']['player_data_pointer_offset']#, #lambda x: int(x, 16))
self.p1_movelist = []
self.p2_movelist = []
self.p1_movelist_to_use = None
self.p2_movelist_to_use = None
self.p1_movelist_parser = None
self.p2_movelist_parser = None
def ReacquireEverything(self):
self.needReacquireModule = True
self.needReaquireGameState = True
self.flagToReacquireNames = True
self.pid = -1
def GetValueFromAddress(self, processHandle, address, isFloat=False, is64bit=False, isString=False):
if isString:
data = c.create_string_buffer(16)
bytesRead = c.c_ulonglong(16)
elif is64bit:
data = c.c_ulonglong()
bytesRead = c.c_ulonglong()
else:
data = c.c_ulong()
bytesRead = c.c_ulonglong(4)
successful = ReadProcessMemory(processHandle, address, c.byref(data), c.sizeof(data), c.byref(bytesRead))
if not successful:
e = GetLastError()
print("ReadProcessMemory Error: Code " + str(e))
self.ReacquireEverything()
value = data.value
if isFloat:
return struct.unpack("<f", value)[0]
elif isString:
try:
return value.decode('utf-8')
except:
print("ERROR: Couldn't decode string from memory")
return "ERROR"
else:
return int(value)
def GetBlockOfData(self, processHandle, address, size_of_block):
data = c.create_string_buffer(size_of_block)
bytesRead = c.c_ulonglong(size_of_block)
successful = ReadProcessMemory(processHandle, address, c.byref(data), c.sizeof(data), c.byref(bytesRead))
if not successful:
e = GetLastError()
print("Getting Block of Data Error: Code " + str(e))
#print('{} : {}'.format(address, self.GetValueFromFrame(data, self.c['PlayerDataAddress']['simple_move_state'])))
return data
def GetValueFromDataBlock(self, frame, offset, player_2_offset = 0x0, is_float=False):
address = offset
address += player_2_offset
bytes = frame[address: address + 4]
if not is_float:
return struct.unpack("<I", bytes)[0]
else:
return struct.unpack("<f", bytes)[0]
def GetValueAtEndOfPointerTrail(self, processHandle, data_type, isString):
addresses_str = self.c['NonPlayerDataAddresses'][data_type]
# The pointer trail is stored as a string of addresses in hex in the config. Split them up and convert
addresses = list(map(to_hex, addresses_str.split()))
value = self.module_address
for i, offset in enumerate(addresses):
if i + 1 < len(addresses):
value = self.GetValueFromAddress(processHandle, value + offset, is64bit=True)
else:
value = self.GetValueFromAddress(processHandle, value + offset, isString=isString)
return value
def IsForegroundPID(self):
pid = c.wintypes.DWORD()
active = c.windll.user32.GetForegroundWindow()
active_window = c.windll.user32.GetWindowThreadProcessId(active, c.byref(pid))
return pid.value == self.pid
def GetWindowRect(self):
#see https://stackoverflow.com/questions/21175922/enumerating-windows-trough-ctypes-in-python for clues for doing this without needing focus using WindowsEnum
if self.IsForegroundPID():
rect = c.wintypes.RECT()
c.windll.user32.GetWindowRect(c.windll.user32.GetForegroundWindow(), c.byref(rect))
return rect
else:
return None
def HasWorkingPID(self):
return self.pid > -1
def IsDataAFloat(self, data):
return data in ('x', 'y', 'z', 'activebox_x', 'activebox_y', 'activebox_z')
def GetUpdatedState(self, rollback_frame = 0):
gameSnapshot = None
if not self.HasWorkingPID():
self.pid = PIDSearcher.GetPIDByName(b'TekkenGame-Win64-Shipping.exe')
if self.HasWorkingPID():
print("Tekken pid acquired: " + str(self.pid))
else:
print("Tekken pid not acquired. Trying to acquire...")
return gameSnapshot
if (self.needReacquireModule):
print("Trying to acquire Tekken library in pid: " + str(self.pid))
self.module_address = ModuleEnumerator.GetModuleAddressByPIDandName(self.pid, 'TekkenGame-Win64-Shipping.exe')
if self.module_address == None:
print("TekkenGame-Win64-Shipping.exe not found. Likely wrong process id. Reacquiring pid.")
self.ReacquireEverything()
elif(self.module_address != self.c['MemoryAddressOffsets']['expected_module_address']):
print("Unrecognized location for TekkenGame-Win64-Shipping.exe module. Tekken.exe Patch? Wrong process id?")
else:
print("Found TekkenGame-Win64-Shipping.exe")
self.needReacquireModule = False
if self.module_address != None:
processHandle = OpenProcess(0x10, False, self.pid)
try:
player_data_base_address = self.GetValueFromAddress(processHandle, self.module_address + self.player_data_pointer_offset, is64bit = True)
if player_data_base_address == 0:
if not self.needReaquireGameState:
print("No fight detected. Gamestate not updated.")
self.needReaquireGameState = True
self.flagToReacquireNames = True
else:
last_eight_frames = []
second_address_base = self.GetValueFromAddress(processHandle, player_data_base_address, is64bit = True)
for i in range(8): # for rollback purposes, there are 8 copies of the game state, each one updatating once every 8 frames
potential_second_address = second_address_base + (i * self.c['MemoryAddressOffsets']['rollback_frame_offset'])
potential_frame_count = self.GetValueFromAddress(processHandle, potential_second_address + self.c['GameDataAddress']['frame_count'])
last_eight_frames.append((potential_frame_count, potential_second_address))
if rollback_frame >= len(last_eight_frames):
print("ERROR: requesting {} frame of {} long rollback frame".format(rollback_frame, len(last_eight_frames)))
rollback_frame = len(last_eight_frames) - 1
best_frame_count, player_data_second_address = sorted(last_eight_frames, key=lambda x: -x[0])[rollback_frame]
p1_bot = BotSnapshot()
p2_bot = BotSnapshot()
player_data_frame = self.GetBlockOfData(processHandle, player_data_second_address, self.c['MemoryAddressOffsets']['rollback_frame_offset'])
for data_type, value in self.c['PlayerDataAddress'].items():
p1_value = self.GetValueFromDataBlock(player_data_frame, value, 0, self.IsDataAFloat(data_type))
p2_value = self.GetValueFromDataBlock(player_data_frame, value, self.c['MemoryAddressOffsets']['p2_data_offset'], self.IsDataAFloat(data_type))
p1_bot.player_data_dict['PlayerDataAddress.'+data_type] = p1_value
p2_bot.player_data_dict['PlayerDataAddress.'+data_type] = p2_value
for data_type, value in self.c['EndBlockPlayerDataAddress'].items():
p1_value = self.GetValueFromDataBlock(player_data_frame, value)
p2_value = self.GetValueFromDataBlock(player_data_frame, value, self.c['MemoryAddressOffsets']['p2_end_block_offset'])
p1_bot.player_data_dict['EndBlockPlayerDataAddress.'+data_type] = p1_value
p2_bot.player_data_dict['EndBlockPlayerDataAddress.'+data_type] = p2_value
bot_facing = self.GetValueFromDataBlock(player_data_frame, self.c['GameDataAddress']['facing'])
timer_in_frames = self.GetValueFromDataBlock(player_data_frame, self.c['GameDataAddress']['timer_in_frames'])
pda = self.c['PlayerDataAddress']
# This is ugly and hacky
for axis, startingAddress in ((k, v) for k,v in self.c['PlayerDataAddress'].items() if k in ('x', 'y', 'z')):
positionOffset = 32 # our xyz coordinate is 32 bytes, a 4 byte x, y, and z value followed by five 4 byte values that don't change
p1_coord_array = []
p2_coord_array = []
for i in range(23):
p1_coord_array.append(self.GetValueFromDataBlock(player_data_frame, startingAddress + (i * positionOffset), 0, is_float=True))
p2_coord_array.append(self.GetValueFromDataBlock(player_data_frame, startingAddress + (i * positionOffset), self.c['MemoryAddressOffsets']['p2_data_offset'], is_float=True))
p1_bot.player_data_dict['PlayerDataAddress.'+axis] = p1_coord_array
p2_bot.player_data_dict['PlayerDataAddress.'+axis] = p2_coord_array
#print("numpy.array(" + str(p1_coord_array) + ")")
#list = p1_bot.player_data_dict[self.c['PlayerDataAddress']['y']]
#print('{} [{}]'.format(max(list), list.index(max(list))))
#print("--------------------")
# FIXME: This seems like it would always be true.
# The old code seems to be doing the same, so I don't know.
p1_bot.player_data_dict['use_opponent_movelist'] = p1_bot.player_data_dict['PlayerDataAddress.movelist_to_use'] == self.p2_movelist_to_use
p2_bot.player_data_dict['use_opponent_movelist'] = p2_bot.player_data_dict['PlayerDataAddress.movelist_to_use'] == self.p1_movelist_to_use
p1_bot.player_data_dict['movelist_parser'] = self.p1_movelist_parser
p2_bot.player_data_dict['movelist_parser'] = self.p2_movelist_parser
if self.original_facing is None and best_frame_count > 0:
self.original_facing = bot_facing > 0
if self.needReaquireGameState:
print("Fight detected. Updating gamestate.")
self.needReaquireGameState = False
p1_bot.Bake()
p2_bot.Bake()
if self.flagToReacquireNames:
if p1_bot.character_name != CharacterCodes.NOT_YET_LOADED.name and p2_bot.character_name != CharacterCodes.NOT_YET_LOADED.name:
self.opponent_name = self.GetValueAtEndOfPointerTrail(processHandle, "OPPONENT_NAME", True)
self.opponent_side = self.GetValueAtEndOfPointerTrail(processHandle, "OPPONENT_SIDE", False)
self.is_player_player_one = (self.opponent_side == 1)
#print(self.opponent_char_id)
#print(self.is_player_player_one)
self.p1_movelist_to_use = p1_bot.player_data_dict['PlayerDataAddress.movelist_to_use']
self.p2_movelist_to_use = p2_bot.player_data_dict['PlayerDataAddress.movelist_to_use']
self.p1_movelist_block, p1_movelist_address = self.PopulateMovelists(processHandle, "P1_Movelist")
self.p2_movelist_block, p2_movelist_address = self.PopulateMovelists(processHandle, "P2_Movelist")
self.p1_movelist_parser = MovelistParser.MovelistParser(self.p1_movelist_block, p1_movelist_address)
self.p2_movelist_parser = MovelistParser.MovelistParser(self.p2_movelist_block, p2_movelist_address)
#self.WriteMovelistsToFile(self.p1_movelist_block, p1_bot.character_name)
#self.WriteMovelistsToFile(self.p2_movelist_block, p2_bot.character_name)
self.p1_movelist_names = self.p1_movelist_block[0x2E8:200000].split(b'\00') #Todo: figure out the actual size of the name movelist
self.p2_movelist_names = self.p2_movelist_block[0x2E8:200000].split(b'\00')
#print(self.p1_movelist_names[(1572 * 2)])
self.flagToReacquireNames = False
gameSnapshot = GameSnapshot(p1_bot, p2_bot, best_frame_count, timer_in_frames, bot_facing, self.opponent_name, self.is_player_player_one)
finally:
CloseHandle(processHandle)
return gameSnapshot
def WriteMovelistsToFile(self, movelist, name):
with open('RawData/' + name + ".dat", 'wb') as fw:
fw.write(movelist)
def PopulateMovelists(self, processHandle, data_type):
movelist_str = self.c["NonPlayerDataAddresses"][data_type]
movelist_trail = list(map(to_hex, movelist_str.split()))
movelist_address = self.GetValueFromAddress(processHandle, self.module_address + movelist_trail[0], is64bit=True)
movelist_block = self.GetBlockOfData(processHandle, movelist_address, self.c["MemoryAddressOffsets"]["movelist_size"])
return movelist_block, movelist_address
def GetNeedReacquireState(self):
return self.needReaquireGameState
class BotSnapshot:
def __init__(self):
self.player_data_dict = {}
def Bake(self):
d = self.player_data_dict
#self.xyz = (d['PlayerDataAddress.x'], d['PlayerDataAddress.y'], d['PlayerDataAddress.z'])
self.move_id = d['PlayerDataAddress.move_id']
self.simple_state = SimpleMoveStates(d['PlayerDataAddress.simple_move_state'])
self.attack_type = AttackType(d['PlayerDataAddress.attack_type'])
self.startup = d['PlayerDataAddress.attack_startup']
self.startup_end = d['PlayerDataAddress.attack_startup_end']
self.attack_damage = d['PlayerDataAddress.attack_damage']
self.complex_state = ComplexMoveStates(d['PlayerDataAddress.complex_move_state'])
self.damage_taken = d['PlayerDataAddress.damage_taken']
self.move_timer = d['PlayerDataAddress.move_timer']
self.recovery = d['PlayerDataAddress.recovery']
self.char_id = d['PlayerDataAddress.char_id']
self.throw_flag = d['PlayerDataAddress.throw_flag']
self.rage_flag = d['PlayerDataAddress.rage_flag']
self.input_counter = d['PlayerDataAddress.input_counter']
self.input_direction = InputDirectionCodes(d['PlayerDataAddress.input_direction'])
self.input_button = InputAttackCodes(d['PlayerDataAddress.input_attack'] % InputAttackCodes.xRAGE.value)
self.rage_button_flag = d['PlayerDataAddress.input_attack'] >= InputAttackCodes.xRAGE.value
self.stun_state = StunStates(d['PlayerDataAddress.stun_type'])
self.power_crush_flag = d['PlayerDataAddress.power_crush'] > 0
cancel_window_bitmask = d['PlayerDataAddress.cancel_window']
self.is_cancelable = (CancelStatesBitmask.CANCELABLE.value & cancel_window_bitmask) == CancelStatesBitmask.CANCELABLE.value
self.is_bufferable = (CancelStatesBitmask.BUFFERABLE.value & cancel_window_bitmask) == CancelStatesBitmask.BUFFERABLE.value
self.is_parry_1 = (CancelStatesBitmask.PARRYABLE_1.value & cancel_window_bitmask) == CancelStatesBitmask.PARRYABLE_1.value
self.is_parry_2 = (CancelStatesBitmask.PARRYABLE_2.value & cancel_window_bitmask) == CancelStatesBitmask.PARRYABLE_2.value
self.throw_tech = ThrowTechs(d['PlayerDataAddress.throw_tech'])
#self.highest_y = max(d['PlayerDataAddress.y'])
#self.lowest_y = min(d['PlayerDataAddress.y'])
#self.hitboxes = [d['PlayerDataAddress.hitbox1'], d['PlayerDataAddress.hitbox2'], d['PlayerDataAddress.hitbox3'], d['PlayerDataAddress.hitbox4'], d['PlayerDataAddress.hitbox5']]
self.skeleton = (d['PlayerDataAddress.x'], d['PlayerDataAddress.y'], d['PlayerDataAddress.z'])
self.active_xyz = (d['PlayerDataAddress.activebox_x'], d['PlayerDataAddress.activebox_y'], d['PlayerDataAddress.activebox_z'])
self.is_jump = d['PlayerDataAddress.jump_flags'] & JumpFlagBitmask.JUMP.value == JumpFlagBitmask.JUMP.value
self.hit_outcome = HitOutcome(d['PlayerDataAddress.hit_outcome'])
self.mystery_state = d['PlayerDataAddress.mystery_state']
#self.movelist_to_use = d['PlayerDataAddress.movelist_to_use']
self.wins = d['EndBlockPlayerDataAddress.round_wins']
self.combo_counter = d['EndBlockPlayerDataAddress.display_combo_counter']
self.combo_damage = d['EndBlockPlayerDataAddress.display_combo_damage']
self.juggle_damage = d['EndBlockPlayerDataAddress.display_juggle_damage']
self.use_opponents_movelist = d['use_opponent_movelist']
self.movelist_parser = d['movelist_parser']
try:
self.character_name = CharacterCodes(d['PlayerDataAddress.char_id']).name
except:
self.character_name = "UNKNOWN"
def PrintYInfo(self):
#print("h: " + str(self.highest_y) + " l: " + str(self.lowest_y) + ' d: ' + str(self.highest_y - self.lowest_y))
print('{:.4f}, {:.4f}, {:.4f}'.format(self.highest_y, self.lowest_y, self.highest_y - self.lowest_y))
def GetInputState(self):
return (self.input_direction, self.input_button, self.rage_button_flag)
def GetTrackingType(self):
#if self.complex_state.value < 8:
return self.complex_state
#else:
# return ComplexMoveStates.UNKN
def IsBlocking(self):
return self.complex_state == ComplexMoveStates.BLOCK
def IsGettingCounterHit(self):
return self.hit_outcome in (HitOutcome.COUNTER_HIT_CROUCHING, HitOutcome.COUNTER_HIT_STANDING)
def IsGettingGroundHit(self):
return self.hit_outcome in (HitOutcome.GROUNDED_FACE_DOWN, HitOutcome.GROUNDED_FACE_UP)
def IsGettingWallSplatted(self):
return self.simple_state in (SimpleMoveStates.WALL_SPLAT_18, SimpleMoveStates.WALL_SPLAT_19)
def IsGettingHit(self):
return self.stun_state in (StunStates.BEING_PUNISHED, StunStates.GETTING_HIT)
#return not self.is_cancelable and self.complex_state == ComplexMoveStates.RECOVERING and self.simple_state == SimpleMoveStates.STANDING_FORWARD and self.attack_damage == 0 and self.startup == 0 #TODO: make this more accurate
def IsHitting(self):
return self.stun_state == StunStates.DOING_THE_HITTING
def IsPunish(self):
return self.stun_state == StunStates.BEING_PUNISHED
def IsAttackMid(self):
return self.attack_type == AttackType.MID
def IsAttackUnblockable(self):
return self.attack_type in {AttackType.HIGH_UNBLOCKABLE, AttackType.LOW_UNBLOCKABLE, AttackType.MID_UNBLOCKABLE}
def IsAttackAntiair(self):
return self.attack_type == AttackType.ANTIAIR_ONLY
def IsAttackThrow(self):
return self.throw_flag == 1
def IsAttackLow(self):
return self.attack_type == AttackType.LOW
def IsInThrowing(self):
return self.attack_type == AttackType.THROW
def GetActiveFrames(self):
return self.startup_end - self.startup + 1
def IsAttackWhiffing(self):
return self.complex_state in {ComplexMoveStates.END1, ComplexMoveStates.F_MINUS, ComplexMoveStates.RECOVERING, ComplexMoveStates.UN17, ComplexMoveStates.SS, ComplexMoveStates.WALK}
def IsOnGround(self):
return self.simple_state in {SimpleMoveStates.GROUND_FACEDOWN, SimpleMoveStates.GROUND_FACEUP}
def IsBeingJuggled(self):
return self.simple_state == SimpleMoveStates.JUGGLED
def IsAirborne(self):
return self.simple_state == SimpleMoveStates.AIRBORNE
def IsHoldingUp(self):
return self.input_direction == InputDirectionCodes.u
def IsHoldingUpBack(self):
return self.input_direction == InputDirectionCodes.ub
def IsTechnicalCrouch(self):
return self.simple_state in (SimpleMoveStates.CROUCH, SimpleMoveStates.CROUCH_BACK, SimpleMoveStates.CROUCH_FORWARD)
def IsTechnicalJump(self):
return self.is_jump
#return self.simple_state in (SimpleMoveStates.AIRBORNE, SimpleMoveStates.AIRBORNE_26, SimpleMoveStates.AIRBORNE_24)
def IsHoming1(self):
return self.complex_state == ComplexMoveStates.S_PLUS
def IsHoming2(self):
return self.complex_state == ComplexMoveStates.S
def IsPowerCrush(self):
return self.power_crush_flag
def IsBeingKnockedDown(self):
return self.simple_state == SimpleMoveStates.KNOCKDOWN
def IsWhileStanding(self):
return (self.simple_state in {SimpleMoveStates.CROUCH, SimpleMoveStates.CROUCH_BACK, SimpleMoveStates.CROUCH_FORWARD})
def IsWallSplat(self):
return self.move_id == 2396 or self.move_id == 2387 or self.move_id == 2380 or self.move_id == 2382 #TODO: use the wall splat states in ComplexMoveStates #move ids may be different for 'big' characters
def IsInRage(self):
return self.rage_flag > 0
def IsAbleToAct(self):
#print(self.cwb)
return self.is_cancelable
def IsParryable1(self):
return self.is_parry_1
def IsParryable2(self):
return self.is_parry_2
def IsBufferable(self):
return self.is_bufferable
def IsAttackStarting(self):
#return self.complex_state in {ComplexMoveStates.ATTACK_STARTING_1, ComplexMoveStates.ATTACK_STARTING_2, ComplexMoveStates.ATTACK_STARTING_3, ComplexMoveStates.ATTACK_STARTING_5, ComplexMoveStates.ATTACK_STARTING_6, ComplexMoveStates.ATTACK_STARTING_7} #doesn't work on several of Kazuya's moves, maybe others
if self.startup > 0:
is_active = self.move_timer <= self.startup
return is_active
else:
return False
class GameSnapshot:
def __init__(self, bot, opp, frame_count, timer_in_frames, facing_bool, opponent_name, is_player_player_one):
self.bot = bot
self.opp = opp
self.frame_count = frame_count
self.facing_bool = facing_bool
self.timer_frames_remaining = timer_in_frames
self.opponent_name = opponent_name
self.is_player_player_one = is_player_player_one
def FromMirrored(self):
return GameSnapshot(self.opp, self.bot, self.frame_count, self.timer_frames_remaining, self.facing_bool, self.opponent_name, self.is_player_player_one)
def GetDist(self):
#print('{}, {} : {}, {}'.format(self.bot.skeleton[0][22], self.opp.skeleton[0][22], self.bot.skeleton[2][22], self.opp.skeleton[2][22]))
return math.hypot(self.bot.skeleton[0][22] - self.opp.skeleton[0][22], self.bot.skeleton[2][22] - self.opp.skeleton[2][22])
class TekkenGameState:
def __init__(self):
self.gameReader = TekkenGameReader()
self.isPlayer1 = True
self.duplicateFrameObtained = 0
self.stateLog = []
self.mirroredStateLog = []
self.isMirrored = False
self.futureStateLog = None
def Update(self, buffer = 0):
gameData = self.gameReader.GetUpdatedState(buffer)
if(gameData != None):
if len(self.stateLog) == 0 or gameData.frame_count != self.stateLog[-1].frame_count: #we don't run perfectly in sync, if we get back the same frame, throw it away
self.duplicateFrameObtained = 0
frames_lost = 0
if len(self.stateLog) > 0:
frames_lost = gameData.frame_count - self.stateLog[-1].frame_count - 1
if frames_lost > 0:
pass
#print("DROPPED FRAMES: " + str(frames_lost))
for i in range(min(7 - buffer, frames_lost)):
#print("RETRIEVING FRAMES")
droppedState = self.gameReader.GetUpdatedState(min(7, frames_lost + buffer) - i)
self.AppendGamedata(droppedState)
self.AppendGamedata(gameData)
return True
elif gameData.frame_count == self.stateLog[-1].frame_count:
self.duplicateFrameObtained += 1
return False
def AppendGamedata(self, gameData):
if not self.isMirrored:
self.stateLog.append(gameData)
self.mirroredStateLog.append(gameData.FromMirrored())
else:
self.stateLog.append(gameData.FromMirrored())
self.mirroredStateLog.append(gameData)
if (len(self.stateLog) > 300):
self.stateLog.pop(0)
self.mirroredStateLog.pop(0)
def FlipMirror(self):
tempLog = self.mirroredStateLog
self.mirroredStateLog = self.stateLog
self.stateLog = tempLog
self.isMirrored = not self.isMirrored
def BackToTheFuture(self, frames):
if self.futureStateLog != None:
raise AssertionError('Already called BackToTheFuture, need to return to the present first, Marty')
else:
self.futureStateLog = self.stateLog[0 - frames:]
self.stateLog = self.stateLog[:0 - frames]
def ReturnToPresent(self):
if self.futureStateLog == None:
raise AssertionError("We're already in the present, Marty, what are you doing?")
else:
self.stateLog += self.futureStateLog
self.futureStateLog = None
def IsGameHappening(self):
return not self.gameReader.GetNeedReacquireState()
def IsBotOnLeft(self):
isPlayerOneOnLeft = self.gameReader.original_facing == self.stateLog[-1].facing_bool
if not self.isMirrored:
return isPlayerOneOnLeft
else:
return not isPlayerOneOnLeft
def GetBotHealth(self):
return max(0, 170 - self.stateLog[-1].bot.damage_taken)
def GetDist(self):
return self.stateLog[-1].GetDist()
def DidOppComboCounterJustStartXFramesAgo(self, framesAgo):
if len(self.stateLog) > framesAgo:
return self.stateLog[0 - framesAgo].opp.combo_counter == 1 and self.stateLog[0 - framesAgo - 1].opp.combo_counter == 0
else:
return False
def DidOppComboCounterJustEndXFramesAgo(self, framesAgo):
if len(self.stateLog) > framesAgo:
return self.stateLog[0 - framesAgo].opp.combo_counter == 0 and self.stateLog[0 - framesAgo - 1].opp.combo_counter > 0
else:
return False
def GetOppComboDamageXFramesAgo(self, framesAgo):
if len(self.stateLog) > framesAgo:
return self.stateLog[0 - framesAgo].opp.combo_damage
else:
return 0
def GetOppComboHitsXFramesAgo(self, framesAgo):
if len(self.stateLog) > framesAgo:
return self.stateLog[0 - framesAgo].opp.combo_counter
else:
return 0
def GetOppJuggleDamageXFramesAgo(self, framesAgo):
if len(self.stateLog) > framesAgo:
return self.stateLog[0 - framesAgo].opp.juggle_damage
else:
return 0
def DidBotStartGettingPunishedXFramesAgo(self, framesAgo):
if len(self.stateLog) > framesAgo:
return self.stateLog[0 - framesAgo].bot.IsPunish()
else:
return False
def DidOppStartGettingPunishedXFramesAgo(self, framesAgo):
if len(self.stateLog) > framesAgo:
return self.stateLog[0 - framesAgo].opp.IsPunish()
else:
return False
def BotFramesUntilRecoveryXFramesAgo(self, framesAgo):
if len(self.stateLog) > framesAgo:
return self.stateLog[0 - framesAgo].bot.recovery - self.stateLog[0 - framesAgo].bot.move_timer
else:
return 99
def OppFramesUntilRecoveryXFramesAgo(self, framesAgo):
if len(self.stateLog) > framesAgo:
return self.stateLog[0 - framesAgo].opp.recovery - self.stateLog[0 - framesAgo].opp.move_timer
else:
return 99
def IsBotBlocking(self):
return self.stateLog[-1].bot.IsBlocking()
def IsBotGettingCounterHit(self):
return self.stateLog[-1].bot.IsGettingCounterHit()
def IsBotGettingHitOnGround(self):
return self.stateLog[-1].bot.IsGettingGroundHit()
def IsOppBlocking(self):
return self.stateLog[-1].opp.IsBlocking()
def IsOppGettingHit(self):
return self.stateLog[-1].opp.IsGettingHit()
def IsBotGettingHit(self):
return self.stateLog[-1].bot.IsGettingHit()# or self.GetFramesSinceBotTookDamage() < 15
#return self.GetFramesSinceBotTookDamage() < 15
def IsOppHitting(self):
return self.stateLog[-1].opp.IsHitting()
def IsBotStartedGettingHit(self):
if len(self.stateLog) > 2:
return self.IsBotGettingHit() and not self.stateLog[-2].bot.IsGettingHit()
else:
return False
def IsBotStartedBeingThrown(self):
if len(self.stateLog) > 2:
return self.IsBotBeingThrown() and not self.stateLog[-2].opp.IsInThrowing()
else:
return False
def IsBotComingOutOfBlock(self):
if(len(self.stateLog) >= 2):
previousState = self.stateLog[-2].bot.IsBlocking()
currentState = self.stateLog[-1].bot.IsBlocking()
return previousState and not currentState
else:
return False
def GetRecoveryOfMoveId(self, moveID):
largestTime = -1
for state in reversed(self.stateLog):
if(state.bot.move_id == moveID):
largestTime = max(largestTime, state.bot.move_timer)
return largestTime
def GetLastMoveID(self):
for state in reversed(self.stateLog):
if(state.bot.startup > 0):
return state.bot.move_id
return -1
def GetBotJustMoveID(self):
return self.stateLog[-2].bot.move_id
def DidBotRecentlyDoMove(self):
if len(self.stateLog) > 5:
return self.stateLog[-1].bot.move_timer < self.stateLog[-5].bot.move_timer
else:
return False
def DidBotRecentlyDoDamage(self):
if len(self.stateLog) > 10:
if self.stateLog[-1].opp.damage_taken > self.stateLog[-20].opp.damage_taken:
return True
return False
def IsBotCrouching(self):
return self.stateLog[-1].bot.IsTechnicalCrouch()
def IsOppAttackMid(self):
return self.stateLog[-1].opp.IsAttackMid()
def IsOppAttackUnblockable(self):
return self.stateLog[-1].opp.IsAttackUnblockable()
def IsOppAttackAntiair(self):
return self.stateLog[-1].opp.IsAttackAntiair()
def IsOppAttackThrow(self):
return self.stateLog[-1].opp.IsAttackThrow()
def IsOppAttackLow(self):
return self.stateLog[-1].opp.IsAttackLow()
def IsOppAttacking(self):
return self.stateLog[-1].opp.IsAttackStarting()
def GetOppMoveInterruptedFrames(self): #only finds landing canceled moves?
if len(self.stateLog) > 3:
if self.stateLog[-1].opp.move_timer == 1:
interruptedFrames = self.stateLog[-2].opp.move_timer - (self.stateLog[-3].opp.move_timer + 1)
if interruptedFrames > 0: #landing animation causes move_timer to go *up* to the end of the move
return interruptedFrames
return 0
def GetFramesUntilOutOfBlock(self):
#print(self.stateLog[-1].bot.block_flags)
if not self.IsBotBlocking():
return 0
else:
recovery = self.stateLog[-1].bot.recovery
blockFrames = self.GetFramesBotHasBeenBlockingAttack()
return (recovery ) - blockFrames
def GetFrameProgressOfOppAttack(self):
mostRecentStateWithAttack = None
framesSinceLastAttack = 0
for state in reversed(self.stateLog):
if mostRecentStateWithAttack == None:
if state['p2_attack_startup'] > 0:
mostRecentStateWithAttack = state
elif (state['p2_move_id'] == mostRecentStateWithAttack.opp.move_id) and (state.opp.move_timer < mostRecentStateWithAttack.opp.move_timer):
framesSinceLastAttack += 1
else:
break
return framesSinceLastAttack
def GetFramesBotHasBeenBlockingAttack(self):
if not self.stateLog[-1].bot.IsBlocking():
return 0
else:
opponentMoveId = self.stateLog[-1].opp.move_id
opponentMoveTimer = self.stateLog[-1].opp.move_timer
framesSpentBlocking = 0
for state in reversed(self.stateLog):
#print(state.opp.move_timer)
#print(state.opp.move_id)
#print(opponentMoveId)
if state.bot.IsBlocking() and (state.opp.move_timer <= opponentMoveTimer) and (state.opp.move_id == opponentMoveId) and state.opp.move_timer > state.opp.startup:
framesSpentBlocking += 1
opponentMoveTimer = state.opp.move_timer
else:
break
#print(framesSpentBlocking)
return framesSpentBlocking
def IsOppWhiffingXFramesAgo(self, framesAgo):
if len(self.stateLog) > framesAgo:
return self.stateLog[0 - framesAgo].opp.IsAttackWhiffing()
else:
return False
def IsOppWhiffing(self):
return self.stateLog[-1].opp.IsAttackWhiffing()
def IsBotWhiffing(self):
return self.stateLog[-1].bot.IsAttackWhiffing()
def IsBotWhileStanding(self):
return self.stateLog[-1].bot.IsWhileStanding()
def GetBotFramesUntilRecoveryEnds(self):
return (self.stateLog[-1].bot.recovery) - (self.stateLog[-1].bot.move_timer)
def IsBotMoveChanged(self):
if (len(self.stateLog) > 2):
return self.stateLog[-1].bot.move_id != self.stateLog[-2].bot.move_id
else:
return False
def IsBotWhiffingAlt(self):
currentBot = self.stateLog[-1].bot
if currentBot.startup == 0: #we might still be in recovery
for i, state in enumerate(reversed(self.stateLog)):
if state.bot.startup > 0:
pass
else:
return currentBot.IsAttackWhiffing()
def GetOpponentMoveIDWithCharacterMarker(self):
characterMarker = self.stateLog[-1].opp.char_id
return (self.stateLog[-1].opp.move_id + (characterMarker * 10000000))
def GetOppStartup(self):
return self.stateLog[-1].opp.startup
def GetBotStartupXFramesAgo(self, framesAgo):
if len(self.stateLog) > framesAgo:
return self.stateLog[0 - framesAgo].bot.startup
else:
return False
def GetOppActiveFrames(self):
return self.stateLog[-1].opp.GetActiveFrames()
def GetLastActiveFrameHitWasOn(self, frames):
returnNextState = False
for state in reversed(self.stateLog[-(frames + 2):]):
if returnNextState:
return (state.opp.move_timer - state.opp.startup) + 1
if state.bot.move_timer == 1:
returnNextState = True
return 0
#return self.stateLog[-1].opp.move_timer - self.stateLog[-1].opp.startup
#elapsedActiveFrames = 0
#opp_move_timer = -1
#for state in reversed(self.stateLog):
#elapsedActiveFrames += 1
#if state.bot.move_timer == 1 or state.opp.move_timer == state.opp.startup:
#return elapsedActiveFrames
#return -1
def GetOppActiveFramesXFramesAgo(self, framesAgo):
if len(self.stateLog) > framesAgo:
return self.stateLog[0 - framesAgo].opp.GetActiveFrames()
else:
return 0
def GetOppRecovery(self):
return self.stateLog[-1].opp.recovery
def GetOppFramesTillNextMove(self):
return self.GetOppRecovery() - self.GetOppMoveTimer()
def GetBotFramesTillNextMove(self):
return self.GetBotRecovery() - self.GetBotMoveTimer()
def GetBotRecovery(self):
return self.stateLog[-1].bot.recovery
def GetOppMoveId(self):
return self.stateLog[-1].opp.move_id
def GetOppAttackType(self):
return self.stateLog[-1].opp.attack_type
def GetOppAttackTypeXFramesAgo(self, framesAgo):
if len(self.stateLog) > framesAgo:
return self.stateLog[0 - framesAgo].opp.attack_type
else:
return False
def GetBotMoveId(self):
return self.stateLog[-1].bot.move_id
def GetBotStartup(self):
return self.stateLog[-1].bot.startup
def GetBotMoveTimer(self):
return self.stateLog[-1].bot.move_timer
def GetOppMoveTimer(self):
return self.stateLog[-1].opp.move_timer
def IsBotAttackStarting(self):
return (self.GetBotStartup() - self.GetBotMoveTimer()) > 0
def GetOppTimeUntilImpact(self):
return self.GetOppStartup() - self.stateLog[-1].opp.move_timer + self.stateLog[-1].opp.GetActiveFrames()
def GetBotTimeUntilImpact(self):
return self.GetBotStartup() - self.stateLog[-1].bot.move_timer + self.stateLog[-1].bot.GetActiveFrames()
def IsBotOnGround(self):
return self.stateLog[-1].bot.IsOnGround()
def IsBotBeingKnockedDown(self):
return self.stateLog[-1].bot.IsBeingKnockedDown()
def IsBotBeingWallSplatted(self):
return self.stateLog[-1].bot.IsGettingWallSplatted()
def GetOppDamage(self):
return self.stateLog[-1].opp.attack_damage
def GetMostRecentOppDamage(self):
if self.stateLog[-1].opp.attack_damage > 0:
return self.stateLog[-1].opp.attack_damage
currentHealth = self.stateLog[-1].bot.damage_taken
for state in reversed(self.stateLog):
if state.bot.damage_taken < currentHealth:
return currentHealth - state.bot.damage_taken
return 0
def GetOppLatestNonZeroStartupAndDamage(self):
for state in reversed(self.stateLog):
damage = state.opp.attack_damage
startup = state.opp.startup
if damage > 0 or startup > 0:
return (startup, damage)
return (0, 0)
def IsBotJustGrounded(self):
if (len(self.stateLog) > 2):
return self.stateLog[-1].bot.IsOnGround() and not self.stateLog[-2].bot.IsOnGround() and not self.stateLog[-2].bot.IsBeingJuggled() and not self.stateLog[-2].bot.IsBeingKnockedDown()
else:
return False
def IsBotBeingJuggled(self):
return self.stateLog[-1].bot.IsBeingJuggled()
def IsBotStartedBeingJuggled(self):
if (len(self.stateLog) > 2):
return self.stateLog[-1].bot.IsBeingJuggled() and not self.stateLog[-2].bot.IsBeingJuggled()
else:
return False
def IsBotBeingThrown(self):
return self.stateLog[-1].opp.IsInThrowing()
def IsOppWallSplat(self):
return self.stateLog[-1].opp.IsWallSplat()
def DidBotJustTakeDamage(self, framesAgo = 1):
if(len(self.stateLog) > framesAgo ):
return max(0, self.stateLog[0 - framesAgo].bot.damage_taken - self.stateLog[0 - framesAgo - 1].bot.damage_taken)
else:
return 0
def DidOppJustTakeDamage(self, framesAgo=1):
if (len(self.stateLog) > framesAgo):
return max(0, self.stateLog[0 - framesAgo].opp.damage_taken - self.stateLog[0 - framesAgo - 1].opp.damage_taken)
else:
return 0