-
Notifications
You must be signed in to change notification settings - Fork 0
/
AtBatResult.py
624 lines (496 loc) · 22.7 KB
/
AtBatResult.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
import random
import ProbabilityEngine as PrEng
from Globals import *
from FieldGameState import *
from PlayerStats import *
from Play import *
#####
USE_NONRANDOM_PITCHES = 0
nextPitch = 0
gsPitches = None
DEBUG_PITCHZONES = 0
#####
class BatBallContactResult:
def __init__(self,
batterAbil=None,
pitcherAbil=None):
self.__batterAbil = batterAbil
self.__pitcherBall = pitcherAbil
#0 is first base line
#90 is third base line
# < 0 is foul ball
#> 90 is foul ball
self.__Theta = random.randint(gsTHETA_LEFTFIELD_FOULPOLE-gsTHETA_FOUL_RANGE,
gsTHETA_RIGHTFIELD_FOULPOLE+gsTHETA_FOUL_RANGE)
#self.__Theta = random.normalvariate(45, 15)
#R is Radius or distance of hit, if its in the Air
#this is where it will land
#if its a grandball this the power
#which can eventually determine error rates
#NOTE: this will become magnitude or velocity of ball off the bat
# which together will determine the distance with _phi
# we could also define the radius to be the distance
# the ball would be hit if phi = 45 degrees (i.e. the optimal angle)
#self.__Radius = random.normalvariate(150, 100+50+self.__batterAbil.getBattingPowerZones()[0])
self.__Radius = random.randint(1, gsPLAYER_POWER_MAX_RADIUS_INIT+self.__batterAbil.getBattingPowerZones()[0])
#the angle that the ball leaves the bat
#for now 0 is a ground ball and 1 is in the air
self.__Phi = random.randint(0,1)
def getHitParams(self):
return (self.__Theta, self.__Phi, self.__Radius)
####
#
#
####
class AtBatResult:
def __init__(self,
batterGUID, batterAbil, batterSkills,
pitcherGUID, pitcherAbil, pitcherSkills,
fieldState): #(numOuts, numOnBase) TODO: make this a proper object
self.__pitcherGUID = pitcherGUID
self.__pitcherAbil = pitcherAbil
self.__pitcherSkills = pitcherSkills
self.__pitcherStats = PitcherStats(gsSTATSUBTYPE_SINGLEPLAYSTATS)
self.__pitcherStats.addBatterFaced()
self.__batterGUID = batterGUID
self.__batterAbil = batterAbil
self.__batterSkills = batterSkills
self.__batterStats = BatterStats(gsSTATSUBTYPE_SINGLEPLAYSTATS)
self.__batterStats.addAtBat()
self.__fieldState = fieldState
#we have to copy this because we are going to modify it
self.__allowedEvents = gsCONTACTMADEEVENTS[:]#gsBATTINGEVENTS[:]
self.__contactMade = False
#fill these in later
self.__playObj = None
self.__atBatEventLog = [] #list of strings
self.__runnersOut = []
#self.__runnersScored = [] #[playerGUID,]
self.__resultCode = gsNULL_ATBATRESULT_CODE
#TO USE NON RANDOM PITCH DATA
if USE_NONRANDOM_PITCHES:
global gsPitches
if gsPitches == None:
file = open("pitch.loc", "r")
pitches = file.readline()
file.close()
gsPitches = eval(pitches)
def __del__(self):
#TODO: make sure we aren't causing memory leak
#don't delete these next TWO objects because
#they are references from the player object
self.__pitcherAbil = None
self.__batterAbil = None
#don't delete this because it is stored in the GameState Obj
self.__fieldState = None
del(self.__pitcherStats)
self.__pitcherStats = None
del(self.__batterStats)
self.__batterStats = None
def __str__(self):
s = "AtBatEvent Object(%d):" % id(self)
s += self.__getstate__()
return s
def contactMade(self):
return self.__contactMade
def getPitcherStats(self):
return self.__pitcherStats
def getBatterStats(self):
return self.__batterStats
def __getstate__(self):
s = "{'pitcherGUID':%d," +\
"'pitcherStats':%s," +\
"'batterGUID':%d," +\
"'batterStats':%s," +\
"'fieldState':%s," +\
"'allowedEvents':%s," +\
"'contactMade':%s," +\
"'atBatEventLog':%s," +\
"'runnersOut':%s," +\
"'resultCode':%s}"
return s % (self.__pitcherGUID,
self.__pitcherStats,
self.__batterGUID,
self.__batterStats,
str(self.__fieldState),
str(self.__allowedEvents),
str(self.__contactMade),
str(self.__atBatEventLog),
str(self.__runnersOut),
self.__resultCode)
def _logAtBatEvent(self, eventStr):
self.__atBatEventLog += [eventStr]
def _getNextPitch(self):
#CAN USE TO DECRESE ENTRPOY IN THE SYSTEM
if USE_NONRANDOM_PITCHES:
global gsPitches
global nextPitch
nextPitch += 1
#jeffk 07/28/09 DIRTY HACK: to increase number of balls temporarily
#b = random.randint(0,2)
z = -1
#if b == 0:
# z = 9
#weight the number of balls thrown out of the
#strikezone according to the pitchers control
prBall = PrEng.PrBall(self.__pitcherAbil.getPitcherControl())
b = random.randint(0,99)
z = -1
if float(b) < 100*prBall:
z = gsBALLZONE
else:
#its a strike so randomly select the strike zone 0-8
z = random.randint(0,len(gsPITCHZONES)-2)
if DEBUG_PITCHZONES:
print "Pitch - PrBall(%f)=%f\t%d %d" % (self.__pitcherAbil.getPitcherControl(),
prBall, b, z)
#TODO: weight the pitchtype and pitchzone according to the pitchers strengths
# decided not to do this because it would favor the pitchers too much
r = random.randint(0,len(gsPITCHTYPES)-1)
return (gsPITCHTYPES[r], gsPITCHZONES[z])
#def _getNextSwing(self):
# global gsSwings
# global nextSwing
# print gsSwings[nextSwing]
# nextSwing += 1
# return gsSwings[nextSwing]
def simPitch(self, pitcherAbil=None, batterAbil=None, pitch=None):
if pitcherAbil == None:
pitcherAbil = self.__pitcherAbil
if batterAbil == None:
batterAbil = self.__batterAbil
pitchType = None
pitchZone = -1
if pitch == None:
(pitchType, pitchZone) = self._getNextPitch()
else:
(pitchType, pitchZone) = pitch
swungAtBall = False
#r = random.randint(0,100)
if pitchZone not in gsSTRIKEZONE:# and r >=20:
#the pitch is in the strike zone
#TODO: calculate batter pateince to see if he swings at this pitch
#if (batter swings) :
# => it's a strike
prSwingAtBall = PrEng.PrSwingAtBall(self.__batterAbil.getBatterPatience())
r = random.randint(0,99)
if r < int(100*prSwingAtBall):
#he swung
swungAtBall = True
#TODO: base on pitchers control decide whether or not he hit the batter
# if gsATBATRESULT_HITBYPITCH
if swungAtBall:
None
elif not swungAtBall and self.__pitcherStats.getBalls() == gsMAXBALLCOUNT-1:
#TODO: need to check to see if runs score and generate a Play()
#print "*** ATBATRESULT: WALK ***"
playObj = Play(self.__batterGUID, self.__pitcherGUID,
pitchType, pitchZone, 0,
self.__pitcherStats.getBalls(),
self.__pitcherStats.getStrikes(),
gsATBATRESULT_WALK) #earlyResultCode
bases = self.__fieldState.getBasesState()
runnersAdvancedList = bases.simBaseRunners(gsATBATRESULT_WALK)
playObj.setResult(gsATBATRESULT_WALK)
playObj.setRunnersAdvanced(runnersAdvancedList)
playObj.createPlayEncoding()
self.__resultCode = str(playObj)
#print playObj
self.__pitcherStats.addPitchThrown(pitchType,
pitchZone,
0,#walks don't count as at bats
gsPITCHCALL_WALK,
playObj)
#TODO: need to use fieldState to determine who
# scored and set appropriately
# in the playObj because in the case of a WALK/HBP runs can
# score without a ball being in play
self.__batterStats.addPitchReceived(pitchType,
pitchZone,
0,
gsPITCHCALL_WALK,
self.__fieldState.numRunnersInScoringPos(),
playObj)
self.__playObj = playObj
#print "WALK"
return gsPITCHCALL_WALK
else:# not swungAtBall:
#this addPitchReceived does nothing for now
#because we don't track
#individual pitches for batters
self.__pitcherStats.addPitchThrown(pitchType,
pitchZone,
0,
gsPITCHCALL_BALL)
self.__batterStats.addPitchReceived(pitchType,
pitchZone,
0,
gsPITCHCALL_BALL,
0)
return gsPITCHCALL_BALL
#else:
#it's in the strike zone
#we always swing this call get the probability that the
#batter makes contact
if not swungAtBall:
pr = PrEng.PrContactNew(pitcherAbil, self.__pitcherSkills,
batterAbil, self.__batterSkills,
(pitchType, pitchZone))
#using the probability of contact we then
#do our monte carlo simulation to determine
#if the ball is actually hit
r = random.randint(0,999)
if r <= (pr * 1000):
#fuckin' contact!
self.__contactMade = True
playObj = Play(self.__batterGUID, self.__pitcherGUID,
pitchType, pitchZone, 0,
self.__pitcherStats.getBalls(),
self.__pitcherStats.getStrikes())
self.simBallInPlay(playObj)
if playObj.isFoul():#.startswith(gsPITCHCALL_FOUL):
self.__contactMade = False
self.__pitcherStats.addPitchThrown(pitchType,
pitchZone,
0,
gsPITCHCALL_FOUL)
self.__batterStats.addPitchReceived(pitchType,
pitchZone,
0,
gsPITCHCALL_FOUL,
0)
self.__resultCode = gsNULL_ATBATRESULT_CODE
self.__playObj = playObj
return gsPITCHCALL_FOUL
else:
playObj.createPlayEncoding()
self.__resultCode = str(playObj)
self.__pitcherStats.addPitchThrown(pitchType,
pitchZone,
0,
None,
playObj)
self.__batterStats.addPitchReceived(pitchType,
pitchZone,
0,
None,
self.__fieldState.numRunnersInScoringPos(),
playObj)
self.__playObj = playObj
return gsPITCHCALL_CONTACT
#else:
#he whiff'd!
if self.__pitcherStats.getStrikes() == gsMAXSTRIKECOUNT-1:
#it's a strikeout
playObj = Play(self.__batterGUID, self.__pitcherGUID,
pitchType, pitchZone, 0,
self.__pitcherStats.getBalls(),
self.__pitcherStats.getStrikes(),
gsATBATRESULT_STRIKEOUT) #earlyResultCode
self.__fieldState.incOuts(1)
bases = self.__fieldState.getBasesState()
runnersAdvancedList = bases.simBaseRunners(gsATBATRESULT_STRIKEOUT)
playObj.setResult(gsATBATRESULT_STRIKEOUT)
playObj.setRunnersAdvanced(runnersAdvancedList)
playObj.createPlayEncoding()
self.__resultCode = str(playObj)
self.__pitcherStats.addPitchThrown(pitchType,
pitchZone,
0,
gsPITCHCALL_STRIKEOUT,
playObj)
self.__batterStats.addPitchReceived(pitchType,
pitchZone,
0,
gsPITCHCALL_STRIKEOUT,
self.__fieldState.numRunnersInScoringPos(),
playObj)
self.__playObj = playObj
return gsPITCHCALL_STRIKEOUT
else:
#its just a strike
if swungAtBall:
#print "SWUNG AT BALL"
None
self.__pitcherStats.addPitchThrown(pitchType,
pitchZone,
0,
gsPITCHCALL_STRIKE)
self.__batterStats.addPitchReceived(pitchType,
pitchZone,
0,
gsPITCHCALL_STRIKE,
0)
return gsPITCHCALL_STRIKE
#########
#
#
#
#
#########
def _startSimAtBat(self):
return
def _endSimAtBat(self, ret):
return ret
def simAtBat(self, pitcherAbil=None, batterAbil=None, pitch=None):
self._startSimAtBat()
if pitcherAbil == None:
pitcherAbil = self.__pitcherAbil
if batterAbil == None:
batterAbil = self.__batterAbil
ret = ""
while 1:
ret = self.simPitch(pitcherAbil, batterAbil, pitch)
if ret == gsPITCHCALL_FOUL:
continue
if ret != gsPITCHCALL_BALL and ret != gsPITCHCALL_STRIKE: #or FOUL
return self._endSimAtBat(ret)
return self._endSimAtBat(ret)
########################
#heart of simulation code
#needs to simluate the physics of the bat hitting the ball to determine its trajectory
#and use inconjunction with the player abilities in the field and the players abilities
#on base to determine how the play is fielded and who advances on base
#the playObj is fully described in the playObj which is modified as it is passed
########################
def simBallInPlay(self, playObj):
#def _generateAtBatResult(self):
self._findAllowedEvents()
bbcr = BatBallContactResult(self.__batterAbil, self.__pitcherAbil)
fieldState = self.__fieldState#DefensiveFieldState()#self.__bases, self.__outs)#FieldGeometry, None)
((result, fielder, radius), runnersAdvancedList) = fieldState.simDefense(bbcr)#FieldBallContact(bbcr)
#print bbcr.getHitParams()
#print "%s %s %d" % (result, fielder, r)
playObj.setFieldersInPlay(fielder)
(theta, phi, radius) = bbcr.getHitParams()
playObj.setHitEndLocation(theta, phi, radius)
playObj.setResult(result)
playObj.setRunnersAdvanced(runnersAdvancedList)
self.__play = playObj
self.__resultCode = str(playObj)
def _safeRemoveEvent(self, list, eventStr):
if eventStr in list:
list.remove(eventStr)
def _findAllowedEvents(self):
(numOuts, numOnBase) = self.__fieldState.getStateOutsAndOnBase()
#allowedEvents = self.gsBATTINGEVENTS[:]
if numOuts == 2 or numOnBase == 0:
self._safeRemoveEvent(self.__allowedEvents, gsATBATRESULT_SACOUT)
self._safeRemoveEvent(self.__allowedEvents, gsATBATRESULT_DOUBLEPLAY)
self._safeRemoveEvent(self.__allowedEvents, gsATBATRESULT_TRIPLEPLAY)
elif numOuts <= 1 and numOnBase > 0:
if numOuts == 0 and numOnBase >= 2:
#allowedEvents = allowedEvents
None
else:
self._safeRemoveEvent(self.__allowedEvents, gsATBATRESULT_SACOUT)
self._safeRemoveEvent(self.__allowedEvents, gsATBATRESULT_TRIPLEPLAY)
if self.__contactMade:
self._safeRemoveEvent(self.__allowedEvents, gsATBATRESULT_HITBYPITCH)
return
def logAtBatEvent(self, eventStr):
self.__atBatEventLog += [eventStr]
def atBatEventLog(self):
return self.__atBatEventLog
def isOut(self):
x = [outevent for outevent in gsOUTEVENTS if self.__resultCode.startswith(outevent)]
return len(x) != 0#self.__resultCode in gsOUTEVENTS
def outsMade(self):
x = [outevent for outevent in gsSINGLEOUTPLAYS if self.__resultCode.startswith(outevent)]
#if self.__resultCode in gsSINGLEOUTPLAYS:
if len(x) != 0:
return 1
if self.DoublePlay():
return 2
if self.TriplePlay():
return 3
return 0
def countsAsAtBat(self):
x = [event for event in gsNOTATBAT if self.__resultCode.startswith(event)]
return len(x) > 0
#return self.__resultCode not in gsNOTATBAT
def runsScored(self):
return len(self.__runnersScored)
def runnersAdvance(self):
x = [event for event in gsRUNNERSADVANCEEVENTS if self.__resultCode.startswith(event)]
return len(x) > 0
def Single(self):
return self.__resultCode.startswith(gsATBATRESULT_SINGLE)
def isHit(self):
x = [event for event in gsHITS if self.__resultCode.startswith(event)]
return len(x) != 0 #self.__resultCode in gsHITS
def Double(self):
return self.__resultCode.startswith(gsATBATRESULT_DOUBLE)
def Triple(self):
return self.__resultCode.startswith(gsATBATRESULT_TRIPLE)
def HomeRun(self):
return self.__resultCode.startswith(gsATBATRESULT_HOMERUN)
def Walk(self):
return self.__resultCode.startswith(gsATBATRESULT_WALK)
def HitByPitch(self):
return self.__resultCode.startswith(gsATBATRESULT_HITBYPITCH)
def StrikeOut(self):
return self.__resultCode.startswith(gsATBATRESULT_STRIKEOUT)
def GroundOut(self):
return self.__resultCode.startswith(gsATBATRESULT_GROUNDOUT)
def FlyOut(self):
return self.__resultCode.startswith(gsATBATRESULT_AIROUT)
def SacrificeOut(self):
return self.__resultCode.startswith(gsATBATRESULT_SACOUT)
def DoublePlay(self):
return self.__resultCode.startswith(gsATBATRESULT_DOUBLEPLAY)
def TriplePlay(self):
return self.__resultCode.startswith(gsATBATRESULT_TRIPLEPLAY)
def teamScored(self):
if self.__playObj == None:
return False
return self.__playObj.runsScoredOnPlay() > 0
#DEPRECATED
#def setRunnersScored(self, runnerGUIDList):
# self.__runnersScored = runnerGUIDList
def getRunnersScored(self):
return self.__playObj.getRunnerScoredList()
def getResultCode(self):
return self.__resultCode
def getPitcherGUID(self):
return self.__pitcherGUID
def getBatterGUID(self):
return self.__batterGUID
#def getPitchCounts(self):
# return (self.__totPitches, self.__strikeCount + self.__fouls, self.__ballCount)
old = """def _OLDgenerateAtBatResult(self):
self._findAllowedEvents()
if self.__ballCount == 4:
self.__resultCode = 'BB'
return
if self.__strikeCount == 3:
self.__resultCode = 'SO'
return
random.seed()
r = random.randint(0,len(self.__allowedEvents)-1)
self.__resultCode = self.__allowedEvents[r]
#if self__resultCode == 'HR':
#TODO: populate event log for different kinds of events
return"""
old = """def RANDOMLYgeneratePitchCount(self):
#generate pitches
if self.__resultCode == 'SO':
self.__strikeCount = 3
self.__ballCount = random.randint(0,3)
elif self.__resultCode == 'BB':
self.__strikeCount = random.randint(0,2)
self.__ballCount = 4
else:
self.__strikeCount = random.randint(0,2)
self.__ballCount = random.randint(0,3)
if self.__strikeCount >= 2:
self.__fouls = random.randint(self.__ballCount + self.__strikeCount,
gsMAXPITCHCOUNT)
self.__totPitches = self.__ballCount + self.__strikeCount + self.__fouls
else:
self.__totPitches = self.__ballCount + self.__strikeCount
if self.__resultCode == 'HBP':
self.__ballCount += 1
if self.__resultCode not in gsDONTADDPITCH:
self.__totPitches += 1
return """