Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- from collections import Counter
- import matplotlib.pyplot as plt
- # ============================================================
- # Configuration
- # ============================================================
- SIMULATIONS = 1_000_000
- RATE_UP = 0.007 # 0.7%
- RATE_OFF = 0.00022115 # 0.022115%
- STEP_SIZE = 1
- GRAPH_LABEL_STEP_SIZE = 50
- EXTRA_GRAPH_LABEL_STEP = [70, 130, 150, 170, 270, 330, 350, 370]
- NEW_SYSTEM_EXTRA_10_PULLS = [70, 130, 150, 170, 270, 330, 350, 370]
- # ============================================================
- # Gacha pull
- # ============================================================
- def pull(target):
- """
- Pull once.
- The currently targeted character has RATE_UP.
- The other character has RATE_OFF.
- Returns:
- "a"
- "b"
- None
- """
- if target == "a":
- rate_a = RATE_UP
- rate_b = RATE_OFF
- else:
- rate_a = RATE_OFF
- rate_b = RATE_UP
- roll = random.random()
- if roll < rate_a:
- return "a"
- if roll < rate_a + rate_b:
- return "b"
- return None
- # ============================================================
- # New rule pity
- # ============================================================
- def apply_new_rule_pity(pity_count):
- """
- Apply the new rule's pity system.
- 100th pull:
- 50% chance to get the currently targeted character.
- 200th pull:
- Guaranteed currently targeted character.
- Returns:
- True if pity gave the target.
- """
- if pity_count == 100:
- return random.random() < 0.5
- if pity_count == 200:
- return True
- return None
- # ============================================================
- # Group 1 - Unlimited pulls old rule
- # ============================================================
- def simulate_group_unlimited_old_rule():
- """
- Unlimited pulls until both A and B are obtained.
- Rate-up starts on A.
- Once A is obtained, rate-up switches to B.
- Returns:
- Number of pulls required.
- """
- have_a = False
- have_b = False
- target = "a"
- pull_count = 0
- while not (have_a and have_b):
- pull_count += 1
- result = pull(target)
- if result == "a":
- have_a = True
- # Switch rate-up from A to B
- if target == "a":
- target = "b"
- elif result == "b":
- have_b = True
- # This normally means B appeared before A.
- # Continue targeting A.
- if target == "b":
- target = "a"
- # ----------------------------------------------------
- # Old rule: choose missing character at 200
- # ----------------------------------------------------
- if pull_count % 200 == 0:
- if not have_a:
- have_a = True
- if target == "a":
- target = "b"
- elif not have_b:
- have_b = True
- return pull_count
- # ============================================================
- # Group 1 - Unlimited pulls new rule
- # ============================================================
- def simulate_group_unlimited_new_rule():
- """
- Unlimited pulls until both A and B are obtained.
- Rate-up starts on A.
- Once A is obtained, rate-up switches to B.
- """
- have_a = False
- have_b = False
- target = "a"
- pull_count = 0
- paid_pull_count = 0
- pity_count = 0
- free_pull_count = 0
- while not (have_a and have_b):
- if free_pull_count == 0:
- paid_pull_count += 1
- else:
- free_pull_count -= 1
- pull_count += 1
- pity_count += 1
- is_pity = apply_new_rule_pity(pity_count)
- if is_pity:
- if target == "a":
- have_a = True
- pity_count = 0
- target = "b"
- elif target == "b":
- have_b = True
- elif is_pity == False:
- continue
- if have_a and have_b:
- break
- # extra pull from milestone
- if pull_count in NEW_SYSTEM_EXTRA_10_PULLS:
- free_pull_count += 10
- result = pull(target)
- if result == "a":
- have_a = True
- # Switch rate-up to B
- if target == "a":
- target = "b"
- pity_count = 0
- elif result == "b":
- have_b = True
- return paid_pull_count
- def get_pull_range(pulls, range_size=STEP_SIZE):
- start = ((pulls - 1) // range_size) * range_size + 1
- end = start + range_size - 1
- return f"{start}-{end}"
- # ============================================================
- # Run simulation
- # ============================================================
- def simulate(simulations=SIMULATIONS):
- results = {
- "old_rule": Counter(),
- "new_rule": Counter(),
- }
- for i in range(simulations):
- if i % 10000 == 0:
- print(i)
- pulls = simulate_group_unlimited_old_rule()
- results["old_rule"][get_pull_range(pulls)] += 1
- pulls = simulate_group_unlimited_new_rule()
- results["new_rule"][get_pull_range(pulls)] += 1
- return results
- # ============================================================
- # Write result
- # ============================================================
- def write_results(results, filename="gacha_results.txt"):
- with open(filename, "w", encoding="utf-8") as file:
- file.write("GACHA SIMULATION RESULTS\n")
- file.write("=" * 80 + "\n\n")
- file.write(f"Simulations: {SIMULATIONS:,}\n")
- file.write(f"Rate-up: {RATE_UP * 100:.5f}%\n")
- file.write(f"Off-rate: {RATE_OFF * 100:.5f}%\n\n")
- for name, counter in results.items():
- file.write("-" * 80 + "\n")
- file.write(f"{name}\n")
- file.write("-" * 80 + "\n")
- total = sum(counter.values())
- file.write(f"{'Pull Range':>15} {'Count':>15} {'Probability':>15}\n")
- for pull_range, count in sorted(
- counter.items(),
- key=lambda x: (
- float("inf") if x[0] == "FAILED" else int(x[0].split("-")[0])
- ),
- ):
- probability = count / total
- file.write(
- f"{pull_range:>15} {count:>15,} {probability * 100:>14.5f}%\n"
- )
- file.write("\n")
- def plot_cumulative(results, filename="gacha_cumulative.png"):
- plt.figure(figsize=(12, 7))
- for name, counter in results.items():
- # Ignore FAILED
- data = {key: value for key, value in counter.items() if key != "FAILED"}
- # Sort by pull range
- data = dict(sorted(data.items(), key=lambda x: int(x[0].split("-")[0])))
- ranges = list(data.keys())
- counts = list(data.values())
- total = sum(counter.values())
- # Calculate cumulative probability
- cumulative = []
- current = 0
- for count in counts:
- current += count
- cumulative.append(current / total * 100)
- # Use the end of each range for X
- x = [int(pull_range.split("-")[1]) for pull_range in ranges]
- plt.plot(x, cumulative, label=name.replace("_", " ").title())
- for i, (x_value, y_value) in enumerate(zip(x, cumulative)):
- if (i + 1) % GRAPH_LABEL_STEP_SIZE == 0 or (
- i + 1
- ) in EXTRA_GRAPH_LABEL_STEP:
- plt.plot(x[i], cumulative[i], marker="o", linestyle="none")
- plt.annotate(
- f"{y_value:.2f}%",
- (x_value, y_value),
- xytext=(0, 8),
- textcoords="offset points",
- ha="center",
- fontsize=8,
- )
- plt.xlabel("Number of paid pulls")
- plt.ylabel("Cumulative probability (%)")
- plt.title("Cumulative Probability of Getting Both Characters")
- plt.grid(axis="both", alpha=0.3)
- plt.legend()
- plt.tight_layout()
- plt.savefig(filename, dpi=150)
- plt.close()
- # ============================================================
- # Main
- # ============================================================
- if __name__ == "__main__":
- results = simulate()
- write_results(results)
- plot_cumulative(results)
- print("Simulation completed.")
- print("Results written to gacha_results.txt")
Advertisement
Add Comment
Please, Sign In to add comment