def test_sortable(self): """Shadows can be sorted by their starting points.""" first = Shadow(0, 0.1) second = Shadow(0.1, 0.2) third = Shadow(0.2, 0.3) expected = [first, second, third] actual = sorted([third, first, second]) self.assertListEqual(expected, actual)
def test_can_tell_if_it_covers_a_tile(self): """The ShadowLine can tell if it covers a given tile.""" line = ShadowLine([Shadow(0, 0.2), Shadow(0.5, 1.0)]) projected_into_darkness = Shadow(0, 0.1) projected_into_light = Shadow(0.3, 0.4) self.assertTrue(line.is_in_shadow(projected_into_darkness)) self.assertFalse(line.is_in_shadow(projected_into_light))
def test_shadows_can_overlap(self): """A Shadow X overlaps with Shadow Y if: - X ends after Y starts AND Y starts before X ends """ first = Shadow(0, 0.4) second = Shadow(0.4, 0.8) third = Shadow(0.81, 0.95) self.assertTrue(first.adjacent(second)) self.assertTrue(second.adjacent(first)) self.assertFalse(second.adjacent(third))
def test_initializes_with_shadows(self): "Init takes an iterable of Shadows." shadows = [Shadow(0, 1), Shadow(3, 5)] actual = ShadowLine(shadows) expected = ShadowLine() for shadow in shadows: expected.add(shadow) self.assertEqual(expected, actual)
def test_shadows_can_cover_other_shadows(self): """ A Shadow X covers another Shadow Y if: - X starts before or at the same place as Y - X ends after or at the same place as Y """ bigger = Shadow(0, 0.7) smaller = Shadow(0.2, 0.6) also_small = Shadow(0.2, 0.3) self.assertTrue(bigger.covers(smaller)) self.assertFalse(smaller.covers(bigger)) self.assertTrue(smaller.covers(also_small))
def test_coalesces_two_overlapping_shadows(self): """Two Shadows that overlap are coalesced into a single Shadow. [0, 0.1] + [0.1, 0.2] = [0, 0.2] """ actual = ShadowLine([Shadow(0, 0.1)]) actual.add(Shadow(0.1, 0.2)) expected = ShadowLine([Shadow(0, 0.2)]) self.assertEqual(expected, actual)
def test_can_tell_if_entire_row_is_shadow(self): """Can tell if the entire row is visible""" line = ShadowLine() # First quarter covered: line.add(Shadow(0, 0.25)) self.assertFalse(line.is_full_shadow()) # Add last quarter, half covered: line.add(Shadow(0.75, 1)) self.assertFalse(line.is_full_shadow()) # Add the missing two middle quarters, fully covered: line.add(Shadow(0.25, 0.75)) self.assertTrue(line.is_full_shadow())
def test_only_coalesces_adjacent_shadows(self): """ [0, 0.1] + [0.4, 0.5] = [0, 0.1], [0.4, 0.5] + [0.2, 0.4] = [0, 0.1], [0.2 0.5] """ actual = ShadowLine([Shadow(0, 0.1)]) actual.add(Shadow(0.4, 0.5)) actual.add(Shadow(0.2, 0.4)) expected = ShadowLine([Shadow(0.0, 0.1), Shadow(0.2, 0.5)]) self.assertEqual(expected, actual)
def test_coalesces_multiple_overlapping_shadows(self): """Adding a Shadow that creates overlap between previously non-contiguous shadows should coalesce all three into one big Shadow. [0, 0.1] + [0.3, 0.4] = [0, 0.1], [0.3, 0.4] + [0.1, 0.3] = [0, 0.4] """ actual = ShadowLine([Shadow(0, 0.1)]) actual.add(Shadow(0.3, 0.4)) actual.add(Shadow(0.1, 0.3)) expected = ShadowLine([Shadow(0, 0.4)]) self.assertEqual(expected, actual)
def prep_shadows_left(self): """Show how many Shadows are left.""" self.shadows = Group() for shadow_number in range(self.stats.shadow_lives_left): shadow = Shadow(self.ti_game) shadow.rect.x = 10 + shadow_number * shadow.rect.width shadow.rect.y = 10 self.shadows.add(shadow)
def test_handles_many_shadows(self): # Try permuting the order to ensure that it does not matter shadows = [ Shadow(0, 0.1), Shadow(0.05, 0.08), Shadow(0.125, 0.175), Shadow(0.2, 0.325), Shadow(0.5, 0.55), Shadow(0.275, 0.450), Shadow(0.6, 0.8), Shadow(0.3, 0.99) ] line = ShadowLine() for shadow in shadows: line.add(shadow) self.assertFalse(line.is_full_shadow())
def main(): my_hero = Hero() goblin = Goblin() zombie = Zombie() medic = Medic() shadow = Shadow() while (goblin.alive() or zombie.alive()) and my_hero.alive(): my_hero.print_status() print() print("What do you want to do?") print("1. fight goblin") print("2. fight zombie") print("3. fight medic") print("4. fight shadow") print("5. do nothing") print("6. flee") print("> ",) user_input = input() if user_input == "1": goblin.print_status() # my_hero attacks goblin my_hero.attack(goblin) if goblin.health > 0: # Goblin attacks my_hero goblin.attack(my_hero) elif user_input == "2": zombie.print_status() my_hero.attack(zombie) zombie.attack(my_hero) zombie.alive() elif user_input == "3": medic.print_status() my_hero.attack(medic) medic.attack(my_hero) medic.alive() elif user_input == "4": shadow.print_status() shadow.attack(my_hero) my_hero.attack(shadow) shadow.alive() elif user_input == "5": pass elif user_input == "6": print("Goodbye.") break else: print("Invalid input %r" % user_input)
def __init__(self): super(Gameplay, self).__init__() w, h = SCREEN_RECT.size self.all_sprites = pg.sprite.LayeredUpdates() self.background = make_background((w, h)) self.fog = pg.Surface((w, h), pg.SRCALPHA) self.fog.fill((0, 0, 0, 255)) self.player = Player(SCREEN_RECT.center, self.all_sprites) self.wolves = pg.sprite.Group() for _ in range(10): pos = randint(32, w - 32), randint(32, h - 32) Wolf(pos, self.wolves, self.all_sprites) self.trees = pg.sprite.Group() for _ in range(25): pos = randint(0, w), randint(0, h) Tree(pos, self.trees, self.all_sprites) self.tree_shadows = [] for tree in self.trees: self.tree_shadows.append(Shadow(tree.footprint))
def setUp(self): self.tmp_dir = tempfile.mkdtemp() self.kernel_dir = os.path.join(self.tmp_dir, 'boot') self.rootfs_dir = os.path.join(self.tmp_dir, 'rootfs') self.snap_dir = os.path.join(self.tmp_dir, 'shadow') self.shadow = Shadow(rootfs_dir=self.rootfs_dir, kernel_dir=self.kernel_dir, snapshot_dir=self.snap_dir) self.timestamp = self.shadow._get_timestamp() os.makedirs(self.kernel_dir) os.makedirs(self.rootfs_dir) if not os.path.exists(self.snap_dir): os.makedirs(self.snap_dir) # preload some test "kernels" and "ramdisks" for x in [ 'kernel26.img', 'vmlinuz26', 'initrd.img-2.6.38', 'vmlinuz.2.6.38' ]: f = open(os.path.join(self.kernel_dir, x), 'w') f.write(x) f.close() for x in range(10): r_dir = ''.join(Random().sample(string.letters, 8)) os.makedirs(os.path.join(self.rootfs_dir, r_dir))
def test_repr_is_evalable(self): """The __repr__ of an instance should return a string that could be evaluated to reconstruct the instance. """ line = ShadowLine([Shadow(0, 1)]) self.assertEqual(line, eval(repr(line)))
def summon_shadow(self, position, direction, maze): if self.power_points > 0: shadow = Shadow(position, self.number, direction, 'shadow') maze.CREATURES.append(shadow) self.power_points -= 1
def test_shadows_do_not_always_overlap(self): """ Distinct Shadows should not overlap.""" first = Shadow(0, 0.1) second = Shadow(0.3, 0.4) self.assertFalse(first.adjacent(second))
def test_valid_constructor(self): """Shadow initializes with given values.""" start, end = 0, 1 shadow = Shadow(start, end) self.assertEqual(shadow.start, start) self.assertEqual(shadow.end, end)
def test_repr_is_evalable(self): """The __repr__ of an instance should return a string that could be evaluated to reconstruct the instance. """ shadow = Shadow(0, 0.25) self.assertEqual(shadow, eval(repr(shadow)))
import random from hero import Hero from goblin import Goblin from zombie import Zombie from medic import Medic from shadow import Shadow from ascii_art import character_list_art, options_list_art, goodbye, welcome hero = Hero(10, 5) goblin = Goblin(6, 2) zombie = Zombie(10, 1) medic = Medic(8, 2) shadow = Shadow(1, 4) characters = [hero, goblin, zombie, medic, shadow] store_items = [] def get_enemies(user_fighter_choice): enemies = [] for character in characters: if character.type != user_fighter_choice.type: enemies.append(character) return enemies def pause(): input("Press any key to continue...")
def test_equality(self): """Two Shadows with the same starting and ending points are considered equal.""" first = Shadow(0, 1) second = Shadow(0, 1) self.assertEqual(first, second)
print("What do you want to do?") for i in range(len(Store.items)): item = Store.items[i] print("{}. buy {} ({})".format(i + 1, item.name, item.cost)) print("10. leave") input1 = int(input("> ")) if input1 == 10: break else: if hero.coins >= item.cost: ItemToBuy = Store.items[input1 - 1] item = ItemToBuy() hero.buy(item) else: print("You don't have enough coins for that.") if __name__ == "__main__": hero = Hero() enemies = [Goblin(), Wizard(), Shadow()] battle_engine = Battle() shopping_engine = Store() for enemy in enemies: hero_won = battle_engine.do_battle(hero, enemy) if not hero_won: print("YOU LOSE!") exit(0) shopping_engine.do_shopping(hero) print("YOU WIN!")
def load(map_name, game, new_pos=0, face=0): """ Load a map from a map folder. Returns a list of surfaces that are on the map. Parses the custom map format. Kinda messy. """ game.EntityHandler.clear() surfaces = [] shadow_check = 0 game.links = [] game.solid_list = [] inside = 0 l = os.path.abspath(__file__).replace('\\', '/').split('/') l.pop() main_direc = os.path.join(game.main_path, 'rec', 'maps', map_name) if new_pos: game.Player.setPos(literal_eval(new_pos)) if face: game.Player.setFace(face) # get dict from positions.txt pos_dict = {} positions = open(os.path.join(main_direc, 'positions.txt'), 'r').read() for line in positions.split('\n'): if not line: pass elif line.startswith('#'): pass elif 'LINK' in line: line_bits = line.split(':') game.links.append(line_bits) game.solid_list.append('LINK') elif 'SET_PLAYER' in line: game.Player.setPos(literal_eval(line.split(':')[1])) elif 'SURFACE' in line: ln = line.split(':') pos_dict[ln[1]] = ln elif 'SOLID' in line: ln = line.split(':') game.solid_list.append(pygame.rect.Rect(literal_eval(ln[1]))) elif 'BOUNDS' in line: ln = line.split(':') borders = literal_eval(ln[1]) elif "INSIDE" in line: shadow_check = int(line.split(':')[1]) game.INSIDE = shadow_check # load all buildings tile = pygame.image.load(os.path.join(main_direc, 'tile.png')).convert() game.tile = [tile, tile.get_size()] for time in [1, 2]: for index, fi in enumerate( os.listdir(os.path.join(main_direc, 'buildings/'))): pos_dict[fi][3] = pos_dict[fi][3].replace('\r', '') if pos_dict[fi][3] == 'ground%s' % time: img = pygame.image.load( os.path.join(main_direc, 'buildings/', fi)) surfaces.append([ img.convert_alpha(), literal_eval(pos_dict[fi][2]), 3, pygame.mask.from_surface(img) ]) if time == 1: surfaces.append('player') if not shadow_check: game.HUD.screen_cover.set_alpha(game.HUD.outside_alpha) for surf in surfaces: if 'player' in surf: pass else: shad = Shadow(game, surf[0], surf[1]) game.shadows.append(shad) else: game.HUD.outside_alpha = game.HUD.screen_cover.get_alpha() game.HUD.screen_cover.set_alpha(0) game.blit_list = surfaces game.Grid = Grid(game, borders) return surfaces
from sayan import Sayan from shadow import Shadow from store import Store from thief import Thief from wizard import Wizard from zombie import Zombie from mimic import Mimic hero = Hero('Oakley') enemies = [ Goblin('Bob'), Wizard('Jethro'), Medic('Mercy'), Thief('Barry'), Mimic('Harry'), Zombie('Rick'), Shadow('Matt'), Sayan('Goku') ] # enemies = [Thief('Barry')] Goblin('Bob'), Wizard('Jethro'), Medic('Mercy'), Thief('Barry'), Zombie('Rick'), Shadow('Matt'), Sayan('Goku'), battle_engine = Battle() shopping_engine = Store() for enemy in enemies: hero_won = battle_engine.do_battle(hero, enemy) if not hero_won: print("YOU LOSE!") exit(0) shopping_engine.do_shopping(hero, enemy) print("YOU WIN!")
def test_handles_invalid_parameters_gracefully(self): """Shadow start should be less than shadow end.""" start, end = 0.5, 0 shadow = Shadow(start, end) self.assertEqual(shadow.start, end) self.assertEqual(shadow.end, start)
def main(): # constants WIN_X = 640 WIN_Y = 480 FONT_SIZE = 16 S_U = Shadow.U # shadow unit size taken from Shadow class BASE_RESET_TICKS = 60 * 3 # 3 seconds to reset after being caught # pygame setup pygame.init() screen = pygame.display.set_mode((WIN_X, WIN_Y)) font = pygame.font.SysFont("Courier", FONT_SIZE, True) clock = pygame.time.Clock() # player data player = Player() # Shadow/Guard data for each level. These two lists need to be # of the same size, otherwise, there will be some extra data # that is unused in either list, and the game may not do level # transition properly. The lists for the individual levels' data # within the main list can be of any size. shadows = [[Shadow(0, 0, 1, 1), Shadow(WIN_X - S_U, WIN_Y - S_U, 1, 1), Shadow(100, 100, 8, 2), Shadow(275, 300, 8, 2)], [Shadow(0, 0, 1, 1), Shadow(100, 100, 1, 8), Shadow(200, 100, 8, 2), Shadow(500, 100, 2, 10), Shadow(WIN_X - S_U, WIN_Y - S_U, 1, 1)], [Shadow(0, 0, 1, 1), Shadow(WIN_X - S_U, WIN_Y - S_U, 1, 1), Shadow(150, 70, 2, 3), Shadow(360, 150, 2, 2), Shadow(450, 70, 2, 5), Shadow(150, 240, 2, 3), Shadow(300, 240, 2, 3), Shadow(450, 270, 2, 5), Shadow(170, 350, 5, 1)], [Shadow(0, 0, 1, 1), Shadow(WIN_X - S_U, WIN_Y - S_U, 1, 1), Shadow(85, 75, 2, 8), Shadow(180, 300, 7, 2), Shadow(225, 225, 2, 2), Shadow(290, 150, 2, 2), Shadow(370, 95, 2, 2), Shadow(450, 70, 5, 4), Shadow(565, 230, 2, 6)]] guards = [[Guard(500, 75, 500-250, 75+250), Guard(85, 400, 85+250, 400-250)], [Guard(400, 400, 250, 250), Guard(500, 200, 250, 450), Guard(100, 50, 100-75, 50+75)], [Guard(190, 50, 190+130, 50+130), Guard(330, 225, 330-150, 225+150), Guard(265, 410, 265+170, 410-170)], [Guard(60, 300, 60+100, 300+100), Guard(220, 160, 220+110, 160+110), Guard(500, 300, 500-220, 300-220), Guard(610, 215, 610-160, 215+160)]] # ---------------------------------------------------------- # metagame data ticksToReset = BASE_RESET_TICKS levelComplete = False levelFailed = False level = 0 NUM_LEVELS = len(shadows) levelDisplay = "Level: {0}/{1}".format(level + 1, NUM_LEVELS) status = "You are undetected." bg = pygame.image.load("bg.png").convert() while True: ## EVENTS ---------------------------------------------- nextEvent = pygame.event.poll() # quit game if nextEvent.type == pygame.QUIT: break # accept character movement if level is yet completed if not levelComplete and not levelFailed: keysDown = pygame.key.get_pressed() if keysDown[pygame.K_UP] and player.posY > 0: player.move("UP") if keysDown[pygame.K_DOWN] and player.posY < WIN_Y: player.move("DN") if keysDown[pygame.K_LEFT] and player.posX > 0: player.move("LT") if keysDown[pygame.K_RIGHT] and player.posX < WIN_X: player.move("RT") ## UPDATE ---------------------------------------------- # update player data based on new position, shadows, and guards player.update(shadows[level], guards[level]) # update guards for guard in guards[level]: guard.update() # check for necessary changes to metagame flags if player.getX() >= WIN_X - 16 and player.getY() >= WIN_Y - 16: levelComplete = True if player.isCaught(): levelFailed = True # update status text and counter if not levelComplete and not levelFailed: status = "You are undetected." elif levelComplete: if level + 1 < NUM_LEVELS: status = "Transition in {0}...".format(ticksToReset / 60 + 1) ticksToReset -= 1 else: status = "Game complete!" elif levelFailed: status = "Caught! Restart in {0}...".format(ticksToReset / 60 + 1) ticksToReset -= 1 # reset level if necessary if levelFailed and ticksToReset == 0: ticksToReset = BASE_RESET_TICKS levelFailed = False player.reset() for guard in guards[level]: guard.reset() # level transition if necessary if levelComplete and ticksToReset == 0: ticksToReset = BASE_RESET_TICKS levelComplete = False level += 1 levelDisplay = "Level: {0}/{1}".format(level + 1, NUM_LEVELS) status = "You are undetected." player.reset() ## RENDER ---------------------------------------------- # render background screen.blit(bg, (0,0)) # render player player.draw(screen) # render guards for guard in guards[level]: guard.draw(screen) # render shadows for shadow in shadows[level]: shadow.draw(screen) # render visibility display player.drawVisibility(screen) # display status text line1 = font.render(levelDisplay, True, (0, 0, 0)) line2 = font.render(status, True, (0, 0, 0)) screen.blit(line1, (10, WIN_Y - 10 - 2 * FONT_SIZE)) screen.blit(line2, (10, WIN_Y - 10 - FONT_SIZE)) pygame.display.flip() clock.tick(60) pygame.quit()
import os from persistence import Persistence from shadow import Shadow from recomendation import Recomendation from users import User, Users from texttable import Texttable """ Main interface of the program. """ if __name__ == "__main__": recomendation = Recomendation() shadow = Shadow("./etc/shadow", recomendation) users = Users("./etc/passwd") db = Persistence() print(''' ) ( ( /( ( ) ) ( ( )\ ) )\()) ( ( ( )\ ) ( ( ( ) ( /(( ` ) ( /( ( ( )\))( (()/( ((_)\ ))\ )\))( (()/( ))\ ( ))\ )( ( /( )\())\ ( ( /(/( )(_)))\ )\((_)()\ ((_)) _((_)/((_((_)()\ /(_))_ /((_))\ ) /((_(()\ )(_)(_))((_) )\ )\ ) ((_)_\((_)_((_((__(()((_) _| | | \| (_)) _(()((_) (_)) __(_)) _(_/((_)) ((_((_)_| |_ (_)((_)_(_/( | '_ \/ _` (_-(_-\ V V / _` | | .` / -_)\ V V / | (_ / -_| ' \)/ -_)| '_/ _` | _|| / _ | ' \)) | .__/\__,_/__/__/\_/\_/\__,_| |_|\_\___| \_/\_/ \___\___|_||_|\___||_| \__,_|\__||_\___|_||_| |_| ''') print(