def main(): """Run main program""" rules_and_agreements() enemy = Enemy() enemy.make_battlefield() enemy.make_ships() player = Player() player.make_battlefield() player.make_ships() print(player.battlefield.get_map) my_turn = ask_yes_no("Would you like to move first?") if my_turn == "n": my_turn = False game_over = None while not game_over: if my_turn: game_over = player.fire(enemy) if game_over: enemy.says_after_losing() else: game_over = enemy.fire(player) if game_over: enemy.says_after_victory() my_turn = not my_turn
def fight(Enemy,hp_plus): global Player Enemy = Enemy(100+hp_plus, 5, 0) print("Перед вами стоит варвар\n" "У него в руках огромная дубина и он размахивает ей,очевидно зазывая вас на поединок\n" "Вы решаете испытать свои судьбу и попиздиться") print(f"У тебя {Player.health} здоровья.\n" f"У врага {Enemy.health} здоровья.") while True: print("Ваш ход,что будете делать? ") action = input() if not action.isdigit(): print("Даун,введи команду из списка...") continue if int(action) != 1 and int(action) != 2: print("Всё хуйня, давай по новой") continue if int(action) == 1: damage = round(Player.attack * random.uniform(0, 2)) - Enemy.armor if damage < 0: damage = 0 Enemy.health = Enemy.health - damage print(f"Ты нанёс {damage} урона врагу, у него осталось {Enemy.health} жизней") elif int(action) == 2: if Player.potion != 0: Player.potion -= 1 Player.health += 15 print(f"Тёплый эликсир разливается по твоему телу, ты похилился на 15 очков, теперь у тебя " f"{Player.health} здоровья, а хилок {Player.potion}") else: print("Лох,ты проебал все хилки и не можешь похилится))))") if Enemy.health < 0: print(f" Варвар получает смертельный удар, и спуская дух успеваете сказать: {Enemy.death_phrase}\n" f"На этом его приключение заканчивается...\n" f"\t\tПоздравялю, вы победили!!") return True damage = round(Enemy.attack * random.uniform(0, 2)) - Enemy.armor if damage < 0: damage = 0 Player.health = Player.health - damage print(f"Враг нанёс тебе {damage} урона , у тебя осталось {Player.health} жизней") if Player.health < 0: print(f"Вы получаете смертельный удар, и спуская дух успеваете сказать: {Player.death_phrase}\n" f"На этом ваши приключение заканчиваются...") return False
def prepare_enemies(self, enem_types): bees, ninjas, tanks, rangers, boss = 0, 0, 0, 0, 0 if enem_types == 1: bees = self.num_enemies elif enem_types == 2: bees = math.floor(self.num_enemies * .5) ninjas = math.floor(self.num_enemies * .2) rangers = math.ceil(self.num_enemies * .3) elif enem_types == 3: bees = math.floor(self.num_enemies * .5) ninjas = math.ceil(self.num_enemies * .3) tanks = math.floor(self.num_enemies * .2) elif enem_types == 4: boss = self.num_enemies for i in range(self.num_enemies): x_pos = random.randint(70, 730) y_pos = random.randint(70, 525) if bees > 0: e = Enemy(x_pos, y_pos) self.enemy_group.add(e) bees -= 1 elif boss == 1: e = Boss(400, 290) self.enemy_group.add(e) boss -= 1 elif bees == 0 and ninjas > 0: e = Ninja(x_pos, y_pos) self.enemy_group.add(e) ninjas -= 1 elif bees == 0 and ninjas == 0 and rangers > 0: e = Ranger(x_pos, y_pos) self.enemy_group.add(e) rangers -= 1 elif bees == 0 and ninjas == 0 and rangers == 0 and tanks > 0: e = Tank(x_pos, y_pos) self.enemy_group.add(e) tanks -= 1
def spawn(level): if game.level == 1: for i in range(1, 11): enemy = Enemy("badguy", { "x": random.randint(1, width - 100), "y": random.randint(-1000, 0) }, False, 2) enemies.append(enemy) elif game.level == 2: for i in range(1, 11): enemy = Enemy("badguy", { "x": random.randint(1, width - 100), "y": random.randint(-1000, 0) }, False, 3) enemies.append(enemy) elif game.level == 3: for i in range(1, 16): enemy = Enemy("badguy", { "x": random.randint(1, width - 100), "y": random.randint(-1000, 0) }, False, 3) enemies.append(enemy) elif game.level == 4: for i in range(1, 21): enemy = Enemy("badguy", { "x": random.randint(1, width - 100), "y": random.randint(-2000, 0) }, False, 4) enemies.append(enemy) elif game.level == 5: for i in range(1, 11): enemy = Enemy("badguy", { "x": random.randint(1, width - 100), "y": random.randint(-1000, 0) }, False, 5) enemies.append(enemy) elif game.level == 6: for i in range(1, 41): enemy = Enemy("badguy", { "x": random.randint(1, width - 100), "y": random.randint(-3000, 0) }, False, 5) enemies.append(enemy)
window.blit(bg, (0, 0)) score_current = font.render("Score: " + str(score), 1, (0, 0, 0)) window.blit(score_current, (390, 10)) Rab.draw(window) goblin.draw(window) for shell in bullets: shell.draw(window) pygame.display.update() clock = pygame.time.Clock() font = pygame.font.SysFont('comicsans', 30, True) Rab = Player(300, 410, 64, 64) goblin = Enemy(100, 410, 64, 64, 450) shoot_loop = 0 bullets = [] running = True while running: clock.tick(27) if goblin.visible: if Rab.hitbox[1] < goblin.hitbox[1] + goblin.hitbox[3] and Rab.hitbox[ 1] + Rab.hitbox[3] > goblin.hitbox[1]: if Rab.hitbox[0] + Rab.hitbox[2] > goblin.hitbox[0] and Rab.hitbox[ 0] < goblin.hitbox[0] + goblin.hitbox[2]: Rab.hit(window) score -= 5
for item in person.items: person.removeItem(item) person.room.addItem(item) backpack.dropFunction = MethodType(dropEverything, backpack) food = Item('Some food',['food', 'foods']) water = Item('A bottle of water',['water', 'bottle', 'waters']) boots = Item('Walking boots',['boots', 'walking boots', 'shoes']) stick = Item('Stick',['stick', 'twig', 'branch']) #Define some enemies cow = Enemy('Cow') #Construct some rooms startRoom = Room() startRoom.description = "DofE storage warehouse, everything you need is layed out in front of you" startRoom.shortDescription = "DofE warehouse" startRoom.addItem(potatoes) startRoom.addItem(backpack) startRoom.addItem(food) startRoom.addItem(water) startRoom.addItem(boots) Footpath1 = Room() Footpath1.description = 'A footpath' Footpath1.addItem(stick)
def start(display, settings): """This is the main body of the game logic""" counter = 0 boss_alive = False if settings.settings["Music"] == "On": pygame.mixer.music.load('assets/main_game.wav') pygame.mixer.music.play(-1) player_img, enemy_img, capital_ship_img = "assets/player_ship.png", "assets/alienship.png", "assets/capital_ship.png" bullet, fired_bullets, on_screen_enemies, turn_timer = False, [], 1, 0 enemy_list = [Enemy(enemy_img, display) for i in range(on_screen_enemies)] player = Player(player_img, display) FPS = settings.settings["Framerate"] num_stars = 800 stars = [ Stars(settings.settings["Resolution"]["X"], settings.settings["Resolution"]["Y"]) for i in range(num_stars) ] # Game loop while True: display.fill(colour.black) # Draw stars for star in stars: star.draw(display) if star.y > settings.settings["Resolution"]["Y"]: stars.remove(star) new_height = 1 # Add new stars - we want this to be somewhat random new_stars = [ Stars(settings.settings["Resolution"]["X"], new_height) for i in range(int(random.uniform(0.25, 1.25))) ] for new_star in new_stars: stars.append(new_star) if turn_timer > 500: on_screen_enemies += 1 for e in [ Enemy(enemy_img, display) for i in range(on_screen_enemies) ]: enemy_list.append(e) turn_timer = 0 for e in enemy_list: e.draw() if e.load_weapons < 1: e.load_weapons = 100 fired_bullets.append(e.fire()) e.load_weapons -= 1 # If bullet has been fired, draw it and assess whether it hits the target or not for b in fired_bullets: # Remove the bullets at the bottom so you don't move into them if b.y > 1080: fired_bullets.remove(b) b.draw() player_status = player.hit(b) if player_status == "hit": # Handle edge case where bullet goes off screen but still has causal power try: fired_bullets.remove(b) except: pass elif player_status == "dead": try: fired_bullets.remove(b) except: pass # End game return True, player for e in enemy_list: hit_result = e.hit(b, player) if hit_result == "dead": fired_bullets.remove(b) enemy_list.remove(e) elif hit_result == "hit": fired_bullets.remove(b) player.draw() draw_text(display, player) if (player.score % 4 == 0 and player.score != 0) and boss_alive == False: new_boss = True boss_alive = True counter = 100 enemy_list.append(create_boss(capital_ship_img, display)) if counter > 0 and new_boss == True: draw_boss_text(display, settings) counter -= 1 else: counter = 120 new_boss = False # Checks what events have been created and takes them off the queue for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): terminate() elif (event.type == KEYDOWN and event.key == K_a): player.x -= 25 elif (event.type == KEYDOWN and event.key == K_d): player.x += 25 elif (event.type == KEYDOWN and event.key == K_SPACE): fired_bullets.append(player.fire()) turn_timer += 1 # update() draws Surface object to screen pygame.display.update() pygame.time.Clock().tick(FPS)
def create_boss(boss_img, display): """Creates a 'boss'-type unit""" boss = Enemy(boss_img, display) boss.health = 5 boss.draw() return boss
from time import sleep from classes import Hero, Enemy import effects from random import randint # criando heroi hero_test = Hero('Tobs', 'Male', 100, 1, 'Psyco') hero_test.battle_skills(50, 8, 6, 10) # criando inimigo drunk_man = Enemy('Drunk Man', 50, 7, 5, 9) def fight(hero, enemy): round_counter = 0 while hero.health > 0 and enemy.health > 0: round_counter += 1 print( f'{effects.bold}{effects.red}{round_counter}º TURNO!{effects.normal}' ) # contador de turnos current_enemy_attack = enemy.attacks[randint(0, len(enemy.attacks) - 1)] # enemy attacks hero.health -= current_enemy_attack[0] print(f'{enemy.name} attacks you with a {current_enemy_attack[1]}.') current_hero_attack = hero.attacks[randint(0, len(hero.attacks) - 1)] # hero attacks enemy.health -= current_hero_attack[0]
def Game(): pygame.init() display_width = 700 display_height = 700 gameDisplay = pygame.display.set_mode((display_width, display_height)) pygame.display.set_caption('Pacman') clock = pygame.time.Clock() dead = False win = False #starting position of the player var = 0 for i in range(len(level)): for j in range(len(level[i])): if level[i][j] == 2: var = 1 break if var == 1: break x = j * 34 + 2 y = i * 34 + 2 x_change = 0 y_change = 0 #starting position of the enemy enemypos = [] var = 0 enemyarr = [] dotcount = 0 print(len(level), len((level[0]))) for i in range(len(level)): for j in range(len(level[i])): if level[i][j] == 3: enemypos += [[i, j]] enemyarr += [[i, j]] if level[i][j] == 0: dotcount += 1 if level[i][j] == 2: playerpos = [j, i] print(playerpos) print(playerpos) for i in range(len(enemypos)): enemypos[i][0], enemypos[i][ 1] = enemypos[i][1] * 34 + 2, enemypos[i][0] * 34 + 2 pl = Player.Player() e = Enemy.Enemy() m = Map.Map(level) score = 0 while not dead and not win: t = time.time() for event in pygame.event.get(): dead, x_change, y_change = pl.movePlayer(x_change, y_change, event) gameDisplay.fill(white) graph = m.renderMap(display_width, display_height, gameDisplay, level) #check whether position to be moving in is valid score, dead, x_change, y_change = m.checkCollision( score, x_change, y_change, x, y, level) #move player x += x_change y += y_change # print(x, y) # print(playerpos) playerpos[0] += x_change // 34 playerpos[1] += y_change // 34 # print(enemyarr) # e.moveEnemy(enemyarr, graph, playerpos[1], playerpos[0]) pl.renderPlayer(x, y, gameDisplay) e.renderEnemy(enemypos, gameDisplay) pygame.display.update() clock.tick(30) if score == dotcount: win = True pygame.quit() quit()
import unittest from classes import Hero, Enemy, Weapon, Spell pesho = Hero('Petr', 'Pedo', 100, 100, 2) vrago = Enemy(100, 100, 20) weapon = Weapon('Sword of Bad Manners', 20) spell = Spell('Fireball', 60, 100, 3) class TestHeroClass(unittest.TestCase): def test_hero_init(self): result = pesho.health expected = 100 self.assertEqual(result, expected) def test_hero_take_damage_and_is_alive(self): pesho.take_damage(100) result = pesho.is_alive() expected = False self.assertEqual(result, expected) def test_hero_take_damage_and_get_health(self): pesho.take_damage(57) result = pesho.get_health() expected = 43
### CHARACTERS ################################ max_img = pygame.image.load( "/Users/dylan/dc_projects/max_run/resources/max.png") max_img = pygame.transform.scale(max_img, (100, 125)) max_img = pygame.transform.flip(max_img, 0, 180) max = Character("Max", { "x": width / 2, "y": height / 2 }, (game.level * 50) / 2) # list containinig every bully he hugged new_friends = [] friend = Enemy("badguy", { "x": random.randint(1, width - 100), "y": random.randint(0, height) }, True, 0) enemies = [] badguy_running = [] counter_ones = 0 counter_tens = 0 # append the images to enable the running visual effect for i in range(1, 43): badguy_running.append( pygame.image.load( f"/Users/dylan/dc_projects/max_run/resources/badguy/run/1_0{counter_tens}{counter_ones}.png" )) counter_ones += 1 if counter_ones > 9: counter_ones = 0
def game(): while True: if player1.xp >= player1.lvlXp: player1.lvlup() player1.stats() startThreading() print("------------------") print("MENU") print("------------------") print("1 > Fight") print("2 > Town") print("3 > Inventory") print("4 > Player info") print("5 > Recipe Book") print("6 > Save") print("") print("7 > Exit") print("------------------\n") what = input(": ") if what == "1": if player1.expLocation == "none": print("Rolling the dice...") time.sleep(2) rndNum = randint(1, 6) print(rndNum) if rndNum in range(1, 5): ogre = Enemy("Ogre", [item2, item70], 50, 0, 15, 5, 20) dwarf = Enemy("Dwarf", [item70], 40, 0, 15, 25, 15) enemies = [ogre, dwarf] tempHp = battle(player1, random.choice(enemies)) player1.hp = tempHp player1.round = 1 clear() elif rndNum == 6: if player1.battles >= 10: ogreKing = Boss("Ogre King", [item1, item2, item3], 150, 10, 30, 15, 150, 400) enemies = [ogreKing] tempHp = battle(player1, random.choice(enemies)) player1.hp = tempHp player1.round = 1 clear() else: print( "Your battles arent over 10. You can't fight boss now" ) time.sleep(1) else: print("You are exploring now you can't fight") time.sleep(1) elif what == "2": print("TOWN") print("------------------") print("1 > Shop") print("2 > Explore") print("3 > Blacksmith") print("------------------") tempInp = input(": ") if tempInp == "1": shop([item70, item71, item72, item350], player1) elif tempInp == "2": explore(player1, "cave") elif tempInp == "3": pass elif what == "3": #inventory while True: clear() print("\n") player1.showEquiped() print("[ Inventory ]") print("==================") player1.showInv() #for i in range(len(player1.data)): # try: # print(player1.data[i].name) # except: # print(player1.data[i]) print("==================") print("1 > Use 2 > Info 3 > Unequip 4 > Drop 5 > Back") invOp = input("") if invOp == "1": #using / equiping stuff whichItem = int(input("Item(number): ")) whichItem -= 1 try: if isinstance(player1.data[whichItem], Potion) == True: #if is a potion player1.data[whichItem].heal(player1) player1.removeItem(player1.data[whichItem]) elif isinstance(player1.data[whichItem], Weapon) == True: #if is a weapon if any(isinstance(x, Weapon) for x in player1.on) == True: for i in range(len(player1.on)): if isinstance(player1.on[i], Weapon) == True: print( "You can equip it, you already have a weapon equiped" ) time.sleep(1) else: player1.equip(player1.data[whichItem]) elif isinstance(player1.data[whichItem], Helmet) == True: #if is a helmet if any(isinstance(x, Helmet) for x in player1.on) == True: for i in range(len(player1.on)): if isinstance(player1.on[i], Helmet) == True: print( "You can equip it, you already have a helmet equiped" ) time.sleep(1) else: player1.equip(player1.data[whichItem]) elif isinstance(player1.data[whichItem], Chestplate) == True: #if is a weapon if any( isinstance(x, Chestplate) for x in player1.on) == True: for i in range(len(player1.on)): if isinstance(player1.on[i], Chestplate) == True: print( "You can equip it, you already have a chestplate equiped" ) time.sleep(1) else: player1.equip(player1.data[whichItem]) elif isinstance(player1.data[whichItem], Leggings) == True: #if is a weapon if any( isinstance(x, Leggings) for x in player1.on) == True: for i in range(len(player1.on)): if isinstance(player1.on[i], Leggings) == True: print( "You can equip it, you already have leggings equiped" ) time.sleep(1) else: player1.equip(player1.data[whichItem]) elif isinstance(player1.data[whichItem], Boots) == True: #if is a weapon if any(isinstance(x, Boots) for x in player1.on) == True: for i in range(len(player1.on)): if isinstance(player1.on[i], Boots) == True: print( "You can equip it, you already have boots equiped" ) time.sleep(1) else: player1.equip(player1.data[whichItem]) elif isinstance(player1.data[whichItem], Bag) == True: #if is a bag if player1.items != player1.bagLimit: player1.data[whichItem].giveLoot(player1) player1.removeItem(player1.data[whichItem]) else: print("Bag is full") time.sleep(1) elif isinstance(player1.data[whichItem], CraftingScroll) == True: #if is a craftingScroll player1.learnRecipe( globals()[player1.data[whichItem].varN]) player1.removeItem(player1.data[whichItem]) time.sleep(1) else: print("You can't use this item") time.sleep(1) except: print("Wrong item number or nothing in inventory") time.sleep(5) if invOp == "2": #info about items whichItem = int(input("Item(number): ")) whichItem -= 1 try: if isinstance(player1.data[whichItem], Item) == True: #if is a potion player1.data[whichItem].showDescription() print("Press Enter to return") tempInp = input(": ") else: #if is a weapon print("What?") except: print("Wrong item number or nothing in inventory") if invOp == "4": #droping an item try: print("Are you sure?") print("1 > Yes") print("2 > No") inp = input(": ") if inp == "1": try: whichItem = int(input("Item(number):")) whichItem -= 1 player1.drop(player1.data[whichItem]) except: print("Something went wrong") if inp == "2": pass except: print("Something went wrong") if invOp == "3": #unequiping stuff whichItem = int(input("Item(number):")) whichItem -= 1 try: player1.unEquip(player1.on[whichItem]) except: print("Wrong item number or nothing equiped") if invOp == "5": #gettin back break elif what == "4": #player info print("Player info:") player1.stats() print("Number of battles:", player1.battles, "\n") player1.showEquiped() tempInp = input("Press Enter to return") elif what == "5": while True: player1.showRecipes() print("1 > Craft 2 > Back") inp = input(": ") if inp == "1" or inp == "craft": whichItem = int(input("Item(number): ")) whichItem -= 1 try: player1.craft(player1.recipes[whichItem]) except: print("Error") else: break elif what == "6": #saving save(int(player1.saveSlot)) elif what == "7": #exit exit() elif what == "420": player1.xp += 199 elif what == "69": player1.giveItem(item4) elif "give item" in what: what = what.replace("give item ", "") if player1.items != player1.bagLimit: try: player1.giveItem(globals()[what]) except: print("Wrong item name") else: print("Bag is full") elif "give money" in what: what = what.replace("give money ", "") what = int(what) try: player1.money += what except: print("yeet")