Games...
- Pierce Dolan
- Feb 21
- 9 min read
I have created a text-based game, if anyone wants to try it out. Just go to an online Python compiler and paste the script into it. It should work pretty well.
import time
import random
# Function to simulate slow text output
def print_slow(str):
for letter in str:
print(letter, end='', flush=True)
time.sleep(0.02)
print()
# Character Class: Base for player and enemy
class Character:
def __init__(self, name, health, strength, defense, level, weapons=None, armor=None):
self.name = name
self.health = health
self.strength = strength
self.defense = defense
self.level = level
self.weapons = weapons if weapons else []
self.armor = armor if armor else []
self.experience = 0
def take_damage(self, damage):
self.health -= max(0, damage - self.defense)
return self.health
def is_alive(self):
return self.health > 0
def attack(self, target):
if self.weapons:
weapon = random.choice(self.weapons)
damage = weapon.attack()
else:
damage = random.randint(1, self.strength)
print(f"{self.name} attacks {target.name} with {weapon.name if self.weapons else 'fists'} for {damage} damage!")
target.take_damage(damage)
def level_up(self):
self.level += 1
self.strength += 2
self.health += 10
self.defense += 1
print(f"{self.name} leveled up! Now at level {self.level}. Strength, health, and defense increased!")
class Potion:
def __init__(self, name, effect, level):
self.name = name
self.effect = effect # Effect of the potion (e.g., health, attack, defense, etc.)
self.level = level # Level of the potion, determining the strength of the effect
def apply(self, character):
# Apply the potion effect to a character (Player, Enemy, etc.)
multiplier = 1 + (self.level * 0.1) # Level-based multiplier
if self.effect == "Health":
healing = 10 * multiplier # Increase health
character.health += healing
print(f"{character.name} drinks {self.name} and heals for {healing}!")
elif self.effect == "Attack":
increase = 2 * multiplier # Increase attack
character.strength += increase
print(f"{character.name} drinks {self.name} and gains {increase} attack power!")
elif self.effect == "Defense":
increase = 2 * multiplier # Increase defense
character.defense += increase
print(f"{character.name} drinks {self.name} and gains {increase} defense!")
elif self.effect == "Hunger":
decrease = 10 * multiplier # Reduce hunger
character.hunger = max(0, character.hunger - decrease) # Don't allow hunger to go below 0
print(f"{character.name} drinks {self.name} and reduces hunger by {decrease}!")
elif self.effect == "Thirst":
decrease = 10 * multiplier # Reduce thirst
character.thirst = max(0, character.thirst - decrease) # Don't allow thirst to go below 0
print(f"{character.name} drinks {self.name} and reduces thirst by {decrease}!")
def __str__(self):
return f"{self.name} (Level {self.level}): Effect = {self.effect}"
class Weapon:
def __init__(self, name, damage, durability):
self.name = name
self.damage = damage
self.durability = durability # The number of uses before the weapon breaks
def attack(self):
if self.durability > 0:
self.durability -= 1
return random.randint(self.damage - 2, self.damage + 2)
else:
print_slow(f"{self.name} is broken and can no longer be used!")
return 0
def is_broken(self):
return self.durability <= 0
class Armor:
def __init__(self, name, defense, protection):
self.name = name
self.defense = defense
self.protection = protection # The number of uses before the armor breaks
def take_damage(self, damage):
if self.protection > 0:
self.protection -= 1
return max(0, damage - self.defense)
else:
print_slow(f"{self.name} is broken and provides no protection!")
return damage
def is_broken(self):
return self.protection <= 0
class PermanentWeapon(Weapon):
def __init__(self, name="Fist", damage=7):
# Permanent weapon has infinite durability
super().__init__(name, damage, durability=float('inf'))
def attack(self):
# Always deal the damage, never runs out of durability
return self.damage
# Enemy Class
class Enemy(Character):
def __init__(self, name, health, strength, defense, level, weapons=None, armor=None):
super().__init__(name, health, strength, defense, level, weapons, armor)
class Player(Character):
def __init__(self, name):
super().__init__(name, health=300, strength=10, defense=5, level=1)
self.inventory = []
self.armor_equipped = None
self.hunger = 100 # Player hunger (100 = full, 0 = starving)
self.thirst = 100 # Player thirst (100 = hydrated, 0 = dehydrated)
self.special_ability_used_today = False
self.day_counter = 1
self.found_nuclear_area = False # Flag to indicate if the player found the launch area
self.experience_meter = 0 # New experience meter
self.money = 100000000 #Money in New Dataries
def use_potion(self, potion):
# Apply potion effect to the player
potion.apply(self)
def heal(self):
heal_amount = random.randint(5, 20)
self.health += heal_amount
print(f"{self.name} heals for {heal_amount} health!")
def add_to_inventory(self, item):
self.inventory.append(item)
print(f"{self.name} found {item.name} ({item.__class__.__name__}) and added it to their inventory!")
def use_item(self, item_name):
item = next((item for item in self.inventory if item.name.lower() == item_name.lower()), None)
if item:
if isinstance(item, Weapon):
print(f"{self.name} equipped {item.name} as their weapon!")
self.weapons.append(item)
elif isinstance(item, Armor):
print(f"{self.name} equipped {item.name} armor!")
self.armor_equipped = item
self.inventory.remove(item)
else:
print(f"{item_name} is not in your inventory.")
def select_item(self):
if not self.inventory:
print("Your inventory is empty.")
return
print("Your inventory contains:")
for idx, item in enumerate(self.inventory, start=1):
print(f"{idx}. {item.name} ({item.__class__.__name__})")
selection = input("Select an item by number to equip or use: ")
try:
idx = int(selection) - 1
item = self.inventory[idx]
self.use_item(item.name)
except (ValueError, IndexError):
print("Invalid selection.")
def daily_special_ability(self, enemy):
if not self.special_ability_used_today:
damage = enemy.health // 2
enemy.take_damage(damage)
self.special_ability_used_today = True
print(f"{self.name} used their special ability and dealt {damage} damage to {enemy.name}!")
else:
print(f"{self.name} has already used their special ability today.")
def rest(self):
self.hunger -= 10
self.thirst -= 10
self.health += 20
print(f"{self.name} rested. Health increased, but hunger and thirst increased as well.")
def update_day(self):
self.day_counter += 1
self.special_ability_used_today = False
self.hunger -= 20
self.thirst -= 20
print(f"Day {self.day_counter}: Hunger and Thirst are up, your special ability is reset.")
self.experience_meter += 10 # The player gains experience daily
# Check for broken items in inventory and remove them
self.check_inventory_for_broken_items()
def check_inventory_for_broken_items(self):
for item in self.inventory[:]:
if isinstance(item, Weapon) and item.is_broken():
print_slow(f"{item.name} is broken and has been removed from your inventory.")
self.inventory.remove(item) # Remove the broken weapon
elif isinstance(item, Armor) and item.is_broken():
print_slow(f"{item.name} is broken and has been removed from your inventory.")
self.inventory.remove(item) # Remove the broken armor
# If the equipped armor is broken, remove it from the equipped armor slot
if self.armor_equipped and self.armor_equipped.is_broken():
print_slow(f"{self.armor_equipped.name} is broken and has been removed from your equipment.")
self.armor_equipped = None
def check_status(self):
print(f"{self.name} - Health: {self.health}, Hunger: {self.hunger}, Thirst: {self.thirst}, Experience: {self.experience_meter}, New Dataries: {self.money}")
def is_starving(self):
return self.hunger <= 0
def is_dehydrated(self):
return self.thirst <= 0
# NPC Class (for trading and interaction)
class NPC:
def __init__(self, name):
self.name = name
# Tradeable items will vary by NPC type
if name == "Trader":
self.items_for_trade = [
Weapon("Laser Gun", 15, 10),
Armor("Tactical Vest", 7, 5),
Weapon("Grenade", 20, 1)
]
elif name == "Scientist":
self.items_for_trade = [
Armor("Hazmat Suit", 10, 15),
Weapon("Plasma Rifle", 25, 8),
Armor("Energy Shield", 5, 10)
]
elif name == "Merchant":
self.items_for_trade = [
Weapon("Crossbow", 18, 10),
Armor("Kevlar Jacket", 8, 6),
Weapon("Molotov Cocktail", 15, 2)
]
elif name == "Wasteland King":
self.items_for_trade = [
Weapon("Minigun", 30, 5),
Armor("Battle Armor", 12, 8),
Weapon("Nuclear Bomb", 100, 1)
]
elif name == "Veteran":
self.items_for_trade = [
Weapon("Rusty Sword", 12, 24),
Armor("Rusty Old Chainmail", 7, 20),
Weapon("1911 Pistol", 24, 70),
]
elif name == "Copilot":
self.items_for_trade = [
]
else:
self.items_for_trade = [
Weapon("Rusty Knife", 5, 10),
Armor("Old Jacket", 3, 3),
Weapon("Pistol", 10, 7)
]
def interact(self, player):
print_slow(f"{self.name} approaches and offers to trade.")
print_slow(f"{self.name}: 'I can trade items for your experience points.'")
print_slow("Available items for trade:")
for idx, item in enumerate(self.items_for_trade, start=1):
print(f"{idx}. {item.name} ({item.__class__.__name__}) - Cost: 50 XP")
print(f"{idx}. {item.name} ({item.__class__.__name__}) - Cost: 100 New Dataries")
choice = input("Choose an item to trade for by number or type 'exit' to leave: ")
if choice == 'exit':
print_slow(f"{self.name} nods and turns away.")
else:
print_slow("...")
try:
idx = int(choice) - 1
item = self.items_for_trade[idx]
if player.experience_meter >= 50:
player.use_item(item.name)
player.experience_meter -= 50
print_slow(f"{self.name} gave you {item.name}. You now have {player.experience_meter} XP left.")
elif player.money >= 100:
player.use_item(item.name)
player.money -=100
print_slow(f"{self.name} gave you {item.name}. You now have {player.money} New Dataries left.")
else:
print_slow("You don't have enough experience to trade.")
except (ValueError, IndexError):
print_slow("Invalid selection.")
# Nuclear Bomb Scenario
class NuclearBomb:
def __init__(self):
self.timer = 55 # The number of turns before detonation.
def countdown(self):
self.timer -= 1
if self.timer <= 0:
return True
return False
# Intro Function
def intro():
print_slow("Your goal: Travel across the wasteland, defeat enemies, level up, and stop the launch of a nuclear weapon.")
print_slow("You must find water, food, weapons, and armor while surviving the desert and other dangers.")
print()
# Battle Function
def battle(player, enemy):
print_slow(f"A wild {enemy.name} appears!")
while player.is_alive() and enemy.is_alive():
print(f"\n{player.name}: {player.health} HP")
print(f"{enemy.name}: {enemy.health} HP")
action = input("What do you want to do? (A = Attack / H = Heal / I = Inventory / S = Special Ability): ").lower()
if action == "a":
player.attack(enemy)
elif action == "h":
player.heal()
elif action == "i":
player.select_item()
elif action == "s":
player.daily_special_ability(enemy)
else:
print_slow("Invalid action! You just wait for the enemy to strike.")
if enemy.is_alive():
enemy.attack(player)
if player.is_alive():
print_slow(f"{player.name} defeated the {enemy.name}!")
player.experience_meter += 10
if player.experience_meter >= player.level * 20:
player.level_up()
print(f"{player.name} gained experience.")
else:
print_slow(f"{player.name} has been defeated. Game Over.")
exit()
# Room Exploration
def Spaceship(player):
print_slow("You are in an A-67 model spacecraft. It is the year 2719, and you are returning to your ancestral home, Earth. Your oldest known ancestor, Isaac R Dewey, fled Earth after nuclear war broke out. At roughly the year 2102, Dewey touched down on Planet B-17awEXT, an exoplanet at the edge of the galaxy. Your family has lived there with the other families that also fled Earth. You were born and raised there, taught to be a spacecraft pilot. Eventually, you built up the courage to become the first human to return to Earth after centuries of war had ravaged the planet. And now, your ship hovers over the beige and rusty-red planet that was once green and blue.")
npc = NPC("Copilot")
print_slow("Your copilot turns to you.")
print_slow("You should check the rest of the ship for items, he says.")
print_slow("You nod, leaving the task of piloting to your friend.")
def Hallway(player):
print_slow("You walk down the passage leading to the armory. On your way, you see an Experience station. You walk towards it.")
print_slow("You get the familiar feeling as hundreds of experience levels flow into your body, leveling you up.")
print_slow("You continue down the dimly lit hallway until you reach the armory.")
def Armory(player):
print_slow("You reach the armory, with its weapons and armor placed neatly on racks.")
weapon = Weapon("Force Machine", 130, 999999999999999999)
player.add_to_inventory(weapon)
weapon = Weapon("LR-58", 250, 999999999999999999)
player.add_to_inventory(weapon)
weapon = Weapon("RPG-7", 500, 7)
armor = Armor("Body Shield", 900, 9000)
player.add_to_inventory(weapon)
player.add_to_inventory(armor)
def Spaceship_1(player):
print_slow("You return to the ship's bridge, your copilot waiting for you.")
print_slow("Suddenly, the proximity alarm beeps slightly. The copilot just looks at it and taps it a couple times on its glass shielding. The beeping subsides.")
print_slow("See?, he says, it's probably nothing.")
print_slow("You nod your head in affirmation. Suddenly, the ship shudders violently and begins to groan.")
print_slow("The ship begins to tilt. You fall down, banging your head on the wall. You crumple to the ground as everything fades to black...")
def room_1(player):
print_slow("You awaken in a desolate desert. The sun beats down mercilessly as you struggle to breathe in the hot air. You find the remains of your ship scattered around you. The sun is scorching, and there’s no sign of life for miles.")
weapon = Weapon("Old Boxing Glove", 7, 999999999999999999)
player.add_to_inventory(weapon)
print_slow("You found an old boxing glove. It appears functional but still faded in color.")
enemy = Enemy("Mutated Dog", 30, 8, 2, 2)
battle(player, enemy)
def room_2(player):
print_slow("You find a small abandoned shelter with supplies inside. There's a broken-down military truck outside.")
armor = Armor("Old Combat Armor", 5, 3)
player.add_to_inventory(armor)
print_slow("You found some Old Combat Armor! It will protect you from attacks.")
enemy = Enemy("Raider", 40, 12, 5, 3)
battle(player, enemy)
def room_3(player):
print_slow("You find a hidden bunker and see a large underground facility marked 'Launch Area'. You have now discovered the nuclear launch site!")
player.found_nuclear_area = True
print_slow("The nuclear bomb detonation sequence will begin now that you've found the launch area. You have limited time to act.")
bomb = NuclearBomb()
while bomb.timer > 0 and player.is_alive():
print_slow(f"Bomb timer: {bomb.timer} turns remaining.")
choice = input("Do you want to attempt to disarm the bomb or explore? (D = Disarm / E = Explore): ").lower()
if choice == "d":
if random.random() < 0.5:
print_slow("You successfully disarmed the bomb! The world is saved.")
break
else:
print_slow("You failed to disarm the bomb. The countdown continues.")
elif choice == "e":
print_slow("You search the area, but find nothing useful.")
else:
print_slow("Invalid action. The bomb's timer continues.")
if bomb.countdown():
print_slow("The bomb has detonated. The world is lost.")
exit()
def room_4(player):
print_slow("You enter a ruined city, where abandoned vehicles and collapsed buildings litter the landscape.")
npc = NPC("Trader")
npc.interact(player)
enemy = Enemy("Mutant Scavenger", 45, 10, 3, 3)
battle(player, enemy)
def room_5(player):
print_slow("You stumble into a forested area. The vegetation is sparse, but it offers some cover from the harsh sun.")
npc = NPC("Merchant")
npc.interact(player)
enemy = Enemy("Crazed Survivor", 30, 8, 2, 2)
battle(player, enemy)
def room_6(player):
print_slow("You walk into a strange area with water in a shallow pool. There is a multitude if plants and vegetation, with shade shielding you from the harsh sun.")
npc = NPC("Scientist")
npc.interact(player)
npc = NPC("Veteran")
npc.interact(player)
npc = NPC("Trader")
npc.interact(player)
def room_7(player):
print_slow("You walk into a small passage leading underground. Upon arrival of the underground bunker, you find items scattered all over the floor.")
armor = Armor("Old Kevlar Armor [2013 model]", 50, 100)
player.add_to_inventory(armor)
weapon = Weapon("2020 Model AK-47", 200, 300)
player.add_to_inventory(weapon)
enemy = Enemy("Overlord", 70, 20, 20, 0)
battle(player, enemy)
def room_10(player):
print_slow("You continue down the tunnel to the light. A room opens up before you, a strange beast chained at the center.")
# Boss Enemy: Mutated Overlord
boss = Enemy("Mutated Overlord", 1000, 150, 40, 50,
weapons=[Weapon("Flame Thrower", 250, 10)],
armor=[Armor("Titanium Armor", 100, 50)])
# Print the introduction of the boss
print_slow(f"A wild {boss.name} appears!")
print_slow(f"{boss.name} is towering, covered in a metallic shell, and carrying a massive weapon!")
# Battle the boss
battle(player, boss)
# Reward for defeating the boss
if player.is_alive():
print_slow(f"Congratulations! {player.name} has defeated the {boss.name}.")
# The player gets a lot of experience points for defeating the boss
player.experience_meter += 500 # Huge XP drop
print_slow(f"{player.name} gained 500 XP!")
# Optional: The player could level up after such a big XP gain
if player.experience_meter >= player.level * 20:
player.level_up()
def main():
player_name = input("Enter your character's name: ")
player = Player(player_name)
rooms = [Spaceship, Hallway, Armory, Spaceship_1, room_1, room_2, room_3, room_4, room_5, room_6, room_7, room_10]
intro()
for room in rooms: # Loop through each room in order
if player.is_alive():
room(player)
player.update_day()
else:
print_slow("Game Over! You have died.")
break
if __name__ == "__main__":
main()
Rating
0%👍
0%👎
0%Don't know
Komentarze