def main(): framecount = 0 exit = False nodes = [] tiles = load_tiles() tile_size = 16 pygame.init() pygame.display.set_caption("Monster AI Prototype") screen = pygame.display.set_mode( (len(tiles) * tile_size, len(tiles) * tile_size)) clock = pygame.time.Clock() background = pygame.Surface(screen.get_size()) background = background.convert() background.fill((255, 255, 255)) util.init(background, tile_size, tiles) nodes = ai.init(len(tiles)) key_player = entity.Entity(tiles, 1, 1, (255, 0, 0)) mouse_player = entity.Entity(tiles, len(tiles) - 2, 1, (0, 255, 0)) monster = entity.Entity(tiles, int(len(tiles) / 2), int(len(tiles) / 2), (0, 0, 0)) while not exit: clock.tick(60) screen.blit(background, (0, 0)) draw_tiles(background, tiles, tile_size) key_player.draw() mouse_player.draw() monster.draw() for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): return elif event.type == KEYDOWN: if event.key == K_DOWN: key_player.add_pos(0, 1) elif event.key == K_UP: key_player.add_pos(0, -1) elif event.key == K_LEFT: key_player.add_pos(-1, 0) elif event.key == K_RIGHT: key_player.add_pos(1, 0) mx, my = pygame.mouse.get_pos() mouse_player.set_pos(mx / tile_size, my / tile_size) ai_move = ai.ai_step(framecount, nodes, monster, (mouse_player, )) framecount += 1 pygame.display.flip()
def UnitTest(m=None): """This unit test relies on a particular model configuration, located in testModel.xml""" import entity if not m: m = Model() m.load("testModel.xml") appt = m.entityTypes["Application"] app = m.entities["app"] = entity.Entity(appt,(0,0),(100,20)) sgt = m.entityTypes["ServiceGroup"] sg = m.entities["sg"] = entity.Entity(sgt,(0,0),(100,20)) if not app.canContain(sg): raise "Test failed" if sg.canContain(app): raise "Test failed" if not sg.canBeContained(app): raise "Test failed" if app.canBeContained(sg): raise "Test failed" # Now hook the sg up and then test it again app.containmentArrows.append(ContainmentArrow(app,(0,0),sg,(0,0))) app2 = m.entities["app2"] = entity.Entity(appt,(0,0),(100,20)) if not sg.canBeContained(app): raise "Test failed: should return true because sg is contained in app" if sg.canBeContained(app2): raise "Test failed: should return false because sg can only be contained in one app" m.entities["appSG"].createInstance((0,0),(100,40),"sg0") m.instances[sg0.data["name"]] = sg0
def cruiser(x, y): combatship_component = combatship.CombatShip(hull=80, shields=20, defense=0, power=3) ai_component = ai.BasicAI() inventory_component = inventory.Inventory(5) item_component1 = item.Item(use_function=item_functions.target_shot, targeting='auto_on', targeting_message='', quantity=50, max_charge_time=2, damage=10, maximum_range=10, accuracy=70, mode='damage', name='Laser Turret', color='light blue') turret1 = entity.Entity(None, None, '#', 'yellow', 'Laser Turret', render_order=RenderOrder.ITEM, ai=ai.TurretAI(), item=item_component1) inventory_component.items.append(turret1) item_component2 = item.Item(use_function=item_functions.target_shot, targeting='auto_on', targeting_message='', quantity=50, max_charge_time=2, damage=10, maximum_range=10, accuracy=70, mode='damage', name='Laser Turret', color='light blue') turret2 = entity.Entity(None, None, '#', 'yellow', 'Laser Turret', render_order=RenderOrder.ITEM, ai=ai.TurretAI(), item=item_component2) inventory_component.items.append(turret2) enemy = entity.Entity(x, y, 'c', 'green', 'Cruiser', blocks=True, render_order=RenderOrder.ACTOR, combatship=combatship_component, ai=ai_component, inventory=inventory_component) return enemy
def f(*args): pos = makePos(*args) # coords of the top left tile. if (x, y) is the top left # then (x+1, y) is the top right, and (x, y+1) and (x+1, y+1) # the left and right walls of the pipe. sheet = vars.tile_data['tile_sheets']['main'] tl = kwargs.get('top_left') height = args[3] data = [tl[0], tl[1] + 1, tl[0] + 1, tl[1] + 1] * (height - 1) data.extend([tl[0], tl[1], tl[0] + 1, tl[1]]) e = entity.Entity(pos=pos) e.add_component( comp.TiledGfx(tile_sheet=sheet['file'], sheet_size=sheet['sheet_size'], tile_data=data, width=2, height=height, size=vars.tile_size)) shape = sh.Rect(width=2 * vars.tile_size, height=height * vars.tile_size) e.add_component( comp.Collider(flag=vars.flags.platform, mask=1, tag=1, shape=shape)) foe = kwargs.get('foe', None) exit = kwargs.get('exit', None) if foe: foe_tag = monkey.engine.get_next_tag() pct = 1 if exit: if exit not in vars.disable_update_on_start: vars.disable_update_on_start[exit] = [] vars.disable_update_on_start[exit].append(foe_tag) pct = 0.5 p = plant(model=foe, pct=pct)(1, height, -0.1) p.tag = foe_tag plant_id = e.add(p) sensor = entity.Entity(pos=(vars.tile_size, height * vars.tile_size)) size = (8.0, 0.4, 0.0) sensor.add_component( comp.Collider(debug=True, flag=vars.flags.foe, mask=vars.flags.player, tag=vars.tags.generic_hotspot, shape=sh3d.AABB(size=size, offset=(-size[0] * 0.5, 0.0, 0.0)))) sensor.add_component( comp.Info(on_enter=freeze_plant(p.tag, False), on_leave=freeze_plant(p.tag, True))) e.add(sensor) warp_info = kwargs.get('warp', None) if warp_info: w = warp()(1, height, 0, warp_info[0], warp_info[1]) e.add(w) return e
def __init__(self): self.game_exit = False self.use_joystick = False self.player = player.Player(surface, 500, 330, self.use_joystick) if pygame.joystick.get_count(): self.joystick = pygame.joystick.Joystick(0) self.joystick.init() self.use_joystick = True self.player.use_joystick = True self.entity1 = entity.Entity(400, 400, 30, 80, 0, surface, 0, (0, 0, 0)) self.entity2 = entity.Entity(490, 400, 80, 30, 0, surface, 0, (0, 0, 0))
def render(con, entities, items, levelmap, screen_width, screen_height): for y in range(levelmap.width): for x in range(levelmap.height): wall = levelmap.tiles[x][y].solid if wall: draw_entity(0, ent.Entity(0, x, y, '#', (255, 255, 255))) else: draw_entity(0, ent.Entity(0, x, y, ' ', (0, 0, 0))) for entity in entities: draw_entity(con, entity) for item in items: draw_entity(con, item)
def get_game_variables(constants): player = playerships.player_cruiser() targeting_cursor = entity.Entity( 0, 0, '#', 'yellow', 'TargetingCursor', blocks=False, render_order=RenderOrder.INACTIVE_TARGETING) entities = [player, targeting_cursor] game_map = GameMap(constants['map_width'], constants['map_height']) game_map.make_map(constants['max_asteroids'], constants['max_asteroid_radius'], entities, constants['max_enemies_per_screen'], constants['max_items_per_screen'], constants['max_stars_per_screen']) message_log = MessageLog(constants['message_x'], constants['message_width'], constants['message_height']) game_state = GameStates.PLAYERS_TURN return player, entities, game_map, message_log, game_state
def test_entity(self): """ Creates an entity :return: None """ ent = entity.Entity((0, 0, 0), (0, 0)) self.assertTrue(isinstance(ent, entity.Entity))
def setUp(self): self.e = entity.Entity() self.e.add_component(components.mortal.Mortal()) c = component.Component() c.attributes = [("test", True)] c.handlers = [("handler", lambda e, p: e.add_attribute("handled"))] self.e.add_component(c)
def f(*args): pos = (args[0], args[1], args[2]) width = args[3] height = args[4] depth = args[5] offset = (0, 0, 0) if len(args) > 6: offset = (args[6], args[7], args[8]) color = kwargs.get('color', [1, 1, 1, 1]) e = entity.Entity(pos=pos) shape = sh3d.AABB(size=(width, height, depth), offset=offset) e.add_component(comp.ShapeGfxColor(shape=shape, color=color)) e.add_component( comp.Collider(shape=shape, flag=vars.flags.platform, mask=0, tag=vars.tags.platform)) tx_top = kwargs.get('top', None) tx_front = kwargs.get('front', None) if tx_top: e.add( make_plat( glm.vec3(0, height, depth) + offset, (width, depth), tx_top)) if tx_front: e.add( make_wall( glm.vec3(0, 0, depth) + offset, (width, height), tx_front)) #e.add(make_wall(offset + glm.vec3(0, 0, depth), (width, height), '2')) #e.add(make_wall(offset + glm.vec3(width, 0, depth), (depth, height), '2', 90)) return e
def f(*args): key = args[0] is_player = key == vars.current_player desc = args[1] model = desc.get('model', None) text_color = desc.get('text_color', [255, 255, 255, 255]) text_offset = desc.get('text_offset', [0, 60]) pos = desc.get('pos') tag = desc.get('tag', key) s = None dir = desc.get('dir', 's') ways = desc.get('ways', 4) if model: s = entity.Sprite(model=model, pos=pos, tag='player' if is_player else tag) #s.add_component(compo.Collider(debug=True, flag=vars.Collision.Flags.player, mask=vars.Collision.Flags.other, # tag=vars.Collision.Tags.player, shape=shapes.Rect(width=8, height=2, offset=[-4, 0]))) if is_player: s.add_component(compo.Follow()) else: s = entity.Entity(pos=pos, tag='player' if is_player else tag) s.add_component( scumm.components.CharacterController(dir=dir, speed=100, text_color=text_color, text_offset=text_offset, ways=ways)) on_create_script = desc.get('script', None) if on_create_script: s.on_create = getattr(scripts, on_create_script) return s
def f(*args): pos = makePos(*args) e = entity.Entity(pos=pos) e.add_component( comp.TiledGfx(tile_sheet='gfx/smb1.png', sheet_size=[16, 16], tile_data=[15, 5], width=1, height=1, size=vars.tile_size, repx=args[3], repy=1)) e.add_component( comp.Collider(flag=vars.flags.platform_passthrough, mask=vars.flags.player, tag=0, shape=sh.Line( a=[0, vars.tile_size, 0], b=[args[3] * vars.tile_size, vars.tile_size, 0]))) e.add_component( comp.PolygonalMover(origin=(pos[0], pos[1]), loop=args[6], pct=args[4], moves=[{ 'delta': [0, args[5] * vars.tile_size], 'speed': args[7], 'hold': 0 }])) e.add_component(comp.Platform()) return e
def f(*args): pos = makePos(*args) # coords of the top left tile. if (x, y) is the top left # then (x+1, y) is the top right, and (x, y+1) and (x+1, y+1) # the left and right walls of the pipe. sheet = vars.tile_data['tile_sheets']['main'] tl = kwargs.get('top_left') width = args[3] height = args[4] data = [tl[0], tl[1]] data.extend([tl[0] + 1, tl[1]] * (width - 2)) data.extend([tl[0] + 2, tl[1]]) e = entity.Entity(pos=pos) e.add_component( comp.TiledGfx(tile_sheet=sheet['file'], sheet_size=sheet['sheet_size'], tile_data=data, width=width, height=1, size=vars.tile_size)) shape = sh.Line(a=(0, vars.tile_size), b=(width * vars.tile_size, vars.tile_size)) e.add_component( comp.Collider(flag=vars.flags.platform, mask=1, tag=1, shape=shape, debug=True)) return e
def f(*args): shape = None tile_set_id = kwargs['id'] tile_set = vars.tile_data['tile_sets'][tile_set_id] pos = makePos2(*args) sheet_id = tile_set['sheet'] sheet = vars.tile_data['tile_sheets'][sheet_id] width = tile_set['size'][0] height = tile_set['size'][1] solid = tile_set['solid'] data = tile_set['data'] e = entity.Entity(pos=pos) e.add_component( comp.TiledGfx(tile_sheet=sheet['file'], sheet_size=sheet['sheet_size'], tile_data=data, width=width, height=height, size=vars.tile_size)) if solid: shape = sh.Rect(width=width * vars.tile_size, height=height * vars.tile_size) e.add_component( comp.Collider(flag=vars.flags.platform, mask=1, tag=1, shape=shape)) return e
def f(*args): # the first argument is the callback function # the second, if present, is the model model = kwargs.get('model', None) callback = kwargs.get('func') info = kwargs.get('info', None) pos = makePos2(*args) if model is None: a = entity.Entity(pos=pos) size = [args[2] * vars.tile_size, args[3] * vars.tile_size, 0] a.add_component( comp.Collider(debug=True, flag=vars.flags.foe, mask=vars.flags.player, tag=vars.tags.key, shape=sh3d.AABB(size=size))) a.add_component( comp.Info(func=callback, info=info, args=args, bounds=[0, 0, size[0], size[1]])) else: a = entity.Sprite(model=model, pos=pos) a.add_component( comp.SmartCollider(debug=True, flag=vars.flags.foe, mask=vars.flags.player, tag=vars.tags.key)) a.add_component(comp.Info(func=callback, info=info, args=args)) return a
def create_mob(self, player): """Spawn a new mob, randomly generating any required fields. Parameters ---------- player : Player the Player entity to generate a fair mob based on. """ name = create_name() health_min = int(player.health * min(config.variance)) health_max = int(player.health * max(config.variance)) health = random.randint(health_min, health_max) damage_limits = [] damage_min = [ int(min(player.damage_range) * x) for x in config.variance ] damage_limits.append(random.randint(min(damage_min), max(damage_min))) damage_max = [ int(max(player.damage_range) * x) for x in config.variance ] damage_limits.append(random.randint(min(damage_max), max(damage_max))) if min(damage_limits) == max(damage_limits): damage_limits = [min(damage_limits), min(damage_limits) + 1] damage_range = range(min(damage_limits), max(damage_limits)) return entity.Entity(name, max_health=health, damage_range=damage_range)
def enter(self): self.music = game.get_game().resource_manager.get( 'sound', 'Main Body.ogg') self.music.play(loops=-1) game.get_game().renderer.cleanup() game.get_game().entity_manager.add_entity( entity.Entity("vortexspawner"))
def Network_Login(self, message): #message: name, password ##Add network authentication name = message['name'] if not self._server.ChannelActive( name): #Make sure that player isn't already logged in. ##I hate everything about this if self._server.playerEntities.has_key(name): self.entity = self._server.playerEntities[name] self.entity.channel = self ##need to make this an entity func else: ent = entity.Entity(name, "e" + name, 0, 0) ent.channel = self self._server.playerEntities[name] = ent self.entity = ent self.entity.SetMap(mapManager.maps[0][0]) self._server.LogIn(name, self) self.loggedIn = True else: self.Send(messages.Chat("You're already logged on"))
def CurseBees(position: entity.Position): class _CurseBees(Curse): def generate_map(self, entity: entity.Entity, user_entity: entity.Entity, mapp: map.Map, menu: panel.Menu): difficulty = user_entity.stat('level') curse_map = map.TwoRooms(30, 30, can_escape=False) for _ in range(25): beehive = monster.Beehive.generator(level=difficulty)((0, 0)) x, y = curse_map.random_passable_position_for(beehive) beehive.component('Position').set(x, y) curse_map.add_entity(beehive) curse_map.commit() return curse_map import monster, uuid x, y = position return entity.Entity( str(uuid.uuid4()), components={ 'Stats': entity.Stats({}, stat_inc_per_level=loot.LEVEL_PC_STAT_INC), 'Position': entity.Position(x, y), 'Render': entity.Render(character='?', colour=tcod.yellow), 'Usable': entity.ConsumeAfter(_CurseBees()), 'Item': entity.Item( "Curse of bees", 'Network item; force a player to encounter a floor full of bees' ), }, ttype='CurseBees')
def __init__(self): #set physics variables self.clock = pygame.time.Clock() self.__physics_FPS = 100.0 self.__dt = 1.0 / self.__physics_FPS self.time_current = self.get_time() self.accumulator = 0.0 self.tile_size = 32 self.camera = camera.Camera((1280, 720)) tile_images = { "tile_grass": IMAGES.tile_grass, "tile_dirt": IMAGES.tile_dirt, "tile_wall": IMAGES.tile_wall } world = WORLD.World("level.map", tile_images) self.path_finder = pathfinder.PathFinder(world.nodes) player = entity.Player(IMAGES.player) dummy = entity.Entity(IMAGES.player, spawn_location = (16, 2)) self.entities = pygame.sprite.Group(player, dummy) self.objects = dict(world=world, player=player, dummy=dummy) self.console = console.Console() s = item.Sword(IMAGES.key) b = item.Bandage(IMAGES.key) player.hand.add(s) player.bag.add(0, b)
def f(*args): key = args[0] desc = args[1] cio = desc.get('create_if_owned', False) if (not cio) and vars.someone_owns(key): # item is in inventory. don't create it return None pos = desc.get('pos') model = desc.get('model', None) #text = monkey.engine.read(desc.get('text')) s = None if model: anim = monkey.engine.read(desc.get('anim', None)) s = entity.Sprite(model=model, pos=pos, anim= anim) else: s = entity.Entity(pos = pos) #s.tag = desc.get('tag', None) s.tag= key # if a size is provided, add a hotspot size = desc.get('size', None) if size: prio = desc.get('priority', 0) s.add_component(compo.HotSpot(shape=shapes.Rect(width=size[0], height=size[1]), priority=prio, onenter=func.hover_on(key), onleave=func.hover_off(key), onclick=func.prova())) return s
def update(self, data): self.players.update(data['players'], data.get('full', False), self) self.entities.update(data['entities'], data.get('full', False), self) self.npcs.update(data['npcs'], data.get('full', False), self) if len(data['players']) != 0: for i in data['players']: p = entity.Player(self) # TODO: create from data p.id = i['id'] p.standalone = False p.original_center = (i['x'], i['y']) p.update(data['players'], data.get('full', False), self) p.update({'target': self.target}) self.players.add(p) if len(data['entities']) != 0: for i in data['entities']: p = entity.Entity(self) # TODO: create from data p.id = i['id'] p.original_center = (i['x'], i['y']) p.update(data['players'], data.get('full', False), self) p.update({'target': self.target}) self.entities.add(p) if len(data['npcs']) != 0: for i in data['npcs']: p = entity.NPC(self) # TODO: create from data p.id = i['id'] p.original_center = (i['x'], i['y']) p.update(data['npcs'], data.get('full', False), self) p.update({'target': self.target}) self.npcs.add(p)
def f(*args): ym = kwargs.get('y_min') y0 = kwargs.get('y_min_goto') wa: WalkAreaInfo = vars.walk_areas[y0[0]] ymg = wa.transform(y0[1:]) print('y m goto = ' + str(ymg)) yM = kwargs.get('y_max') y1 = kwargs.get('y_max_goto') wa: WalkAreaInfo = vars.walk_areas[y1[0]] yMg = wa.transform(y1[1:]) print('y M goto = ' + str(yMg)) x0 = args[0] depth_y = args[2] * math.sqrt(2.0) y0 = args[1] - args[2] z0 = -depth_y pos = (x0, y0, z0) e = entity.Entity(pos=pos) e.add_component( comp.Collider(debug=True, shape=sh3d.AABB(size=(args[3], args[4], args[5])), flag=vars.flags.foe, mask=vars.flags.player, tag=vars.tags.ladder)) e.add_component( comp.Info(x=522, y_min=ym, y_max=yM, y_min_goto=ymg, y_max_goto=yMg)) return e
def tree(): tree = entity.Entity() tree.add_component(components.mortal.Mortal()) tree.add_component(components.position.Position()) tree.add_component(components.senescence.Senescence()) tree.add_component(components.woundable.Woundable()) tree.add_attribute("type", "tree") return tree
def f(*args): desc = args[1] pos = desc.get('pos') size = desc.get('size') s = entity.Entity(pos=pos) fu = getattr(scripts.actions, desc.get('func')) s.add_component(compo.HotSpot(shape=shapes.Rect(width=size[0], height=size[1]), onclick=fu)) return s
def test_add_entity(self): """ Adds an entity to the entity manager :return: """ ent = entity.Entity((0, 0, 0), (0, 0)) result = self.entity_manager.add_entity(ent) self.assertTrue(result)
def execute(self): print("Building brush entity, currently geo " + str(id(command.GeoCommand._geo)) + " has " + str(len(command.GeoCommand._geo)) + " brushes.") brush_entity = entity.Entity(classname="func_detail", brushes=command.GeoCommand._geo) command.MapCommand._map.append(brush_entity) print(command.MapCommand._map[len(command.MapCommand._map) - 1])
def test_exits(self): e = en.Entity(5, 30, 10) e.update_move() e.move_in_exits([0, 16]) self.assertEqual((e.rect.x, e.rect.y), (20, 30)) e.current_dir = 'right' e.update_move() e.move_in_exits([0, 16]) self.assertEqual((e.rect.x, e.rect.y), (2, 30))
def f(*args): desc = args[1] pos = desc.get('pos') size = desc.get('size') s = entity.Entity(pos=pos) s.add_component(compo.Collider(flag=vars.Collision.Flags.other, mask=vars.Collision.Flags.player, tag=vars.Collision.Tags.trap, shape=shapes.Rect(width=size[0],height=size[1]),debug=True)) s.add_component(compo.Info(on_enter=desc.get('on_enter', None), on_leave=desc.get('on_leave', None))) return s
def generate_free_camera(): """ Generates free camera at (0, 0) """ camera = creature.Creature("camera", False, team=None, walk_through_tile=True) free_camera = entity.Entity(0, 0, "camera", creature=camera) return free_camera