https://gist.github.com/f1d4a15db7c02052fc9a9e0783fab79c.git
Today, I took a deep dive into the base_running logic of my Python baseball simulation. At first, the code felt like a black box, but by breaking it down line by line and using metaphors like "Excel SUM," I finally claimed ownership of the logic. Here is how it works.
The "Clean Slate" Strategy (scored = 0)
Before any play begins, we must reset the current plate's score. This ensures that runs from the previous batter don't bleed into the current one. It's a temporary "basket" for the current hit's results.Handling Home Runs with "Excel Logic"
Python
if advance == 4:
scored = sum(self.bases) + 1
I applied my knowledge of Excel's SUM function here. We treat True as 1 and False as 0. By summing the bases and adding 1 (the batter), we get the total runs instantly. Simple and elegant!The "Anti-Collision" Reverse Loop
Python
for i in range(2, -1, -1): # Checking 3rd -> 2nd -> 1st base
This is the most critical part. To prevent "runner collision" (where a runner moves twice in one turn), we must process the bases from 3rd to 1st. By clearing the path ahead, each runner moves exactly as they should.The Logic of Movement (True vs False)
Scoring: If i + advance >= 3, the runner leaves the field (becomes False) and enters the score sheet (scored += 1).
Advancing: If they stay on the field, we plant a new flag (True) at their new position.
Cleanup: Regardless of where they go, the original base must be cleared (False).
Conclusion
I started the day feeling overwhelmed by the complexity, but by slowing down and translating the code into my own words, I turned stress into a "1% incremental growth."
PS: I've added detailed comments in the code to explain the base-running logic after a hit.
Top comments (0)