def select_object(kind): global classType, PreyObj, special_on allSims = all_sim(Black_Hole.__bases__[0]) for name in allSims: if name.__name__ == kind: classType = name if name.__name__ == "Prey": PreyObj = name if kind == "Remove": classType = kind elif kind == "Special": if special_on == False: special_on = True for s in sim: if isinstance(s, Hunter): x, y = s.get_location() w, h = s.get_dimension() specialOb = Special(x, y) specialOb.set_dimension(w, h) sim.add(specialOb) controller.the_canvas.delete(s) sim.remove(s) else: special_on = False for s in sim: if isinstance(s, Special): x, y = s.get_location() w, h = s.get_dimension() hunterOb = Hunter(x, y) hunterOb.set_dimension(w, h) sim.add(hunterOb) controller.the_canvas.delete(s) sim.remove(s)
def addHunters(self, num=1): # Add the foods for _ in range(num): newHunter = Hunter(world=self) newHunter.pos = self.tank.randomPosition() self.hunters.append(newHunter)
def bullet(self): self._counter += 1 if self._counter == 80: x = Hunter(self._x, self._y) x.radius = 3 x.color = 'white' model.add(x) self._counter = 0
def __init__(self): super(Hunting, self).__init__() self.world_surf = pg.Surface(prepare.WORLD_SIZE).convert() self.world_rect = self.world_surf.get_rect() self.background = make_background(prepare.WORLD_SIZE) self.all_sprites = pg.sprite.LayeredDirty() self.colliders = pg.sprite.Group() self.ui = pg.sprite.Group() self.noise_detector = NoiseDetector((10, 80), self.ui) self.hunter = Hunter(self.world_rect.center, 0, self.noise_detector, self.all_sprites) self.turkeys = self.add_turkeys() self.bullets = pg.sprite.Group() self.make_trees() hx, hy = self.hunter.rect.center self.ammo_crate = AmmoCrate((hx - 50, hy - 50), self.colliders, self.all_sprites) self.all_sprites.clear(self.world_surf, self.background) self.leaves = pg.sprite.Group() self.roasts = pg.sprite.Group() self.flocks = pg.sprite.Group() self.animations = pg.sprite.Group() self.rustle_sounds = [prepare.SFX["rustle{}".format(x)] for x in range(1, 21)] self.wind_gust() style = {"font_path": prepare.FONTS["pretzel"], "font_size": 24, "text_color": (58, 41, 18)} self.shell_label = Label("{}".format(self.hunter.shells), {"topleft": (50, 10)}, **style) self.roasts_label = Label("{}".format(self.hunter.roasts), {"topleft": (50, 50)}, **style) Icon((20, 3), "shell", self.ui) Icon((10, 45), "roast", self.ui) self.add_flock()
def init(): harvesters = [] hunters = [] storages = [] supplies = [] for i in range(num_harvesters): harvesters.append( Harvester(random.randint(0, 10), random.randint(0, 10), [random.randint(0, 500), random.randint(0, 500)], None)) #print(dna) for i in range(num_hunters): hunters.append( Hunter(random.randint(0, 10), random.randint(0, 10), [random.randint(0, 500), random.randint(0, 500)])) for i in range(num_storages): storages.append( Storage([random.randint(0, 500), random.randint(0, 500)])) for i in range(num_supplies): supplies.append( Supply([random.randint(0, 500), random.randint(0, 500)])) return np.array(harvesters), np.array(hunters), np.array( storages), np.array(supplies)
def create_world(self): for i in range(self.num_hunters): x = randint(2, self.FIELD_LENGTH - 2) y = randint(2, self.FIELD_WIDTH - 2) hunter = Hunter(x, y, 5, self.field, 'h', 'r', 5) self.field.objects_array[x][y] = hunter self.field.array[x][y] = 'h' self.hunters.append(hunter) for i in range(self.num_rabbits): x = randint(2, self.FIELD_LENGTH - 2) y = randint(2, self.FIELD_WIDTH - 2) rabbit = Rabbit(x, y, 6, self.field, 'r', 'c', 5) self.field.objects_array[x][y] = rabbit self.field.array[x][y] = 'r' self.rabbits.append(rabbit) for i in range(self.num_carrots): x = randint(2, self.FIELD_LENGTH - 2) y = randint(2, self.FIELD_WIDTH - 2) carrot = Carrot(x, y, self.field) self.field.array[x][y] = 'c' self.field.objects_array[x][y] = carrot self.carrots.append(carrot) self.carrots_clone = self.carrots self.update()
def mouse_click(x, y): global object if object == 'Ball': balls.add(Ball(x, y, random_angle())) elif object == "Floater": balls.add(Floater(x, y, random_angle())) elif object == "Black_Hole": simu.add(Black_Hole(x, y)) elif object == "Pulsator": simu.add(Pulsator(x, y)) elif object == "Remove": g = balls h = set() k = set() for f in g: if f.contains((x, y)): h.add(f) for s in simu: if s.contains((x, y)): k.add(s) for l in h: remove(l) for b in k: simu.remove(b) pass elif object == "Hunter": simu.add(Hunter(x, y, random_angle()))
def start(self): prev = "" while 1: resp = self.s.recv(1024) + prev if '\n' not in resp: prev = resp continue resp = resp.split('\n') currResp = resp[0] resp.pop(0) prev = '\n'.join(resp) # print currResp if 'done' in currResp: break if 'sendname' in currResp: self.sendOutput(self.teamname) continue if 'hunter' in currResp: self.playerType = 'hunter' self.flag = 0 continue elif 'prey' in currResp: self.playerType = 'prey' self.flag = 0 continue currResp = currResp.split(' ') currResp = self.parseInput(currResp) if self.flag == 0: self.flag = 1 self.player = Hunter( currResp) if self.playerType == 'hunter' else Prey( currResp) self.sendOutput(self.parseOutput(self.player.move(currResp))) self.s.close()
def update(self): eat = Hunter.update(self) if eat: daughter_ameba = Special(self._x, self._y) daughter_ameba.set_dimension(self._width, self._height) daughter_ameba.set_angle(self._angle+math.pi) model.add(daughter_ameba)
def main(): def handler(signum, frame): hunter.force_closure = True hunter.early_shutdown() parser = argparse.ArgumentParser(description='Find a golden nonce.') parser.add_argument('k', metavar='k', help='Name of AWS key pair') parser.add_argument('n', metavar='n', type=int, help='The number of desired workers to run') parser.add_argument('d', metavar='d', type=int, help='The desired difficulty') parser.add_argument('ami', metavar='ami', help='Name of AMI') parser.add_argument( '-c', metavar='c', type=float, help= 'Confidence of finding golden nonce within time limit t. Between 0 and 1. Notes: overrides n (worker count), t argument must also be passed to use this', default=-1) parser.add_argument('-t', metavar='t', type=float, help='Time limit (seconds)', default=-1) parser.add_argument( '-p', metavar='p', type=float, help='Cost limit (in dollars ($)). Note: overriden by time limit', default=-1) # Create golden nonce finder hunter = Hunter(parser) signal.signal(signal.SIGINT, handler) hunter.start()
def __init__(self): super(Hunting, self).__init__() self.world_surf = pg.Surface(prepare.WORLD_SIZE).convert() self.world_rect = self.world_surf.get_rect() self.background = make_background(prepare.WORLD_SIZE) self.all_sprites = pg.sprite.LayeredDirty() self.colliders = pg.sprite.Group() self.ui = pg.sprite.Group() self.noise_detector = NoiseDetector((10, 80), self.ui) self.hunter = Hunter(self.world_rect.center, 0, self.noise_detector, self.all_sprites) self.turkeys = self.add_turkeys() self.bullets = pg.sprite.Group() self.make_trees() hx, hy = self.hunter.rect.center self.ammo_crate = AmmoCrate((hx - 50, hy - 50), self.colliders, self.all_sprites) self.all_sprites.clear(self.world_surf, self.background) self.leaves = pg.sprite.Group() self.roasts = pg.sprite.Group() self.flocks = pg.sprite.Group() self.animations = pg.sprite.Group() self.rustle_sounds = [ prepare.SFX["rustle{}".format(x)] for x in range(1, 21) ] self.wind_gust() style = { "font_path": prepare.FONTS["pretzel"], "font_size": 24, "text_color": (58, 41, 18) } self.shell_label = Label("{}".format(self.hunter.shells), {"topleft": (50, 10)}, **style) self.roasts_label = Label("{}".format(self.hunter.roasts), {"topleft": (50, 50)}, **style) Icon((20, 3), "shell", self.ui) Icon((10, 45), "roast", self.ui) self.add_flock()
def mouse_click(x, y): if button == 'Ball': simulation.add(Ball(x, y)) elif button == 'Floater': simulation.add(Floater(x, y)) elif button == 'Black_Hole': simulation.add(Black_Hole(x, y)) elif button == 'Pulsator': simulation.add(Pulsator(x, y)) elif button == 'Hunter': simulation.add(Hunter(x, y)) elif button == 'Special': simulation.add(Special(x, y)) elif button == 'Remove': for i in simulation.copy(): if i.distance((x, y)) < i.radius: remove(i)
def mouse_click(x,y): global selection, simultons if selection == 'Remove': #Need to finish for sim in simultons.copy(): if sim.contains( (x,y) ): remove(sim) elif selection == 'Ball': add( Ball(x,y,5,5,0,5) ) elif selection == 'Floater': add( Floater(x,y,5,5,0,5) ) elif selection == 'Black_Hole': add( Black_Hole(x,y,20,20) ) elif selection == 'Pulsator': add( Pulsator(x,y,20,20) ) elif selection == 'Hunter': add( Hunter(x,y,20,20,0,5) ) elif selection == 'Special': add( Special(x,y,5,5,0,10) )
def mouse_click(x,y): try: if object_name == 'Ball': balls.add(Ball(x,y)) elif object_name == 'Floater': balls.add(Floater(x,y)) elif object_name == 'Black_Hole': balls.add(Black_Hole(x,y)) elif object_name == 'Pulsator': balls.add(Pulsator(x,y)) elif object_name == 'Hunter': balls.add(Hunter(x,y)) elif object_name == 'Special': balls.add(Special(x,y)) elif object_name == 'Remove': for i in find(lambda a: a.contains((x,y))): balls.remove(i) except: pass
def mouse_click(x, y): global balls if select_kind == 'Remove': for b in balls: coor = b.get_location() if coor[0] - 5 < x and x < coor[0] + 5 and coor[ 1] - 5 < y and y < coor[1] + 5: remove(b) break elif select_kind == 'Ball': add(Ball(x, y)) elif select_kind == 'Floater': add(Floater(x, y)) elif select_kind == 'Black_Hole': add(Black_Hole(x, y)) elif select_kind == 'Pulsator': add(Pulsator(x, y)) elif select_kind == 'Hunter': add(Hunter(x, y)) elif select_kind == 'Special': add(Special(x, y))
def mouse_click(x,y): global balls, click, remove_set if str(click) == "Remove": try: for ele in balls: if ele.contains((x,y)): remove(ele) except: pass else: if str(click) == "Ball": add(Ball(x,y)) elif str(click) == 'Black_Hole': add(Black_Hole(x,y)) elif str(click) == 'Floater': add(Floater(x,y)) elif str(click) == 'Hunter': add(Hunter(x,y)) elif str(click) == 'Pulsator': add(Pulsator(x,y)) elif str(click) == "Special": add(Special(x,y))
def __init__(self): super(Hunting, self).__init__() map_data = MapData() map_layer = BufferedRenderer(map_data, prepare.SCREEN_SIZE) self.all_sprites = PyscrollGroup(map_layer=map_layer) self.colliders = pg.sprite.Group() self.ui = pg.sprite.Group() self.noise_detector = NoiseDetector((10, 80), self.ui) self.animations = pg.sprite.Group() self.hunter = Hunter(map_layer.map_rect.center, 0, self.noise_detector, self.all_sprites) self.leaves = pg.sprite.Group() self.roasts = pg.sprite.Group() self.flocks = pg.sprite.Group() self.turkeys = self.add_turkeys() self.bullets = pg.sprite.Group() self.make_trees() hx, hy = self.hunter.rect.center self.ammo_crate = AmmoCrate((hx - 50, hy - 50), self.colliders, self.all_sprites) self.rustle_sounds = [prepare.SFX["rustle{}".format(x)] for x in range(1, 21)] self.wind_gust() style = {"font_path": prepare.FONTS["pretzel"], "font_size": 24, "text_color": (58, 41, 18)} self.shell_label = Label("{}".format(self.hunter.shells), {"topleft": (50, 10)}, **style) self.roasts_label = Label("{}".format(self.hunter.roasts), {"topleft": (50, 50)}, **style) Icon((20, 3), "shell", self.ui) Icon((10, 45), "roast", self.ui) self.add_flock()
win = window.Window(width=500, height=500, vsync=True, resizable=True) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) # needed so that egi knows where to draw egi.InitWithPyglet(win) # prep the fps display fps_display = clock.ClockDisplay() # register key and mouse event handlers win.push_handlers(on_key_press) win.push_handlers(on_mouse_press) win.push_handlers(on_resize) # create a world for agents world = World(500, 500) # add one agent world.agents.append(Agent(world)) world.hunter.append(Hunter(world)) # unpause the world ready for movement world.paused = False while not win.has_exit: win.dispatch_events() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # show nice FPS bottom right (default) delta = clock.tick() world.update(delta) world.render() fps_display.draw() # swap the double buffer win.flip()
win = window.Window(width=500, height=500, vsync=True, resizable=True) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) # needed so that egi knows where to draw egi.InitWithPyglet(win) # prep the fps display fps_display = clock.ClockDisplay() # register key and mouse event handlers win.push_handlers(on_key_press) win.push_handlers(on_mouse_release) win.push_handlers(on_resize) # create a world for agents world = World(500, 500) # add one agent world.hunter = Hunter(world) world.agents.append(Prey(world)) # add HideObjects for _ in range(5): obj = HideObject(world) world.hideObjects.append(obj) # unpause the world ready for movement world.paused = False while not win.has_exit: win.dispatch_events() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # show nice FPS bottom right (default) delta = clock.tick() world.update(delta) world.render()
class Hunting(GameState): """The main game state.""" def __init__(self): super(Hunting, self).__init__() self.world_surf = pg.Surface(prepare.WORLD_SIZE).convert() self.world_rect = self.world_surf.get_rect() self.background = make_background(prepare.WORLD_SIZE) self.all_sprites = pg.sprite.LayeredDirty() self.colliders = pg.sprite.Group() self.ui = pg.sprite.Group() self.noise_detector = NoiseDetector((10, 80), self.ui) self.hunter = Hunter(self.world_rect.center, 0, self.noise_detector, self.all_sprites) self.turkeys = self.add_turkeys() self.bullets = pg.sprite.Group() self.make_trees() hx, hy = self.hunter.rect.center self.ammo_crate = AmmoCrate((hx - 50, hy - 50), self.colliders, self.all_sprites) self.all_sprites.clear(self.world_surf, self.background) self.leaves = pg.sprite.Group() self.roasts = pg.sprite.Group() self.flocks = pg.sprite.Group() self.animations = pg.sprite.Group() self.rustle_sounds = [ prepare.SFX["rustle{}".format(x)] for x in range(1, 21) ] self.wind_gust() style = { "font_path": prepare.FONTS["pretzel"], "font_size": 24, "text_color": (58, 41, 18) } self.shell_label = Label("{}".format(self.hunter.shells), {"topleft": (50, 10)}, **style) self.roasts_label = Label("{}".format(self.hunter.roasts), {"topleft": (50, 50)}, **style) Icon((20, 3), "shell", self.ui) Icon((10, 45), "roast", self.ui) self.add_flock() def wind_gust(self): """Play wind sound and set up next gust.""" prepare.SFX["wind"].play() task = Task(self.wind_gust, randint(15000, 45000)) self.animations.add(task) def add_turkeys(self): """Spawn turkeys.""" turkeys = pg.sprite.Group() w, h = prepare.WORLD_SIZE for _ in range(35): pos = randint(20, w - 20), randint(20, h - 20) Turkey(pos, turkeys, self.all_sprites) return turkeys def make_trees(self): """Spawn trees.""" self.trees = pg.sprite.Group() w, h = prepare.WORLD_SIZE for _ in range(120): while True: pos = (randint(50, w - 20), randint(20, h - 20)) tree = Tree(pos) collisions = (tree.collider.colliderect(other.collider) for other in self.colliders) if not any(collisions) and not tree.collider.colliderect( self.hunter.collider): break self.trees.add(tree) self.colliders.add(tree) self.all_sprites.add(tree) def add_flock(self): """Add a Flock of birds.""" flock = Flock((self.hunter.collider.centerx, -1500), self.animations, self.all_sprites, self.flocks) next_flock = randint(45000, 150000) #next flock in 45-150 seconds task = Task(self.add_flock, next_flock) self.animations.add(task) def update(self, dt): self.animations.update(dt) keys = pg.key.get_pressed() self.hunter.update(dt, keys, self.bullets, self.turkeys, self.colliders, self.all_sprites, self.animations) self.turkeys.update(dt, self.trees) self.bullets.update(dt) for sprite in self.all_sprites: self.all_sprites.change_layer(sprite, sprite.collider.bottom) tree_hits = pg.sprite.groupcollide(self.bullets, self.trees, True, False, footprint_collide) for bullet in tree_hits: for tree in tree_hits[bullet]: choice(self.rustle_sounds).play() num = randint(3, 9) for spot_info in sample(leaf_spots[tree.trunk], num): self.add_leaf(tree, spot_info) turkey_hits = pg.sprite.groupcollide(self.bullets, self.turkeys, True, True, footprint_collide) for t_bullet in turkey_hits: for turkey in turkey_hits[t_bullet]: Roast(turkey.pos, self.roasts, self.all_sprites) if self.hunter.shells < self.hunter.max_shells: if self.hunter.collider.colliderect( self.ammo_crate.rect.inflate(16, 16)): prepare.SFX["gunload"].play() self.hunter.shells = self.hunter.max_shells if self.hunter.state == "move": self.scare_turkeys() self.noise_detector.update(dt) self.shell_label.set_text("{}".format(self.hunter.shells)) self.roasts_label.set_text("{}".format(self.hunter.roasts)) roast_collisions = pg.sprite.spritecollide(self.hunter, self.roasts, True, footprint_collide) if roast_collisions: prepare.SFX["knifesharpener"].play() self.hunter.roasts += len(roast_collisions) self.flocks.update(self.hunter) def scare_turkeys(self): """Make turkeys flee depending on distance and the player's noise level.""" size = self.noise_detector.noise_level scare_rect = self.hunter.collider.inflate(size, size) scared_turkeys = ( t for t in self.turkeys if t.collider.colliderect(scare_rect) and t.state.name != "flee") for scared in scared_turkeys: scared.flee(self.hunter) def add_leaf(self, tree, spot_info): """Add a falling leaf.""" fall_time = randint(2000, 2500) leaf = Leaf(tree, spot_info, self.leaves, self.all_sprites) y = leaf.rect.centery + leaf.fall_distance ani = Animation(centery=y, duration=fall_time, round_values=True) ani.callback = leaf.land ani.start(leaf.rect) ani2 = Animation(centery=leaf.collider.centery + leaf.fall_distance, duration=fall_time, round_values=True) ani2.start(leaf.collider) fade = Animation(img_alpha=0, duration=3000, delay=fall_time, round_values=True) fade.callback = leaf.kill fade.update_callback = leaf.set_alpha fade.start(leaf) self.animations.add(ani, ani2, fade) def get_view_rect(self): """ Return the currently visible portion of the world map centered on the player. """ view_rect = pg.Rect((0, 0), prepare.SCREEN_SIZE) view_rect.center = self.hunter.pos view_rect.clamp_ip(self.world_rect) return view_rect def draw(self, surface): self.all_sprites.draw(self.world_surf) rect = self.get_view_rect() surf = self.world_surf.subsurface(rect) surface.blit(surf, (0, 0)) self.shell_label.draw(surface) self.roasts_label.draw(surface) self.ui.draw(surface)
def __init__(self, x, y): Hunter.__init__(self, x, y) self._image = PhotoImage(file='pig.png')
def update(self): Hunter.update(self) self.speed_gain() self.bullet() self.move()
def __init__(self, x, y): Hunter.__init__(self, x, y) self.width = 8 self.length = 10 self._speed = 1 self._counter = 0
def step(): global cycle_count cycle_count += 1 for b in balls.copy(): if type(b) == Black_Hole: temp_set = set() for obj in balls: if type(obj) == Ball or type(obj) == Floater: temp_set.add(obj) for obj in temp_set: ans = b.contains(obj.get_location()) if ans != None: b.obj_eaten.add(obj) balls.remove(obj) b.update(model) elif type(b) == Pulsator: temp_set = set() for obj in balls: if type(obj) == Ball or type(obj) == Floater: temp_set.add(obj) for obj in temp_set: ans = b.contains(obj.get_location()) if ans != None: b.obj_eaten.add(obj) balls.remove(obj) updated = b.update(model) if updated == 'Dead': balls.remove(b) else: updated elif type(b) == Hunter: temp_set = set() for obj in balls: if type(obj) == Ball or type(obj) == Floater: temp_set.add(obj) for obj in temp_set: ans = b.contains(obj.get_location()) if ans != None: b.obj_eaten.add(obj) balls.remove(obj) close = Hunter.distance(b, obj.get_location()) if close <= b.vision: b._close_items.append((obj, close)) try: b._smallest = b._close_items[0] for obj, dist in b._close_items: if dist < b._smallest[1]: b._smallest = (obj, dist) b.set_angle( math.atan2( b._smallest[0].get_location()[1] - b.get_location()[1], b._smallest[0].get_location()[0] - b.get_location()[0])) except: pass updated = b.update(model) if updated == 'Dead': balls.remove(b) else: updated elif type(b) == Special: temp_set = set() for obj in balls: if type(obj) == Black_Hole or type(obj) == Pulsator or type( obj) == Hunter: temp_set.add(obj) for obj in temp_set: ans = b.contains(obj.get_location()) if ans != None: balls.remove(obj) updated = b.update(model) if updated == 'Dead': balls.remove(b) else: updated else: b.update(model)
def visible_distance(self, xy): return Hunter.visible_distance(self, xy) and abs(self.get_angle()-self.angle_to(xy[0], xy[1])) <= math.pi/4
class IO: HOST = 'localhost' s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) teamname = 'jeopardy' def __init__(self, port): self.flag = 0 self.portNo = port self.s.connect((self.HOST, self.portNo)) def start(self): prev = "" while 1: resp = self.s.recv(1024) + prev if '\n' not in resp: prev = resp continue resp = resp.split('\n') currResp = resp[0] resp.pop(0) prev = '\n'.join(resp) # print currResp if 'done' in currResp: break if 'sendname' in currResp: self.sendOutput(self.teamname) continue if 'hunter' in currResp: self.playerType = 'hunter' self.flag = 0 continue elif 'prey' in currResp: self.playerType = 'prey' self.flag = 0 continue currResp = currResp.split(' ') currResp = self.parseInput(currResp) if self.flag == 0: self.flag = 1 self.player = Hunter( currResp) if self.playerType == 'hunter' else Prey( currResp) self.sendOutput(self.parseOutput(self.player.move(currResp))) self.s.close() def parseInput(self, resp): info = {} info['timeLeft'] = resp[0] info['gameNum'] = resp[1] info['tickNum'] = resp[2] info['maxWalls'] = int(resp[3]) info['wallPlacementDelay'] = resp[4] info['boardSizeX'] = int(resp[5]) info['boardSizeY'] = int(resp[6]) info['currentWallTimer'] = resp[7] info['hunter'] = Coordinate(resp[8], resp[9], resp[10], resp[11]) info['prey'] = Coordinate(resp[12], resp[13]) info['numWalls'] = int(resp[14]) info['walls'] = [] for i in range(0, info['numWalls']): info['walls'].append( Wall(int(resp[15 + i * 4]), int(resp[16 + i * 4]), int(resp[17 + i * 4]), int(resp[18 + i * 4]))) return info def parseOutput(self, infoMap): output = [] output.append(infoMap['gameNum']) output.append(infoMap['tickNum']) if self.playerType == 'hunter': # 0 for none, 1 for horizontal, 2 for vertical # Wall will be created for whole axes until other wall is encountered # or board's end is reached output.append(str(infoMap['wallAdd'])) # wallDelete should be a list for i in infoMap['wallDelete']: output.append(str(i)) else: # prey # x and y should 0, -1, 1 output.append(str(infoMap['x'])) output.append(str(infoMap['y'])) return " ".join(output) def sendOutput(self, out): self.s.sendall(out + "\n")
def spawn_player(self, location=(0, 0)): self.player_hunters.append(Hunter(location)) self.state[(location[0], location[1], self.object_layer["H"])] = 1
class Hunting(GameState): """The main game state.""" def __init__(self): super(Hunting, self).__init__() self.world_surf = pg.Surface(prepare.WORLD_SIZE).convert() self.world_rect = self.world_surf.get_rect() self.background = make_background(prepare.WORLD_SIZE) self.all_sprites = pg.sprite.LayeredDirty() self.colliders = pg.sprite.Group() self.ui = pg.sprite.Group() self.noise_detector = NoiseDetector((10, 80), self.ui) self.hunter = Hunter(self.world_rect.center, 0, self.noise_detector, self.all_sprites) self.turkeys = self.add_turkeys() self.bullets = pg.sprite.Group() self.make_trees() hx, hy = self.hunter.rect.center self.ammo_crate = AmmoCrate((hx - 50, hy - 50), self.colliders, self.all_sprites) self.all_sprites.clear(self.world_surf, self.background) self.leaves = pg.sprite.Group() self.roasts = pg.sprite.Group() self.flocks = pg.sprite.Group() self.animations = pg.sprite.Group() self.rustle_sounds = [prepare.SFX["rustle{}".format(x)] for x in range(1, 21)] self.wind_gust() style = {"font_path": prepare.FONTS["pretzel"], "font_size": 24, "text_color": (58, 41, 18)} self.shell_label = Label("{}".format(self.hunter.shells), {"topleft": (50, 10)}, **style) self.roasts_label = Label("{}".format(self.hunter.roasts), {"topleft": (50, 50)}, **style) Icon((20, 3), "shell", self.ui) Icon((10, 45), "roast", self.ui) self.add_flock() def wind_gust(self): """Play wind sound and set up next gust.""" prepare.SFX["wind"].play() task = Task(self.wind_gust, randint(15000, 45000)) self.animations.add(task) def add_turkeys(self): """Spawn turkeys.""" turkeys = pg.sprite.Group() w, h = prepare.WORLD_SIZE for _ in range(35): pos = randint(20, w - 20), randint(20, h - 20) Turkey(pos, turkeys, self.all_sprites) return turkeys def make_trees(self): """Spawn trees.""" self.trees = pg.sprite.Group() w, h = prepare.WORLD_SIZE for _ in range(120): while True: pos = (randint(50, w - 20), randint(20, h - 20)) tree = Tree(pos) collisions = (tree.collider.colliderect(other.collider) for other in self.colliders) if not any(collisions) and not tree.collider.colliderect(self.hunter.collider): break self.trees.add(tree) self.colliders.add(tree) self.all_sprites.add(tree) def add_flock(self): """Add a Flock of birds.""" flock = Flock((self.hunter.collider.centerx, -1500), self.animations, self.all_sprites, self.flocks) next_flock = randint(45000, 150000) #next flock in 45-150 seconds task = Task(self.add_flock, next_flock) self.animations.add(task) def update(self, dt): self.animations.update(dt) keys = pg.key.get_pressed() self.hunter.update(dt, keys, self.bullets, self.turkeys, self.colliders, self.all_sprites, self.animations) self.turkeys.update(dt, self.trees) self.bullets.update(dt) for sprite in self.all_sprites: self.all_sprites.change_layer(sprite, sprite.collider.bottom) tree_hits = pg.sprite.groupcollide(self.bullets, self.trees, True, False, footprint_collide) for bullet in tree_hits: for tree in tree_hits[bullet]: choice(self.rustle_sounds).play() num = randint(3, 9) for spot_info in sample(leaf_spots[tree.trunk], num): self.add_leaf(tree, spot_info) turkey_hits = pg.sprite.groupcollide(self.bullets, self.turkeys, True, True, footprint_collide) for t_bullet in turkey_hits: for turkey in turkey_hits[t_bullet]: Roast(turkey.pos, self.roasts, self.all_sprites) if self.hunter.shells < self.hunter.max_shells: if self.hunter.collider.colliderect(self.ammo_crate.rect.inflate(16, 16)): prepare.SFX["gunload"].play() self.hunter.shells = self.hunter.max_shells if self.hunter.state == "move": self.scare_turkeys() self.noise_detector.update(dt) self.shell_label.set_text("{}".format(self.hunter.shells)) self.roasts_label.set_text("{}".format(self.hunter.roasts)) roast_collisions = pg.sprite.spritecollide(self.hunter, self.roasts, True, footprint_collide) if roast_collisions: prepare.SFX["knifesharpener"].play() self.hunter.roasts += len(roast_collisions) self.flocks.update(self.hunter) def scare_turkeys(self): """Make turkeys flee depending on distance and the player's noise level.""" size = self.noise_detector.noise_level scare_rect = self.hunter.collider.inflate(size, size) scared_turkeys = (t for t in self.turkeys if t.collider.colliderect(scare_rect) and t.state.name != "flee") for scared in scared_turkeys: scared.flee(self.hunter) def add_leaf(self, tree, spot_info): """Add a falling leaf.""" fall_time = randint(2000, 2500) leaf = Leaf(tree, spot_info, self.leaves, self.all_sprites) y = leaf.rect.centery + leaf.fall_distance ani = Animation(centery=y, duration=fall_time, round_values=True) ani.callback = leaf.land ani.start(leaf.rect) ani2 = Animation(centery=leaf.collider.centery + leaf.fall_distance, duration=fall_time, round_values=True) ani2.start(leaf.collider) fade = Animation(img_alpha=0, duration=3000, delay=fall_time, round_values=True) fade.callback = leaf.kill fade.update_callback = leaf.set_alpha fade.start(leaf) self.animations.add(ani, ani2, fade) def get_view_rect(self): """ Return the currently visible portion of the world map centered on the player. """ view_rect = pg.Rect((0, 0), prepare.SCREEN_SIZE) view_rect.center = self.hunter.pos view_rect.clamp_ip(self.world_rect) return view_rect def draw(self, surface): self.all_sprites.draw(self.world_surf) rect = self.get_view_rect() surf = self.world_surf.subsurface(rect) surface.blit(surf, (0, 0)) self.shell_label.draw(surface) self.roasts_label.draw(surface) self.ui.draw(surface)
def __init(self, x, y): Hunter.__init__(x, y)
def __init__(self, x, y): Hunter.__init__(self, x, y) self.mycolor = "red"
def __init__(self, x, y): Hunter.__init__(self, x, y) self._color = 'green'
glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) # needed so that egi knows where to draw egi.InitWithPyglet(win) # prep the fps display fps_display = clock.ClockDisplay() # register key and mouse event handlers win.push_handlers(on_key_press) win.push_handlers(on_mouse_press) win.push_handlers(on_resize) # create a world for agents world = World(500, 500) # add one agent world.agents.append(Agent(world, 10, 0.01)) world.hunters.append(Hunter(world, 10, 0.01)) world.obstacles.append(Obstacle(Vector2D(100, 150), 75)) world.obstacles.append(Obstacle(Vector2D(300, 150), 75)) world.obstacles.append(Obstacle(Vector2D(300, 400), 75)) # unpause the world ready for movement world.paused = False while not win.has_exit: win.dispatch_events() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # show nice FPS bottom right (default) delta = clock.tick() world.update(delta) world.render() fps_display.draw()
pygame.init() score_value = 0 font = pygame.font.Font('freesansbold.ttf', 28) def show_score(): score = font.render('Score : ' + str(score_value), True, (255, 0, 0)) Screen.screen.blit(score, (10, 10)) if __name__ == '__main__': run = True ai = [Pedestrian()] vampire_hunter = Hunter() while run: if int(time()) % 5 == 0 and len(ai) < 3: ai.append(Pedestrian()) Screen.load() deletion_list = [] for event in pygame.event.get(): if event.type == pygame.QUIT: run = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: