Skip to content

Instantly share code, notes, and snippets.

@dlareau
Created September 21, 2021 20:52
Show Gist options
  • Save dlareau/e999d20f411b9a794eafc09bafe5a0f8 to your computer and use it in GitHub Desktop.
Save dlareau/e999d20f411b9a794eafc09bafe5a0f8 to your computer and use it in GitHub Desktop.
# takes a whole game of packets
def add_fields(packets):
batCount = -1
# Pretend the first packet has been repeated
batSet = [packets[0]]
lastPacket = packets[0]
# Iterate over all game packets
for packet in packets:
# calculate run difference between current and last packet
# suitable for use in RBI and such
if(packet["topOfInning"]):
runs_scored = packet["awayScore"] - lastPacket["awayScore"]
packet["currentBatter"] = packet["awayBatter"]
packet["currentPitcher"] = packet["homePitcher"]
else:
packet["currentBatter"] = packet["homeBatter"]
packet["currentPitcher"] = packet["awayPitcher"]
runs_scored = packet["homeScore"] - lastPacket["homeScore"]
packet["runs_scored"] = runs_scored
# Set default value
packet["lastInBatCount"] = False
if(packet["type"] == 209):
packet["currentBatter"] = batSet[0]["currentBatter"]
# Only look at "batting events"
if(packet["type"] in allowable_plays):
# update batCount any time there is a new batterId for either team
if(lastPacket["homeTeamBatterCount"] + 1 == packet["homeTeamBatterCount"] or
lastPacket["awayTeamBatterCount"] + 1 == packet["awayTeamBatterCount"]):
# We're already past the last event, set the previous event as the last event
batSet[-1]["lastInBatCount"] = True
# The last event usually doesn't actually have the batter set, set it.
if(len(batSet) > 1):
if(batSet[-1]["currentBatter"] is None):
batSet[-1]["currentBatter"] = batSet[-2]["currentBatter"]
processBatSet(batSet)
determine_baserunners(packet, lastPacket)
# we're now in the next batCount, reset the batSet
batCount += 1
batSet = []
batSet.append(packet)
packet["batCount"] = style(str(batCount), fg='green')
else:
packet["batCount"] = style("-1", fg='red')
determine_baserunners(packet, lastPacket)
# we're done, on to the next packet.
lastPacket = packet
# Set the last event in the last batSet of the game to True
batSet[-1]["lastInBatCount"] = True
if(len(batSet) > 1):
if(batSet[-1]["currentBatter"] is None):
batSet[-1]["currentBatter"] = batSet[-2]["currentBatter"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment