Okay, this is going to be fun! We'll create a text-based Pokémon-style battle game in Python. It will have the core elements: choosing Pokémon, selecting moves, turn-based combat, HP, and a bit of Game Boy flavor with text art.
Here's what we'll build:
- Pokémon Data: Define a few Pokémon with stats (HP, Type) and moves (Name, Power, Accuracy, Type, PP - though we might simplify PP for now).
- Battle Screen: A text-based representation of the battle.
- Turn Logic: Player chooses a move, then the AI opponent does.
- Move Execution: Calculate damage, consider accuracy, and eventually type effectiveness.
- Win/Loss Condition: When a Pokémon's HP reaches 0.
- Fun Factor:
- Descriptive battle messages.
- ASCII art for Pokémon (simple).
- Critical hits!
- Type effectiveness.
- Maybe some simple "sound" effects (like
\a bell character).
Let's start coding!
import random
import time
import os
# --- Helper Functions ---
def clear_screen():
"""Clears the terminal screen."""
os.system('cls' if os.name == 'nt' else 'clear')
def type_print(text, delay=0.03):
"""Prints text character by character for a retro feel."""
for char in text:
print(char, end='', flush=True)
time.sleep(delay)
print() # Newline at the end
def display_hp_bar(current_hp, max_hp, bar_length=20):
"""Displays a simple text-based HP bar."""
filled_length = int(bar_length * current_hp / max_hp)
bar = '█' * filled_length + '-' * (bar_length - filled_length)
return f"HP: [{bar}] {current_hp}/{max_hp}"
# --- Pokémon and Move Data ---
# Type effectiveness chart: attacking_type -> defending_type -> multiplier
TYPE_CHART = {
"Normal": {"Rock": 0.5, "Ghost": 0, "Steel": 0.5},
"Fire": {"Fire": 0.5, "Water": 0.5, "Grass": 2, "Ice": 2, "Bug": 2, "Rock": 0.5, "Dragon": 0.5, "Steel": 2},
"Water": {"Fire": 2, "Water": 0.5, "Grass": 0.5, "Ground": 2, "Rock": 2, "Dragon": 0.5},
"Electric": {"Water": 2, "Electric": 0.5, "Grass": 0.5, "Ground": 0, "Flying": 2, "Dragon": 0.5},
"Grass": {"Fire": 0.5, "Water": 2, "Grass": 0.5, "Poison": 0.5, "Ground": 2, "Flying": 0.5, "Bug": 0.5, "Rock": 2, "Dragon": 0.5, "Steel": 0.5},
"Ice": {"Fire": 0.5, "Water": 0.5, "Grass": 2, "Ice": 0.5, "Ground": 2, "Flying": 2, "Dragon": 2, "Steel": 0.5},
"Fighting": {"Normal": 2, "Ice": 2, "Poison": 0.5, "Flying": 0.5, "Psychic": 0.5, "Bug": 0.5, "Rock": 2, "Ghost": 0, "Dark": 2, "Steel": 2, "Fairy": 0.5},
"Poison": {"Grass": 2, "Poison": 0.5, "Ground": 0.5, "Rock": 0.5, "Ghost": 0.5, "Steel": 0, "Fairy": 2},
"Ground": {"Fire": 2, "Electric": 2, "Grass": 0.5, "Poison": 2, "Flying": 0, "Bug": 0.5, "Rock": 2, "Steel": 2},
"Flying": {"Electric": 0.5, "Grass": 2, "Fighting": 2, "Bug": 2, "Rock": 0.5, "Steel": 0.5},
"Psychic": {"Fighting": 2, "Poison": 2, "Psychic": 0.5, "Dark": 0, "Steel": 0.5},
"Bug": {"Fire": 0.5, "Grass": 2, "Fighting": 0.5, "Poison": 0.5, "Flying": 0.5, "Psychic": 2, "Ghost": 0.5, "Dark": 2, "Steel": 0.5, "Fairy": 0.5},
"Rock": {"Fire": 2, "Ice": 2, "Fighting": 0.5, "Ground": 0.5, "Flying": 2, "Bug": 2, "Steel": 0.5},
"Ghost": {"Normal": 0, "Psychic": 2, "Ghost": 2, "Dark": 0.5},
"Dragon": {"Dragon": 2, "Steel": 0.5, "Fairy": 0},
"Dark": {"Fighting": 0.5, "Psychic": 2, "Ghost": 2, "Dark": 0.5, "Fairy": 0.5},
"Steel": {"Fire": 0.5, "Water": 0.5, "Electric": 0.5, "Ice": 2, "Rock": 2, "Steel": 0.5, "Fairy": 2},
"Fairy": {"Fire": 0.5, "Fighting": 2, "Poison": 0.5, "Dragon": 2, "Dark": 2, "Steel": 0.5}
}
def get_effectiveness(move_type, opponent_pokemon_type):
"""Calculates type effectiveness multiplier."""
if move_type in TYPE_CHART and opponent_pokemon_type in TYPE_CHART[move_type]:
return TYPE_CHART[move_type][opponent_pokemon_type]
return 1 # Default effectiveness
POKEMON_DATA = {
"Pikachu": {
"hp": 120,
"type": "Electric",
"moves": [
{"name": "Thunder Shock", "power": 40, "accuracy": 100, "type": "Electric"},
{"name": "Quick Attack", "power": 40, "accuracy": 100, "type": "Normal"},
{"name": "Iron Tail", "power": 100, "accuracy": 75, "type": "Steel"},
{"name": "Volt Tackle", "power": 120, "accuracy": 100, "type": "Electric", "recoil_pct": 0.25} # Recoil damage
],
"art": """
_.--""--._
.' `.
/ O O \\
| \ ^^ / |
\ `----' /
`. _______ .'
//_____\\\\
(( ____ ))
`------'
"""
},
"Charizard": {
"hp": 160,
"type": "Fire", # Secondary type Flying ignored for simplicity here
"moves": [
{"name": "Flamethrower", "power": 90, "accuracy": 100, "type": "Fire"},
{"name": "Slash", "power": 70, "accuracy": 100, "type": "Normal"},
{"name": "Dragon Claw", "power": 80, "accuracy": 100, "type": "Dragon"},
{"name": "Fire Blast", "power": 110, "accuracy": 85, "type": "Fire"}
],
"art": """
.--''--.
/ \\
| O O |
| .__. |
\ `----' /
.' // \\\\ `.
/ (( )) \\
| `----' |
\ /
`------------'
"""
},
"Blastoise": {
"hp": 170,
"type": "Water",
"moves": [
{"name": "Water Gun", "power": 40, "accuracy": 100, "type": "Water"},
{"name": "Hydro Pump", "power": 110, "accuracy": 80, "type": "Water"},
{"name": "Bite", "power": 60, "accuracy": 100, "type": "Dark"},
{"name": "Skull Bash", "power": 130, "accuracy": 100, "type": "Normal", "charge_turn": True} # Charge move
],
"art": """
.--""--.
/ \\
| .--. |
| ( OO ) |
\ `----' /
.' ______ `.
/ | | \\
| `.____.' |
\ /
`.__________.'
"""
},
"Venusaur": {
"hp": 165,
"type": "Grass", # Secondary type Poison ignored for simplicity
"moves": [
{"name": "Vine Whip", "power": 45, "accuracy": 100, "type": "Grass"},
{"name": "Razor Leaf", "power": 55, "accuracy": 95, "type": "Grass", "crit_chance_bonus": 0.125}, # High crit
{"name": "Sludge Bomb", "power": 90, "accuracy": 100, "type": "Poison"},
{"name": "Solar Beam", "power": 120, "accuracy": 100, "type": "Grass", "charge_turn": True}
],
"art": """
.--""--.
/ _ _ \\
| / \/ \ |
| ( O O ) |
\ `----' /
.' `""` `.
/ /\____/\ \\
| / \ |
\ |________| /
`------------'
"""
}
}
# --- Battle Class ---
class Battle:
def __init__(self, player_pokemon_name, opponent_pokemon_name):
self.player_pokemon = self._prepare_pokemon(player_pokemon_name, is_player=True)
self.opponent_pokemon = self._prepare_pokemon(opponent_pokemon_name, is_player=False)
self.player_charging_move = None
self.opponent_charging_move = None
self.turn_count = 0
def _prepare_pokemon(self, name, is_player=False):
data = POKEMON_DATA[name].copy() # Use a copy to modify HP etc.
data["name"] = name
data["max_hp"] = data["hp"]
data["is_player"] = is_player
data["art"] = data.get("art", "No art available :(") # Add default art
return data
def display_battle_state(self):
clear_screen()
# Opponent display (top)
type_print(f"Opponent's {self.opponent_pokemon['name']}:", 0.01)
print(self.opponent_pokemon['art'])
type_print(display_hp_bar(self.opponent_pokemon['hp'], self.opponent_pokemon['max_hp']), 0.01)
print("\n" + "="*40 + "\n")
# Player display (bottom)
type_print(f"Your {self.player_pokemon['name']}:", 0.01)
print(self.player_pokemon['art'])
type_print(display_hp_bar(self.player_pokemon['hp'], self.player_pokemon['max_hp']), 0.01)
print("-" * 40)
def player_choose_move(self):
type_print("Choose your move:")
for i, move in enumerate(self.player_pokemon["moves"]):
type_print(f"{i+1}. {move['name']} ({move['type']}, Pow: {move['power']}, Acc: {move['accuracy']})")
while True:
try:
choice = int(input("> ")) - 1
if 0 <= choice < len(self.player_pokemon["moves"]):
return self.player_pokemon["moves"][choice]
else:
type_print("Invalid choice. Try again.")
except ValueError:
type_print("Please enter a number.")
def opponent_choose_move(self):
# Simple AI: Choose a random move
# Could be made smarter (e.g., prioritize super-effective, avoid 0-power)
available_moves = [m for m in self.opponent_pokemon["moves"]]
if not available_moves: # Should not happen if Pokemon have moves
return None
return random.choice(available_moves)
def execute_turn(self, attacker, defender, move):
if not move: # Should not happen
type_print(f"{attacker['name']} couldn't move!", 0.02)
return
# Handle charge moves
if attacker.get("is_charging"): # If attacker was charging, this is the attack turn
charge_move_name = attacker.pop("is_charging") # Get the move name and remove charging status
type_print(f"{attacker['name']} unleashed {charge_move_name}!", 0.02)
# The 'move' passed to execute_turn is the one just selected,
# but we need the stats of the original charge move.
# Find the original charge move from the attacker's move list.
original_charge_move = next((m for m in attacker["moves"] if m["name"] == charge_move_name), None)
if original_charge_move:
move = original_charge_move # Use the charged move's stats
else: # Failsafe, should not happen
type_print(f"Error: Could not find charge move {charge_move_name}", 0.02)
return
elif move.get("charge_turn"):
type_print(f"{attacker['name']} is charging up {move['name']}!", 0.02)
attacker["is_charging"] = move["name"] # Store the name of the move being charged
# Store the actual move object if needed by AI or other logic for next turn
if attacker['is_player']:
self.player_charging_move = move
else:
self.opponent_charging_move = move
return # Skip attack this turn
type_print(f"{attacker['name']} used {move['name']}!", 0.02)
time.sleep(0.5)
# Accuracy check
if random.randint(1, 100) > move["accuracy"]:
type_print("But it missed!", 0.02)
time.sleep(1)
return
# Calculate base damage
# Pokemon damage formula is complex, we'll use a simplified version
# Damage = ( ( (2 * Level / 5 + 2) * Power * A / D ) / 50 + 2 ) * Modifier
# Simplified: Power * (Attacker's effective attack / Defender's effective defense) * Modifiers
# Even simpler for now: base power adjusted by types and critical hit
base_damage = move["power"]
# Critical Hit (base 6.25% chance, can be modified by moves)
crit_chance = 0.0625 + move.get("crit_chance_bonus", 0)
is_critical = random.random() < crit_chance
if is_critical:
base_damage *= 1.5 # Gen VI+ critical hit damage
type_print("A critical hit!", 0.02)
print("\a", end="") # Bell sound for fun
time.sleep(0.5)
# Type effectiveness
effectiveness = get_effectiveness(move["type"], defender["type"])
if effectiveness > 1:
type_print("It's super effective!", 0.02)
time.sleep(0.5)
elif effectiveness < 1 and effectiveness > 0:
type_print("It's not very effective...", 0.02)
time.sleep(0.5)
elif effectiveness == 0:
type_print(f"It doesn't affect {defender['name']}...", 0.02)
time.sleep(1)
defender["hp"] = max(0, defender["hp"]) # Ensure HP doesn't go negative
return
damage = int(base_damage * effectiveness * random.uniform(0.85, 1.0)) # Add some randomness
defender["hp"] -= damage
defender["hp"] = max(0, defender["hp"]) # Ensure HP doesn't go negative
type_print(f"It dealt {damage} damage.", 0.02)
# Recoil damage
if move.get("recoil_pct"):
recoil_damage = int(damage * move["recoil_pct"]) # Recoil based on damage dealt
if recoil_damage > 0 :
attacker["hp"] -= recoil_damage
attacker["hp"] = max(0, attacker["hp"])
type_print(f"{attacker['name']} took {recoil_damage} in recoil damage!", 0.02)
time.sleep(1)
def check_fainted(self, pokemon):
return pokemon["hp"] <= 0
def run(self):
type_print("A wild battle begins!", 0.05)
time.sleep(1)
current_turn_player = True # Player goes first (can be randomized)
while not self.check_fainted(self.player_pokemon) and not self.check_fainted(self.opponent_pokemon):
self.turn_count += 1
self.display_battle_state()
# --- Player's Turn ---
if current_turn_player:
# If player was charging, execute the charged move
if self.player_pokemon.get("is_charging"):
self.execute_turn(self.player_pokemon, self.opponent_pokemon, self.player_charging_move)
self.player_charging_move = None # Reset after use
else: # Normal turn, player chooses a move
chosen_move = self.player_choose_move()
self.execute_turn(self.player_pokemon, self.opponent_pokemon, chosen_move)
if self.check_fainted(self.opponent_pokemon):
self.display_battle_state() # Show final HP
type_print(f"\nOpponent's {self.opponent_pokemon['name']} fainted!", 0.05)
type_print(f"You defeated {self.opponent_pokemon['name']}!", 0.05)
print("\a") # Victory sound
break
# --- Opponent's Turn ---
else:
type_print(f"\n--- Opponent's {self.opponent_pokemon['name']}'s turn ---", 0.02)
time.sleep(1)
# If opponent was charging, execute the charged move
if self.opponent_pokemon.get("is_charging"):
self.execute_turn(self.opponent_pokemon, self.player_pokemon, self.opponent_charging_move)
self.opponent_charging_move = None # Reset after use
else: # Normal turn, opponent chooses a move
chosen_move = self.opponent_choose_move()
self.execute_turn(self.opponent_pokemon, self.player_pokemon, chosen_move)
if self.check_fainted(self.player_pokemon):
self.display_battle_state() # Show final HP
type_print(f"\nYour {self.player_pokemon['name']} fainted!", 0.05)
type_print("You were defeated...", 0.05)
break
# Check for faints again after recoil (if any)
if self.check_fainted(self.player_pokemon) and not self.check_fainted(self.opponent_pokemon):
self.display_battle_state() # Show final HP
type_print(f"\nYour {self.player_pokemon['name']} fainted from recoil!", 0.05)
type_print("You were defeated...", 0.05)
break
if self.check_fainted(self.opponent_pokemon) and not self.check_fainted(self.player_pokemon):
self.display_battle_state() # Show final HP
type_print(f"\nOpponent's {self.opponent_pokemon['name']} fainted from recoil!", 0.05)
type_print(f"You defeated {self.opponent_pokemon['name']}!", 0.05)
print("\a") # Victory sound
break
# Switch turns
current_turn_player = not current_turn_player
if current_turn_player: # Before player's next actual turn, add a small pause
print("\n" + "-"*20 + " Your Turn " + "-"*20)
time.sleep(1)
type_print(f"\nBattle ended in {self.turn_count} turns.", 0.05)
# --- Game Start ---
if __name__ == "__main__":
clear_screen()
type_print("Welcome to Pokémon PyBattle!", 0.05)
time.sleep(1)
available_pokemon = list(POKEMON_DATA.keys())
type_print("\nChoose your Pokémon:", 0.02)
for i, name in enumerate(available_pokemon):
type_print(f"{i+1}. {name}", 0.02)
player_choice_idx = -1
while True:
try:
player_choice_idx = int(input("> ")) - 1
if 0 <= player_choice_idx < len(available_pokemon):
break
else:
type_print("Invalid choice. Try again.", 0.02)
except ValueError:
type_print("Please enter a number.", 0.02)
player_pokemon_name = available_pokemon[player_choice_idx]
# Opponent chooses randomly (and not the same as player if possible)
opponent_options = [p for p in available_pokemon if p != player_pokemon_name]
if not opponent_options: # If only one pokemon is defined or player picked the only other one
opponent_options = available_pokemon
opponent_pokemon_name = random.choice(opponent_options)
type_print(f"\nYou chose {player_pokemon_name}!", 0.02)
type_print(f"Your opponent chose {opponent_pokemon_name}!", 0.02)
time.sleep(1.5)
battle = Battle(player_pokemon_name, opponent_pokemon_name)
battle.run()
type_print("\nThanks for playing Pokémon PyBattle!", 0.05)
How to Make it "Really Fun" (and what's included):
-
Retro Feel:
type_print() function: Simulates text appearing character by character, like old RPGs.
clear_screen(): Keeps the display clean between turns.
- Simple ASCII art for Pokémon: Gives a visual cue.
-
Core Pokémon Mechanics:
- HP Bars: Visual representation of health.
- Moves with Power & Accuracy: Basic combat stats.
- Turn-Based Combat: Player and AI take turns.
- Type Effectiveness: Implemented with a
TYPE_CHART. This adds a huge strategic layer. Messages like "It's super effective!" are key.
- Critical Hits: Adds an element of luck and excitement. A small bell sound (
\a) is attempted.
- Recoil Moves: (e.g., Volt Tackle) Adds risk/reward.
- Charge Moves: (e.g., Solar Beam, Skull Bash) Adds a tactical delay.
-
User Experience:
- Clear prompts for choosing Pokémon and moves.
- Descriptive messages for actions, misses, effectiveness, and fainting.
- A little bit of "flair" text.
-
AI (Simple but Functional):
- The opponent chooses moves randomly. This is a starting point; it could be made smarter (e.g., prefer super-effective moves, avoid moves that won't work).
To Run This Game:
- Save the code as a Python file (e.g.,
pybattle.py).
- Open a terminal or command prompt.
- Navigate to the directory where you saved the file.
- Run
python pybattle.py.
Further "Fun" Enhancements (If you want to expand it):
- More Pokémon and Moves: The more variety, the better.
- Status Effects: Poison, Burn, Paralysis, Sleep, Freeze. This adds a lot of depth.
- Stat-Changing Moves: Growl (lower attack), Swords Dance (raise attack), etc.
- PP (Power Points): Limit the number of times a move can be used.
- Items: Potions for healing.
- Switching Pokémon: Allow players to have a team and switch mid-battle.
- Smarter AI:
- Prioritize super-effective moves.
- Avoid moves that have no effect (e.g., Ground vs. Flying).
- Use status moves strategically.
- Switch out if at a disadvantage.
- Music/Sound Effects: Use libraries like
playsound or pygame.mixer for actual audio.
- Simple GUI: Instead of pure text, use
tkinter or PyQt for a basic graphical interface. pygame would be a bigger step but much more visually appealing.
- Saving/Loading Progress: For longer play.
- EVs/IVs/Natures: For true Pokémon stat nerds (much more complex).
- More elaborate ASCII art.
This version provides a solid and "fun" foundation for a Game Boy-style Pokémon battle! Enjoy!