小学生用のポケモン計算コード(日記)


```Python
# hp_update.py
# プログラム名: hp_update.py
# Simple HP update and sanity check / シンプルなHP更新と検算

def update_hp(hp_before, damage):
    """
    Update HP after taking damage.
    HP更新：攻撃後の残りHPを計算する
    
    Args:
        hp_before (int): HP before attack / 攻撃前のHP
        damage (int): Damage dealt / 与えたダメージ
    
    Returns:
        int: HP after attack / 攻撃後の残りHP
    """
    hp_after = hp_before - damage
    return max(hp_after, 0)

if __name__ == "__main__":
    # --- Example parameters / 例としての値 ---
    hp_before = 100   # 攻撃前のHP / HP before attack
    damage    = 30    # 与えたダメージ / Damage dealt

    # HPを更新 / Update HP
    hp_after = update_hp(hp_before, damage)

    # 結果を表示 / Print results
    print(f"HP Before: {hp_before}")
    print(f"Damage:    {damage}")
    print(f"HP After:  {hp_after}")

    # --- Sanity check / 検算 ---
    # HP_after は hp_before - damage と一致するはず
    assert hp_after == max(hp_before - damage, 0), "HP update calculation error!"
    print("Sanity check passed. / 検算OK")


```

```Python

# damage_multiplier.py
# プログラム名: damage_multiplier.py
# Apply multipliers (STAB, type effectiveness, critical, randomness) to base damage
# 素ダメージに同種技ボーナス、タイプ相性、急所、乱数を掛け合わせて最終ダメージを計算

import math

def calculate_final_damage(base, stab, type_eff, crit, rand):
    """
    Calculate final damage by multiplying all factors.
    各種倍率を掛け合わせて最終ダメージを計算する
    
    Args:
        base (int): 素ダメージ / Base damage
        stab (float): 同種技ボーナス（1.0 or 1.5）/ Same-Type Attack Bonus
        type_eff (float): タイプ相性（0.0, 0.5, 1.0, 2.0）/ Type effectiveness
        crit (float): 急所倍率（1.0, 1.5 or 2.0）/ Critical hit multiplier
        rand (float): 乱数（0.85～1.00 の一様値）/ Random factor
    
    Returns:
        int: 最終ダメージ（切り捨て）/ Final damage (floored)
    """
    damage = math.floor(base * stab * type_eff * crit * rand)
    return damage

if __name__ == "__main__":
    # --- Example parameters / 例としての値 ---
    base      = 100    # 素ダメージ / Base damage
    stab      = 1.5    # 同種技ボーナス / STAB
    type_eff  = 2.0    # 効果抜群 / Super effective
    crit      = 1.5    # 急所 / Critical hit
    rand      = 0.95   # 固定乱数 / Fixed random factor

    # --- Calculate damage / ダメージ計算 ---
    damage = calculate_final_damage(base, stab, type_eff, crit, rand)

    # --- Print results / 結果を表示 ---
    print(f"Base Damage: {base}")
    print(f"STAB:        {stab}")
    print(f"TypeEff:     {type_eff}")
    print(f"Crit:        {crit}")
    print(f"Rand:        {rand}")
    print(f"Final Damage: {damage}")

    # --- Sanity check / 検算 ---
    assert damage >= 0, "Damage must be non-negative! / ダメージは非負である必要があります"
    print("Sanity check passed. / 検算OK")

```

```Python
# first_move_probability.py
# プログラム名: first_move_probability.py
# Calculate and print first-move probabilities for equal Speed and with Quick Claw
# スピード同速時およびせんせいのツメ使用時の先手確率を計算して表示する

def prob_first_equal_speed():
    """
    Probability of moving first when speeds are equal.
    スピードが同速のときに先手を取れる確率を返す
    """
    equal_prob = 1 / 2  # 数学的に 50% / Mathematically 50%
    return equal_prob

def prob_first_with_quick_claw(qc_rate=0.2):
    """
    Probability of moving first when holding Quick Claw.
    せんせいのツメ使用時の先手確率を返す
    
    発動時は100%先手、非発動時は同速タイブレーク（50%） / If activated: 100% first, else 50%
    """
    base_prob = prob_first_equal_speed()
    qc_prob = qc_rate + (1 - qc_rate) * base_prob
    return qc_prob

if __name__ == "__main__":
    # --- パラメータ / Parameters ---
    qc_rate = 0.2  # せんせいのツメ発動率（デフォルト20%）/ Quick Claw activation rate

    # --- 計算 / Calculations ---
    equal_prob = prob_first_equal_speed()
    qc_prob    = prob_first_with_quick_claw(qc_rate)

    # --- 結果出力 / Print results ---
    print(f"Equal-Speed First Move Probability: {equal_prob:.2%}")    # 英語ラベル
    print(f"スピード同速時の先手確率:             {equal_prob:.2%}")    # 日本語ラベル
    print(f"Quick Claw First Move Probability:   {qc_prob:.2%}")     # 英語ラベル
    print(f"せんせいのツメ使用時の先手確率:       {qc_prob:.2%}")     # 日本語ラベル

    # --- 検算 / Sanity check ---
    assert 0.0 <= equal_prob <= 1.0, "Equal speed probability out of range!"
    assert 0.0 <= qc_prob    <= 1.0, "Quick Claw probability out of range!"
    print("Sanity check passed. / 検算OK")

```
```Python
# -*- coding: utf-8 -*-
# Program Name: pokemon_stat_ratios.py
# Analyze Pokémon stat ratios (e.g., Attack / Defense)

import pandas as pd
import matplotlib.pyplot as plt

# --- Sample Pokémon Data ---
data = {
    'Name': ['Charmander', 'Charizard', 'Geodude', 'Snorlax', 'Alakazam'],
    'HP': [39, 78, 40, 160, 55],
    'Attack': [52, 84, 80, 110, 50],
    'Defense': [43, 78, 100, 65, 45],
    'Sp_Atk': [60, 109, 30, 65, 135],
    'Sp_Def': [50, 85, 30, 110, 95],
    'Speed': [65, 100, 20, 30, 120]
}

df = pd.DataFrame(data)

# --- Calculate Stat Ratios ---
df['Atk_Def_Ratio'] = df['Attack'] / df['Defense']            # Attack / Defense
df['SpAtk_SpDef_Ratio'] = df['Sp_Atk'] / df['Sp_Def']         # Sp. Atk / Sp. Def
df['Off_Def_Balance'] = (df['Attack'] + df['Sp_Atk']) / (df['Defense'] + df['Sp_Def'])  # Offensive / Defensive balance

# --- Display Results ---
print(df[['Name', 'Atk_Def_Ratio', 'SpAtk_SpDef_Ratio', 'Off_Def_Balance']])

# --- Plotting Ratios ---
plt.figure(figsize=(10, 6))
plt.bar(df['Name'], df['Atk_Def_Ratio'], label='Attack / Defense', alpha=0.7)
plt.bar(df['Name'], df['SpAtk_SpDef_Ratio'], label='Sp. Atk / Sp. Def', alpha=0.7)
plt.title("Pokémon Stat Ratios")
plt.xlabel("Pokémon")
plt.ylabel("Ratio")
plt.legend()
plt.xticks(rotation=30)
plt.tight_layout()
plt.show()

```

```Python
# -*- coding: utf-8 -*-
# Program Name: pokemon_math_trainer_variables.py
# ポケモン世界で学ぶ比・割合・速さ・面積！ すべての数値と結果を変数で管理します

# --- ① Ratio & Percentage ---

pichu_count_base = 2  # ピチュー基準数
pichu_count_target = 5
pichu_ratio_percent = (pichu_count_target / pichu_count_base) * 100

pikachu_group_1 = 4
pikachu_group_2 = 8
pikachu_percent = (pikachu_group_1 / pikachu_group_2) * 100

snorlax_weight_total = 50  # カビゴンの体重
snorlax_weight_40p = snorlax_weight_total * 0.4

pokeball_price_full = 200  # モンスターボールの通常価格
pokeball_discount_price = pokeball_price_full * 0.3

route_distance_short = 3
route_distance_total = 6
route_fraction = (route_distance_short / route_distance_total) * 2

voltorb_area_base = 60  # ビリリダマの占拠面積
voltorb_area_150p = voltorb_area_base * 1.5

print("① 比と割合（Ratio & Percentage）")
print("Q1: ピチュー2匹を基準に5匹は", pichu_ratio_percent, "%")
print("Q2: ピカチュウ4匹は8匹の", pikachu_percent, "%")
print("Q3: カビゴンの40%体重は", snorlax_weight_40p, "kg")
print("Q4: モンスターボール30%価格は", pokeball_discount_price, "円")
print("Q5: 3kmは6kmの", int(route_fraction), "/ 2")
print("Q6: ビリリダマの面積60cm²の150%は", voltorb_area_150p, "cm²")

# --- ② Type Count ---
pokemon_class_total = 32
water_type_ratio = 0.25
non_water_pokemon = pokemon_class_total * (1 - water_type_ratio)

print("\n② タイプ分布")
print("Q7: 水タイプ以外のポケモン数 =", int(non_water_pokemon), "匹")

# --- ③ Area Question ---
nazonokusa_field_total = 50
potato_patch_area = 35
other_patch_area = nazonokusa_field_total - potato_patch_area

print("\n③ 畑の広さ")
print("Q8: ナゾノクサ畑でじゃがいも以外の面積 =", other_patch_area, "㎡")

# --- ④ Discount Reverse Calculation ---
pokeball_discount_paid = 560
discount_ratio = 0.3
pokeball_price_original = pokeball_discount_paid / discount_ratio

print("\n④ 割引されたどうぐ")
print("Q9: 定価のモンスターボールの値段 =", int(pokeball_price_original), "円")

# --- ⑤ Speed / Distance / Time ---
eevee_distance_m = 250
eevee_time_min = 5
eevee_speed_mpm = eevee_distance_m / eevee_time_min

rhyhorn_distance_km = 285
rhyhorn_time_hr = 3
rhyhorn_speed_kph = rhyhorn_distance_km / rhyhorn_time_hr

pidgey_speed_mpm = 80
pidgey_time_min = 45
pidgey_distance_m = pidgey_speed_mpm * pidgey_time_min

rapidash_speed_kph = 47
rapidash_time_hr = 2
rapidash_distance_km = rapidash_speed_kph * rapidash_time_hr

charmander_distance_m = 1300
charmander_speed_mpm = 65
charmander_time_min = charmander_distance_m / charmander_speed_mpm

charizard_distance_km = 24
charizard_speed_kph = 80
charizard_time_hr = charizard_distance_km / charizard_speed_kph

print("\n⑤ ポケモンの移動")
print("Q10: イーブイの速さ =", eevee_speed_mpm, "m/分")
print("Q11: サイホーンの速さ =", rhyhorn_speed_kph, "km/h")
print("Q12: ポッポの移動距離 =", pidgey_distance_m, "m")
print("Q13: ギャロップの移動距離 =", rapidash_distance_km, "km")
print("Q14: ヒトカゲの移動時間 =", int(charmander_time_min), "分")
print("Q15: リザードンの移動時間 =", round(charizard_time_hr, 2), "時間")

# --- ⑥ Speed Reverse ---
moltres_speed_kph = 840
moltres_time_min = 6
moltres_distance_km = moltres_speed_kph * (moltres_time_min / 60)

tauros_speed_kph = 72
tauros_speed_mpm = tauros_speed_kph * 1000 / 60

pidgeotto_distance_m = 2000
pidgeotto_speed_mpm = 75
pidgeotto_time_min = pidgeotto_distance_m / pidgeotto_speed_mpm

dragonite_distance_m = 9000
dragonite_speed_mpm = 720
dragonite_time_min = dragonite_distance_m / dragonite_speed_mpm

print("\n⑥ 速さの逆算")
print("Q16: ファイヤーの6分移動距離 =", round(moltres_distance_km, 1), "km")
print("Q17: ケンタロスの分速 =", int(tauros_speed_mpm), "m")
print("Q18: ピジョットの移動時間 =", round(pidgeotto_time_min, 1), "分")
print("Q19: カイリューの移動時間 =", round(dragonite_time_min, 1), "分")

# --- ⑦ Proportional Travel ---
gear_distance_km = 260
gear_time_hr = 4
gear_speed_kph = gear_distance_km / gear_time_hr
gear_new_time_hr = 6
gear_new_distance_km = gear_speed_kph * gear_new_time_hr

print("\n⑦ ギアルの比例移動")
print("Q20: 6時間で進む距離 =", int(gear_new_distance_km), "km")

```