├── .gitignore ├── class_based_text_rpg ├── Character.py ├── Dragon.py ├── GameSettings.py ├── Goblin.py ├── Hero.py ├── Monster.py ├── Shop.py ├── Shop_starter_with_dictionary.py ├── Troll.py ├── Zombie.py ├── battle_engine_function.py ├── battle_engine_function_object_update.py └── game.py ├── classesAndObjects ├── A_Class_name.py ├── Character.py ├── IPhone.py ├── IphoneX.py ├── Phone.py ├── classesAndObjects.py ├── inheritance.py └── objects101.py ├── codeChallenges ├── CustomerAndPremiumCustomer.py ├── bubbleSort.py ├── caesarCipher.py ├── caesarCipherList.py ├── groceryStore.py ├── guessTheNumber.py ├── guessTheNumberTimes.py ├── guessTheNumberUntil.py ├── guessTheNumberWithOr.py └── palNumbersEuler4.py ├── ninjas-vs-monsters ├── Background.py ├── GameButton.py ├── Monster.py ├── Ork.py ├── Player.py ├── Treasure.py ├── Troll.py ├── check_events.py ├── game.py ├── image_load.py ├── images.md ├── images │ ├── background4.png │ ├── treasures.png │ └── treasures_vase.png ├── ork_and_troll_starter_stats.py └── update_screen.py ├── projectEuler ├── erasSieve.py ├── names.txt ├── pe1.py ├── pe10.py ├── pe11.py ├── pe12.py ├── pe13.py ├── pe14.py ├── pe15.js ├── pe15.py ├── pe16.py ├── pe17.py ├── pe18.py ├── pe19.py ├── pe19b.py ├── pe2.py ├── pe20.py ├── pe20Simple.py ├── pe21.py ├── pe22.py ├── pe23.py ├── pe25.py ├── pe26.py ├── pe3.py ├── pe4.py ├── pe5.py ├── pe6.py ├── pe7.py ├── pe8.py ├── pe8_starter.py ├── pe9.py ├── radixPE22.py ├── radixSort.py └── randomStrGen.py ├── text_rpg ├── Initial Task List.md ├── battle_engine.py ├── calc.py ├── game.py ├── game_data.py ├── importing.py └── varsByReferenceAndValue.py └── theBasics ├── casting.py ├── conditionalsAndSpacing.py ├── dictionary.py ├── fib100.py ├── function.py ├── interpolationStrings.py ├── lists.py ├── looping_through_strings.py ├── loops.py ├── numberMethods.py ├── pythonBasics.py ├── pythonMath.py ├── return_palidrome.py ├── stringMethods.py ├── test.py └── tuplesAndSets.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | bin 3 | lib 4 | include 5 | *.cfg 6 | ninjas-vs-monsters/images/ninja 7 | ninjas-vs-monsters/images/1_TROLL 8 | ninjas-vs-monsters/images/2_TROLL 9 | ninjas-vs-monsters/images/3_TROLL 10 | ninjas-vs-monsters/images/1_ORK 11 | ninjas-vs-monsters/images/2_ORK 12 | ninjas-vs-monsters/images/3_ORK 13 | ninjas-vs-monsters/Scripts 14 | *.mp4 15 | projectEuler/pe12Notes.py 16 | projectEuler/parabolic.html 17 | projectEuler/pe16.js 18 | -------------------------------------------------------------------------------- /class_based_text_rpg/Character.py: -------------------------------------------------------------------------------- 1 | 2 | class Character(): 3 | #all classes start with an init dunder method 4 | def __init__(self,character_name,attack_power,defense,max_hp,hp,weapon): 5 | self.character_name = character_name 6 | self.attack_power = attack_power 7 | self.defense = defense 8 | self.max_hp = max_hp 9 | self.hp = hp 10 | self.weapon = weapon 11 | #by default do no more or less damage 12 | self.damage_modifier = 1 13 | #by default take no more or less damage 14 | self.defense_modifier = 1 15 | 16 | def take_damage(self,other_char_obj): 17 | #hero_power_hit = take the hero's attack_power - monster's defense 18 | #reduce the monster's hp by hero_power_hit 19 | power_hit = (other_char_obj.attack_power * other_char_obj.damage_modifier) - (self.defense * self.defense_modifier) 20 | self.hp -= power_hit 21 | return power_hit -------------------------------------------------------------------------------- /class_based_text_rpg/Dragon.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | from Monster import Monster 4 | class Dragon(Monster): 5 | def __init__(self): 6 | self.character_name = "Dragon" 7 | self.xp_drop = 100 8 | self.gold_drop = 500 9 | self.attack_power = random.randint(100,150) 10 | self.defense = 60 11 | self.max_hp = 700 12 | self.hp = random.randint(500,700) 13 | self.weapon = "Dragon Claws" 14 | #super() is the same as calling the Monster class 15 | super().__init__(self.character_name, self.xp_drop, self.gold_drop, 16 | self.attack_power,self.defense, 17 | self.max_hp,self.hp,self.weapon) 18 | 19 | 20 | def special_power(self): 21 | print("Goblin calls for help") 22 | -------------------------------------------------------------------------------- /class_based_text_rpg/GameSettings.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class GameSettings(): 4 | def __init__(self): 5 | self.main_options = [ 6 | { 7 | "text" : "Go into the dark forest in search of adventure and loot", 8 | "input_key" : "1", 9 | }, 10 | { 11 | "text" : "Go to the shop", 12 | "input_key" : "2", 13 | }, 14 | { 15 | "text" : "Do a dance", 16 | "input_key" : "3" 17 | }, 18 | { 19 | "text" : "Sleep and adventure another day (exit)", 20 | "input_key" : "q" 21 | } 22 | ] 23 | #levels is where we keep {} for each level 24 | self.levels = [ 25 | {}, #0 26 | {}, #1 27 | { 28 | "threshold" : 15, #amount of xp to go to this level 29 | "attack_increase" : 2, 30 | "defense_increase" : 1, 31 | "hp_increase" : 7, 32 | }, #2 33 | { 34 | "threshold" : 35, #amount of xp to go to this level 35 | "attack_increase" : 2, 36 | "defense_increase" : 1, 37 | "hp_increase" : 9, 38 | }, #3 39 | { 40 | "threshold" : 80, #amount of xp to go to this level 41 | "attack_increase" : 3, 42 | "defense_increase" : 2, 43 | "hp_increase" : 10, 44 | }, #4 45 | ] 46 | self.colors = { 47 | #Colors for Python terminal 48 | "red" : "\033[1;31;40m", 49 | "redB" : "\033[0;31;47m", 50 | "white" : "\033[1;37;40m", 51 | "blue" : "\033[1;34;40m", 52 | "blueB" : "\033[0;34;47m", 53 | "yellow" : "\033[1;33;40m", 54 | "green" : "\033[1;32;40m", 55 | "greenB" : "\033[0;32;47m", 56 | "normal" : "\033[0;37;40m", 57 | } -------------------------------------------------------------------------------- /class_based_text_rpg/Goblin.py: -------------------------------------------------------------------------------- 1 | 2 | from Monster import Monster 3 | class Goblin(Monster): 4 | def __init__(self): 5 | self.character_name = "Goblin" 6 | self.xp_drop = 1 7 | self.gold_drop = 5 8 | self.attack_power = 3 9 | self.defense = 3 10 | self.max_hp = 7 11 | self.hp = 7 12 | self.weapon = "fists" 13 | #super() is the same as calling the Monster class 14 | super().__init__(self.character_name, self.xp_drop, self.gold_drop, 15 | self.attack_power,self.defense, 16 | self.max_hp,self.hp,self.weapon) 17 | 18 | 19 | def special_power(self): 20 | print("Goblin calls for help") 21 | -------------------------------------------------------------------------------- /class_based_text_rpg/Hero.py: -------------------------------------------------------------------------------- 1 | from Character import Character 2 | 3 | class Hero(Character): 4 | def __init__(self, character_name, xp, level, gold, 5 | attack_power,defense,max_hp,hp,weapon, 6 | inventory,game_settings): 7 | self.xp = xp 8 | self.level = level 9 | self.gold = gold 10 | self.inventory = inventory 11 | self.game_settings = game_settings 12 | #we call super, which is the Character class. And we call it's init method 13 | #we only pass the things the Character class init method needs 14 | super().__init__(character_name,attack_power,defense,max_hp,hp,weapon) 15 | 16 | def battle_victory(self,vanquished_foe): 17 | # print("Check to see if hero has leveled up") 18 | print(f"Well done, magnificant {self.character_name}, {self.game_settings.colors['red']}thou hast slain the impudent {vanquished_foe.character_name}{self.game_settings.colors['normal']}.") 19 | #the hero won, so grant the hero some gold and xp 20 | self.gold += vanquished_foe.gold_drop 21 | self.xp += vanquished_foe.xp_drop 22 | print(f"Thou has gained {self.game_settings.colors['yellow']}{vanquished_foe.gold_drop} gold{self.game_settings.colors['normal']} and {self.game_settings.colors['green']}{vanquished_foe.xp_drop} experience{self.game_settings.colors['normal']}.") 23 | print(f"Thou now hasts {self.game_settings.colors['white']}total{self.game_settings.colors['normal']} of {self.game_settings.colors['yellow']}{self.gold} gold {self.game_settings.colors['normal']}and {self.game_settings.colors['green']}{self.xp} experience{self.game_settings.colors['normal']}.") 24 | #check to see if the hero has made a new level 25 | new_level_data = self.game_settings.levels[self.level + 1] 26 | if(self.xp >= new_level_data["threshold"]): 27 | #hero has leveled up! 28 | self.level += 1 #increase hero level 29 | self.attack_power += new_level_data["attack_increase"] 30 | self.defense += new_level_data["defense_increase"] 31 | self.max_hp += new_level_data["hp_increase"] 32 | #reset current hp to max_hp 33 | self.hp = self.max_hp 34 | print(f"Well done, brave {self.character_name}! {self.game_settings.colors['green']}Thou has reached a new level of {self.level}{self.game_settings.colors['normal']}.") 35 | print(f"Thine hp is now {self.hp}, thine attack is now {self.attack_power} and thine defense is {self.defense}.") 36 | def set_weapon(self,weapon): 37 | self.weapon = weapon 38 | if(weapon == "Magic Sword"): 39 | self.attack_power = self.attack_power * 1.15 40 | print(f"{self.game_settings.colors['green']}Thou grasp the Magic Sword and power flows through thine body.{self.game_settings.colors['normal']}") 41 | def set_armor(self, armor): 42 | if(armor == "Magic Armor"): 43 | self.defense = self.defense * 1.15 44 | print(f"{self.game_settings.colors['green']}Thou placeth the Magic Armor on thine body and power flows through you.{self.game_settings.colors['normal']}") -------------------------------------------------------------------------------- /class_based_text_rpg/Monster.py: -------------------------------------------------------------------------------- 1 | 2 | from Character import Character 3 | 4 | class Monster(Character): 5 | def __init__(self, character_name, xp_drop, gold_drop, attack_power,defense,max_hp,hp,weapon): 6 | self.xp_drop = xp_drop 7 | self.gold_drop = gold_drop 8 | super().__init__(character_name,attack_power,defense,max_hp,hp,weapon) 9 | 10 | def growl(): 11 | print(f"The monster has holwed in anger") -------------------------------------------------------------------------------- /class_based_text_rpg/Shop.py: -------------------------------------------------------------------------------- 1 | class Shop(): 2 | def __init__(self): 3 | self.items = [ 4 | { 5 | "item_name" : "Health Potion", 6 | "py_name" : "health_potion", 7 | "desc" : "Refresh all hit points", 8 | "cost" : 10, 9 | }, 10 | { 11 | "item_name" : "Magic Sword", 12 | "py_name" : "magic_sword", 13 | "desc" : "Attack Power +15%", 14 | "cost" : 1, 15 | }, 16 | { 17 | "item_name" : "Magic Armor", 18 | "py_name" : "magic_armor", 19 | "cost" : 50, 20 | "desc" : "Defense +15%", 21 | }, 22 | { 23 | "item_name" : "Evasion Potion", 24 | "py_name" : "evasion_potion", 25 | "cost" : 20, 26 | "desc" : "+20% chance to evade attack", 27 | }, 28 | { 29 | "item_name" : "Magic Carpet", 30 | "py_name" : "magic_carpet", 31 | "cost" : 30, 32 | "desc" : "Guarantee fight escape", 33 | }, 34 | { 35 | "item_name" : "Leave", 36 | "py_name" : "leave", 37 | "cost" : "", 38 | "desc" : "Leave the shop", 39 | }, 40 | ] 41 | def display(self,hero,game_settings): 42 | #display the shop options to the player 43 | keep_shopping = True #bool to keep the shop loop running 44 | annoy_tries = 0 45 | while(keep_shopping): 46 | print(f"Thou hast entered the shop with {game_settings.colors['yellow']}{hero.gold} gold{game_settings.colors['normal']}.") 47 | counter = 0 48 | for item in self.items: 49 | counter += 1 #counter is to give the user the number to push 50 | #each item is a {} in self.items 51 | print(f"{counter}. {item['item_name']}, {item['cost']} - {item['desc']}") 52 | shop_action = input("The keeper of the shop is gruff and short with you. Well? What do you want? > ") 53 | #to get the index in self.items that matches what the user entered, we -1 because the indicies start at 0 54 | index_in_items = int(shop_action) - 1 55 | #get the item from self.items based on the index 56 | item_to_buy = self.items[index_in_items] 57 | #did the player choose to leave 58 | if(item_to_buy['py_name'] == "leave"): 59 | keep_shopping = False 60 | #does the user have the money to buy the item? 61 | elif(hero.gold >= item_to_buy["cost"]): 62 | #the user has enough gold! 63 | hero.gold -= item_to_buy["cost"] #reduce the amount of gold the hero has... ie. pay for the time 64 | if(item_to_buy['py_name'] == "health_potion"): 65 | hero.inventory.append('health_potion') 66 | elif(item_to_buy['py_name'] == "magic_sword"): 67 | hero.set_weapon(item_to_buy['item_name']) 68 | elif(item_to_buy['py_name'] == "magic_armor"): 69 | hero.set_armor(item_to_buy['item_name']) 70 | print(f"{game_settings.colors['blue']}{item_to_buy['item_name']}{game_settings.colors['normal']} has been added to your inventory!") 71 | else: 72 | #the user does NOT have enough gold 73 | annoy_tries += 1 #each time the player tries to buy something they do not have the money for, increase annoy_tries 74 | if(annoy_tries == 1): 75 | #just one time making a mistake 76 | print(f"The keeper responds, 'dont waste my time. Go earn some coin, and come back'") 77 | elif(annoy_tries == 2): 78 | print(f"{game_settings.colors['blue']}The shop owner eyes you angrily... You cannot afford that item.{game_settings.colors['normal']}") 79 | elif(annoy_tries == 3): 80 | print(f"{game_settings.colors['red']}The shopkeeper howls. He grabs you by the coller and throws you out of the shop!{game_settings.colors['normal']}") 81 | keep_shopping = False 82 | -------------------------------------------------------------------------------- /class_based_text_rpg/Shop_starter_with_dictionary.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class Shop(): 4 | def __init__(self): 5 | self.items = [ 6 | { 7 | "item_name" : "Health Potion", 8 | "py_name" : "health_potion", 9 | "desc" : "Refresh all hit points", 10 | "cost" : 10, 11 | }, 12 | { 13 | "item_name" : "Magic Sword", 14 | "py_name" : "magic_sword", 15 | "desc" : "Attack Power +15%", 16 | "cost" : 50, 17 | }, 18 | { 19 | "item_name" : "Magic Armor", 20 | "py_name" : "magic_armor", 21 | "cost" : 50, 22 | "desc" : "Defense +15%", 23 | }, 24 | { 25 | "item_name" : "Evasion Potion", 26 | "py_name" : "evasion_potion", 27 | "cost" : 20, 28 | "desc" : "+20% chance to evade attack", 29 | }, 30 | { 31 | "item_name" : "Magic Carpet", 32 | "py_name" : "magic_carpet", 33 | "cost" : 30, 34 | "desc" : "Guarantee fight escape", 35 | }, 36 | { 37 | "item_name" : "Leave", 38 | "py_name" : "leave", 39 | "cost" : "", 40 | "desc" : "", 41 | }, 42 | ] 43 | -------------------------------------------------------------------------------- /class_based_text_rpg/Troll.py: -------------------------------------------------------------------------------- 1 | 2 | from Monster import Monster 3 | 4 | class Troll(Monster): 5 | def __init__(self): 6 | self.character_name = "Troll" 7 | self.xp_drop = 15 8 | self.gold_drop = 20 9 | self.attack_power = 35 10 | self.defense = 13 11 | self.max_hp = 45 12 | self.hp = 45 13 | self.weapon = "Troll Hammer" 14 | #super() is the same as calling the Monster class 15 | super().__init__(self.character_name, self.xp_drop, self.gold_drop, 16 | self.attack_power,self.defense, 17 | self.max_hp,self.hp,self.weapon) 18 | 19 | 20 | -------------------------------------------------------------------------------- /class_based_text_rpg/Zombie.py: -------------------------------------------------------------------------------- 1 | 2 | from Monster import Monster 3 | class Zombie(Monster): 4 | 5 | def __init__(self): 6 | self.character_name = "Zombie" 7 | self.xp_drop = 2 8 | self.gold_drop = 5 9 | self.attack_power = 5 10 | self.defense = 2 11 | self.max_hp = 7 12 | self.hp = 9 13 | self.weapon = "fists" 14 | #super() is the same as calling the Monster class 15 | super().__init__(self.character_name, self.xp_drop, self.gold_drop, 16 | self.attack_power,self.defense, 17 | self.max_hp,self.hp,self.weapon) 18 | 19 | 20 | def special_power(self): 21 | print("Zombie is enraged") 22 | -------------------------------------------------------------------------------- /class_based_text_rpg/battle_engine_function.py: -------------------------------------------------------------------------------- 1 | import random 2 | # from Character import Character 3 | from Monster import Monster #Monster is a subclass of Character 4 | import time #part of core 5 | import os #os is part of core, stands for operating system 6 | from Troll import Troll 7 | from Zombie import Zombie 8 | from Goblin import Goblin 9 | 10 | #if the player decides to fight, this function will run 11 | def battle_engine(the_hero,game_settings): 12 | #inside of battle_engine, make some enemies 13 | troll = Troll() 14 | goblin = Goblin() 15 | zombie = Zombie() 16 | # zombie = Monster(character_name="Zombie",xp_drop = 2, 17 | # gold_drop = 5, attack_power=5, defense = 2, 18 | # max_hp=7, hp = 9, weapon="fists",) 19 | enemies = [goblin, zombie, troll] 20 | random_list = ([0] * 5) + ([1] * 4) + [2] 21 | # [0,0,0,0,0,1,1,1,1,2] 22 | 23 | # os.system('cls') #this is for windows 24 | os.system('clear') #this is for Mac 25 | #time.sleep(x) will force the program to stop for x seconds 26 | print(f"{game_settings.colors['red']}Thou hast entered the forest. Danger creeps everywhere...{game_settings.colors['normal']}") 27 | time.sleep(2) #pause for 2 seconds 28 | 29 | # os.system("say Hooray, Hero!") 30 | 31 | #randint is a method from random. It takes 2 args: 32 | #1. integer to start at 33 | #2. integer to end at 34 | total_enemies = len(enemies) 35 | # random_number = random.randint(0,total_enemies-1) 36 | # random_index = random.randint(0,total_enemies-1) 37 | random_index = random.choice(random_list) 38 | #we need to use the copy method, so that we don't change the original 39 | enemy_to_fight = enemies[random_index] 40 | in_fight = True #boolean that keeps us in the fight loop 41 | print(f"{the_hero.character_name}, thou hast encountered the {game_settings.colors['blue']}{enemy_to_fight.character_name}{game_settings.colors['normal']}. The battle has begun!") 42 | while(in_fight): 43 | print(f"Thou hast {the_hero.hp} health points. Thine enemy has {enemy_to_fight.hp} health points.") 44 | #this loop is the back and forth during a battle. Until someone wins 45 | print(f"1. Attack with thine {the_hero.weapon}.") 46 | health_potion_count = the_hero.inventory.count("health_potion") 47 | print(f"2. Drink the health potion. Thou hast {health_potion_count} potions.") 48 | print(f"3. Defend and heal.") 49 | print(f"4. Do a little dance.") 50 | print(f"5. Flee for your miserable, pitiful life.") 51 | battle_action = input("What would you like to do? > ") #this is the chioce the player will make in the fight 52 | #hero's turn 53 | if(battle_action == "1"): 54 | #the_hero has chosen to attack 55 | power_hit = enemy_to_fight.take_damage(the_hero) 56 | print(f"Thou hast struck thine enemy with {the_hero.weapon} for {power_hit} damage.") 57 | elif(battle_action == "2"): 58 | #this means, players wants to drink a potion 59 | if(health_potion_count > 0): 60 | #restore all hp 61 | # health_potion_count -= 1 #this will not work! Because we get the count from the list in the_hero 62 | #remove is like append, but we pass it the value to find and remove 63 | the_hero.inventory.remove('health_potion') 64 | the_hero.hp = the_hero.max_hp 65 | print(f"Thou hast drank thy potion. Thine hp is restored to full. ") 66 | else: 67 | #player had no potions. Make the enemy take advantage 68 | print(f"Thou fool. Thou hast no potions of health, thine enemy has taken advatange of thine blunder") 69 | enemy_to_fight.damage_modifier = 2 70 | the_hero.defense_modifier = 1 #reset the defense mod for the hero to 1 71 | elif(battle_action == "3"): 72 | #player has chosen to heal and defend 73 | the_hero.defense_modifier = 2 74 | elif(battle_action == "5"): 75 | print("Fight has ended") 76 | in_fight = False 77 | return #return will keep the enemy from getting a chance to attack 78 | #enemy's turn, if alive 79 | if(enemy_to_fight.hp > 0): 80 | #enemy is alive. Attack back. 81 | power_hit = the_hero.take_damage(enemy_to_fight) 82 | print(f"Thine enemy {enemy_to_fight.character_name} has struck thee with {enemy_to_fight.weapon} for {power_hit} damage.") 83 | #check to see if hero has hp > 0 84 | #if not... break out of the fight loop 85 | if(the_hero.hp <= 0): 86 | in_fight = False 87 | print(f"Thou hast been slain by {enemy_to_fight.character_name}") 88 | else: 89 | #the enemy has no more hp. Fight is won for the hero 90 | the_hero.battle_victory(enemy_to_fight) 91 | in_fight = False #the fight is over! End the loop -------------------------------------------------------------------------------- /class_based_text_rpg/battle_engine_function_object_update.py: -------------------------------------------------------------------------------- 1 | import random 2 | from Character import Character 3 | 4 | #if the player decides to fight, this function will run 5 | def battle_engine(the_hero): 6 | #inside of battle_engine, make some enemies 7 | goblin = Character(character_name="Goblin",xp = 0, level = 1, 8 | gold = 5, attack_power=3, defense = 3, 9 | max_hp=7, hp = 7, weapon="fists", 10 | inventory=[]) 11 | zombie = Character(character_name="Zombie",xp = 0, level = 1, 12 | gold = 5, attack_power=5, defense = 2, 13 | max_hp=7, hp = 9, weapon="fists", 14 | inventory=[]) 15 | enemies = [goblin,zombie] 16 | 17 | #randint is a method from random. It takes 2 args: 18 | #1. integer to start at 19 | #2. integer to end at 20 | total_enemies = len(enemies) 21 | # random_number = random.randint(0,total_enemies-1) 22 | random_index = random.randint(0,total_enemies-1) 23 | #we need to use the copy method, so that we don't change the original 24 | enemy_to_fight = enemies[random_index] 25 | in_fight = True #boolean that keeps us in the fight loop 26 | print(f"{the_hero.character_name}, thou hast encountered the {enemy_to_fight.character_name}. The battle has begun!") 27 | while(in_fight): 28 | enemy_attack_modifier = 1 #by default the enemy does no more or less damage 29 | print(f"Thou hast {the_hero.hp} health points. Thine enemy has {enemy_to_fight.hp} health points.") 30 | #this loop is the back and forth during a battle. Until someone wins 31 | print(f"1. Attack with thine {the_hero.weapon}.") 32 | health_potion_count = the_hero.inventory.count("health_potion") 33 | print(f"2. Drink the health potion. Thou hast {health_potion_count} potions.") 34 | print(f"3.Defend and heal.") 35 | print(f"4. Do a little dance.") 36 | print(f"5. Flee for your miserable, pitiful life.") 37 | battle_action = input("What would you like to do? > ") #this is the chioce the player will make in the fight 38 | #hero's turn 39 | if(battle_action == "1"): 40 | #user has chosen to attack 41 | #hero_power_hit = take the hero's attack_power - monster's defense 42 | #reduce the monster's hp by hero_power_hit 43 | hero_power_hit = the_hero.attack_power - enemy_to_fight.defense 44 | enemy_to_fight.hp -= hero_power_hit 45 | print(f"Thou hast struck thine enemy with {the_hero.weapon} for {hero_power_hit} damage.") 46 | elif(battle_action == "2"): 47 | #this means, players wants to drink a potion 48 | if(health_potion_count > 0): 49 | #restore all hp 50 | # health_potion_count -= 1 #this will not work! Because we get the count from the list in the_hero 51 | #remove is like append, but we pass it the value to find and remove 52 | the_hero.inventory.remove('health_potion') 53 | the_hero.hp = the_hero.max_hp 54 | print(f"Thou hast drank thy potion. Thine hp is restored to full. ") 55 | else: 56 | #player had no potions. Make the enemy take advantage 57 | print(f"Thou fool. Thou hast no potions of health, thine enemy has taken advatange of thine blunder") 58 | enemy_attack_modifier = 2 59 | elif(battle_action == "5"): 60 | print("Fight has ended") 61 | in_fight = False 62 | #enemy's turn, if alive 63 | if(enemy_to_fight.hp > 0): 64 | #enemy is alive. Attack back. 65 | #monster_power_hit = take the monster's attack_power - hero's defense 66 | #reduce the hero's hp by monster_power_hit 67 | monster_power_hit = (enemy_to_fight.attack_power * enemy_attack_modifier)- the_hero.defense 68 | print(f"Thine enemy {enemy_to_fight.character_name} has struck thee with {enemy_to_fight.weapon} for {monster_power_hit} damage.") 69 | the_hero.hp -= monster_power_hit 70 | else: 71 | #the enemy has no more hp. Fight is won for the hero 72 | print(f"Well done, magnificant {the_hero.character_name}, thou hast slain the impudent {enemy_to_fight.character_name}.") 73 | #the hero won, so grant the hero some gold and xp 74 | the_hero.gold += enemy_to_fight.gold_drop 75 | the_hero.xp += enemy_to_fight.xp_drop 76 | print(f"Thou has gained {enemy_to_fight.gold_drop} gold and {enemy_to_fight.xp_drop} experience.") 77 | print(f"Thou now hasts {the_hero.gold} gold and {the_hero.xp} experience.") 78 | in_fight = False #the fight is over! End the loop -------------------------------------------------------------------------------- /class_based_text_rpg/game.py: -------------------------------------------------------------------------------- 1 | # from Character import Character 2 | from Hero import Hero #Hero is a subclass of Character 3 | from GameSettings import GameSettings 4 | from battle_engine_function import battle_engine 5 | from Shop import Shop 6 | 7 | shop = Shop() 8 | game_settings = GameSettings() 9 | charater_name = input("What is thy name, brave adventurer? > ") 10 | the_hero = Hero(charater_name, xp = 0, level = 1, 11 | gold = 5, attack_power = 10, 12 | defense = 2, max_hp = 10, hp = 10, 13 | weapon = "fists", 14 | inventory = ['health_potion'], 15 | game_settings = game_settings) 16 | 17 | #make a boolean that will control our main game loop 18 | game_on = True 19 | while(game_on): 20 | print(f"What would you like to do, {the_hero.character_name}?") 21 | for option in game_settings.main_options: 22 | print(f"{option['input_key']}. {option['text']}") 23 | action = input(" > ") #this will BLOCK the loop, until the user answer 24 | if(action == "1"): 25 | #call the battle engine 26 | battle_engine(the_hero,game_settings) 27 | if(the_hero.hp <= 0): 28 | print(f"All hope is lost...") 29 | game_on = False 30 | #game over :( 31 | elif(action == "2"): 32 | #player has chosen to enter the shop 33 | shop.display(the_hero,game_settings) #run the display method on our shop object. Pass the hero object, and the game_settings object 34 | elif(action == "q"): 35 | game_on = False -------------------------------------------------------------------------------- /classesAndObjects/A_Class_name.py: -------------------------------------------------------------------------------- 1 | #an exmaple to show you the convetion is ok to break, 2 | #for Python, but don't break it without a good reason 3 | 4 | class aaa_Character_haha(): 5 | name = "The Hero" 6 | hp = 10 7 | 8 | def print_name(): 9 | print(f"Hello from Character class, {name}") 10 | 11 | 12 | -------------------------------------------------------------------------------- /classesAndObjects/Character.py: -------------------------------------------------------------------------------- 1 | 2 | #self is a special key word that is used to reference 3 | #the object's stuff. It is used in the class, NOT 4 | #by the object, becuase the object knows it's variable name (the_hero, goblin, zombie) 5 | #the class just knows it's an object, so thje class 6 | #must use "self" to reference the object 7 | 8 | class Character(): 9 | #python has dunder method 10 | #dunder = a method that starts and ends with __ 11 | #dunder methods run at special times, i.e. we do not call them 12 | def __init__(self,character_name,hp): 13 | #init is a dunder method that belongs in a class 14 | #it is also known in oop as the constructor method 15 | #it runs ONE time. When a new object is created 16 | self.name = character_name 17 | self.hp = hp 18 | 19 | #all methods in a class MUST take self as the first param 20 | def print_name(self): 21 | # global name #global is ALWAYS neccessary if the variable is not defined localally 22 | print(f"Hello from Character class, {self.name}") 23 | 24 | 25 | -------------------------------------------------------------------------------- /classesAndObjects/IPhone.py: -------------------------------------------------------------------------------- 1 | from Phone import Phone 2 | 3 | #An iPhone IS ALWAYS a phone 4 | #How do we make this a subclass of Phone? 5 | #we want the methods and attributes that Phones have 6 | #we pass the parent/super class to the () 7 | class IPhone(Phone): 8 | def __init__(self,model,carrier,contacts): 9 | self.os = "iOS" 10 | self.make = "Apple" 11 | #super is a built in function to Python 12 | #super = the parent class 13 | super().__init__(self.make,model,carrier,self.os,contacts) 14 | def open_facetime(self): 15 | print("Opening Facetime...") 16 | 17 | #overriding = allows us to overrive a method from 18 | #a parent/super class 19 | def open_app_store(self): 20 | print("This is the Apple App Store") -------------------------------------------------------------------------------- /classesAndObjects/IphoneX.py: -------------------------------------------------------------------------------- 1 | from IPhone import IPhone 2 | #the iphoneX was the first iphone to use facial id 3 | #the inheritance tree goes like this... 4 | #Phone ---> IPhone ---> IPhoneX 5 | class IPhoneX(IPhone): 6 | def __init__(self,carrier,contacts): 7 | self.facial_id = True 8 | #super is the parent class 9 | super().__init__('iPhoneX',carrier,contacts) 10 | 11 | #the same attribute with self, will be used instead of the method 12 | def run_facial_id(self): 13 | print("Running facial ID") 14 | 15 | #this would run if enabled for all IPhoneX 16 | # def open_app_store(self): 17 | # print("This is the Apple App Store for IPhoneX") -------------------------------------------------------------------------------- /classesAndObjects/Phone.py: -------------------------------------------------------------------------------- 1 | 2 | class Phone(): 3 | def __init__(self,make,model,carrier,os,contacts): 4 | print("Phone class __init__ running") 5 | self.make = make 6 | self.model = model 7 | self.carrier = carrier 8 | self.os = os 9 | self.contacts = contacts 10 | 11 | def call_first_contact(self): 12 | print("Calling first contact...") 13 | def open_app_store(self): 14 | print("Opening the app store...") -------------------------------------------------------------------------------- /classesAndObjects/classesAndObjects.py: -------------------------------------------------------------------------------- 1 | 2 | #class names should be uppercase for the first letter 3 | #and uppercase, no spaces, for each word in the 4 | #class name. 5 | #when we make a class, we put it in its own file 6 | #this makes life better! 7 | #we also call the file name the same as the class name 8 | #the class name follows normal rules for functions 9 | #and for variable, i.e. no starting with a number, 10 | #no spaces, etc. 11 | -------------------------------------------------------------------------------- /classesAndObjects/inheritance.py: -------------------------------------------------------------------------------- 1 | from Phone import Phone 2 | from IPhone import IPhone 3 | from IphoneX import IPhoneX 4 | #inheritance - is a way in Python to allow one class 5 | #to have all the methods and attributes of another 6 | 7 | jims_phone = Phone('Apple','iphone 9','Verizon',"iOS",["Jamie"]) 8 | cedrics_phone = Phone('Google','Pixel 7 Pro','EE',"Android",["Sherlock","Marie"]) 9 | ravis_phone = IPhone("iphone 13",'Vodaphone',[]) 10 | marias_phone = IPhoneX('ATT',['Jose','David']) 11 | 12 | # print(jims_phone.make) 13 | # print(jims_phone.contacts) 14 | # cedrics_phone.call_first_contact() 15 | # print(ravis_phone.os) 16 | # print(ravis_phone.make) 17 | # print("Calling contact from Ravis phone...") 18 | # ravis_phone.call_first_contact() 19 | # print(ravis_phone.carrier) 20 | # ravis_phone.open_facetime() 21 | # jims_phone.open_facetime() 22 | 23 | #mariasPhone is a IPhoneX 24 | #but... an IPhoneX is a IPhone 25 | #and an IPhone is a Phone 26 | marias_phone.call_first_contact() #Phone 27 | marias_phone.open_facetime() #IPhone 28 | marias_phone.run_facial_id() #IPhoneX 29 | marias_phone.open_app_store() #This is in Phone, BUT is also in IPhone and because IPhone is lower, it uses that one -------------------------------------------------------------------------------- /classesAndObjects/objects101.py: -------------------------------------------------------------------------------- 1 | from Character import Character 2 | 3 | #the_hero is an object. What type of object? A Character object 4 | #Character is the class 5 | the_hero = Character("Axe",10) 6 | goblin = Character("a simple goblin",8) 7 | zombie = Character("a brain seeking zombie",10) 8 | print(the_hero) 9 | print(f"The hero has {the_hero.hp} hp.") 10 | #unlike dictionaries, we can go straight to our 11 | # "attributes" which are variables and methods/functions 12 | #we use . to get to our object "stuff" 13 | 14 | #python, whether we like it or not, is ALWAYS 15 | #going to send "self" to any object method 16 | # the_hero.print_name() #uhh, do we pass it something here, or not? 17 | # goblin.print_name() 18 | # zombie.print_name() 19 | # print(the_hero.name) #self.name in the class, variable_name.name in the place where the object exists 20 | 21 | zombie.hp -= 3 22 | print(f"{zombie.name} has taken 3 damage. Now has {zombie.hp}.") 23 | print(f"{the_hero.name} has {the_hero.hp} hp.") 24 | the_hero.hp -= 2 25 | print(f"{the_hero.name} has taken 2 damage. {the_hero.name} now has {the_hero.hp} hp.") 26 | goblin.hp -= 3 27 | print(f"{goblin.name} has taken 3 damage. Now has {goblin.hp}.") 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /codeChallenges/CustomerAndPremiumCustomer.py: -------------------------------------------------------------------------------- 1 | 2 | class Customer(): 3 | def __init__(self,make,model,carrier,os,contacts): 4 | print("Phone class __init__ running") 5 | self.make = make 6 | self.model = model 7 | self.carrier = carrier 8 | self.os = os 9 | self.contacts = contacts 10 | 11 | def call_first_contact(self): 12 | print("Calling first contact...") 13 | def open_app_store(self): 14 | print("Opening the app store...") -------------------------------------------------------------------------------- /codeChallenges/bubbleSort.py: -------------------------------------------------------------------------------- 1 | #Sorting an unsorted list is a classic computer science problem 2 | #Bubble sort, the one we are doing here, is the entry level sort 3 | #I will give you a list of random numbers. You should write a function 4 | #that implaments bubble sort to put them in the correct order. 5 | #Bubble sort loops through the list, looking at each number in the list 6 | #The first time through, it compares 1 and 2. If 1 is bigger, they swap places 7 | #Otherwise they stay in their place. 8 | #Then it compares 2 and 3... same thing, swap if 1 is bigger, otherwise leave alone 9 | #Go to the end of the list, then start over 10 | #It is called bubble sort because the large numbers "bubble up" to the top 11 | 12 | def bubbleSort(random_list): 13 | #get length of the list so we can loop through 14 | list_length = len(random_list) 15 | swapped = False 16 | #no reason to check the last number 17 | for i in range(0,list_length-1): 18 | #we don't need to loop through all numbers... 19 | #because each time through, we know the number 20 | #just moved to the end is largest 21 | for j in range(0, list_length-i-1): 22 | if random_list[j] > random_list[j + 1]: 23 | swapped = True 24 | #stash random_list[j] because we need to overwrite it 25 | temp = random_list[j] 26 | random_list[j] = random_list[j + 1] 27 | random_list[j + 1] = temp 28 | 29 | #if we get through the whole list without a swap, the 30 | #list is already in order so stop 31 | if(swapped == False): 32 | # break #break isn't enough because it will only stop 33 | #the current loop. We need to end the sort 34 | return 35 | 36 | 37 | #Seed data 38 | list_of_random_numbers = [14,91,201,5,2,34,55] 39 | 40 | bubbleSort(list_of_random_numbers) 41 | 42 | print(f"Sorted list is: {''.join(str(list_of_random_numbers))}") -------------------------------------------------------------------------------- /codeChallenges/caesarCipher.py: -------------------------------------------------------------------------------- 1 | 2 | # Caesar Cipher Code Challenge 3 | # I will give you a string, and you must print out the Caesar Cipher of that string. The string is defined below, but it is: 4 | # "buqhdydw xem je setu yi byau q cqwys jhysa. edsu oek kdtuhijqdt, yj yi dej jxqj ycfhuiiylu, rkj kdjyb oek te, yj yi cqwys." 5 | # Research Caesar Cipher if you need to! Here is a helpful image that won't tempt you to look at code: 6 | # https://en.wikipedia.org/wiki/Caesar_cipher#/media/File:Caesar_cipher_left_shift_of_3.svg 7 | #Don't cheat or give up early, and don't go too long and get frustrated or discouraged. 8 | 9 | encrypted_message = "buqhdydw fojxed yi byau buqhdydw q cqwys jhysa. edsu oek adem xem yj mehai, yj iuuci iycfbu, rkj kdjyb oek te, yj'i cqwys!" 10 | decrypted_alphabet = "abcdefghijklmnopqrstuvwxyz" 11 | decrypted_alphabet_as_list = list(decrypted_alphabet) 12 | encrypted_alphabet1 = "klmnopqrstuvwxyzabcdefghij" 13 | encrypted_alphabet1_as_list = list(encrypted_alphabet1) 14 | encrypted_alphabet2 = "qrstuvwxyzabcdefghijklmnop" 15 | encrypted_alphabet2_as_list = list(encrypted_alphabet2) 16 | decrypted_message = "" 17 | 18 | def decrypt_function(encrypted_letter): 19 | index = encrypted_alphabet2.find(encrypted_letter) 20 | if(index == -1): 21 | return encrypted_letter 22 | else: 23 | decrypted_letter = decrypted_alphabet[index] 24 | return decrypted_letter 25 | 26 | for letter in encrypted_message: 27 | correct_letter = decrypt_function(letter) 28 | decrypted_message += correct_letter 29 | 30 | print(decrypted_message) 31 | 32 | -------------------------------------------------------------------------------- /codeChallenges/caesarCipherList.py: -------------------------------------------------------------------------------- 1 | #===============As list with with loop============= 2 | message = "buqhdydw fojxed yi byau buqhdydw q cqwys jhysa. edsu oek adem xem yj mehai, yj iuuci iycfbu, rkj kdjyb oek te, yj'i cqwys!" 3 | decrypted_alphabet = "abcdefghijklmnopqrstuvwxyz" 4 | decrypted_alphabet_as_list = list(decrypted_alphabet) 5 | encrypted_alphabet1 = "klmnopqrstuvwxyzabcdefghij" 6 | encrypted_alphabet1_as_list = list(encrypted_alphabet1) 7 | encrypted_alphabet2 = "qrstuvwxyzabcdefghijklmnop" 8 | encrypted_alphabet2_as_list = list(encrypted_alphabet2) 9 | decrypted_message = "" 10 | 11 | def decrypt_function(encrypted_letter): 12 | for i in range(0,len(encrypted_alphabet2_as_list)): 13 | if(encrypted_alphabet2_as_list[i] == encrypted_letter): 14 | # i is the index we are after! 15 | return decrypted_alphabet[i] 16 | return encrypted_letter 17 | 18 | for letter in message: 19 | correct_letter = decrypt_function(letter) 20 | decrypted_message += correct_letter 21 | 22 | print(decrypted_message) 23 | 24 | #===============As list with index============= 25 | encrypted_message = "buqhdydw fojxed yi byau buqhdydw q cqwys jhysa. edsu oek adem xem yj mehai, yj iuuci iycfbu, rkj kdjyb oek te, yj'i cqwys!" 26 | decrypted_alphabet = "abcdefghijklmnopqrstuvwxyz" 27 | decrypted_alphabet_as_list = list(decrypted_alphabet) 28 | encrypted_alphabet1 = "klmnopqrstuvwxyzabcdefghij" 29 | encrypted_alphabet1_as_list = list(encrypted_alphabet1) 30 | encrypted_alphabet2 = "qrstuvwxyzabcdefghijklmnop" 31 | encrypted_alphabet2_as_list = list(encrypted_alphabet2) 32 | decrypted_message = "" 33 | 34 | def decrypt_function(encrypted_letter): 35 | if(encrypted_letter == " " or encrypted_letter == "." or encrypted_letter == "," or encrypted_letter == "'" or encrypted_letter == "!" ): 36 | return encrypted_letter 37 | else: 38 | index = encrypted_alphabet2_as_list.index(encrypted_letter) 39 | decrypted_letter = decrypted_alphabet[index] 40 | return decrypted_letter 41 | 42 | for letter in encrypted_message: 43 | correct_letter = decrypt_function(letter) 44 | decrypted_message += correct_letter 45 | 46 | print(decrypted_message) 47 | 48 | 49 | -------------------------------------------------------------------------------- /codeChallenges/groceryStore.py: -------------------------------------------------------------------------------- 1 | # List of grocery items with dictionaries containing item_type, price, and quantity 2 | grocery_list = [ 3 | {"item_name": "Apples", "price": 1.5, "quantity": 10}, 4 | {"item_name": "Donut", "price": 1.4, "quantity": 6}, 5 | {"item_name": "Milk", "price": 5.0, "quantity": 1}, 6 | {"item_name": "Spaghetti", "price": 2.5, "quantity": 3}, 7 | {"item_name": "Eggs", "price": 4.0, "quantity": 1} 8 | ] 9 | money_on_hand = 35.0 # Initial amount of money on hand 10 | cart = [] # List to store maximum purchase statements 11 | 12 | def buy_item(item): 13 | #make variables for price and quantity to make things look a little neater 14 | price = item["price"] 15 | quantity = item["quantity"] 16 | 17 | #use the global key word or we can't use the money_on_hand variable in a function 18 | global money_on_hand 19 | 20 | #buy if possible 21 | item_total_price = price * quantity #to get the total, multiply price and quantity 22 | if(money_on_hand > item_total_price): #if you have enough money conditional 23 | money_on_hand -= item_total_price # update money by subtracting price of item * quantity 24 | cart.append(item) #update cart with the item 25 | #buy as many as possible 26 | # for i in range(quantity,0,-1): #looping down means starting at quantity, down to 0, and stepping by -1 27 | # item_total_price = price * i # get the price of the quantity as you count down * price 28 | # if(money_on_hand > item_total_price): # see above 29 | # item["quantity"] = i #update item quantity to be what you can afford 30 | # money_on_hand -= item_total_price #see above 31 | # cart.append(item) #add to cart 32 | # break #stop the loop because we found the max we can buy 33 | 34 | for item in grocery_list: 35 | #call buy_item and send the item 36 | buy_item(item) 37 | 38 | print("You were able to purchase") 39 | for item in cart: 40 | print(f" {item['quantity']} {item['item_name']}") 41 | 42 | print(f"Money leftover: {money_on_hand}") 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /codeChallenges/guessTheNumber.py: -------------------------------------------------------------------------------- 1 | 2 | #1. Assign a variable to an integer between 1 and 10 3 | correct_number = 3 4 | #2. Ask the user to guess a number between 1 and 10 5 | guessed_number = input("Please guess a number between 1 and 10 > ") 6 | #3. Cast the number the user gave you into an int 7 | guessed_number_as_int = int(guessed_number) 8 | #3b. Cast the correct number into a string 9 | correct_number_as_string = str(correct_number) 10 | #4. If the user's number equals the correct number, 11 | if(guessed_number_as_int == correct_number): 12 | #5. if so, print an awesome message to the screen 13 | print("You are awesome! You guessed it!") 14 | elif(guessed_number_as_int + 1 == correct_number): 15 | #8. if the number is within 1, print a message that they were close 16 | #and what the number was 17 | print("You were close! The number was " + str(correct_number)) 18 | elif(guessed_number_as_int - 1 == correct_number): 19 | print("You were close! The number was " + str(correct_number)) 20 | else: 21 | #6. if not, print a sad message to the screen 22 | # print("Sorry, that is not the number") 23 | #7. add to the message what the number was 24 | #sorry that is not correct. the number was 3 25 | print("Sorry, that is not the number. The number was " + str(correct_number)) 26 | -------------------------------------------------------------------------------- /codeChallenges/guessTheNumberTimes.py: -------------------------------------------------------------------------------- 1 | correct_number = 3 2 | # The loop needs to start here 3 | # Allow the user to keep guessing until guess the right answer 4 | number_of_tries = input("How many guesses would you like? > ") 5 | number_of_tries = int(number_of_tries) 6 | # i is just a variable name! 7 | # we could call it "guess_num" 8 | # start i at 1, and stop (dont include) number_of_tries +1 9 | for i in range(1,number_of_tries+1): 10 | print(f"You are currently on guess {i}.") 11 | guessed_number = input("Please guess a number between 1 and 10 > ") 12 | guessed_number_as_int = int(guessed_number) 13 | correct_number_as_string = str(correct_number) 14 | if(guessed_number_as_int == correct_number): 15 | print("You are awesome! You guessed it!") 16 | # Inside of a for loop, if you want to break out early 17 | # use ... the break command 18 | break 19 | elif(guessed_number_as_int + 1 == correct_number): 20 | print("You were close!") 21 | elif(guessed_number_as_int - 1 == correct_number): 22 | print("You were close!") 23 | else: 24 | print("You are not even close!") 25 | print(f"It took you {i}") -------------------------------------------------------------------------------- /codeChallenges/guessTheNumberUntil.py: -------------------------------------------------------------------------------- 1 | correct_number = 3 2 | # The loop needs to start here 3 | # Allow the user to keep guessing until guess the right answer 4 | keep_guessing = True 5 | while(keep_guessing): 6 | guessed_number = input("Please guess a number between 1 and 10 > ") 7 | guessed_number_as_int = int(guessed_number) 8 | correct_number_as_string = str(correct_number) 9 | if(guessed_number_as_int == correct_number): 10 | print("You are awesome! You guessed it!") 11 | # When the user guesses the right answer, the loop can stop! 12 | # To stop the loop, change the bool in the while 13 | # to be false 14 | keep_guessing = False 15 | elif(guessed_number_as_int + 1 == correct_number): 16 | print("You were close!") 17 | elif(guessed_number_as_int - 1 == correct_number): 18 | print("You were close!") 19 | else: 20 | print("You are not even close!") 21 | -------------------------------------------------------------------------------- /codeChallenges/guessTheNumberWithOr.py: -------------------------------------------------------------------------------- 1 | 2 | #1. Assign a variable to an integer between 1 and 10 3 | correct_number = 3 4 | #2. Ask the user to guess a number between 1 and 10 5 | guessed_number = input("Please guess a number between 1 and 10 > ") 6 | #3. Cast the number the user gave you into an int 7 | guessed_number_as_int = int(guessed_number) 8 | #3b. Cast the correct number into a string 9 | correct_number_as_string = str(correct_number) 10 | #4. If the user's number equals the correct number, 11 | if(guessed_number_as_int == correct_number): 12 | #5. if so, print an awesome message to the screen 13 | print("You are awesome! You guessed it!") 14 | #if checking a data type, you dont compare to a string like "int" 15 | #you use the key word for that data type, such as int, str, float, etc. 16 | elif(type(guessed_number_as_int) == int 17 | #if using "and" and "or" together... use () !!!!! to group them 18 | and 19 | (guessed_number_as_int + 1 == correct_number 20 | #2 or's ... just 1 needs to be true 21 | #an and, both need to be true 22 | or 23 | guessed_number_as_int - 1 == correct_number)): 24 | #8. if the number is within 1, print a message that they were close 25 | #and what the number was 26 | print("You were close! The number was " + str(correct_number)) 27 | else: 28 | #6. if not, print a sad message to the screen 29 | # print("Sorry, that is not the number") 30 | #7. add to the message what the number was 31 | #sorry that is not correct. the number was 3 32 | print("Sorry, that is not the number. The number was " + str(correct_number)) 33 | 34 | 35 | -------------------------------------------------------------------------------- /codeChallenges/palNumbersEuler4.py: -------------------------------------------------------------------------------- 1 | # This challenge comes from the website https://projecteuler.net/problem=4. 2 | # You'll have no trouble finding help online with these if you need it ;) 3 | 4 | # A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. 5 | # Find the largest palindrome made from the product of two 3-digit numbers. 6 | 7 | def amIAPalindrome(numberToCheck): 8 | # Step one is to check if the number is a palidrome 9 | # reverse would be handy here, so convert the str to a list 10 | # First convert to a string and then to a list... 11 | # in one fell swoop! 12 | numAsList = list(str(numberToCheck)) 13 | numAsList.reverse() 14 | # convert back to a number 15 | numReversed = int(''.join(numAsList)) 16 | 17 | #wow, that was a nusience. But we reversed a number by going 18 | #number --> str --> list -- .reverse() --> strin --> int 19 | #are they identical? If so then numberToCheck is a palindrome. 20 | if(numberToCheck == numReversed): 21 | #Palindrome found. Return true 22 | return True 23 | else: 24 | return False 25 | 26 | #init our result 27 | highestKnownPalidrome = 0 28 | 29 | # We are looking for the largest product of 2, 3 digit numbers 30 | # Start with the 2 smallest 3 digit numbers and go up from there 31 | for i in range(100,1000): 32 | # Same, start at 100 and count up to 999 33 | for j in range(100,1000): 34 | #stash product of i and j 35 | currentProduct = i * j 36 | 37 | #see if our stashed var is a palidrome 38 | if ( amIAPalindrome(currentProduct)): 39 | # console.log(currentProduct) 40 | #Check if it's larger than highestKnownPalidrome and, if so, store it 41 | if ( currentProduct > highestKnownPalidrome ): 42 | highestKnownPalidrome = currentProduct 43 | print(highestKnownPalidrome) 44 | 45 | # print(highestKnownPalidrome) -------------------------------------------------------------------------------- /ninjas-vs-monsters/Background.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | 3 | class Background(): 4 | def __init__(self,screen,screen_size): 5 | self.screen = screen 6 | #grab our image off the hard drive and load it into pygame 7 | self.background_image = pygame.image.load('./images/background4.png') 8 | #change the size of the image 9 | #scale method! scale takes 2 args: 10 | #1. what to scale 11 | # 2.tuple of the new coords 12 | self.background_image = pygame.transform.scale(self.background_image,screen_size) 13 | self.background_rect = self.background_image.get_rect() 14 | # print(background_rect) 15 | 16 | def draw_bg(self,screen): 17 | #blit = block image transfer 18 | #blit takes 2 args: 19 | #1. what to draw 20 | #2. where to draw it (x,y coords which we get from get_rect) 21 | screen.blit(self.background_image,self.background_rect) -------------------------------------------------------------------------------- /ninjas-vs-monsters/GameButton.py: -------------------------------------------------------------------------------- 1 | import pygame.font 2 | 3 | class GameButton(): 4 | def __init__(self,screen,button_text,text_color, 5 | background_color,location_x,location_y, 6 | button_height,button_width,font_size, 7 | center_on_screen): 8 | self.screen = screen 9 | self.background_color = background_color 10 | self.text_color = text_color 11 | self.background_color = background_color 12 | 13 | self.font = pygame.font.Font(None,font_size) 14 | self.rect = pygame.Rect(0,0,button_width,button_height) 15 | if(center_on_screen): 16 | self.screen_rect = self.screen.get_rect() 17 | self.rect.center = self.screen_rect.center 18 | else: 19 | self.rect.x = location_x 20 | self.rect.y = location_y 21 | # msg_image calls render. Render is how pygame 22 | # takes text, and makes it into an "image" 23 | self.msg_image = self.font.render(button_text,True,text_color,background_color) 24 | # positioning stuff 25 | self.msg_image_rect = self.msg_image.get_rect() 26 | self.msg_image_rect.center = self.rect.center 27 | def draw_me(self): 28 | self.screen.blit(self.msg_image,self.msg_image_rect) 29 | def update_text(self,new_text): 30 | self.msg_image = self.font.render(new_text,True,self.text_color,self.background_color) 31 | 32 | -------------------------------------------------------------------------------- /ninjas-vs-monsters/Monster.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from image_load import monster_image_load 3 | from pygame.sprite import Sprite 4 | 5 | #monster is now a sub class of Sprite 6 | class Monster(Sprite): 7 | def __init__(self,random_monster): 8 | #run the constructor method for the Sprite (super class) 9 | super().__init__() 10 | # self.x = 1000 11 | # self.y = 200 12 | self.anim_image = 0 13 | self.image_type = "WALK" 14 | self.stop_attacking_at = False 15 | self.is_attacking = False 16 | self.should_move = True 17 | self.image_types = random_monster['images'] 18 | starter_image = self.image_types[self.image_type][self.anim_image] 19 | self.rect = starter_image.get_rect() 20 | self.rect.x = self.x #init the rect at the correct image position 21 | self.rect.y = self.y 22 | self.speed = random_monster['speed'] 23 | self.hp = random_monster['hp'] 24 | self.attack = random_monster['attack'] 25 | 26 | def draw_monster(self, screen, tick): 27 | cur_image = self.image_types[self.image_type][self.anim_image] 28 | cur_image_height = cur_image.get_height() 29 | if(self.should_move): 30 | #the monster only moves left... flip image 31 | #only time we flip 32 | self.x -= self.speed 33 | cur_image = pygame.transform.flip(cur_image,True,False) 34 | if(tick % 5 == 0): 35 | #anim_image only changes every 5 ticks 36 | self.anim_image += 1 37 | if(self.anim_image == 7): 38 | #we only have 0-9 images, so 10 is too far 39 | self.anim_image = 0 40 | #update the x on teh rect of the monster, to self.x 41 | self.rect.x = self.x 42 | # self.rect.y is what pygame uses to determine where to collide 43 | #self.y is where we manage his location, blit we can send either 44 | self.rect.y = self.y - cur_image_height 45 | #blit draws the monster 46 | screen.blit(cur_image,(self.x,self.rect.y)) 47 | 48 | def stop_and_attack(self): 49 | #set our bool to True 50 | self.is_attacking = True 51 | self.should_move = False 52 | #start the animation for attack 53 | self.image_type = "ATTAK" 54 | #start the attack animation from the beginning 55 | self.anim_image = 0 56 | 57 | def move_on(self): 58 | #move on means, stopped attacking, start walking 59 | self.is_attacking = False 60 | self.should_move = True 61 | self.image_type = "WALK" 62 | self.anim_image = 0 63 | 64 | def take_damage(self, player,player_score_button): 65 | #reduce monster health 66 | self.hp -= player.attack_power 67 | #check how much health monster has left 68 | if(self.hp <= 0): 69 | self.image_type = "DIE" 70 | self.anim_image = 0 #reset anim image to 0 71 | #0, change animation to dead 72 | #0, remove him from the group 73 | #0, player kill_counter += 1 74 | player.score += 1 75 | player_score_button.update_text(f"Monsters Taken Down: {player.score}") 76 | else: 77 | #monster has at least 1 health 78 | #1+, animate goes to hurt 79 | self.image_type = "HURT" 80 | self.anim_image = 0 #reset anim image to 0 -------------------------------------------------------------------------------- /ninjas-vs-monsters/Ork.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from Monster import Monster 3 | from image_load import monster_image_load 4 | import random 5 | 6 | class Ork(Monster): 7 | ork_images = { 8 | "ork1": monster_image_load("1_ORK","ork"), #CLASS VARIABLE 9 | "ork2": monster_image_load("2_ORK","ork"), 10 | "ork3": monster_image_load("3_ORK","ork"), 11 | } 12 | 13 | def __init__(self): 14 | display_info = pygame.display.Info() 15 | self.y = random.randint(50,display_info.current_h - 250) 16 | self.x = display_info.current_w - 50 17 | 18 | ork_stats = [{ 19 | "hp" : 20, 20 | "speed" : 1.2, 21 | "attack" : 3, 22 | "name" : "ork1", 23 | "images" : Ork.ork_images['ork1'], 24 | }, 25 | { 26 | "hp" : 25, 27 | "speed" : 1, 28 | "attack" : 3, 29 | "name" : "ork2", 30 | "images" : Ork.ork_images['ork2'], 31 | }, 32 | { 33 | "hp" : 15, 34 | "speed" : 1, 35 | "attack" : 4, 36 | "name" : "ork3", 37 | "images" : Ork.ork_images['ork3'], 38 | }] 39 | random_index = random.randint(0,2) 40 | random_ork = ork_stats[random_index] 41 | super().__init__(random_ork) -------------------------------------------------------------------------------- /ninjas-vs-monsters/Player.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from image_load import player_image_load 3 | from pygame.sprite import Sprite 4 | 5 | #images from https://opengameart.org/content/ninja-adventure-free-sprite 6 | class Player(Sprite): 7 | def __init__(self,screen): 8 | super().__init__() #call the Sprite super class constructor 9 | self.screen = screen 10 | self.x = 200 11 | self.y = 200 12 | self.attack_power = 5 13 | # anim_image is the number cooresponding to the number in the filename of the that image 14 | self.anim_image = 0 15 | self.image_type = "Idle" 16 | self.stop_attacking_at = False 17 | self.should_move_up = False 18 | self.should_move_down = False 19 | self.should_move_left = False 20 | self.should_move_right = False 21 | self.image_types = player_image_load() 22 | self.score = 0 23 | 24 | # print(self.image_types) 25 | #load the image from the hd 26 | self.image = pygame.image.load("./images/ninja/Idle__000.png") 27 | self.image = pygame.transform.scale_by(self.image,.35) 28 | #get the coords of the image 29 | self.rect = self.image.get_rect() 30 | # print(self.rect) 31 | def draw_player(self,screen,tick,display_info): 32 | # print(tick) 33 | #when we draw the player, we can decide 34 | #where the player should be 35 | if(self.should_move_up and self.y > 0): 36 | self.y -= 10 37 | elif(self.should_move_down and (self.y + self.rect.height) < display_info.current_h): 38 | self.y += 10 39 | ##cannot go up and down at the same time 40 | ##but can go left/right AND down/up at the same time 41 | ##so use 2 different if statements 42 | if(self.should_move_left and self.x > 0): 43 | self.x -= 10 44 | elif(self.should_move_right and (self.x + self.rect.width) < display_info.current_w): 45 | self.x += 10 46 | #the tick is updated everytime through the game loop 47 | #that is A LOT. We can use it to do "time things" 48 | if(tick % 5 == 0): 49 | #anim_image only changes every 5 ticks 50 | self.anim_image += 1 51 | if(self.anim_image == 10): 52 | #we only have 0-9 images, so 10 is too far 53 | self.anim_image = 0 54 | #check to see if the player is attacking, AND it's time to stop 55 | if(self.image_type == "Attack" and tick > self.stop_attacking_at): 56 | self.image_type = "Idle" #the attack is done. Go into idle 57 | #image_types is a dictionary of all possible image_types 58 | #image_type is a particular image_type such as run, idle, or attack 59 | #anim_image is a particular image of a particular image_type 60 | cur_image = self.image_types[self.image_type][self.anim_image] 61 | if(self.should_move_left): 62 | #the player is moving left... flip image 63 | #only time we flip 64 | cur_image = pygame.transform.flip(cur_image,True,False) 65 | #update the player rect based on self.x and self.y 66 | #we use self.x and self.y because it's simple numbers which are really, really fast 67 | self.rect.x = self.x 68 | self.rect.y = self.y 69 | #blit draws the player 70 | screen.blit(cur_image,(self.x,self.y)) 71 | def should_move(self, direction, move_or_not): 72 | #if the user is running, i.e. move_or_not is true 73 | #we want to set the image_type to run 74 | #BUT ONLY if the player is not in the middle of an attack 75 | if(self.image_type == "Attack"): 76 | #return will kill the function in its tracks 77 | return 78 | if(move_or_not): 79 | self.image_type = "Run" 80 | else: 81 | #if move_or_not is false then the user has 82 | #let go of an arrow key, and he should idle 83 | self.image_type = "Idle" 84 | if(direction == "up"): 85 | self.should_move_up = move_or_not 86 | elif(direction == "down"): 87 | self.should_move_down = move_or_not 88 | elif(direction == "left"): 89 | self.should_move_left = move_or_not 90 | elif(direction == "right"): 91 | self.should_move_right = move_or_not 92 | def attack(self,tick): 93 | #All things attack happen here... like, did we hit something? 94 | #set the image_type 95 | self.image_type = "Attack" 96 | #reset the animation_image to 0 because we want to start from the beginning 97 | self.anim_image = 0 98 | #how long does it take for an animation to complete? 99 | #we have 10 images. Each image lasts for 5 ticks 100 | #that means lock the player for 50 ticks 101 | self.stop_attacking_at = tick + 50 102 | def dead(self): 103 | self.image_type = "Dead" 104 | def jump(self): 105 | self.image_type = "Jump" -------------------------------------------------------------------------------- /ninjas-vs-monsters/Treasure.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | import random #use random to randomize our treasure type, also position 3 | 4 | class Treasure(pygame.sprite.Sprite): 5 | treasure_pile = pygame.image.load('./images/treasures.png') 6 | treasure_vase = pygame.image.load('./images/treasures_vase.png') 7 | treasure_pile = pygame.transform.scale_by(treasure_pile,.3) 8 | treasure_vase = pygame.transform.scale_by(treasure_vase,.3) 9 | treasures = [treasure_pile,treasure_vase] 10 | def __init__(self,display_info): 11 | random_treasure = Treasure.treasures[random.randint(0,1)] 12 | self.image = random_treasure 13 | self.rect = self.image.get_rect() 14 | self.x = 200 15 | self.y = random.randint(100,display_info.current_h - 100) 16 | self.rect.x = self.x #self.rect is for pygame, self.x is for us 17 | self.rect.y = self.y 18 | 19 | super().__init__() #this makes the constructor run in the super class 20 | def draw_me(self, screen): 21 | screen.blit(self.image,(self.x,self.y)) -------------------------------------------------------------------------------- /ninjas-vs-monsters/Troll.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from Monster import Monster 3 | from image_load import monster_image_load 4 | import random 5 | 6 | class Troll(Monster): 7 | 8 | #Any variable defined IN a class, but NOT in 9 | #a method, is a class variable. This is in contrast 10 | #with an instance variable. An instance variable 11 | #belongs specifically to an object. A class varaible 12 | #all objects of that class SHARE. 13 | #instance variables use self (in the class) 14 | troll_images = { 15 | "troll1": monster_image_load("1_TROLL","troll"), #CLASS VARIABLE 16 | "troll2": monster_image_load("2_TROLL","troll"), 17 | "troll3": monster_image_load("3_TROLL","troll"), 18 | } 19 | 20 | def __init__(self): 21 | display_info = pygame.display.Info() 22 | self.y = random.randint(50,display_info.current_h - 250) 23 | self.x = display_info.current_w - 50 24 | 25 | troll_stats = [{ 26 | "hp" : 10, 27 | "speed" : 3, 28 | "attack" : 2, 29 | "name" : "troll1", 30 | "images" : Troll.troll_images['troll1'], 31 | }, 32 | { 33 | "hp" : 15, 34 | "speed" : 2.4, 35 | "attack" : 3, 36 | "name" : "troll2", 37 | "images" : Troll.troll_images['troll2'] 38 | }, 39 | { 40 | "hp" : 20, 41 | "speed" : 2, 42 | "attack" : 4, 43 | "name" : "troll3", 44 | "images" : Troll.troll_images['troll3'] 45 | }] 46 | random_index = random.randint(0,2) 47 | random_troll = troll_stats[random_index] 48 | super().__init__(random_troll) -------------------------------------------------------------------------------- /ninjas-vs-monsters/check_events.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | 3 | def check_events(player,tick): 4 | #check to see if if any events occured since 5 | #the last time through the game loop 6 | #call the event we are on (out of possibly many) 7 | #"event" 8 | event_data = {"game_on" : True} 9 | for event in pygame.event.get(): 10 | # print(event) 11 | #check to see what event it was... 12 | if(event.type == pygame.QUIT): 13 | event_data["game_on"] = False 14 | elif(event.type == pygame.KEYDOWN): 15 | # the user pressed a key! 16 | # print(event.key) 17 | if(event.key == pygame.K_DOWN): 18 | # The user pressed the down arrow! 19 | print("User hit the down arrow") 20 | # move the player object in the 21 | # positive y direction 22 | # player.y += 10 23 | player.should_move("down",True) 24 | elif(event.key == pygame.K_UP): 25 | # The user pressed the up arrow! 26 | player.should_move("up",True) 27 | elif(event.key == pygame.K_RIGHT): 28 | # The user pressed the right arrow! 29 | player.should_move("right",True) 30 | elif(event.key == pygame.K_LEFT): 31 | # The user pressed the left arrow! 32 | player.should_move("left",True) 33 | elif(event.key == pygame.K_SPACE): 34 | #player hit the space bar... ATTACK! 35 | #it's not check_events job to mess with the player 36 | #that's the player's job. check_events lets the 37 | #player know what happened 38 | player.attack(tick) 39 | elif(event.key == pygame.K_d): 40 | #if "d" key is pressed, run dead animation 41 | player.dead() 42 | elif(event.key == pygame.K_j): 43 | #if "d" key is pressed, run jump animation 44 | player.jump() 45 | elif(event.type == pygame.KEYUP): 46 | #user released a key... what key is it? 47 | if(event.key == pygame.K_DOWN): 48 | #the down arrow! 49 | player.should_move("down",False) 50 | elif(event.key == pygame.K_UP): 51 | player.should_move("up",False) 52 | elif(event.key == pygame.K_LEFT): 53 | player.should_move("left",False) 54 | elif(event.key == pygame.K_RIGHT): 55 | player.should_move("right",False) 56 | return event_data -------------------------------------------------------------------------------- /ninjas-vs-monsters/game.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from update_screen import update_screen 3 | from Background import Background 4 | from Player import Player 5 | from check_events import check_events 6 | # from Monster import Monster 7 | from Troll import Troll 8 | from Ork import Ork 9 | import random 10 | from Treasure import Treasure 11 | from GameButton import GameButton 12 | 13 | clock = pygame.time.Clock() 14 | # print("Pygame successfully imported!") 15 | pygame.init() #initialize all the pygame stuff 16 | #get the display info... Info is a class! 17 | display_info = pygame.display.Info() 18 | screen_size = (1920, 1080) 19 | screen = pygame.display.set_mode(screen_size) 20 | game_on = True #a boolean for our game loop 21 | game_over_screen = False #boolean for game_over loop 22 | background = Background(screen, screen_size) 23 | player_score_button = GameButton( 24 | screen = screen, 25 | button_text = "Monsters Taken Down: 0", 26 | text_color = (255,255,255), 27 | background_color = None, 28 | location_x = 75, 29 | location_y = 25, 30 | button_height = 100, 31 | button_width = 200, 32 | font_size = 24, 33 | center_on_screen = False 34 | ) 35 | player = Player(screen) 36 | # troll = Monster() 37 | #a Group is a list-like thing in pygame 38 | #it holds Sprites 39 | monsters = pygame.sprite.Group() 40 | treasures = pygame.sprite.Group() 41 | treasures.add(Treasure(display_info),Treasure(display_info),Treasure(display_info),Treasure(display_info),Treasure(display_info)) 42 | tick = 0 43 | random_number = random.randint(0,1) 44 | if(random_number == 0): 45 | monsters.add(Troll()) #start the game with a monster 46 | else: 47 | monsters.add(Ork()) #start the game with a monster 48 | #this is the main game loop... run until quit 49 | while(game_on): 50 | tick += 1 51 | if(tick % 500 == 0): 52 | random_number = random.randint(0,1) 53 | #every 1000 ticks add a monster 54 | if(random_number == 0): 55 | monsters.add(Troll()) 56 | else: 57 | monsters.add(Ork()) 58 | #run check_events where we have moved all our event logic 59 | #check_events returns a dictionary, with a "game_on" key 60 | event_data = check_events(player,tick) 61 | game_on = event_data["game_on"] 62 | # screen.fill("red") #fill changes the color of the screen 63 | #run update_screen which is where we draw, and update stuff 64 | is_game_over = update_screen(screen = screen,player = player, background = background, tick = tick, display_info = display_info, monsters = monsters, treasures=treasures,player_score_button=player_score_button) 65 | if(is_game_over): 66 | game_on = False 67 | game_over_screen = True 68 | clock.tick(60) #the number is the fps (frame per second) 69 | pygame.display.flip() #DRAW OUR STUFF 70 | 71 | # another "game" loop 72 | game_over_button = GameButton(screen = screen, 73 | button_text = "Game Over!", 74 | text_color = (255,255,255), 75 | background_color = (0,0,0), 76 | location_x = 100, 77 | location_y = 100, 78 | button_height = 100, 79 | button_width = 200, 80 | font_size = 36, 81 | center_on_screen = True) 82 | while(game_over_screen): 83 | game_over_button.draw_me() 84 | for event in pygame.event.get(): 85 | if(event.type == pygame.QUIT): 86 | game_over_screen = False #this gives Python a way out 87 | pygame.display.flip() -------------------------------------------------------------------------------- /ninjas-vs-monsters/image_load.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | 3 | def player_image_load(): 4 | image_types = { 5 | "Attack" : [], 6 | "Dead" : [], 7 | "Idle" : [], 8 | "Jump" : [], 9 | "Jump_Attack" : [], 10 | "Jump_Throw" : [], 11 | "Run" : [], 12 | "Slide" : [], 13 | "Throw" : [], 14 | } 15 | 16 | for image_type in image_types: 17 | for i in range(0,10): 18 | image_to_load = pygame.image.load(f"./images/ninja/{image_type}__00{i}.png") 19 | image_to_load = pygame.transform.scale_by(image_to_load,.35) 20 | image_types[image_type].append(image_to_load) 21 | return image_types 22 | 23 | def monster_image_load(monster_name,type): 24 | image_types = { 25 | "ATTAK" : [], 26 | "DIE" : [], 27 | "IDLE" : [], 28 | "HURT" : [], 29 | "JUMP" : [], 30 | "RUN" : [], 31 | "WALK" : [], 32 | } 33 | for image_type in image_types: 34 | for i in range(0,7): 35 | image_to_load = pygame.image.load(f"./images/{monster_name}/{image_type}/{image_type}_00{i}.png") 36 | factor_to_scale_by = .35 37 | if(type == "ork"): 38 | factor_to_scale_by = .2 39 | image_to_load = pygame.transform.scale_by(image_to_load,factor_to_scale_by) 40 | image_types[image_type].append(image_to_load) 41 | return image_types -------------------------------------------------------------------------------- /ninjas-vs-monsters/images.md: -------------------------------------------------------------------------------- 1 | - [Game Background - https://opengameart.org/content/background-texture-for-a-board-game](https://opengameart.org/content/background-texture-for-a-board-game) 2 | - [ninja boy - https://opengameart.org/content/ninja-adventure-free-sprite](https://opengameart.org/content/ninja-adventure-free-sprite) 3 | - [ninja girl - https://opengameart.org/content/ninja-girl-free-sprite](https://opengameart.org/content/ninja-girl-free-sprite) 4 | - [trolls - https://opengameart.org/content/2d-game-trolls-sprite](https://opengameart.org/content/2d-game-trolls-sprite) 5 | - [orcs - https://opengameart.org/content/2d-game-orcs-sprite](https://opengameart.org/content/2d-game-orcs-sprite) 6 | - [treasure - https://opengameart.org/content/golden-treasures](https://opengameart.org/content/golden-treasures) 7 | - [zombie - https://opengameart.org/content/zombie-punk-character-sprite](https://opengameart.org/content/zombie-punk-character-sprite) 8 | - [shiny items - https://opengameart.org/content/shining-coin-shining-health-shining-power-up-sprite-sheets](https://opengameart.org/content/shining-coin-shining-health-shining-power-up-sprite-sheets) 9 | - [more zombies - https://opengameart.org/content/zombie-character-sprite](https://opengameart.org/content/zombie-character-sprite) 10 | - [reaper - https://opengameart.org/content/reaper-man-chibi-sprites](https://opengameart.org/content/reaper-man-chibi-sprites) 11 | - [ogre/goblin - https://opengameart.org/content/orc-ogre-and-goblin-chibi-sprites](https://opengameart.org/content/orc-ogre-and-goblin-chibi-sprites) 12 | - [A UI Sample - https://opengameart.org/content/free-fantasy-game-gui](https://opengameart.org/content/free-fantasy-game-gui) 13 | - [Another bg Example - https://opengameart.org/content/post-apocalyptic-pixel-art-backgrounds](https://opengameart.org/content/post-apocalyptic-pixel-art-backgrounds) 14 | 15 | 16 | -------------------------------------------------------------------------------- /ninjas-vs-monsters/images/background4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/robertbunch/pythonBlitzInTen/b46531905b89560d8d124b241c490d3ebbc9fd27/ninjas-vs-monsters/images/background4.png -------------------------------------------------------------------------------- /ninjas-vs-monsters/images/treasures.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/robertbunch/pythonBlitzInTen/b46531905b89560d8d124b241c490d3ebbc9fd27/ninjas-vs-monsters/images/treasures.png -------------------------------------------------------------------------------- /ninjas-vs-monsters/images/treasures_vase.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/robertbunch/pythonBlitzInTen/b46531905b89560d8d124b241c490d3ebbc9fd27/ninjas-vs-monsters/images/treasures_vase.png -------------------------------------------------------------------------------- /ninjas-vs-monsters/ork_and_troll_starter_stats.py: -------------------------------------------------------------------------------- 1 | troll_stats = [{ 2 | "hp" : 10, 3 | "speed" : 3, 4 | "attack" : 2, 5 | "name" : "troll1", 6 | "images" : Troll.troll_images['troll1'], 7 | }, 8 | { 9 | "hp" : 15, 10 | "speed" : 2.4, 11 | "attack" : 3, 12 | "name" : "troll2", 13 | "images" : Troll.troll_images['troll2'] 14 | }, 15 | { 16 | "hp" : 20, 17 | "speed" : 2, 18 | "attack" : 4, 19 | "name" : "troll3", 20 | "images" : Troll.troll_images['troll3'] 21 | }] 22 | 23 | ork_stats = [{ 24 | "hp" : 20, 25 | "speed" : 1.2, 26 | "attack" : 3, 27 | "name" : "ork1", 28 | "images" : Ork.ork_images['ork1'], 29 | }, 30 | { 31 | "hp" : 25, 32 | "speed" : 1, 33 | "attack" : 3, 34 | "name" : "ork2", 35 | "images" : Ork.ork_images['ork2'], 36 | }, 37 | { 38 | "hp" : 15, 39 | "speed" : 1, 40 | "attack" : 4, 41 | "name" : "ork3", 42 | "images" : Ork.ork_images['ork3'], 43 | }] -------------------------------------------------------------------------------- /ninjas-vs-monsters/update_screen.py: -------------------------------------------------------------------------------- 1 | from pygame.sprite import spritecollide 2 | from pygame.sprite import groupcollide 3 | 4 | #this function is in charge of updating stuff 5 | #on the screen 6 | 7 | def update_screen(screen,player,background,tick,display_info,monsters,treasures,player_score_button): 8 | background.draw_bg(screen) 9 | 10 | #collision detection! 11 | #spritecollide takes 3 args: 12 | #1. the sprite to collide wtih 13 | #2. the group to collide with the sprite 14 | #3. should the sprite in the group, be removed on collision 15 | #retrun value is all sprites in teh group that were collided with 16 | hit_monsters = spritecollide(player,monsters,False) 17 | for monster in hit_monsters: 18 | # print("monster collided with!") 19 | #stop the monster from moving 20 | #start attacking/hurt/die animation 21 | #take and cause damage 22 | if(monster.image_type == "WALK"): 23 | #only run stop_and_attack if teh monster is NOT attacking already 24 | monster.stop_and_attack() 25 | elif(player.image_type == "Attack" and player.anim_image == 0 and tick % 5 == 0): 26 | #the player is attacking and the monster is colliding. 27 | # Take damage! But only if the player is on the first animation 28 | #and the first animation is on the first tick 29 | monster.take_damage(player,player_score_button) 30 | #second loop, handles animations 31 | for monster in monsters: 32 | if(monster.image_type == "DIE" and monster.anim_image == 6): 33 | #monster is done with teh game :) remove him 34 | monsters.remove(monster) #remove from spriteGroup 35 | elif(monster.image_type == "HURT" and monster.anim_image == 6): 36 | #monster is done being hurt. Move back to attack 37 | monster.stop_and_attack() 38 | elif(monster.image_type == "ATTAK" and monster not in hit_monsters): 39 | #for all the monsters that WERE attacking, but are 40 | #no longer colliding, we need to start them up again 41 | #this monster is a NON collided with monster 42 | #and this monster IS attacking 43 | #We need to start him moving again 44 | monster.move_on() 45 | treasure_hit = groupcollide(treasures,monsters,True,False) 46 | if(treasure_hit): 47 | # some treasure was hit! 48 | # print("A treasure was taken!") 49 | return True #let game.py know that the game is over 50 | for monster in monsters: 51 | monster.draw_monster(screen, tick) 52 | for treasure in treasures: 53 | treasure.draw_me(screen) 54 | player_score_button.draw_me() 55 | player.draw_player(screen,tick,display_info) 56 | return 57 | -------------------------------------------------------------------------------- /projectEuler/erasSieve.py: -------------------------------------------------------------------------------- 1 | 2 | known_primes = [2,3] 3 | i = 4 4 | while(len(known_primes) < 10001): 5 | is_prime = True 6 | for a_prime in known_primes: 7 | # print(i,a_prime,i % a_prime) 8 | if(i % a_prime == 0): 9 | is_prime = False 10 | break 11 | if(is_prime): 12 | known_primes.append(i) 13 | i += 1 14 | 15 | print(known_primes) -------------------------------------------------------------------------------- /projectEuler/pe1.py: -------------------------------------------------------------------------------- 1 | # Answer: 233168 2 | import time 3 | #create a point in time as our start. Then go... 4 | start_time = time.time() 5 | 6 | # If we list all the natural numbers below 10 that are multiples of 3 or 5, 7 | # we get 3, 5, 6,and 9. The sum of these multiples is 23. 8 | ## natural numbers = non-negative integers. 1-9, integers 9 | 10 | # Find the sum of all the multiples of 3 or 5 below 1000. 11 | sum_total = 0 #init sum of our multiples if 3 or 5 12 | for i in range(1,1000): 13 | #is i divisible (evenly) by 3 or 5 14 | if(i % 3 == 0 or i % 5 == 0): 15 | #it is a match! 16 | sum_total += i 17 | # print(f"{i} is divisible by 3 or 5") 18 | print(sum_total) 19 | 20 | #ridiculous 1 line answer 21 | x = sum([n for n in range(1,1000) if n % 3 == 0 or n % 5 == 0]) 22 | print(x) 23 | print(f"--- Number of seconds to solve {time.time() - start_time}") -------------------------------------------------------------------------------- /projectEuler/pe10.py: -------------------------------------------------------------------------------- 1 | import time 2 | #answer: 142913828922 3 | # The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. 4 | # Find the sum of all the primes below two million. 5 | 6 | # the goal of the sieve is to mark off the numbers that aren't prime 7 | # because they are factors of a prime. We don't need to store them 8 | # like we did in problem 7, we just need to know if it's prime or not 9 | # if it is: 10 | # sum it 11 | # mark every factor up to our number as false, starting with the square 12 | # if it's not, just move on 13 | # This means that our algorithm isn't looking for primes, it's just 14 | # looking to see if this number has been marked by the time we get to it 15 | # if it hasn't then it's prime, and do a little addition, do our marking 16 | 17 | start_time = time.time() #get our starting time 18 | 19 | def sieveOfEra(upperLimit): 20 | # we need to init our list of 2million numbers. We will put True 21 | # in each index 22 | primes = [True] * upperLimit 23 | # print(len(primes)) 24 | sum = 0 #sum is our running total. start at 0 25 | counter = 0 26 | # we will a loop to start at 2, and keep going as long as we are 27 | # below the upperlimit 28 | for i in range(2,upperLimit): 29 | counter += 1 30 | # check to see if i is prime 31 | if(primes[i]): 32 | # this is prime! Add it 33 | sum += i 34 | # go hunting for multiples to mark False 35 | for j in range(i**2,upperLimit,i): 36 | counter += 1 37 | primes[j] = False 38 | print(sum) 39 | print(counter) 40 | 41 | sieveOfEra(2000000) 42 | end_time = time.time() #get our ending time 43 | print(f"--- Number of seconds to solve {time.time() - start_time}") 44 | 45 | # =================pe7====================== 46 | start_time = time.time() #get our starting time 47 | 48 | #known_primes is where we keep all our known prime # 49 | #once we hit 10001, we have our answer! 50 | #2 and 3 are always prime in this universe, start there 51 | known_primes = [2,3] 52 | num_to_check = 4 #start at 4 and go until we have 10k primes 53 | sum = 0 54 | counter = 0 55 | while(num_to_check < 2000000): 56 | is_prime = True #assume the number is True, until we find it's not 57 | #loop through all numbers from 2 to num_to_check and % for 0 58 | 59 | #we do NOT need to check for all numbers between 2 and num_to_check 60 | #we only need to check for prime numbers 61 | # for i in range(2,num_to_check): #brute force check 62 | for i in known_primes: 63 | # print(i) 64 | counter += 1 65 | if(num_to_check % i == 0): 66 | #this is NOT prime 67 | is_prime = False #bool set to false 68 | break #this will STOP the for loop, no reason to keep going 69 | if(is_prime): 70 | #this number went all the way through and had no factors. 71 | known_primes.append(num_to_check) 72 | sum += i 73 | num_to_check += 1 74 | 75 | print(sum) 76 | print(counter) 77 | 78 | end_time = time.time() #get our ending time 79 | print(f"--- Number of seconds to solve {time.time() - start_time}") -------------------------------------------------------------------------------- /projectEuler/pe11.py: -------------------------------------------------------------------------------- 1 | import time 2 | start_time = time.time() #get our starting time 3 | # Answer: 70600674 4 | 5 | bad_grid = ''' 6 | 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 7 | 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 8 | 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 9 | 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 10 | 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 11 | 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 12 | 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 13 | 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 14 | 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 15 | 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 16 | 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 17 | 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 18 | 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 | 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 20 | 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 21 | 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 22 | 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 23 | 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 24 | 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 25 | 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48''' 26 | 27 | # strip removes all extra stuff on either side 28 | # split will convert each row into an index in the new list 29 | grid = bad_grid.strip().split('\n') #\n is computer speak for new line 30 | for i in range(0,len(grid)): 31 | # split will convert each number in the row, into an index 32 | formatted_row = grid[i].split(' ') 33 | for j in range(0,len(formatted_row)): 34 | formatted_row[j] = int(formatted_row[j]) 35 | grid[i] = formatted_row 36 | 37 | largest_prod = 0 38 | largest_numbers = [] # keep track of the numbers that make largest_prod 39 | counter = 0 #keep track of numbers/operations we do 40 | 41 | #horizontal 42 | for row in range(0,len(grid)): 43 | #grab the row 44 | for col in range(0,len(grid[row])): 45 | counter += 1 #keep track of each new 1-4 digit product 46 | #grab the col/number index 47 | current_numbers = [] 48 | current_product = 1 49 | #max_offset = the number we can safely multiply 50 | max_offset = len(grid[row]) - col 51 | if(max_offset > 4): 52 | max_offset = 4 53 | for i in range(0,max_offset): 54 | curr_number = grid[row][col + i] #always use this row, but the next col in the loop 55 | current_product *= curr_number 56 | current_numbers.append(curr_number) #keep track of our current numbres in case it is the biggest! 57 | if(current_product > largest_prod): 58 | largest_prod = current_product 59 | largest_numbers = current_numbers 60 | print(f"Found a new largest product: {largest_prod} - {largest_numbers}") 61 | 62 | 63 | #vertical 64 | for row in range(0,len(grid)): 65 | #grab the row 66 | for col in range(0,len(grid[row])): 67 | counter += 1 #keep track of each new 1-4 digit product 68 | #grab the col/number index 69 | current_numbers = [] 70 | current_product = 1 71 | #max_offset = the number we can safely multiply 72 | max_offset = len(grid[row]) - row 73 | if(max_offset > 4): 74 | max_offset = 4 75 | for i in range(0,max_offset): 76 | curr_number = grid[row + i][col] #always use this row, but the next col in the loop 77 | current_product *= curr_number 78 | current_numbers.append(curr_number) #keep track of our current numbres in case it is the biggest! 79 | if(current_product > largest_prod): 80 | largest_prod = current_product 81 | largest_numbers = current_numbers 82 | print(f"Found a new largest product: {largest_prod} - {largest_numbers}") 83 | 84 | ##Diag to the right 85 | for row in range(0,len(grid)): 86 | #grab the row 87 | for col in range(0,len(grid[row])): 88 | counter += 1 #keep track of each new 1-4 digit product 89 | #grab the col/number index 90 | current_numbers = [] 91 | current_product = 1 92 | #max_offset = the number we can safely multiply 93 | max_offset_row = len(grid[row]) - col 94 | max_offset_col = len(grid[row]) - row 95 | if(max_offset_row < max_offset_col): 96 | max_offset = max_offset_row 97 | else: 98 | max_offset = max_offset_col 99 | if(max_offset > 4): 100 | max_offset = 4 101 | for i in range(0,max_offset): 102 | curr_number = grid[row + i][col + i] #always use this row, but the next col in the loop 103 | current_product *= curr_number 104 | current_numbers.append(curr_number) #keep track of our current numbres in case it is the biggest! 105 | if(i < 3 and row == 17): 106 | print(current_numbers) 107 | if(current_product > largest_prod): 108 | largest_prod = current_product 109 | largest_numbers = current_numbers 110 | print(f"Found a new largest product: {largest_prod} - {largest_numbers}") 111 | 112 | ##Diag to the Left 113 | for row in range(0,len(grid)): 114 | #grab the row 115 | for col in range(0,len(grid[row])): 116 | counter += 1 #keep track of each new 1-4 digit product 117 | #grab the col/number index 118 | current_numbers = [] 119 | current_product = 1 120 | #max_offset = the number we can safely multiply 121 | max_offset_row = len(grid[row]) - (len(grid[row]) - col) 122 | max_offset_col = len(grid[row]) - row 123 | if(max_offset_row < max_offset_col): 124 | max_offset = max_offset_row 125 | else: 126 | max_offset = max_offset_col 127 | if(max_offset > 4): 128 | max_offset = 4 129 | for i in range(0,max_offset): 130 | curr_number = grid[row + i][col - i] #always use this row, but the next col in the loop 131 | current_product *= curr_number 132 | current_numbers.append(curr_number) #keep track of our current numbres in case it is the biggest! 133 | if(i < 3 and row == 17): 134 | print(current_numbers) 135 | if(current_product > largest_prod): 136 | largest_prod = current_product 137 | largest_numbers = current_numbers 138 | print(f"Found a new largest product: {largest_prod} - {largest_numbers}") 139 | 140 | 141 | print(counter) 142 | 143 | end_time = time.time() #get our ending time 144 | print(f"--- Number of seconds to solve {time.time() - start_time}") 145 | -------------------------------------------------------------------------------- /projectEuler/pe12.py: -------------------------------------------------------------------------------- 1 | import time 2 | start_time = time.time() #get our starting time 3 | import math 4 | # Answer: 76576500 5 | # The sequence of triangle numbers is generated by adding 6 | # the natural numbers. So the 7th triangle number would be 7 | # 1+2+3+4+5+6+7 = 28. The first ten terms would be: 8 | # 1,3,6,10,15,21,28,36,45,55,... 9 | 10 | # Let us list the factors of the first seven triangle numbers: 11 | 12 | # 1: 1 13 | # 2: 3: 1, 3 14 | # 3: 6: 1, 2, 3, 6 15 | # 10: 1, 2, 5, 10 16 | # 15: 1, 3, 5, 15 17 | # 21: 1, 3, 7, 21 18 | # 28: 1, 2, 4, 7, 14, 28 19 | # We can see that 28 is the first triangle number to have over five divisors. 20 | 21 | def get_factors(tri): 22 | #we KNOW that 1 and the number are divisors 23 | factor_list =[1,tri] 24 | tri_sq_root = math.floor(math.sqrt(tri)) 25 | for i in range(2,tri_sq_root): 26 | if(tri % i == 0): 27 | #this is a divisor! add it to the list 28 | factor_list.append(i) 29 | #we need the number ABOVE the sq. root 30 | factor_list.append(tri / i) 31 | return factor_list 32 | 33 | #init factor_list so we can use it 34 | factor_list = [] 35 | #init tri sequence 36 | tri_sequence_num = 0 37 | #init tri value 38 | tri_value = 0 39 | #getting the next tri number until we have 500 divisors 40 | # while(len(factor_list) < 500): 41 | while(len(factor_list) < 500): 42 | # the 7th number is 28, 6 divisors 43 | tri_sequence_num += 1 44 | #we can get the next number by adding the old number 45 | #with the new sequence number 46 | tri_value += tri_sequence_num 47 | factor_list = get_factors(tri_value) 48 | print(f"factor sequence: {tri_sequence_num}, tri value: {tri_value}, factors: {factor_list}") 49 | 50 | end_time = time.time() #get our ending time 51 | print(f"--- Number of seconds to solve {time.time() - start_time}") 52 | 53 | -------------------------------------------------------------------------------- /projectEuler/pe13.py: -------------------------------------------------------------------------------- 1 | import time 2 | start_time = time.time() #get our starting time 3 | # Work out the first ten digits of the sum of the 4 | # following one-hundred 50-digit numbers 5 | # Answer: 5537376230 6 | 7 | num_string = ''' 8 | 37107287533902102798797998220837590246510135740250 9 | 46376937677490009712648124896970078050417018260538 10 | 74324986199524741059474233309513058123726617309629 11 | 91942213363574161572522430563301811072406154908250 12 | 23067588207539346171171980310421047513778063246676 13 | 89261670696623633820136378418383684178734361726757 14 | 28112879812849979408065481931592621691275889832738 15 | 44274228917432520321923589422876796487670272189318 16 | 47451445736001306439091167216856844588711603153276 17 | 70386486105843025439939619828917593665686757934951 18 | 62176457141856560629502157223196586755079324193331 19 | 64906352462741904929101432445813822663347944758178 20 | 92575867718337217661963751590579239728245598838407 21 | 58203565325359399008402633568948830189458628227828 22 | 80181199384826282014278194139940567587151170094390 23 | 35398664372827112653829987240784473053190104293586 24 | 86515506006295864861532075273371959191420517255829 25 | 71693888707715466499115593487603532921714970056938 26 | 54370070576826684624621495650076471787294438377604 27 | 53282654108756828443191190634694037855217779295145 28 | 36123272525000296071075082563815656710885258350721 29 | 45876576172410976447339110607218265236877223636045 30 | 17423706905851860660448207621209813287860733969412 31 | 81142660418086830619328460811191061556940512689692 32 | 51934325451728388641918047049293215058642563049483 33 | 62467221648435076201727918039944693004732956340691 34 | 15732444386908125794514089057706229429197107928209 35 | 55037687525678773091862540744969844508330393682126 36 | 18336384825330154686196124348767681297534375946515 37 | 80386287592878490201521685554828717201219257766954 38 | 78182833757993103614740356856449095527097864797581 39 | 16726320100436897842553539920931837441497806860984 40 | 48403098129077791799088218795327364475675590848030 41 | 87086987551392711854517078544161852424320693150332 42 | 59959406895756536782107074926966537676326235447210 43 | 69793950679652694742597709739166693763042633987085 44 | 41052684708299085211399427365734116182760315001271 45 | 65378607361501080857009149939512557028198746004375 46 | 35829035317434717326932123578154982629742552737307 47 | 94953759765105305946966067683156574377167401875275 48 | 88902802571733229619176668713819931811048770190271 49 | 25267680276078003013678680992525463401061632866526 50 | 36270218540497705585629946580636237993140746255962 51 | 24074486908231174977792365466257246923322810917141 52 | 91430288197103288597806669760892938638285025333403 53 | 34413065578016127815921815005561868836468420090470 54 | 23053081172816430487623791969842487255036638784583 55 | 11487696932154902810424020138335124462181441773470 56 | 63783299490636259666498587618221225225512486764533 57 | 67720186971698544312419572409913959008952310058822 58 | 95548255300263520781532296796249481641953868218774 59 | 76085327132285723110424803456124867697064507995236 60 | 37774242535411291684276865538926205024910326572967 61 | 23701913275725675285653248258265463092207058596522 62 | 29798860272258331913126375147341994889534765745501 63 | 18495701454879288984856827726077713721403798879715 64 | 38298203783031473527721580348144513491373226651381 65 | 34829543829199918180278916522431027392251122869539 66 | 40957953066405232632538044100059654939159879593635 67 | 29746152185502371307642255121183693803580388584903 68 | 41698116222072977186158236678424689157993532961922 69 | 62467957194401269043877107275048102390895523597457 70 | 23189706772547915061505504953922979530901129967519 71 | 86188088225875314529584099251203829009407770775672 72 | 11306739708304724483816533873502340845647058077308 73 | 82959174767140363198008187129011875491310547126581 74 | 97623331044818386269515456334926366572897563400500 75 | 42846280183517070527831839425882145521227251250327 76 | 55121603546981200581762165212827652751691296897789 77 | 32238195734329339946437501907836945765883352399886 78 | 75506164965184775180738168837861091527357929701337 79 | 62177842752192623401942399639168044983993173312731 80 | 32924185707147349566916674687634660915035914677504 81 | 99518671430235219628894890102423325116913619626622 82 | 73267460800591547471830798392868535206946944540724 83 | 76841822524674417161514036427982273348055556214818 84 | 97142617910342598647204516893989422179826088076852 85 | 87783646182799346313767754307809363333018982642090 86 | 10848802521674670883215120185883543223812876952786 87 | 71329612474782464538636993009049310363619763878039 88 | 62184073572399794223406235393808339651327408011116 89 | 66627891981488087797941876876144230030984490851411 90 | 60661826293682836764744779239180335110989069790714 91 | 85786944089552990653640447425576083659976645795096 92 | 66024396409905389607120198219976047599490197230297 93 | 64913982680032973156037120041377903785566085089252 94 | 16730939319872750275468906903707539413042652315011 95 | 94809377245048795150954100921645863754710598436791 96 | 78639167021187492431995700641917969777599028300699 97 | 15368713711936614952811305876380278410754449733078 98 | 40789923115535562561142322423255033685442488917353 99 | 44889911501440648020369068063960672322193204149535 100 | 41503128880339536053299340368006977710650566631954 101 | 81234880673210146739058568557934581403627822703280 102 | 82616570773948327592232845941706525094512325230608 103 | 22918802058777319719839450180888072429661980811197 104 | 77158542502016545090413245809786882778948721859617 105 | 72107838435069186155435662884062257473692284509516 106 | 20849603980134001723930671666823555245252804609722 107 | 53503534226472524250874054075591789781264330331690''' 108 | 109 | #see problem 11 110 | parsed_list = num_string.strip().split("\n") 111 | sum = 0 112 | for num in parsed_list: 113 | sum += int(num) 114 | # print(sum) 115 | sum_as_string = str(sum) 116 | print(sum_as_string[0:10]) 117 | 118 | end_time = time.time() #get our ending time 119 | print(f"--- Number of seconds to solve {time.time() - start_time}") 120 | -------------------------------------------------------------------------------- /projectEuler/pe14.py: -------------------------------------------------------------------------------- 1 | import time 2 | start_time = time.time() #get our starting time 3 | # The following iterative sequence is defined for the set 4 | # of positive integers: 5 | # n -> n/2 (n is even) 6 | # n -> 3n + 1 (n is odd) 7 | # Using the rule above and starting with 13, we generate 8 | # the following sequence: 9 | # 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1. 10 | # 2:1 11 | # 3:7 12 | # 4:2 13 | # 5:5 14 | # 6:8 15 | # 7:13 16 | 17 | # It can be seen that this sequence (starting at 18 | # and finishing at 13 and ending at 1) contains 19 | # 10 terms. Although it has not been proved yet 20 | # (Collatz Problem), it is thought that all starting 21 | # numbers finish at 1. 22 | 23 | # Which starting number, under one million, produces 24 | # the longest chain? 25 | 26 | # NOTE: Once the chain starts the terms are allowed to go 27 | # above one million. 28 | # answer: 837799 29 | 30 | # init our winners 31 | top_num = 0 32 | top_num_chain_count = 0 33 | known_nums = {} 34 | for i in range(2,1000000): 35 | #i needs to stay in the sequence 36 | #cur_num starts at i, then we change it 37 | cur_num = i 38 | cur_num_chain_count = 0 39 | while(cur_num > 1): 40 | if(cur_num in known_nums): 41 | #we have solved this before! Just add the total 42 | cur_num_chain_count += known_nums[cur_num] 43 | cur_num = 1 #end the while 44 | else: 45 | if(cur_num % 2 == 0): 46 | #this number is even! 47 | cur_num /= 2 48 | else: 49 | #odd number 50 | cur_num = (cur_num * 3) + 1 51 | cur_num_chain_count += 1 52 | if(cur_num_chain_count > top_num_chain_count): 53 | #we have a new winner! 54 | top_num = i #not the cur_num, because it will be 1 55 | top_num_chain_count = cur_num_chain_count 56 | known_nums[i] = cur_num_chain_count 57 | print(top_num) 58 | print(top_num_chain_count) 59 | 60 | end_time = time.time() #get our ending time 61 | print(f"--- Number of seconds to solve {time.time() - start_time}") 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /projectEuler/pe15.js: -------------------------------------------------------------------------------- 1 | // Node/JavaScript version 2 | // 137846528820 3 | function findRoutes(gridSize){ 4 | // console.log(gridSize) 5 | let routeMatrix = []; 6 | for(let i = 1; i <= gridSize; i++){ 7 | routeMatrix.push(1); 8 | } 9 | console.log(routeMatrix) 10 | 11 | for(let i = 1; i <= gridSize; i++){ 12 | for(let j = 1; j < gridSize; j++){ 13 | routeMatrix[j] = routeMatrix[j] + routeMatrix[j-1]; 14 | } 15 | console.log(routeMatrix) 16 | 17 | routeMatrix[i] = 2 * routeMatrix[i-1]; 18 | } 19 | console.log(routeMatrix) 20 | return routeMatrix[gridSize] 21 | } 22 | 23 | 24 | console.time('grid') 25 | gridSize = 3; 26 | n = findRoutes(gridSize); 27 | console.log(n) 28 | console.timeEnd('grid') -------------------------------------------------------------------------------- /projectEuler/pe15.py: -------------------------------------------------------------------------------- 1 | import time 2 | start_time = time.time() #get our starting time 3 | # [ 4 | # [1,1,1], 5 | # [1,2,3], 6 | # [1,3,6] 7 | # ] 8 | # Answer: 137,846,528,820 9 | 10 | def find_routes(grid_size): 11 | grid = [] 12 | # grid = [[1] * grid_size] * grid_size WONT WORK!! 13 | for i in range(0,grid_size): 14 | grid.append([1] * grid_size) 15 | # grid[2][2] = 5 #test memory 16 | for i in range(0,grid_size): 17 | for j in range(0,grid_size): 18 | if(i == 0 or j == 0): 19 | #we are in the 1st row or 1st col 20 | #just put a 1 21 | grid[i][j] = 1 22 | else: 23 | number_above = grid[i-1][j] 24 | number_left = grid[i][j-1] 25 | grid[i][j] = number_above + number_left 26 | for row in grid: 27 | print(row) 28 | return grid[grid_size - 1][grid_size - 1] 29 | 30 | #21 = 21 points, so a 20 sided grid 31 | grid_size = 21 32 | answer = find_routes(grid_size) #3 = a 2x2 grid! 33 | print(f"Answer for a {grid_size - 1} x {grid_size - 1} is: {answer}") 34 | 35 | end_time = time.time() #get our ending time 36 | print(f"--- Number of seconds to solve {time.time() - start_time}") 37 | -------------------------------------------------------------------------------- /projectEuler/pe16.py: -------------------------------------------------------------------------------- 1 | import time 2 | start_time = time.time() #get our starting time 3 | # Answer: 1366 4 | # 2^15 is 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26 5 | # What is the sum of the digits of the number 2^1000 6 | 7 | # this is 2 to the 1000th power... 302 digits 8 | big_num = str(2**1000) #convert the integer into a string 9 | sum = 0 10 | for letter in big_num: 11 | sum += int(letter) 12 | print(sum) 13 | 14 | end_time = time.time() #get our ending time 15 | print(f"--- Number of seconds to solve {time.time() - start_time}") 16 | -------------------------------------------------------------------------------- /projectEuler/pe17.py: -------------------------------------------------------------------------------- 1 | import time 2 | start_time = time.time() #get our starting time 3 | # Answer: 21124 4 | 5 | # 1-9... we use these A LOT 6 | digits = [ 7 | "one","two","three","four","five", 8 | "six","seven","eight","nine" 9 | ] 10 | # 10-19 which we only use once per 100 11 | unique_numbers = ["ten","eleven","twelve","thirteen", 12 | "fourteen","fifteen","sixteen","seventeen", 13 | "eighteen","nineteen"] 14 | 15 | # multiples of ten, used once every 100 16 | tens = ["twenty","thirty","forty","fifty","sixty", 17 | "seventy","eighty","ninety"] 18 | 19 | number_list = digits + unique_numbers 20 | 21 | 22 | for t in tens: 23 | number_list.append(t) 24 | for d in digits: 25 | # grab the digit and stick it on the end of ten 26 | number_list.append(t+d) 27 | 28 | # our 100s - we use digit + "hundred" 29 | for h in digits: 30 | this_hundred = h+"hundred" 31 | number_list.append(this_hundred) #"onhundred" or "twohundred" 32 | # grab the first 99 numbers and put this_hundred on the front 33 | for num in range(0,99): 34 | this_num = this_hundred + "and" + number_list[num] 35 | number_list.append(this_num) 36 | # add onethousand 37 | number_list.append("onethousand") 38 | 39 | # for num in number_list: 40 | # print(num) 41 | 42 | count = 0 43 | for word in number_list: 44 | count += len(word) 45 | 46 | print(count) 47 | 48 | end_time = time.time() #get our ending time 49 | print(f"--- Number of seconds to solve {time.time() - start_time}") 50 | -------------------------------------------------------------------------------- /projectEuler/pe18.py: -------------------------------------------------------------------------------- 1 | import time 2 | start_time = time.time() #get our starting time 3 | 4 | # Answer: 1074 5 | # Find the maximum total from top to bottom of the triangle below: 6 | 7 | triangle = '''75 8 | 95 64 9 | 17 47 82 10 | 18 35 87 10 11 | 20 04 82 47 65 12 | 19 01 23 75 03 34 13 | 88 02 77 73 07 63 67 14 | 99 65 04 28 06 16 70 92 15 | 41 41 26 56 83 40 80 70 33 16 | 41 48 72 33 47 32 37 16 94 29 17 | 53 71 44 65 25 43 91 52 97 51 14 18 | 70 11 33 28 77 73 17 78 39 68 17 57 19 | 91 71 52 38 17 14 91 43 58 50 27 29 48 20 | 63 66 04 68 89 53 67 30 73 16 69 87 40 31 21 | 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23 22 | ''' 23 | 24 | parsed_tri = triangle.strip().split('\n') 25 | # convert each row into a list or integers 26 | for i in range(0,len(parsed_tri)): 27 | # create our rows 28 | parsed_tri[i] = parsed_tri[i].strip().split(' ') 29 | for j in range(0,len(parsed_tri[i])): 30 | # convert each col into an int (from a str) 31 | parsed_tri[i][j] = int(parsed_tri[i][j]) 32 | 33 | # start at the 2nd to last row in parsed_tri list 34 | start_tri_row = len(parsed_tri) - 2 35 | 36 | # row loop 37 | for i in range(start_tri_row,-1,-1): 38 | # loop backwards from 14, until 0 and stop at -1 39 | # decrament by each time through 40 | for j in range(0,i+1): #i+1 because the next row has 1 more col than this one 41 | down_left = parsed_tri[i+1][j] 42 | down_right = parsed_tri[i+1][j+1] 43 | if(down_left > down_right): 44 | parsed_tri[i][j] += down_left 45 | else: 46 | parsed_tri[i][j] += down_right 47 | 48 | for row in parsed_tri: 49 | print(row) 50 | 51 | end_time = time.time() #get our ending time 52 | print(f"--- Number of seconds to solve {time.time() - start_time}") 53 | -------------------------------------------------------------------------------- /projectEuler/pe19.py: -------------------------------------------------------------------------------- 1 | import time 2 | start_time = time.time() #get our starting time 3 | # Answer: 171 4 | # You are given the following information, but you may prefer to do some research for yourself. 5 | 6 | # 1 Jan 1900 was a Monday. 7 | # Thirty days has September, 8 | # April, June and November. 9 | # All the rest have thirty-one, 10 | # Saving February alone, 11 | # Which has twenty-eight, rain or shine. 12 | # And on leap years, twenty-nine. 13 | # A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. 14 | # How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? 15 | 16 | def get_num_days(month,year): 17 | if(month == 2): 18 | #this is feb. is it a leap year? 19 | if(year % 400 == 0): 20 | #this is a century leap year 21 | return 29 22 | elif(year % 4 == 0 and year % 100 != 0): 23 | # this is a non-century leap year 24 | return 29 25 | else: 26 | # this is a non-leap feb 27 | return 28 28 | else: 29 | return months[month] 30 | 31 | #0 in index 1 so January can be index 1 32 | months = [0,31,28,31,30,31,30,31,31,30,31,30,31] 33 | day_of_week = 2 #Sunday = 1, Monday = 2, etc. 34 | number_of_sundays = 0 #init final answer 35 | 36 | #year loop 37 | for year in range(1900,2001): 38 | #is this a leap year 39 | for month in range(1,13): 40 | num_days_in_month = get_num_days(month, year) 41 | # print("year: ",year," month: ",month,"-",num_days_in_month) 42 | if(day_of_week == 1 and year != 1900): 43 | # this is a sunday! and the first day of this month 44 | number_of_sundays += 1 45 | for date in range(1,num_days_in_month+1): 46 | # reset day of week to 1 if we were on 7, others incrament by 1 47 | day_of_week = 1 if day_of_week == 7 else day_of_week + 1 48 | 49 | print(number_of_sundays) 50 | 51 | end_time = time.time() #get our ending time 52 | print(f"--- Number of seconds to solve {time.time() - start_time}") 53 | -------------------------------------------------------------------------------- /projectEuler/pe19b.py: -------------------------------------------------------------------------------- 1 | import time 2 | start_time = time.time() #get our starting time 3 | # Answer: 171 4 | # You are given the following information, but you may prefer to do some research for yourself. 5 | 6 | # 1 Jan 1900 was a Monday. 7 | # Thirty days has September, 8 | # April, June and November. 9 | # All the rest have thirty-one, 10 | # Saving February alone, 11 | # Which has twenty-eight, rain or shine. 12 | # And on leap years, twenty-nine. 13 | # A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. 14 | # How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? 15 | 16 | def get_num_days(month,year): 17 | if(month == 2): 18 | #this is feb. is it a leap year? 19 | if(year % 400 == 0): 20 | #this is a century leap year 21 | return 29 22 | elif(year % 4 == 0 and year % 100 != 0): 23 | # this is a non-century leap year 24 | return 29 25 | else: 26 | # this is a non-leap feb 27 | return 28 28 | else: 29 | return months[month] 30 | 31 | #0 in index 0 so January can be index 1 32 | months = [0,31,28,31,30,31,30,31,31,30,31,30,31] 33 | day_of_week = 2 #Sunday = 1, Monday = 2, etc. 34 | number_of_sundays = 0 #init final answer 35 | sundays_by_year = {} 36 | 37 | #year loop - we only need to check every 28 years, becaues the calendar repeats 38 | for year in range(1900,1929): 39 | sundays_by_year[year] = 0 40 | #is this a leap year 41 | for month in range(1,13): 42 | num_days_in_month = get_num_days(month, year) 43 | # print("year: ",year," month: ",month,"-",num_days_in_month) 44 | if(day_of_week == 1): 45 | # this is a sunday! and the first day of this month 46 | sundays_by_year[year] += 1 47 | if(year != 1900): number_of_sundays += 1 48 | for date in range(1,num_days_in_month+1): 49 | # reset day of week to 1 if we were on 7, others incrament by 1 50 | day_of_week = 1 if day_of_week == 7 else day_of_week + 1 51 | 52 | for year in range(1929,2001): 53 | sundays_by_year[year] = sundays_by_year[year - 28] 54 | number_of_sundays += sundays_by_year[year] 55 | 56 | print(number_of_sundays) 57 | print(sundays_by_year) 58 | 59 | end_time = time.time() #get our ending time 60 | print(f"--- Number of seconds to solve {time.time() - start_time}") 61 | -------------------------------------------------------------------------------- /projectEuler/pe2.py: -------------------------------------------------------------------------------- 1 | # Answer: 4613732 2 | # Each new term in the Fibonacci sequence is generated 3 | # by adding the previous two terms. By starting with 4 | # 1 and 2, the first 10 terms will be: 5 | # 1,2,3,5,8,13,21,34,55,89 6 | # By considering the terms in the Fibonacci sequence 7 | # whose values do not exceed four million, find the 8 | # sum of the even-valued terms. 9 | 10 | import time 11 | #create a point in time as our start. Then go... 12 | start_time = time.time() 13 | 14 | sum_of_evens = 2 15 | fib1 = 1 16 | fib2 = 2 17 | newFib = 0 18 | while(fib1 + fib2 < 4000000): 19 | #if we are inside this while loop, then the next 20 | #number in fib is less than 4M 21 | newFib = fib1+fib2 22 | fib1 = fib2 23 | fib2 = newFib 24 | if(fib2 % 2 == 0): 25 | #if so, this is even and in the sequence. Add it! 26 | sum_of_evens += fib2 27 | 28 | print(sum_of_evens) 29 | print(f"--- Number of seconds to solve {time.time() - start_time}") -------------------------------------------------------------------------------- /projectEuler/pe20.py: -------------------------------------------------------------------------------- 1 | import math 2 | import time 3 | start_time = time.time() #get our starting time 4 | # Answer: 648 5 | 6 | sum_total = 0 #init answer 7 | big_num = str(math.factorial(100)) #this is 100! as a string 8 | print((big_num)) 9 | for digit in big_num: 10 | sum_total += int(digit) 11 | print(sum_total) 12 | end_time = time.time() #get our ending time 13 | print(f"--- Number of seconds to solve {time.time() - start_time}") 14 | 15 | # the one line answer 16 | func_total = sum(map(int,str(math.factorial(100)))) 17 | print(func_total) -------------------------------------------------------------------------------- /projectEuler/pe20Simple.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | sum = 0 4 | x = str(math.factorial(100)) 5 | for num in x: 6 | sum += int(num) 7 | print(sum) 8 | -------------------------------------------------------------------------------- /projectEuler/pe21.py: -------------------------------------------------------------------------------- 1 | import math 2 | import time 3 | start_time = time.time() #get our starting time 4 | # Answer: 31626 5 | 6 | # Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into ). 7 | # If d(a) = b and d(b) = a, where a != b, then a and b are an amicable pair and each of a and b are called amicable numbers. 8 | 9 | # For example, the proper divisors of 220 are 1,2,4,5,10,11,20,22,44,55,and 110; 10 | # therefore d(220) = 284. The proper divisors of 284 are 1,2,4,,71, and 142; so d(284) = 220. 11 | 12 | # Evaluate the sum of all the amicable numbers under 10000. 13 | 14 | limit = 10000 #limit is how high we are going to look 15 | factors = [1] * limit 16 | # print(factors) 17 | for i in range(2, limit): 18 | # what are i's divisors 19 | for j in range(2, int(math.sqrt(i))): 20 | if(i % j == 0): 21 | # this is a divisor! 22 | factors[i] += j #the smaller divisor 23 | factors[i] += int(i/j) #this will be the bigger divisor 24 | 25 | # for i, value in enumerate(factors): 26 | # print(i,":",value) 27 | 28 | # find the pairs! 29 | an_sum = 0 30 | for index1 in range(2,limit): 31 | value1 = factors[index1] 32 | # we are lookign for pairs 33 | # one value will always be higher than the index 34 | # and the other index will be higher than the value 35 | if(value1 < index1): 36 | index2 = value1 37 | value2 = factors[index2] 38 | if(value2 == index1): 39 | # this is a match 40 | an_sum += index1 + value1 41 | print(an_sum) 42 | 43 | end_time = time.time() #get our ending time 44 | print(f"--- Number of seconds to solve {time.time() - start_time}") 45 | 46 | ############################# 47 | # Sieve solution 48 | start_time = time.time() #get our starting time 49 | factors = [1] * limit 50 | # we mutliply every possible combo of numbers that 51 | # have a product of less than 10000. 52 | for i in range(2,int(math.sqrt(i))): 53 | for j in range(i,int(limit/i)): 54 | factors[i*j] += i + j 55 | 56 | # find the pairs! 57 | an_sum = 0 58 | for index1 in range(2,limit): 59 | value1 = factors[index1] 60 | # we are lookign for pairs 61 | # one value will always be higher than the index 62 | # and the other index will be higher than the value 63 | if(value1 < index1): 64 | index2 = value1 65 | value2 = factors[index2] 66 | if(value2 == index1): 67 | # this is a match 68 | an_sum += index1 + value1 69 | print(an_sum) 70 | 71 | end_time = time.time() #get our ending time 72 | print(f"--- Number of seconds to solve {time.time() - start_time}") 73 | -------------------------------------------------------------------------------- /projectEuler/pe22.py: -------------------------------------------------------------------------------- 1 | import time 2 | from radixPE22 import radix_sort 3 | start_time = time.time() #get our starting time 4 | # Answer: 871198282 5 | 6 | # opening our file for reading 7 | names_file = open('./names.txt') 8 | # read file into a string and split into a list 9 | names = names_file.read().split(',') 10 | names_file.close() #good practice 11 | # parse our list so the " are gone! 12 | names = [name.strip('"') for name in names] 13 | 14 | # for name in names: 15 | # print(name) 16 | 17 | sorted_names = radix_sort(names) 18 | # sorted_names = sorted(names) #sorted is the default python sort 19 | 20 | sum = 0 #our answer! 21 | # loop through each name and find the value of the char 22 | for i, name in enumerate(sorted_names): 23 | this_name_val = 0 #init this name char value 24 | # loop through the char in this name 25 | for char in name: 26 | # A = 1, B = 2, C = 3, ... we use A as our 27 | # base, and offset by it, +1 28 | this_name_val += ord(char) - ord('A') + 1 29 | sum += this_name_val * (i + 1) 30 | print(sum) 31 | 32 | 33 | end_time = time.time() #get our ending time 34 | print(f"--- Number of seconds to solve {time.time() - start_time}") 35 | 36 | -------------------------------------------------------------------------------- /projectEuler/pe23.py: -------------------------------------------------------------------------------- 1 | import time 2 | import math 3 | start_time = time.time() #get our starting time 4 | # Answer: 4179871 5 | 6 | # Problem: 7 | # DISTRACTION - perfect numbers 8 | # A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be: 9 | # 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. 10 | 11 | # Half distraction - deficient is irrelevant 12 | # A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n. 13 | 14 | # As 12 is the smallest abundant number, 1+2+3+4+6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. 15 | # By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. 16 | # However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit. 17 | 18 | # Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers. 19 | 20 | # Wow. That was wordy. 21 | # Job 1: Find all abundant numbers with the sieve from 21 (really, really fast) 22 | # Job 1b: To do that, we find all proper divisors for every number under our limit 23 | # Job 1c: We don't need to keep all divisors, just add them as we go 24 | # Job 2: Sum every abundant number with every number above it and whatever the sum is, is not in final list 25 | # Job 2b: We can break out of our loop when the sum breaks the limit because we know nothing above that will work 26 | # Job 3: Sum up whatever numbers are left over 27 | 28 | limit = 28123 29 | factors = [1] * limit 30 | # we mutliply every possible combo of numbers that 31 | # have a product of less than our limit. 32 | for i in range(2,math.ceil(math.sqrt(limit))): 33 | for j in range(i,int(limit/i)): 34 | if(i == j): 35 | # this is the sq root. only add it one time 36 | factors[i*j] += i 37 | else: 38 | # add both numbers/divisors 39 | factors[i*j] += i + j 40 | 41 | # factors now contains the sum of all proper divisers of every number below our limit 42 | 43 | abundant_numbers = [] 44 | for i,num in enumerate(factors): 45 | if(num > i): 46 | #this is abundant! Add it to our list 47 | abundant_numbers.append(i) 48 | 49 | # we have all the abundant numbers in our list, + the number 0 at the beginning 50 | abundant_numbers.pop(0) #get rid of 0 at the beginning. It was there to make the code simpler 51 | # print(abundant_numbers[0:10]) 52 | 53 | # assume that all numbers qualify (they dont), remove them when we find a sum 54 | non_abundant_numbers = [num for num in range(limit)] 55 | for i in range(len(abundant_numbers)): 56 | # outer loop is the lower number 57 | for j in range(i,len(abundant_numbers)): 58 | # inner loop is teh upper number 59 | lower_number = abundant_numbers[i] 60 | higher_number = abundant_numbers[j] 61 | sum_of_numbers = lower_number + higher_number 62 | if(sum_of_numbers < limit): 63 | # this number does NOT qualify 64 | # clear out that number from our non_abundant_numbers 65 | non_abundant_numbers[sum_of_numbers] = 0 66 | else: 67 | # we dont need to keep going. We are too high 68 | break 69 | 70 | print(sum(non_abundant_numbers)) 71 | 72 | end_time = time.time() #get our ending time 73 | print(f"--- Number of seconds to solve {time.time() - start_time}") -------------------------------------------------------------------------------- /projectEuler/pe25.py: -------------------------------------------------------------------------------- 1 | import time 2 | start_time = time.time() #get our starting time 3 | # Answer 4782 4 | # Find the index of the first fib number with 1000 digits 5 | 6 | num1 = 1 #first number in the sequence 7 | num2 = 1 #second number in the sequence 8 | count = 2 #the first 2 numbers are 1 9 | while(len(str(num2)) < 1000): 10 | # loop until the new/bigger number has fewer than 1000 digits 11 | new_num = num1 + num2 #next number in the sequence 12 | num1 = num2 #update num1 to be what num2 was 13 | num2 = new_num #num2 is now the new sum 14 | count += 1 15 | print(count) 16 | print(num2) 17 | 18 | end_time = time.time() #get our ending time 19 | print(f"--- Number of seconds to solve {time.time() - start_time}") 20 | 21 | # 1070066266382758936764980584457396885083683896632151665013235203375314520604694040621889147582489792657804694888177591957484336466672569959512996030461262748092482186144069433051234774442750273781753087579391666192149259186759553966422837148943113074699503439547001985432609723067290192870526447243726117715821825548491120525013201478612965931381792235559657452039506137551467837543229119602129934048260706175397706847068202895486902666185435124521900369480641357447470911707619766945691070098024393439617474103736912503231365532164773697023167755051595173518460579954919410967778373229665796581646513903488154256310184224190259846088000110186255550245493937113651657039447629584714548523425950428582425306083544435428212611008992863795048006894330309773217834864543113205765659868456288616808718693835297350643986297640660000723562917905207051164077614812491885830945940566688339109350944456576357666151619317753792891661581327159616877487983821820492520348473874384736771934512787029218636250627816 -------------------------------------------------------------------------------- /projectEuler/pe26.py: -------------------------------------------------------------------------------- 1 | import time 2 | start_time = time.time() #get our starting time 3 | 4 | num = longest = 1 5 | # 1/n is going to produce 1 of 3 decimals 6 | # if it is divisible by only primes 2 and 5, it terminates 7 | # if it is divisible by primes that aren't 2 or 5, it is 8 | # repeats 9 | # if it is divisible by primes 2 and 5 and something else, it 10 | # will have the same cycle as another number from #2 11 | # this means we don't need to check any numbers that are divisible 12 | # by 2 or 5! Eliniating half, and then another 10% 13 | # Can simulate hand division 14 | def long_division(denom): 15 | keep_looping = True 16 | dec_digits = [] 17 | remainders = [] 18 | cur_num = 10 #always at least 10 19 | # make sure that our cur_num is big enough for our first operation 20 | while cur_num < denom: 21 | cur_num *= 10 22 | dec_digits.append(0) 23 | while (keep_looping): 24 | # store the digit without decimal, and the remainder 25 | digit = cur_num // denom 26 | cur_num = cur_num % denom 27 | if cur_num == 0: #terminated. End function 28 | # print(denominator,"Terminates") 29 | return 0 #we will optimize in a bit 30 | if(cur_num in remainders): 31 | return len(remainders) 32 | else: 33 | # add the digit and remainder to the list 34 | dec_digits.append(digit) 35 | remainders.append(cur_num) 36 | # bump up the new number by adding a 0 37 | cur_num *= 10 38 | 39 | largest_denom = 0 40 | largest_sequence = 0 41 | for denominator in range(3, 1000,2): 42 | recurr_cycle = long_division(denominator) 43 | # print(denominator,cycle_lengths,largest_sequence) 44 | if(recurr_cycle > largest_sequence): 45 | largest_sequence = recurr_cycle 46 | largest_denom = denominator 47 | print(largest_denom,largest_sequence) 48 | 49 | end_time = time.time() #get our ending time 50 | print(f"--- Number of seconds to solve {time.time() - start_time}") 51 | -------------------------------------------------------------------------------- /projectEuler/pe3.py: -------------------------------------------------------------------------------- 1 | import time 2 | import math 3 | # The prime factors of 13195 are 5,7,13, and 29. 4 | 5 | # What is the largest prime factor of the number 6 | # 600,851,475,143? 7 | # Answer is 6857 8 | 9 | start_time = time.time() 10 | big_num = 600851475143 11 | # 5 seconds 12 | # 50 13 | # 500 14 | # 5000 15 | # 50000 = 13 hours 16 | 17 | # big_num = 13195 18 | list_of_prime_factors = [] 19 | 20 | def am_i_prime(i): 21 | is_prime = True #assume the number is prime until we find it's not 22 | #is this number, which is a factor, prime? 23 | for n in range(2,i): 24 | #check if i % n is 0. If so... NOT prime 25 | if(i % n == 0): 26 | is_prime = False 27 | break #no reason to keep checking. It's not prime 28 | return is_prime 29 | 30 | 31 | #find all the factors of big_num 32 | top_num = math.floor(math.sqrt(big_num)) + 1 33 | for i in range(2,top_num): 34 | #is it a factor? Use % 35 | if(big_num % i == 0): 36 | #this is a factor! Get it's pair 37 | j = math.floor(big_num / i) 38 | # Find out if it is prime 39 | is_this_factor_prime = am_i_prime(i) 40 | # print(f"{i} - {is_this_factor_prime}") 41 | if(is_this_factor_prime): 42 | list_of_prime_factors.append(i) 43 | is_this_factor_prime = am_i_prime(j) 44 | if(is_this_factor_prime): 45 | list_of_prime_factors.append(j) 46 | # print(f"{j} - {is_this_factor_prime}") 47 | 48 | print(list_of_prime_factors) 49 | 50 | end_time = time.time() 51 | print(f"--- number of secodns to solve... {end_time - start_time}" ) -------------------------------------------------------------------------------- /projectEuler/pe4.py: -------------------------------------------------------------------------------- 1 | import time 2 | # Answer: 906609 3 | # A palindromic number reads the same both ways. 4 | # The largest palindrome made from the product of 5 | # two 2-digit numbers is 9009 = 91 × 99. 6 | # Find the largest palindrome made from the product 7 | # of two 3-digit numbers. 8 | 9 | #our goal is to multply every combo of 3 digit numbers 10 | #loop from 100 - 999, and multiply times 11 | #loop from 100 - 999. This means we will have 12 | # 900*900 = 810,000... but Python will smile 13 | start_time = time.time() 14 | highest_palindrome = 0 15 | highest_palindrome_as_list = [] 16 | 17 | def am_i_a_palindrome(number_to_check): 18 | #reverse method is very nice 19 | #but... reverse is a list method 20 | #cannot cast number -> list 21 | #but we cann cast number -> string -> list 22 | number_as_string = str(number_to_check) 23 | number_as_list = list(number_as_string) 24 | #reverse method is a list method that reverses the indicies 25 | number_as_list.reverse() 26 | # print(f"{number_as_list} {number_to_check}") 27 | #cast number_as_list into a string, then a number 28 | num_reversed = int(''.join(number_as_list)) 29 | # print(f"{number_to_check} - {num_reversed}") 30 | return number_to_check == num_reversed 31 | 32 | for num1 in range(100,1000): #outer loop = num1 33 | #we dont have to check 100->1000 for the inner loop 34 | #every time. we just have to check from num1 to 1000 35 | #because we already checked everything below num1 36 | #on the way up 37 | for num2 in range(num1,1000): 38 | #product = the result of multiplication 39 | product = num1 * num2 40 | #now... find is this a pal 41 | pal_check = am_i_a_palindrome(product) 42 | if(pal_check): 43 | highest_palindrome_as_list.append(product) 44 | if(product > highest_palindrome): 45 | highest_palindrome = product 46 | 47 | # print(highest_palindrome_as_list) 48 | print(highest_palindrome) 49 | end_time = time.time() 50 | print(f"--- number of secodns to solve... {end_time - start_time}" ) -------------------------------------------------------------------------------- /projectEuler/pe5.py: -------------------------------------------------------------------------------- 1 | import time 2 | # Answer: 232,792,560 (232792560) 3 | # 2520 is the smallest number that can be divided by each 4 | # of the numbers 1 to 10 from to without any remainder. 5 | 6 | # What is the smallest positive number that is evenly 7 | # divisible by all of the numbers from 1 to 20 ? 8 | 9 | start_time = time.time() #get our starting time 10 | 11 | def is_divisible_by_1_through_20(num): 12 | # for i in range(1,21): 13 | #we are sending numbers by the 20, so we don't have to 14 | # check 20. We also don't have to check 1 because all 15 | # numbers are divisible by 1 16 | # for i in range(2,20): 17 | # if we check in reverse order, we can break out of 18 | # #function sooner, because less numebrs are divisible 19 | # by 19 than by 2 20 | # for i in range(19,1,-1): 21 | #we dont need to check for numbers that are multiples 22 | #of a number in the list 23 | #2 is a mutliple of 4 24 | #4 is a multiple of 8 and 8 is of 16 25 | # factors_list = [11,12,13,14,15,16,17,18,19] 26 | for i in range(11,20): 27 | if(num % i != 0): 28 | #this is NOT a winner. It is missing a number 29 | return False #end our function 30 | #if we make it this far, then ALL 20 numbers worked. REturn true 31 | return True 32 | 33 | #bool that will keep our loop going until we find an answer 34 | not_found = True 35 | number_to_check = 20 #this is our number we hope is the answer... if not, inc 36 | while(not_found): 37 | answer_found = is_divisible_by_1_through_20(number_to_check) 38 | if(answer_found): 39 | #we have a winner! Stop the loop, and print 40 | not_found = False 41 | else: 42 | #not the answer... incrament number_to_check 43 | #bump it up by one. 44 | number_to_check += 20 45 | 46 | print(number_to_check) #this is the answer! 47 | end_time = time.time() #get our ending time 48 | print(f"--- Number of seconds to solve {time.time() - start_time}") -------------------------------------------------------------------------------- /projectEuler/pe6.py: -------------------------------------------------------------------------------- 1 | import time 2 | #answer: 25164150 3 | # The sum of the squares of the first ten natural numbers 4 | # is 1^2 + 2^2 + 3^2... = 385 5 | # The square of the sum of the first ten natural numbers 6 | # is (1 + 2 + 3 + 4...)^2 == 55^2 = 3025, 7 | # Hence the difference between the sum of the squares 8 | # of the first ten natural numbers and the square of the 9 | # sum is 3025 - 385 = 2640. 10 | # Find the difference between the sum of the squares of 11 | # the first one hundred natural numbers and the square 12 | # of the sum. 13 | 14 | start_time = time.time() #get our starting time 15 | sum_of_squares = 0 16 | sum_for_squaring = 0 17 | 18 | #we need a loop for our number to keep track of 19 | for i in range(1,101): 20 | sum_of_squares += i ** 2 #sum the squares 21 | sum_for_squaring += i #sum the numbers 22 | sum_squared = sum_for_squaring ** 2 23 | print(sum_squared - sum_of_squares) 24 | 25 | end_time = time.time() #get our ending time 26 | print(f"--- Number of seconds to solve {time.time() - start_time}") -------------------------------------------------------------------------------- /projectEuler/pe7.py: -------------------------------------------------------------------------------- 1 | import time 2 | #answer: 104743 3 | 4 | start_time = time.time() #get our starting time 5 | 6 | #known_primes is where we keep all our known prime # 7 | #once we hit 10001, we have our answer! 8 | #2 and 3 are always prime in this universe, start there 9 | known_primes = [2,3] 10 | num_to_check = 4 #start at 4 and go until we have 10k primes 11 | 12 | while(len(known_primes) < 10001): 13 | is_prime = True #assume the number is True, until we find it's not 14 | #loop through all numbers from 2 to num_to_check and % for 0 15 | 16 | #we do NOT need to check for all numbers between 2 and num_to_check 17 | #we only need to check for prime numbers 18 | # for i in range(2,num_to_check): #brute force check 19 | for i in known_primes: 20 | if(num_to_check % i == 0): 21 | #this is NOT prime 22 | is_prime = False #bool set to false 23 | break #this will STOP the for loop, no reason to keep going 24 | if(is_prime): 25 | #this number went all the way through and had no factors. 26 | known_primes.append(num_to_check) 27 | num_to_check += 1 28 | 29 | print(known_primes[-1]) 30 | 31 | end_time = time.time() #get our ending time 32 | print(f"--- Number of seconds to solve {time.time() - start_time}") -------------------------------------------------------------------------------- /projectEuler/pe8.py: -------------------------------------------------------------------------------- 1 | # answer: 23514624000 2 | import time 3 | #Problem 4 | # The four adjacent digits in the 1000-digit number that have the greatest product are 9 * 9 * 8 * 9 = 5832. 5 | # Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product? 6 | #substring version 7 | start_time = time.time() #get our starting time 8 | 9 | num = 7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450 10 | num_as_str = str(num) #cast the int into a str 11 | # num_as_list = list(num_as_str) #cast the str/int into a list 12 | 13 | high_product = 0 #this is the number we are looking for! 14 | low_index = 0 15 | high_index = 13 16 | 17 | while(high_index < 1001): 18 | this_product = 1 #we need a place to keep the product for THIS number 19 | spliced_string = num_as_str[low_index:high_index] 20 | # print(spliced_string) 21 | #optimization 1: if there is a 0, don't bother. it's not going to be higher 22 | if('0' not in spliced_string): 23 | for digit in spliced_string: 24 | this_product *= int(digit) 25 | if(this_product > high_product): 26 | high_product = this_product 27 | low_index += 1 28 | high_index += 1 29 | 30 | print(high_product) 31 | 32 | end_time = time.time() #get our ending time 33 | print(f"--- Number of seconds to solve {time.time() - start_time}") 34 | 35 | ###optiization 2 which is actually slower :) 36 | ###take the current 13 digit product and divide by the 1st number 37 | ###that will give us the 12 digits product, then multiply times the 38 | ###new number 39 | 40 | start_time = time.time() #get our starting time 41 | num = 7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450 42 | num_as_string = str(num) 43 | 44 | highest_product = 1 45 | init_spliced_segment = (num_as_string[0:13]) 46 | for num in init_spliced_segment: 47 | highest_product *= int(num) 48 | 49 | low_index = 1 50 | high_index = 13 #not 14, because this isn't a range, its an index 51 | last_product = highest_product 52 | 53 | while(high_index < 1000): 54 | new_number = int(num_as_string[high_index]) 55 | previous_first_number = int(num_as_string[low_index-1]) 56 | # print(previous_first_number,new_number) 57 | if(last_product == 0): #will include previous_first_number as 0 58 | new_int = num_as_string[low_index:high_index+1] 59 | this_product = 1 60 | for i in new_int: 61 | this_product *= int(i) 62 | elif(new_number == 0): 63 | this_product = 0 64 | else: 65 | this_product = int(last_product / previous_first_number) * new_number 66 | if(this_product > highest_product): 67 | highest_product = this_product 68 | low_index += 1 69 | high_index += 1 70 | last_product = this_product 71 | print(highest_product) 72 | 73 | end_time = time.time() #get our ending time 74 | print(f"--- Number of seconds to solve as swap old with new {time.time() - start_time}") 75 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /projectEuler/pe8_starter.py: -------------------------------------------------------------------------------- 1 | # answer: 23514624000 2 | import time 3 | #Problem 4 | # The four adjacent digits in the 1000-digit number that have the greatest product are 9 * 9 * 8 * 9 = 5832. 5 | # Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product? 6 | #substring version 7 | start_time = time.time() #get our starting time 8 | 9 | num = 7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450 10 | 11 | end_time = time.time() #get our ending time 12 | print(f"--- Number of seconds to solve {time.time() - start_time}") 13 | -------------------------------------------------------------------------------- /projectEuler/pe9.py: -------------------------------------------------------------------------------- 1 | import time 2 | # A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, 3 | # a^2 + b^2 = c^2 4 | # For example, 3^2 + 4^2 = 9 + 16 = 5^2 = 25. 5 | 6 | # There exists exactly one Pythagorean triplet for which a + b + c = 1000. 7 | # Find the product of a*b*c. 8 | # Answer: 31875000 9 | 10 | start_time = time.time() #get our starting time 11 | def find_triplet(): 12 | count = 0 13 | #try all numbers between 1 and 1000 for a and b 14 | for a in range(1,1000): 15 | for b in range(1,1000): 16 | count += 1 17 | c = 1000 - a - b #solve for c 18 | if(a*a + b*b == c*c): 19 | print(f"Counter ran: {count}") 20 | print(a,b,c) 21 | return(a*b*c) 22 | answer = find_triplet() 23 | print(answer) 24 | end_time = time.time() #get our ending time 25 | print(f"--- Number of seconds to solve {time.time() - start_time}") 26 | 27 | 28 | # ==============opt1================ 29 | start_time = time.time() #get our starting time 30 | def find_triplet(): 31 | count = 0 32 | #try all numbers between 1 and 1000 for a and b 33 | for a in range(1,333): #a cannot be bigger than 332 or there won't be room in 1000 for b and c 34 | for b in range(a+1,1000): #b must be larger than a 35 | count += 1 36 | c = 1000 - a - b #solve for c 37 | if(a*a + b*b == c*c): 38 | print(f"Counter ran: {count}") 39 | print(a,b,c) 40 | return(a*b*c) 41 | answer = find_triplet() 42 | print(answer) 43 | end_time = time.time() #get our ending time 44 | print(f"--- Number of seconds to solve {time.time() - start_time}") 45 | 46 | 47 | # ==============opt2================ 48 | start_time = time.time() #get our starting time 49 | def find_triplet(): 50 | count = 0 51 | #try all numbers between 1 and 1000 for a and b 52 | for a in range(1,333): #a cannot be bigger than 332 or there won't be room in 1000 for b and c 53 | for b in range(a+1,500): #b must be larger than a, b must also be less than c, with a max of 500 or there won't be room for c 54 | count += 1 55 | c = 1000 - a - b #solve for c 56 | if(a*a + b*b == c*c): 57 | print(f"Counter ran: {count}") 58 | print(a,b,c) 59 | return(a*b*c) 60 | answer = find_triplet() 61 | print(answer) 62 | end_time = time.time() #get our ending time 63 | print(f"--- Number of seconds to solve {time.time() - start_time}") 64 | -------------------------------------------------------------------------------- /projectEuler/radixPE22.py: -------------------------------------------------------------------------------- 1 | def bucket_sorter(list,char_position): 2 | # make our 26 + 1 buckets 3 | buckets = [[] for i in range(27)] 4 | # go through each word and grab the letter at char_position 5 | # and put it in the right bucket 6 | result = [] #this is going to contain all the words that are still on a ' ' 7 | for word in list: 8 | if(word[char_position] == ' '): 9 | # this is a blank. It goes in the first bucket (list) 10 | result.append(word) 11 | else: 12 | bucket_index = ord(word[char_position]) - ord('A') 13 | # print(bucket_index) 14 | buckets[bucket_index].append(word) 15 | # print(buckets) 16 | # step 2 is concat our buckets into 1 list 17 | 18 | for bucket in buckets: 19 | result += bucket #concat all the buckets onto the first 20 | return result 21 | def radix_sort(list_to_sort): 22 | # get the longest element 23 | longest = max(len(str) for str in list_to_sort) 24 | # print(longest) 25 | # pad all the strings shorter than "longest" 26 | list_to_sort = [str.ljust(longest,' ') for str in list_to_sort] 27 | # print(list_to_sort) 28 | # loop through the characters one at a time, and bucket 29 | for i in range(longest - 1, -1, -1): 30 | list_to_sort = bucket_sorter(list_to_sort,i) 31 | # print(list_to_sort) 32 | sorted_list_without_pad = [word.strip() for word in list_to_sort] 33 | return sorted_list_without_pad 34 | -------------------------------------------------------------------------------- /projectEuler/radixSort.py: -------------------------------------------------------------------------------- 1 | import time 2 | start_time = time.time() #get our starting time 3 | 4 | def bucket_sorter(list,char_position): 5 | # make our 26 + 1 buckets 6 | buckets = [[] for i in range(27)] 7 | print(buckets) 8 | # go through each word and grab the letter at char_position 9 | # and put it in the right bucket 10 | for word in list: 11 | if(word[char_position] == ' '): 12 | # this is a blank. It goes in bucket 26 13 | buckets[26].append(word) 14 | else: 15 | bucket_index = ord(word[char_position]) - ord('a') 16 | # print(bucket_index) 17 | buckets[bucket_index].append(word) 18 | # print(buckets) 19 | # step 2 is concat our buckets into 1 list 20 | result = [] 21 | for bucket in buckets: 22 | result += bucket 23 | return result 24 | def radix_sort(list_to_sort): 25 | # get the longest element 26 | longest = max(len(str) for str in list_to_sort) 27 | # print(longest) 28 | # pad all the strings shorter than "longest" 29 | list_to_sort = [str.ljust(longest,' ') for str in list_to_sort] 30 | # print(list_to_sort) 31 | # loop through the characters one at a time, and bucket 32 | for i in range(longest - 1, -1, -1): 33 | list_to_sort = bucket_sorter(list_to_sort,i) 34 | # print(list_to_sort) 35 | sorted_list_without_pad = [word.strip() for word in list_to_sort] 36 | return sorted_list_without_pad 37 | animals = [ 38 | "cat", 39 | "bat", 40 | "dog", 41 | "elephant", 42 | "giraffe", 43 | "donkey", 44 | "horse", 45 | ] 46 | 47 | sorted_list = radix_sort(animals) 48 | print(sorted_list) 49 | 50 | end_time = time.time() #get our ending time 51 | print(f"--- Number of seconds to solve {time.time() - start_time}") 52 | -------------------------------------------------------------------------------- /projectEuler/randomStrGen.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | final ="" 3 | for i in range(80): 4 | word = list("It just tak3s pract!ce") 5 | for _ in range(1,len(word)): 6 | rand = randint(0,len(word)-1) 7 | final += word.pop(rand) 8 | final += "~~" 9 | print(final) 10 | -------------------------------------------------------------------------------- /text_rpg/Initial Task List.md: -------------------------------------------------------------------------------- 1 | Initial Task List 2 | 1. Hero dictionary 3 | list in dict 4 | 2. game loop and exit on 4 5 | 3. main_options dictionary 6 | 4. zombie dictionary and enemies list (load) 7 | - dict in dict 8 | 5. define fight() 9 | random & pull random monster 10 | 6. fight loop & exit fight 11 | 7. outsource data 12 | 8. import os and clear, sleep and enter 13 | 9. fight_option dict 14 | 10. fight mechanics 15 | 11. hero status inForest 16 | 12. outsource fight 17 | 18 | 19 | -------------------------------------------------------------------------------- /text_rpg/battle_engine.py: -------------------------------------------------------------------------------- 1 | import random 2 | import game_data 3 | 4 | #if the player decides to fight, this function will run 5 | def battle_engine(): 6 | #randint is a method from random. It takes 2 args: 7 | #1. integer to start at 8 | #2. integer to end at 9 | total_enemies = len(game_data.enemies) 10 | # random_number = random.randint(0,total_enemies-1) 11 | random_index = random.randint(0,total_enemies-1) 12 | #we need to use the copy method, so that we don't change the original 13 | enemy_to_fight_og = game_data.enemies[random_index] 14 | # enemy_to_fight = game_data.enemies[random_index].copy() 15 | # print(id(enemy_to_fight_og)) 16 | # print(id(game_data.enemies[random_index])) 17 | enemy_to_fight = enemy_to_fight_og.copy() 18 | # print(id(enemy_to_fight)) 19 | in_fight = True #boolean that keeps us in the fight loop 20 | print(f"{game_data.the_hero['name']}, thou hast encountered the {enemy_to_fight['adjective']} {enemy_to_fight['name']}. The battle has begun!") 21 | while(in_fight): 22 | enemy_attack_modifier = 1 #by default the enemy does no more or less damage 23 | print(f"Thou hast {game_data.the_hero['hp']} health points. Thine enemy has {enemy_to_fight['hp']} health points.") 24 | #this loop is the back and forth during a battle. Until someone wins 25 | print(f"1. Attack with thine {game_data.the_hero['weapon']}.") 26 | health_potion_count = game_data.the_hero['inventory'].count("health_potion") 27 | print(f"2. Drink the health potion. Thou hast {health_potion_count} potions.") 28 | print(f"3.Defend and heal.") 29 | print(f"4. Do a little dance.") 30 | print(f"5. Flee for your miserable, pitiful life.") 31 | battle_action = input("What would you like to do? > ") #this is the chioce the player will make in the fight 32 | #hero's turn 33 | if(battle_action == "1"): 34 | #user has chosen to attack 35 | #hero_power_hit = take the hero's attack_power - monster's defense 36 | #reduce the monster's hp by hero_power_hit 37 | hero_power_hit = game_data.the_hero['attack_power'] - enemy_to_fight['defense'] 38 | enemy_to_fight['hp'] -= hero_power_hit 39 | print(f"Thou hast struck thine enemy with {game_data.the_hero['weapon']} for {hero_power_hit} damage.") 40 | elif(battle_action == "2"): 41 | #this means, players wants to drink a potion 42 | if(health_potion_count > 0): 43 | #restore all hp 44 | # health_potion_count -= 1 #this will not work! Because we get the count from the list in the_hero 45 | #remove is like append, but we pass it the value to find and remove 46 | game_data.the_hero['inventory'].remove('health_potion') 47 | game_data.the_hero['hp'] = game_data.the_hero['max_hp'] 48 | print(f"Thou hast drank thy potion. Thine hp is restored to full. ") 49 | else: 50 | #player had no potions. Make the enemy take advantage 51 | print(f"Thou fool. Thou hast no potions of health, thine enemy has taken advatange of thine blunder") 52 | enemy_attack_modifier = 2 53 | elif(battle_action == "5"): 54 | print("Fight has ended") 55 | in_fight = False 56 | #enemy's turn, if alive 57 | if(enemy_to_fight['hp'] > 0): 58 | #enemy is alive. Attack back. 59 | #monster_power_hit = take the monster's attack_power - hero's defense 60 | #reduce the hero's hp by monster_power_hit 61 | monster_power_hit = (enemy_to_fight['attack_power'] * enemy_attack_modifier)- game_data.the_hero['defense'] 62 | print(f"Thine enemy {enemy_to_fight['name']} has struck thee with {enemy_to_fight['weapon']} for {monster_power_hit} damage.") 63 | game_data.the_hero['hp'] -= monster_power_hit 64 | else: 65 | #the enemy has no more hp. Fight is won for the hero 66 | print(f"Well done, magnificant {game_data.the_hero['name']}, thou hast slain the impudent {enemy_to_fight['name']}.") 67 | #the hero won, so grant the hero some gold and xp 68 | game_data.the_hero['gold'] += enemy_to_fight['gold_drop'] 69 | game_data.the_hero['xp'] += enemy_to_fight['xp_drop'] 70 | print(f"Thou has gained {enemy_to_fight['gold_drop']} gold and {enemy_to_fight['xp_drop']} experience.") 71 | print(f"Thou now hasts {game_data.the_hero['gold']} gold and {game_data.the_hero['xp']} experience.") 72 | in_fight = False #the fight is over! End the loop -------------------------------------------------------------------------------- /text_rpg/calc.py: -------------------------------------------------------------------------------- 1 | 2 | #This file does nothing but house the calc function 3 | #this is good. If we need anything related to calc 4 | #we know exactly where to look. 5 | def calc(op,x,y): 6 | if(op == "sum"): 7 | return x + y 8 | elif(op == "mult"): 9 | return x * y 10 | 11 | #Python also comes with it's owns modules 12 | #That means, it has a "core" which is the stuff 13 | #that automatically comes with the python command 14 | #variables 15 | #lists 16 | #print/loops 17 | print(math.pi) 18 | 19 | #python has a 3rd party module "package manager" 20 | #called pip 21 | #pandas - is not part of core. It has to be installed 22 | #pygame - is not part of core. It has to be installed 23 | 24 | -------------------------------------------------------------------------------- /text_rpg/game.py: -------------------------------------------------------------------------------- 1 | #random is a "CORE" module that comes with python 2 | #it has some cool methods to generate random numbers 3 | import random 4 | #game_data is where our data lives at. We can access it quickly and easily 5 | #but it is out of the way the rest of time 6 | import game_data 7 | from battle_engine import battle_engine 8 | #the entry point (this is the file we run python on) 9 | #for our text based RPG 10 | 11 | game_data.the_hero["name"] = input("What is thy name, brave adventurer? > ") 12 | 13 | #make a boolean that will control our main game loop 14 | game_on = True 15 | while(game_on): 16 | print(f"What would you like to do, {game_data.the_hero['name']}?") 17 | for option in game_data.main_options: 18 | print(f"{option['input_key']}. {option['text']}") 19 | action = input(" > ") #this will BLOCK the loop, until the user answer 20 | if(action == "1"): 21 | battle_engine() #renamed fight to battle_engine since it's a better varaible name 22 | elif(action == "q"): 23 | game_on = False 24 | 25 | -------------------------------------------------------------------------------- /text_rpg/game_data.py: -------------------------------------------------------------------------------- 1 | the_hero = { 2 | "name" : "Incognito", 3 | "xp" : 0, #use xp to determine when level up 4 | "level" : 1, 5 | "gold" : 5, #amount of money the player has to buythings 6 | "attack_power" : 5, 7 | "defense" : 2, 8 | "max_hp" : 10, #this is for reference and will only change when the player levels up 9 | "hp" : 10, #this hp mutates as the player is hurt or heals 10 | "weapon" : "fists", 11 | "inventory" : ["health_potion",] 12 | } 13 | 14 | zombie = { 15 | "name" : "Zombie", 16 | "adjective" : "fearsome", 17 | "hp" : 10, 18 | "attack_power" : 3, 19 | "defense" : 0, 20 | "weapon" : "fist", 21 | "xp_drop" : 2, #this is how much xp the bad guy gives the hero when defeated 22 | "gold_drop" : 1, 23 | "power" : { 24 | "name" : "Berzerk", 25 | "effect" : "attack_up", 26 | "effect_impact" : 5, 27 | } 28 | } 29 | 30 | goblin = { 31 | "name" : "Goblin", 32 | "adjective" : "meek", 33 | "hp" : 8, 34 | "attack_power" : 4, 35 | "defense" : 1, 36 | "weapon" : "fist", 37 | "xp_drop" : 2, #this is how much xp the bad guy gives the hero when defeated 38 | "gold_drop" : 1, 39 | "power" : { 40 | "name" : "Call For Help", 41 | "effect" : "hp_up", 42 | "effect_impact" : 10, 43 | } 44 | } 45 | 46 | enemies = [zombie,goblin] 47 | enemies.append(zombie) 48 | 49 | main_options = [ 50 | { 51 | "text" : "Go into the dark forest in search of adventure and loot", 52 | "input_key" : "1", 53 | }, 54 | { 55 | "text" : "Go to the shop", 56 | "input_key" : "2", 57 | }, 58 | { 59 | "text" : "Do a dance", 60 | "input_key" : "3" 61 | }, 62 | { 63 | "text" : "Sleep and adventure another day (exit)", 64 | "input_key" : "q" 65 | } 66 | ] -------------------------------------------------------------------------------- /text_rpg/importing.py: -------------------------------------------------------------------------------- 1 | from calc import calc # this will grab the calc function from the calc file 2 | import math #this comes with python 3 | # from calc import calc as c - this changes the function or class name in THIS file 4 | 5 | #Python is a modular langauge 6 | #We can move our functions (and classes) to their own file 7 | #and then, because Python is modular, import them into 8 | #our "main" file 9 | sum = calc("sum",3,2) 10 | print(sum) 11 | 12 | -------------------------------------------------------------------------------- /text_rpg/varsByReferenceAndValue.py: -------------------------------------------------------------------------------- 1 | #RULE TO LIVE BY: 2 | #Immutable data types = int, float, strings, booleans, and sets 3 | #if a var is immutable, then it doesn't matter if we use 4 | #an = to copy it to another variable. The value cannot change 5 | #so, we can change it anywhere and teh other varaibles will 6 | #not be affected 7 | #Mutable data types = lists, dictionaries, sets, objects 8 | #if a var is mutable, then you should expect that if you make a 9 | #copy with an = sign, then anywhere you change it, will change 10 | #it everywhere 11 | #x = [] 12 | #y = x 13 | #x.append(1) 14 | #you have changed y 15 | # x = [] 16 | # y = x.copy() #y and x are totally different. 17 | 18 | #To make a copy that will NOT change the original, you use the 19 | # copy method. That will NOT copy the pointer/arrow that the 20 | #= sign does, it will make a copy of the value and that will 21 | #be independent 22 | 23 | 24 | # #id will give us a unique integer to represent that variable 25 | # x = 3 26 | # y = x #we are pointing y at x, UNTIL the value of one changes 27 | # print(id(x)) #same value as line below, because 3 is immutable 28 | # print(id(y)) #same value as line above, because 3 is immutable 29 | # x += 1 #will make x 4 30 | # print(id(x)) #values have diverged. 3 is unchangable so, it must make a new value in memory 31 | # print(id(y)) #same as above. It has not changed 32 | # x -= 1 #x is back to 3 33 | # print(id(x)) #uses teh original 3, because...3 is imutable. Doesn't matter, if x and y are related 34 | # z = 3 35 | # print(id(x)) 36 | # print(id(y)) 37 | # print(id(z)) #Woah. Even though x and z are never associated, Python is smart. It uses the same memory to reference an unchangable integer 38 | 39 | # x = [] 40 | # print(id(x)) #x hasn't changed, its value has 41 | # x.append(1) 42 | # print(id(x)) 43 | # y = x 44 | # print(id(y)) 45 | # x.append(2) #x is adding a number 46 | # y.append("Hello") #y is adding a number 47 | # #lists are mutable!!! Python will not change the id (place in memory) 48 | # #it will change the thing in memory and x and y are changing 49 | # #the same thing 50 | # print(id(x)) 51 | # print(id(y)) 52 | 53 | def fight(monster): 54 | #based on when we talked about scope (local and global) 55 | #will this thing be changable... 56 | #remember... when we pass a variable into a function 57 | #if it is mutable, we pass the reference 58 | monster.append(5) 59 | print(id(monster)) 60 | 61 | enemies = [1,2,3] 62 | print(id(enemies)) 63 | fight(enemies) #we are passing a global, to a function 64 | print(id(enemies)) 65 | print(enemies) -------------------------------------------------------------------------------- /theBasics/casting.py: -------------------------------------------------------------------------------- 1 | 2 | # casting = change a variables data type without changing the variable itself 3 | a_number_as_string = "2" #string 4 | print(int(a_number_as_string) + 2) 5 | print(a_number_as_string + str(2)) 6 | print(float(3)) 7 | 8 | fav_number = input("What is your favorate number? > ") 9 | print(type(fav_number)) 10 | fav_number_plus_three = int(fav_number) + 3 11 | 12 | -------------------------------------------------------------------------------- /theBasics/conditionalsAndSpacing.py: -------------------------------------------------------------------------------- 1 | 2 | name = input("Please enter your name > ") 3 | # print(name) 4 | 5 | # what if we want to say something differnet based 6 | # on who the person is? 7 | if(name == "Rob"): #an if statement takes () and in the () we put Left thing == Right thing 8 | print("Hello, instructor " + name) 9 | #python is an indented language! 10 | else: 11 | print("Hello, Student") 12 | print("Out of conditionals statement") 13 | 14 | # mon nom est - My name is - Huh? Uh, I guess so... 15 | # je m'appelle - I call myself - Ya. That's good. Well done. 16 | 17 | #elif means it is part of the conditional statement 18 | #it falls down like a waterfall, and the first one 19 | #that is true, is the ONLY one that will be run 20 | #in other words, an elif means "which one of these is true" 21 | if(name == "Rob"): 22 | print("Hello, instructor") 23 | elif(name == "Akash"): 24 | print("Hello, assistant!") 25 | else: 26 | print("Hello, there") 27 | 28 | #more than 1 if, means they are evaluated separately 29 | # if(name == "Rob"): 30 | # print("Hello, instructor") 31 | # if(name == "Akash"): 32 | # print("Hello, assistant!") 33 | # else: 34 | # print("Hello, there") 35 | 36 | x = 3 37 | if(x == 3 or x == 5): 38 | print("You're number is 3 or 5") 39 | else: 40 | print("You're number is NOT 3 or 5") 41 | 42 | if(x == 3 and name == "Rob"): 43 | print("You have a common name and a common number") 44 | else: 45 | print("Not Rob and 3") 46 | -------------------------------------------------------------------------------- /theBasics/dictionary.py: -------------------------------------------------------------------------------- 1 | 2 | # #dictionary = a variable of variables 3 | # #unlike lists, it has key:value pairs instead of indicies 4 | # #like lists, it is a variable with many parts, 5 | # #and uses [] when we want to reference it 6 | # #like lists, you can always leave a comma after 7 | # #the last one 8 | 9 | # #we can assign key:values when we make the dictionary 10 | # country1 = { 11 | # "name" : "United States", 12 | # "population" : 35000000, 13 | # "capital" : "Washington D.C.", 14 | # # 3.14 : "What is pi doing here?" #THIS IS BAD. DONT DO THIS. It is valid, but it is confusing! 15 | # } 16 | 17 | # print(country1["name"]) #United States 18 | # # print(country1["other_name"]) #this will give us a KeyError 19 | # # print(country1[3.14]) 20 | # # print(country1[3]) #I would assume this was a list. And it's not!! 21 | # # country1.append('Test') 22 | 23 | # # countries = [ 24 | # # "US", #0 25 | # # "Ireland", #1 26 | # # ] 27 | 28 | # #we can make an empty {} 29 | # #later on we can add key:value 30 | # user_country = {} 31 | # user_country["name"] = "England" 32 | # print(user_country["name"]) 33 | 34 | # user_country["population"] = input("What is your country's population? > ") 35 | # print(user_country["population"]) 36 | # print(f"Your country is {user_country['name']} and population is {user_country['population']}") 37 | 38 | #dictionaries + lists = WOAH. 39 | countries_by_population = [ 40 | { 41 | "name" : "India", 42 | "capital" : "New Delhi", 43 | }, #end of index 0 44 | { 45 | "name" : "China", 46 | "capital" : "Beijing", 47 | }, #end of index 1 48 | { 49 | "name" : "United States", 50 | "capital" : "Washington D.C." 51 | }, #end of index 2 52 | ] 53 | print(f'The name of the country with the largest population in the world is {countries_by_population[0]["name"]}. The capital is {countries_by_population[0]["capital"]}') 54 | 55 | #dictionaries + loops = WOAH. 56 | car = { 57 | "make" : "Tesla", 58 | "model" : "S", 59 | "range" : "250 miles", 60 | } 61 | 62 | car["country_of_origin"] = "United States" 63 | 64 | #when i loop through a dict, I use the variable "key" 65 | for key in car: 66 | print(f"{key} : {car[key]}") 67 | 68 | #dictionaries + loops + lists = !!!!WOAH!!!! 69 | #a LOT of times this is how data comes from a database 70 | for country in countries_by_population: 71 | #in a for loop. indentation matters! 72 | #country = a dictionary inside of the list countries_by_population 73 | country_name = country["name"] 74 | print(f"The country {country_name} has a capital of {country['capital']}") 75 | 76 | #in our game, we will have an enemies list 77 | #each enemy will be a dictionary 78 | #hp, attack, defense, name 79 | 80 | #pulling back a list of orders 81 | #each order will be a dictionary 82 | #invoice #, customer_name, customer_address 83 | 84 | customer_invoices = [ 85 | { 86 | "name" : "company1", 87 | "total" : 123.34 88 | }, 89 | { 90 | "name" : "company1", 91 | "total" : 223.14 92 | }, 93 | { 94 | "name" : "company2", 95 | "total" : 122.63 96 | }, 97 | { 98 | "name" : "company1", 99 | "total" : 13.34 100 | }, 101 | ] 102 | 103 | customer1Total = 0 104 | for invoice in customer_invoices: 105 | #deal with each invoice as it comes 106 | if(invoice["name"] == "company1"): 107 | customer1Total += invoice["total"] 108 | print(f"Customer1 has a total of {customer1Total}") -------------------------------------------------------------------------------- /theBasics/fib100.py: -------------------------------------------------------------------------------- 1 | #Usually we access a list element with list_name[i] 2 | #You can access any element in a list anytime no matter what i is 3 | #For instance list_name[i+1] or list_name[i*3]... 4 | 5 | list_of_fib = [0,1] 6 | 7 | #i should be the sequence number you are calculating 8 | def append_and_print_fib(i): 9 | new_number = list_of_fib[i-1] + list_of_fib[i-2] 10 | list_of_fib.append(new_number) 11 | 12 | #loop here 13 | for i in range(2,100): 14 | #call the function and send the sequence number to calculate 15 | append_and_print_fib(i) 16 | 17 | print(list_of_fib[99]) -------------------------------------------------------------------------------- /theBasics/function.py: -------------------------------------------------------------------------------- 1 | 2 | # a function is a block of code that can be called on 3 | # demand! When we call it we can pass it variables! 4 | # this is good. :) It gives us a way to reuse code 5 | # and to get different results/output because we 6 | # can send it variables 7 | # method is a funciton that belongs to a variable (object) 8 | 9 | #when we define a function (def) the () are known as 10 | #the siganture. The varaibles inside the siganture 11 | #are known as parameters 12 | #by default, they come in order 13 | this_is_a_global = "Testing a global var out" 14 | print(f"1 global. {this_is_a_global}") 15 | def calc(operation,x,y): 16 | # if you want to use a global variable inside a funciton 17 | # you can. Unless... you want to change its value. 18 | #to do that, you need to put the keyword global 19 | #in front of the var name, on its line 20 | # print(this_is_a_global) #do NOT use a global and a local in the same function. Just use a different name for the local 21 | global this_is_a_global #this line says, we are going to use a variable in the funciton called this_is_a_global, and it is the global version, not my own scoped version 22 | this_is_a_global = "I changed a global because I can see it." 23 | n = 7 #this is a local variable! It cannot be seen outside of this function 24 | print(f"You have called Calc. You have sent the {operation} operation.") 25 | if(operation == "Sum"): 26 | #if the function gets "sum" passed to it 27 | #then print off x + y 28 | print(x + y) 29 | print(f"x + y = {x + y} and if I add n we get {x + y + n} ") 30 | # print(f"1 inside calc. {this_is_a_global}") 31 | elif(operation == "Mult"): 32 | #multiply x * y 33 | print(x * y) 34 | 35 | #when we call/invoke a function, the varaibles in () 36 | #are called arguements 37 | #by default the args pass into the params in order 38 | #UNLESS, we use the key/name of the param 39 | print("Line 1") 40 | calc("Sum",2,9) #call/invoke the function calc... which we defined above 41 | print("Line 2") 42 | calc("Mult",10,20) #call/invoke the function calc... which we defined above 43 | calc(x = 9, y = 3, operation="Mult") 44 | # calc(9, 3, "Mult") 45 | # print(n) # this will break our function! 46 | print(f"2. global {this_is_a_global}") -------------------------------------------------------------------------------- /theBasics/interpolationStrings.py: -------------------------------------------------------------------------------- 1 | 2 | # interpolation = co-mingling variables and strings together! 3 | cookie_count = 12 4 | print(f"The cookie count is cookie_count {cookie_count}") 5 | 6 | country = "England" 7 | person = f"Person's name is Joe. Joe is {45 - 13} and Joe is from {country}" 8 | print(person) 9 | -------------------------------------------------------------------------------- /theBasics/lists.py: -------------------------------------------------------------------------------- 1 | 2 | # A list is a "list" of variables 3 | # they are grouped together for some reason 4 | # maybe came from a backend (api, database) 5 | # maybe they are a logical group (countries, animals, etc) 6 | # maybe they need to be looped through 7 | # they come with some awesome tools 8 | 9 | empty_list = [] 10 | # print(type(empty_list)) 11 | countriesByPop = [ 12 | "India", #this is index 0 13 | "China", #1 14 | "US", #2 15 | "Indonesia", #3 16 | ] 17 | print(countriesByPop[3]) 18 | 19 | #len() whatever is in the () len will try and find how many items there 20 | print(f"The length of countriesByPop is: {len(countriesByPop)}.") 21 | 22 | #lists have methods!! 23 | #what is a method? A method is some code that 24 | #python has written/built into the language 25 | #that works on a variable/data type/data structure (class/object) 26 | 27 | #the append method belongs to all lists 28 | #that means if you are a list, you can run .append() 29 | #whatever is inside of the () is what you will add 30 | #to the end of this list 31 | countriesByPop.append('Pakistan') 32 | print(f"The length of countriesByPop is now: {len(countriesByPop)}.") 33 | print(countriesByPop) 34 | print("======================") 35 | 36 | #insert method 37 | #is some code that Python has given us for our lists 38 | #if you're a list, you have the insert method 39 | #you can do a_list.insert() 40 | #we pass insert 2 things, 1. The place to insert, 2. the variable to insert 41 | countriesByPop.insert(4,"Nigeria") 42 | print(countriesByPop) 43 | print("=====================") 44 | 45 | #let's say a new country called "pythonmania" came into being 46 | countriesByPop.insert(0,"Pythonmania") 47 | print(countriesByPop) 48 | print("=====================") 49 | 50 | 51 | #pop and remove 52 | #if you're a list, you have the pop and remove methods 53 | #pop = remove the specified index from the list 54 | #we pass the .pop() the index we want to remove 55 | countriesByPop.pop(0) #this will remove from the list the thing in spot 0 (the first element) 56 | print(countriesByPop) 57 | print("=====================") 58 | 59 | 60 | #remove is like pop, but instead of giving it/passing 61 | #an index, we pass a value 62 | countriesByPop.append("AI") 63 | print(countriesByPop) 64 | countriesByPop.remove("AI") #instead of the index, we give it the value 65 | print(countriesByPop) 66 | 67 | animals = ["Dog","Elephant","Cat","Dog"] 68 | # print(animals) 69 | #clear method = this burns everything in the array 70 | #it is essentially the equiv of starting over from scratch 71 | #we dont need to pass clear anything 72 | # animals.clear() 73 | # animals = [] 74 | # print(animals) 75 | 76 | #count method 77 | #count will "count" the number of times a thing shows up in a list 78 | number_of_dogs = animals.count("dog") 79 | print(number_of_dogs) 80 | 81 | #sort and reverse 82 | #sort method = will sort the list in natural order 83 | #we don't have it anything for natural order, we do pass it something for control (later) 84 | animals.sort() 85 | print(animals) 86 | 87 | #cannot mix data types 88 | # list_of_numbers = [1,3,6,4,2,6,"Hello",2,7,81,3,4] THIS WILL BREAK 89 | list_of_numbers = [1,3,6,4,2,6,2,7,81,3,4] 90 | list_of_numbers.sort() 91 | print(list_of_numbers) 92 | 93 | list_of_different_dt = [ 94 | "Joe", 95 | 4, 96 | 3.14, 97 | True, 98 | [1,2,3] 99 | ] 100 | 101 | #reverse method = switch the order of the indicides exactly 102 | list_of_different_dt.reverse() 103 | print(list_of_different_dt) 104 | -------------------------------------------------------------------------------- /theBasics/looping_through_strings.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | a_string_to_loop_through = "I love Python" 4 | a_string_as_list = list(a_string_to_loop_through) 5 | 6 | # for letter in a_string_to_loop_through: 7 | # print(letter) 8 | 9 | # for letter in a_string_as_list: 10 | # print(letter) 11 | 12 | # print(a_string_to_loop_through[2]) #l 13 | # print(a_string_as_list[2]) #l 14 | 15 | # parsing strings is COMMON in programming 16 | #parsing = looking at the string for whatever reason 17 | # is this a valid phone number 18 | # what credit card company is this card? 19 | # is there a space or a , 20 | 21 | # counter = 0 22 | # for letter in a_string_as_list: 23 | # if(letter == "l"): 24 | # #this is an l. 25 | # print(f"The position of the l is {counter}.") 26 | # print(a_string_to_loop_through[counter]) 27 | # counter += 1 28 | 29 | # len(string) takes an iterable and tells you how long it is 30 | 31 | # number_of_letters = len(a_string_to_loop_through) 32 | # number_of_indicies = len(a_string_as_list) 33 | # print(number_of_letters) 34 | # print(number_of_indicies) 35 | 36 | # for i in range(0,number_of_letters): 37 | # print(a_string_to_loop_through[i]) 38 | # if(a_string_to_loop_through[i] == "l"): 39 | # #this is an l 40 | # print(f"The position of the l is {i}.") 41 | 42 | #lists have an index method 43 | #strings have a find method 44 | #index/find will look through the list/string for 45 | #the FIRST occurance of the var passed and return the index 46 | 47 | index_in_string = a_string_to_loop_through.find("l") 48 | print(index_in_string) 49 | index_in_list = a_string_as_list.index("l") 50 | print(index_in_list) 51 | 52 | # for letter in a_string_as_list: 53 | for letter in a_string_to_loop_through: 54 | if(letter == "l"): 55 | position_of_l = a_string_to_loop_through.find("l") 56 | print(f"The position of the l is {position_of_l}") 57 | print(a_string_to_loop_through[position_of_l]) 58 | print(a_string_as_list[position_of_l]) 59 | 60 | a_new_string = "Hello" 61 | missing_letter = a_new_string.find("z") 62 | print(missing_letter) 63 | a_new_list = list(a_new_string) 64 | missing_letter = a_new_list.index("z") 65 | print(missing_letter) 66 | 67 | -------------------------------------------------------------------------------- /theBasics/loops.py: -------------------------------------------------------------------------------- 1 | 2 | # a loop is a way to run the same code over and over 3 | # and stop when x happens, or when we have done it x times 4 | 5 | #while loop goes until x is not true 6 | # counter = 0 7 | # while(counter < 10): 8 | # # print(counter) 9 | # counter = counter + 1 10 | # print("Loop has ended!") 11 | 12 | # #for loop 13 | # # i = the dish you are on 14 | # # range(0,10) = the 10 dirty dishes in the sink 15 | # for i in range(0,10): 16 | # if(i == 5): 17 | # print("Five") 18 | # else: 19 | # print(i) 20 | 21 | ############For loops with lists############# 22 | # a for loop takes after the "in" an iterable 23 | # iterable = something that has members in the same 24 | # order/sequence that can be iteraed over one at a time 25 | 26 | # for letter in "something": 27 | # print(letter) 28 | 29 | cars = [ 30 | "BMW", 31 | "Ford", 32 | "Toyota", 33 | ] 34 | 35 | #database, api, group 36 | for car in cars: 37 | if(car == "BMW"): 38 | print("You have a BMW") 39 | else: 40 | print(f"I hope you like your car! {car} is a great brand.") -------------------------------------------------------------------------------- /theBasics/numberMethods.py: -------------------------------------------------------------------------------- 1 | 2 | #numbers are floats or integers 3 | print(int(3.14)) 4 | 5 | #Floats have an is_integer() 6 | #will tell you if the float has anything other than .0000... 7 | the_number_pi = 3.14 8 | print(type(the_number_pi)) 9 | print(the_number_pi.is_integer()) 10 | 11 | #abs = absolute value = removes the - from any number 12 | print(abs(-100)) #100 13 | print(abs(100)) #100 14 | 15 | #guess_the_number game, we checked both -1 from the number 16 | #and +1 from the number. We could use abs and write 17 | #that conditional in 1 line 18 | 19 | # pow = power, and it takes 2 numbers, 20 | #first is the number to raise by a power 21 | #second is the power to raise by 22 | print(pow(2,5)) # 2 * 2 * 2 * 2 * 2 = 32 23 | print(pow(5,2)) # 5 * 5 = 25 24 | print(pow(5.2,2.2)) 25 | 26 | #round = round the number to x places 27 | #first = the number to round 28 | #second = the number of decimals to round to 29 | #if we dont give it the number of places, it rounds to int 30 | print(round(2.23423455235423)) 31 | print(round(2.2342355235423,5)) 32 | 33 | -------------------------------------------------------------------------------- /theBasics/pythonBasics.py: -------------------------------------------------------------------------------- 1 | # # # Comments = are anything that is NOT for python 2 | # # # Comments are for the devoloper/human 3 | 4 | # # # variable assignment is var name on left, an =, value on right 5 | # # name = "Rob" # assigning name to Rob 6 | # # # Snake case is used in Python when you have a variable 7 | # # # name that has more than one word. The words are 8 | # # # separated by _ 9 | # # # camel case (alternative to snake) means starting each 10 | # # # new word with a capital letter, except the first 11 | # # #example: cookieCount 12 | # # cookie_count = 12 # assigning cookie_count to 12 13 | # # print("=========expecting 12=============") 14 | # # print(cookie_count) 15 | # # cookie_count = cookie_count - 2 #2 cookies were taken out 16 | # # print("=========expecting 10=============") 17 | # # print(cookie_count) 18 | # # cookie_count = cookie_count + 10 #bake 10 new cookies 19 | # # print("=========expecting 20=============") 20 | # # print(cookie_count) 21 | 22 | # # name = "Rob" 23 | # # print(name) 24 | # # name = 'Rob' 25 | # # print(name) 26 | # # # name = `Rob` Python will not like this! 27 | # # print(name) 28 | 29 | # # Data Types 30 | # # - String = "English" that is meant for the user 31 | # # in VS code, strings are orange 32 | # # we make a string with "", '', or """ 33 | # really_long_text = """they and was they and was they 34 | # and was they and was they and was they and was 35 | # they and was they and was they and was they and 36 | # was """ 37 | # print(really_long_text) 38 | # # - Numbers 39 | # # -- Integers 40 | # an_integer = 1 41 | # # -- Floats 42 | # a_float = 3.14 43 | # # - Booleans 44 | # a_boolean = True # False 45 | 46 | # really_long_text_data_type = type(really_long_text) 47 | # print(really_long_text_data_type) 48 | # an_integer_data_type = type(an_integer) 49 | # print(an_integer_data_type) 50 | # a_float_data_type = type(a_float) 51 | # print(a_float_data_type) 52 | # a_boolean_data_type = type(a_boolean) 53 | # print(a_boolean_data_type) 54 | 55 | # # - List/Dictionaries/Objects 56 | 57 | # cookie_count = 12 + " cookies" 58 | # isDayTime = True #Boolean, True = 1, False = 0 59 | # nonsense = isDayTime + 3 60 | # print(nonsense) 61 | # isNightTime = False 62 | # nonsense2 = isNightTime + 3 63 | # print(nonsense2) 64 | 65 | #input() will PAUSE or BLOCK the program 66 | #until the user enters something 67 | name = input("What is your name? >> ") #input is ALWAYS a string data type 68 | # the + sign is NOT a plus sign. It is called 69 | # concatenate in programming. concatenation is when 70 | # you stick 2 strings together 71 | print("Welcome, " + name) -------------------------------------------------------------------------------- /theBasics/pythonMath.py: -------------------------------------------------------------------------------- 1 | 2 | # # operator - smybol/sign that can manipulate/or do 3 | # # something with an operand 4 | # # operand - is something that an operator affects 5 | 6 | # a_number = 3 + 5 7 | # ########Python operators 8 | # # + = addition/plus sign when used with numbers (float / int) 9 | # a_number = 5 + 3.14 10 | # # + = concatenate symbol when used with strings 11 | # a_string = "Rob " + "Bunch" 12 | # # nonsense = "Rob " + 3 #this will break! 13 | # # nonsense = 3 + "Rob " #this will break! 14 | 15 | # # - = subtraction/minus sign when used with 2 numbers 16 | # # - = a negative sign when used before a number 17 | # negative_number = -2 18 | # a_number = 5 - 3.14 19 | 20 | # # * = multiplication 21 | # a_product = 10 * 2 #20 22 | # # / = division 23 | # a_quotient = 10 / 2 #5 24 | # # > = greater than symbol 25 | # # < = less than symbol 26 | # # print(3 < 2) 27 | # # >= ---> greater than or equal to 28 | # # <= ---> less than or equal to 29 | # print(3 < 3) 30 | # print(3 <= 3) 31 | # # = ---> assigning something 32 | # # == ---> equal to/comparing 2 things for a match 33 | # # != ---> NOT equal to/comparing 2 things for not a match 34 | # print(2 != 3) #True 35 | # print(2 != 2) #False 36 | 37 | print("2" == 2) 38 | print(2 == 2) #True 39 | 40 | -------------------------------------------------------------------------------- /theBasics/return_palidrome.py: -------------------------------------------------------------------------------- 1 | # When you run return, the function terminates instantly 2 | 3 | #palidrome = is a word that is spelled the same forward and backward 4 | #tacocat 5 | 6 | #is_palidrome's job is to find out if the word we send as an arg 7 | #is in fact a palidrome or not. It will return True or False 8 | def is_palidrome(word_to_check): 9 | # modified_word = f"I am checking if {word_to_check} is a palidrome." 10 | #we can covert a string to a list! This will put a letter in each 11 | #index 12 | word_as_list = list(word_to_check) 13 | # print(word_as_list) 14 | #reverse is a method that all lists have that will switch all the indicies in reverse order 15 | word_as_list.reverse() 16 | # print(word_as_list) 17 | #we can turn a list back into a string by using the join method 18 | reversed_word_as_string = ''.join(word_as_list) 19 | if(reversed_word_as_string == word_to_check): 20 | #if the word reversed as a string = what we were sent, it is a palidrome, return True! 21 | return True 22 | else: 23 | #this is not a palidrome 24 | return False 25 | 26 | list_of_strings = [ 27 | "tacocat", 28 | "jump", 29 | "testset", 30 | "William", 31 | ] 32 | 33 | for word in list_of_strings: 34 | is_word_a_palidrome = is_palidrome(word) 35 | print(f"Is {word} a Palidrome? Answer:{is_word_a_palidrome}") -------------------------------------------------------------------------------- /theBasics/stringMethods.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | #like all varaibles, strings have methods 4 | #that make life better 5 | 6 | #Mutation = does the thing change or not. 7 | #when it comes to methods, does the method 8 | # "mutate" the varaible, or does it take the varaible 9 | # do something with it, and return the value 10 | a_string = "i love python" 11 | cap_string = a_string.capitalize() #capitalize will return the string with the first letter capitalized 12 | print(cap_string) 13 | print(a_string) 14 | 15 | #a way to use a method that does not mutate, to mutate 16 | a_string = a_string.title() # cap each letter 17 | print(a_string) 18 | 19 | #lower = make every letter lower case in the string 20 | a_string = a_string.lower() 21 | print(a_string) 22 | 23 | #upper = make every letter upper case in the string 24 | a_string = a_string.upper() 25 | print(a_string) 26 | 27 | #find = you know. It gets the index of the character 28 | print(a_string.find("l")) 29 | print(a_string.find("L")) 30 | 31 | #count = returns the number of times a character appears 32 | print(a_string.count("P")) 33 | 34 | #replace = hand it what to look for, and what to replae it with 35 | #an optional 3rd arg, is how many times to change 36 | a_string = "I think Python is fun fun fun fun!" 37 | a_string = a_string.replace("fun", "hard", 2) 38 | print(a_string) -------------------------------------------------------------------------------- /theBasics/test.py: -------------------------------------------------------------------------------- 1 | print("Hello, students") 2 | print(3+5) -------------------------------------------------------------------------------- /theBasics/tuplesAndSets.py: -------------------------------------------------------------------------------- 1 | 2 | #tuples and sets are built in data types in Python 3 | #tuple = a list that CANNOT be changed. Immutable 4 | #tuple unlike lists which use [] use () 5 | vowels = ("a","e","i","o","u","a") 6 | # print(vowel[0]) 7 | # print(type(vowel)) 8 | #you can make them without ()... this is BAD 9 | a_tuple = 1, 2, 3 #DONT DO THIS. Use () 10 | # print(type(a_tuple)) 11 | 12 | #tuples are iterable because they ALWAYS have the same order 13 | #in programming this is called a discrete structure 14 | for v in vowels: 15 | print(v) 16 | 17 | # vowels.append("a") 18 | # vowels.add("a") 19 | # tuples have 2 methods 20 | # - count() = will return teh number of an element in the tuple 21 | # - index() = just like a list, finds the index of hte element passed 22 | # number_of_a = vowels.count("a") 23 | # number_of_e = vowels.count("e") 24 | # print(number_of_a) 25 | # print(number_of_e) 26 | # number_of_o = vowels.count("oo") 27 | # print(number_of_o) 28 | # index_of_a = vowels.index("a") 29 | # print(index_of_a) 30 | 31 | #set = like a list, except... it has NO order 32 | # AND it cannot have any duplicates 33 | # it uses {} like dict, but has no keys 34 | some_numbers = { 1, 5, 6, 1, 12, 3} 35 | some_numbers2 = { 9,1, 5, 6, 1, 12, 3} 36 | print(some_numbers) 37 | # print(some_numbers[0]) ERROR... no order 38 | #the add method adds a new member. We dont know where 39 | some_numbers.add(1) 40 | some_numbers.add(4) 41 | print(some_numbers) 42 | # some_numbers.clear() #empty the set 43 | # print(some_numbers) 44 | some_numbers.discard(1) 45 | print(some_numbers) 46 | element_removed = some_numbers.pop() # pop will remove a RANDOM element 47 | print(some_numbers) 48 | print(element_removed) 49 | 50 | print(some_numbers) 51 | print(some_numbers.difference_(some_numbers2)) 52 | print(some_numbers) 53 | --------------------------------------------------------------------------------