def renderOneLine(self, y): """Where most of the raytracer happens, the z in range determines the quality of anti aliasing""" for x in range(self.surf.get_width()): total = 0 color = vector.Vector3(0, 0, 0) temp_color = vector.Vector3(0, 0, 0) for z in range(1): L = [] dx = random.uniform(-1, 1) dy = random.uniform(-1, 1) pixelvector = vector.Vector2(x + dx, y + dy) otherpixel = vector.Vector2(x, y) e = math.exp(-((dx**2) / (2 * (0.333**2)) + (dy**2) / (2 * (0.333**2)))) total += e direction = (self.camera.getpixelpos(pixelvector) - self.camera.pos).normalized() ray = Ray(color, self.camera.getpixelpos(pixelvector), direction, 1) b = self.raycast(ray) temp_color += b * e avg_color = temp_color / total color = avg_color.clamp() color = (color * 255).i self.surf.set_at(otherpixel.i, color)
def run_AI(self, school): "Execute the three boid rules and store in steering." self.steering = vector.Vector2(0, 0) # Follow rules of separation, alignment, and cohesion. separation = vector.Vector2(0, 0) alignment = vector.Vector2(0, 0) cohesion = vector.Vector2(0, 0) # Track fish that are too close along with neighbours. too_close = False neighbors = 0 # Loop over all other fish from the school fish is in. for fish in school: if fish is not self: # Get the difference in location and distance. offset = self.location - fish.location length = offset.magnitude # Find fish that are too close to current one. if length < self.DESIRED_SEPARATION: separation += offset.normalize() / length too_close = True # Try joining fish in fish's present vicinity. if length < self.NEIGHBOR_DISTANCE: alignment += fish.velocity cohesion += fish.location neighbors += 1 # Steer away from fish in this school that are nearby. if too_close: self.steering += self.correction(separation) * self.SEP_FACTOR # Gather with and align to schoolmates detected above. if neighbors: self.steering += self.correction(alignment) * self.ALI_FACTOR cohesion /= neighbors cohesion -= self.location self.steering += self.correction(cohesion) * self.ALI_FACTOR
def __init__(self, position, color): """ position: a VectorN of the *center* of this object color: the color to draw it in pygame """ self.mPosition = position.copy() # The center of the object self.mColor = color # The color to draw it in pygame self.mAxes = [vector.Vector2(1, 0), vector.Vector2(0, 1)] # A set of 2 (in 2d) or 3 (in 3d)
def __init__(self, spawn, path_list, patrolling, direction, alignment, type): super().__init__() # parent constructor self.current_pos = vector.Vector2(int(spawn[0]), int(spawn[1])) # customized spawn point for enemy self.acceleration = vector.Vector2(50, 0) self.rest_direction = direction if not patrolling: self.current_direction = self.rest_direction self.aggro_range = 125 # range in pixels the enemy will check for an opponent to chase self.chase_range = 150 # range the enemy must pass in order to trigger a loss in aggro from the enemy self.is_chasing = 0 # boolean actor state to control player chasing self.chase_timer = 0 # timer that controls how long the enemy chases the player after the player leaves chase range self.is_losing_aggro = 0 # boolean actor state to control the use of the chase timer self.is_moving = 1 # boolean actor state to control movement animations self.attack_cd_timer = 0.5 self.move_cd_timer = 0 self.is_patrolling = patrolling self.patrol_path = path_list self.patrol_stage = 0 self.patrol_stage_cap = len(self.patrol_path) - 1 self.max_speed = vector.Vector2(50, 0) self.update_vectors() self.type = type if type == "Guard": self.sprite_sheet = pygame.image.load_extended("Assets/tiles from rpgmaker/badnpc_walk_final.png").convert_alpha() # temporary sprite sheet self.sprite_offset = (0, 0) self.max_health = 100 self.health = self.max_health self.damage = 5 elif type == "Knight": self.sprite_sheet = pygame.image.load_extended("Assets/tiles from rpgmaker/goodnpc_walk_final.png").convert_alpha() # temporary sprite sheet self.sprite_offset = (0, 0) self.max_health = 200 self.health = self.max_health self.damage = 15 elif type == "Boss": if alignment == "Good": self.sprite_sheet = pygame.image.load_extended( "Assets/tiles from rpgmaker/spell_bad_walk.png").convert_alpha() # temporary sprite sheet else: self.sprite_sheet = pygame.image.load_extended( "Assets/tiles from rpgmaker/barb_good_walk.png").convert_alpha() # temporary sprite sheet self.sprite_sheet = pygame.image.load_extended("Assets/tiles from rpgmaker/people4.png").convert_alpha() self.sprite_offset = (0, 0) self.max_health = 300 self.health = self.max_health self.alignment = alignment self.current_weapon = Weapon(self) self.current_weapon.current_weapon = "Spear"
def __init__(self): """ Actor Constructor, should only be called by the super, takes no arguments, yet. """ self.current_direction = vector.Vector2(1, 0) # in rads, resets if it goes beyond -2pi or +2pi self.current_pos = vector.Vector2(64, 64) # in pixels per second self.current_vel = vector.Vector2(0, 0) # starts at rest self.acceleration = vector.Vector2(200, 0) # based on the angle we are looking self.max_speed = vector.Vector2(100, 0) # gotta go fast self.knock_vel = vector.Vector2(0, 0) # for use when being knocked back self.move_buffer = vector.Vector2 (18, 0) # pixel buffer to apply when doing collision detection, updated with the vectors self.strafe_buffer = vector.Vector2(0, 18) self.strafe_vel = vector.Vector2(0, 0) self.max_health = 100 self.health = self.max_health # default self.damage = 0 self.is_attacking = 0 # boolean value for controlling attack animations, particularly "thrusting" ones self.is_swinging = 0 # another boolean value for controlling attack animations, particularly withdraw ones self.is_moving = 0 # boolean value for controlling movement and rest animations self.attack_anim_timer = 0.0 # timer used to smooth out attack animations self.move_anim_timer = 0.0 # timer used to smooth out movement animations self.attack_anim_counter = 0 # counter for controlling the "frame" of animation self.attack_cd_timer = 0 # cool down timer for attacks self.in_range = 0 # boolean used by enemy and npc to see if a target is in range to attack self.is_knocked_back = 0 # boolean value to determine the actor state of being knocked back self.knock_timer = 0 # timer for knockback animation self.actor_collide = 0 self.is_patrolling = 1 self.is_linear_patrol = 1 self.alignment = "Neutral" self.sprite_size = 32 # dimension of the temporary sprites self.sprite_offset = (288, 128) # offset of the temporary sprite within the temporary sheet self.sprite_sheet = pygame.image.load_extended("Assets/tile" "s from rpgmaker/people4.png").convert_alpha() # temporary sprite sheet self.sprite_column = 1 # column number of the default sprite within its relative grid self.sprite_row = 2 # row number of the default sprite within its relative grid self.hit_box = Cuboid((255, 0, 0), self.current_pos, vector.Vector2(16, 32)) self.collision_tiles = [1200] self.patrol_path = [] self.patrol_stage = 0 self.patrol_stage_cap = 0 self.patrol_modifier = 1 self.destination = None self.Sword_Hit = pygame.mixer.Sound("Assets/Sounds/SwordHit.wav") self.current_weapon = Thrusting(self)
def rotate(self, degrees): """ in 2d, this rotates around the z-axis. """ radians = math.radians(degrees) c_rad = math.cos(radians) s_rad = math.sin(radians) cur_x = self.mAxes[0] cur_y = self.mAxes[1] self.mAxes[0] = vector.Vector2(cur_x.x * c_rad + cur_x.y * s_rad, -cur_x.x * s_rad + cur_x.y * c_rad) self.mAxes[1] = vector.Vector2(cur_y.x * c_rad + cur_y.y * s_rad, -cur_y.x * s_rad + cur_y.y * c_rad)
def __init__(self): """ Player constructor, takes no arguments as of yet """ super().__init__() # calling parents constructor self.g_player = self.Good() # good player object self.b_player = self.Evil() # bad player object self.current_pos = self.g_player.pos self.rotate_speed = 10 # speed at which the player rotates in pixels /s # self.sprite_size = 32 # dimension of the players temporary sprites self.sprite_sheet = self.g_player.sprite_sheet self.sprite_offset = self.g_player.sprite_offset # offset of the players temporary sprite within the temporary sheet # self.sprite_sheet = pygame.image.load_extended("good_bad_RPG_art/tiles from rpgmaker/people4.png") # players temporary sprite sheet self.sprite_column = 1 # column number of the default sprite within the grid of the players sprite self.sprite_row = 2 # row number of the default sprite within the grid of the players sprite self.reach = 75 # reach of players weapon self.damage = 15 self.max_speed = vector.Vector2(125, 0) self.Cur_Background_Music = pygame.mixer.Sound("Assets/Sounds/GoodPeopleTravelingMusic.wav") self.Bad_Theme = pygame.mixer.Sound("Assets/Sounds/EvilTravelingMusic.wav") self.Good_Theme = self.Cur_Background_Music self.Cur_Background_Music.set_volume(0.5) self.curr_map = "Good Hub" self.current_weapon = Weapon(self) self.current_weapon.current_weapon = "Spear"
def transition_check(self, player): for box in self.transitions: temp_rect = Cuboid((0, 0, 0), vector.Vector2(box["x"], box["y"]), (box["width"], box["height"])) if player.actor_collision(temp_rect): self.transition(box["Next Map"], box["Player Spawn ID"])
def __init__(self): self.is_active = 0 # boolean to determine if this is the currently selected player # self.level = 0 # self.inventory = {} # to be replaced with inventory class # self.experience = 0 # self.weapons = {} # to be replaced with weapon class # self.armor = {} # to be replaced with armor class # self.trinkets = {} # to be replaced with trinket class self.sprite_sheet = pygame.image.load_extended("Assets/tiles from rpgmaker/spell_bad_walk.png").convert_alpha() # temporary sprite sheet self.sprite_offset = (0, 0) self.is_active = 0 self.pos = vector.Vector2(2650, 3060) # players position in world coords self.direction = vector.Vector2(1, 0) # radians value showing the direction the player is facing self.max_health = 100 self.health = self.max_health self.boss_counter = 0
def __init__(self): super().__init__() self.sprite_offset = (0, 0) self.sprite_sheet = pygame.image.load_extended("Assets/tiles from rpgmaker/shop_walk.png").convert_alpha() self.current_pos = vector.Vector2(600, 2550) self.current_direction = vector.Vector2(1, 0) self.update_sprite_facing() self.health = 50 self.max_health = 50 self.is_activated = 0 self.gui_runner = GUI.GUI() self.gui_runner.SetText("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc pretium lorem vel ligula vulputate ultrices non vel leo. Nunc elementum ipsum vitae tellus faucibus scelerisque. Vivamus consequat, nisl ut porta rhoncus, justo mauris ornare nisl, varius ornare nunc neque vel nisi. Sed aliquet magna eu dui iaculis bibendum. Pellentesque sed tellus dapibus, ultricies ex vel, gravida tellus. Nulla convallis elit nec felis dapibus, et vehicula odio euismod. Vestibulum et eros eu velit mollis laoreet fermentum vitae ligula. Praesent quis est non mauris luctus pharetra. Aenean tincidunt vulputate neque, nec blandit arcu placerat sed. Integer vel elit maximus, aliquam tortor ac.") self.gui_runner.SetColor((255, 255, 255)) self.gui_runner.SetArea((150, 400, 500, 100)) self.gui_runner.SetTriangle(([530, 130], [538, 130], [534, 140]))
def setup(self, background): "Setup the screen and boids before starting simulation." background('black') self.schools = [] self.sources = [] for body_color, trim_color in self.SCHOOLS: new_school = School(body_color, trim_color) new_source = vector.Vector2(random.random() * WIDTH, random.random() * HEIGHT) self.schools.append(new_school) self.sources.append(new_source) self.pointer = 0
def __init__(self): self.pos = vector.Vector3(1, 1, 1) self.rot = vector.Vector2() self.meshFaces = [] self.colliderFaces = [] self.isKinetic = True self.velocity = vector.Vector3() self.useGravity = True self.grounded = False self.fixedTime = .01 self.t = 0
def draw(self, surf, camera): """ draw function for actors, currently animates basic temporary sprites :param surf: pygame style Surface :param camera: camera object for world coordinate conversion :return: nothing """ if self.is_dead(): # dead men tell no tales return temp_rect = camera.apply(self.current_pos) # create temporary list to protect the current position # converts from world coord to screen coords temp_cube = Cuboid(vector.Vector3(0, 0, 0), self.current_weapon.Hitbox.mPos.copy(), vector.Vector2(48, 4)) temp_cube.mAngle = self.current_weapon.Hitbox.mAngle temp_vec = camera.apply(temp_cube.mPos) temp_cube.mPos = temp_vec if isinstance(self, Enemy) and self.is_chasing: if self.sprite_row == 4 or self.sprite_row == 1 or self.sprite_row == 2 or self.sprite_row == 3 or self.sprite_row == 0: x = temp_cube.mPos.x - self.current_weapon.rotated_weap_img.get_width() // 2 y = temp_cube.mPos.y - self.current_weapon.rotated_weap_img.get_height() // 2 surf.blit(self.current_weapon.rotated_weap_img, (x, y)) # Drawing the actor from the sprite sheet using known attributes, and offsets the sprite so current_pos is the #... center of the sprite surf.blit(self.sprite_sheet, (temp_rect[0] - (self.sprite_size // 2), temp_rect[1] - (self.sprite_size // 2)), (self.sprite_column * self.sprite_size + self.sprite_offset[0], self.sprite_row * self.sprite_size + self.sprite_offset[1], self.sprite_size, self.sprite_size)) if isinstance(self, Enemy) and self.is_chasing: if self.sprite_row == 5 or self.sprite_row == 6 or self.sprite_row == 7: x = temp_cube.mPos.x - self.current_weapon.rotated_weap_img.get_width()//2 y = temp_cube.mPos.y - self.current_weapon.rotated_weap_img.get_height()//2 surf.blit(self.current_weapon.rotated_weap_img, (x, y)) pygame.draw.rect(surf, (0, 0, 0), (temp_rect[0] - 20, temp_rect[1] - 20, 40, 3), 0) pygame.draw.rect(surf, (255, 0, 0), (temp_rect[0] - 20, temp_rect[1] - 20, 40 * (self.health/self.max_health), 3), 0) elif isinstance(self, NPC) and self.gui_runner.Visible: self.gui_runner.Draw(surf)
def str_to_Vector2_list(string): temp_list = [] temp_str_1 = "" temp_str_2 = "" build_1 = 1 build_2 = 0 for i in range(0, len(string)): if not string[i] == " " and not string[i] == ",": if build_1 and not string[i] == " ": temp_str_1 += string[i] elif build_2 and not string[i] == ",": temp_str_2 += string[i] elif string[i] == ",": build_1 = 0 build_2 = 1 if string[i] == " " or i == len(string) - 1: build_1 = 1 build_2 = 0 if temp_str_1[0] == "-": temp_str_1 = temp_str_1[1:] modifier_1 = -1 else: modifier_1 = 1 if temp_str_2[0] == "-": temp_str_2 = temp_str_2[1:] modifier_2 = -1 else: modifier_2 = 1 temp_list.append( vector.Vector2( float(temp_str_1) * modifier_1, float(temp_str_2) * modifier_2)) temp_str_1 = "" temp_str_2 = "" return temp_list
def __init__(self, w, h): self.w = w self.h = h self.cx = w // 2 self.cy = h // 2 self.pos = vector.Vector3() self.rot = vector.Vector2() self.half_w, self.half_h = w / 2, h / 2 self.setFov(90) """ self.fov = 90/180*math.pi; self.half_fov = self.fov/2 self.half_w, self.half_h = w/2,h/2 self.projY = self.half_h/math.tan(self.half_fov) self.projX = self.half_w/math.tan(self.half_fov)/(w/h) """ os.environ['SDL_VIDEO_CENTERED'] = '1' self.display = pygame.display.set_mode((w, h))
def move(self, xoffset, yoffset): """ translates this object """ self.mPosition += vector.Vector2(xoffset, yoffset)
def generate_tiled_objects(self, xml_file): """docstring""" tree = ET.parse(xml_file) root = tree.getroot() for objectgroup in root.findall("objectgroup"): for object in objectgroup.findall("object"): filename = object.get("template") #################################################################### # Enemy spawn parsing if filename == "EnemySpawnPosition.tx": template_data = ET.parse(filename) template_root = template_data.getroot() object_width = object.get("width") object_height = object.get("height") spawn_x = float(object.get("x")) spawn_y = float(object.get("y")) patrolling = 1 for i in range(0, len(template_root[0][0])): for property in object[0]: if property.get("name") == "Path": path_id = property.get("value") if path_id == "0": patrolling = 0 else: patrolling = 1 break for i in range(0, len(template_root[0][0])): alignment = None direction = None for property in object[0]: attribute = property.get("name") if attribute == "Alignment": alignment = property.get("value") elif attribute == "Direction": direction = str_to_Vector2_list( property.get("value")) direction = vector.Vector2( direction[0][0], direction[0][1]) if alignment is None: alignment = "Neutral" if direction is None: direction = vector.Vector2(1, 0) for property in object[0]: type = "" if property.get("name") == "Type": type = property.get("value") case = 0 if patrolling: for pathgroup in root.findall("objectgroup"): for path in pathgroup.findall("object"): if path.get("id") == path_id: path_x = float(path.get("x")) path_y = float(path.get("y")) path_list = path[0].get("points") path_list = str_to_Vector2_list(path_list) if path_list[0] == path_list[-1]: case = 1 path_list = path_list[:-1] for point in path_list: point[0] += path_x point[1] += path_y else: path_list = [vector.Vector2(spawn_x, spawn_y)] self.enemies.append( actor.Enemy((spawn_x, spawn_y), path_list, patrolling, direction, alignment, type)) if case: self.enemies[-1].is_linear_patrol = 0 # end enemy spawn parsing #################################################################### if object.get("name") == "Transition": temp_transition = { "x": float(object.get("x")), "y": float(object.get("y")), "width": float(object.get("width")), "height": float(object.get("height")) } for properties in object: for property in properties: name = property.get("name") value = property.get("value") if name == "Player Spawn ID": value = int(value) temp_transition[name] = value self.transitions.append(temp_transition) if object.get("name") == "Player Spawn": self.player_spawns.append([ float(object.get("x")), float(object.get("y")), float(object.get("id")) ])
def draw(self, surf, camera): """ draw function for actors, currently animates basic temporary sprites :param surf: pygame style Surface :param camera: camera object for world coordinate conversion :return: nothing """ if self.is_dead(): # dead men tell no tales return # print(self.current_weapon) # print(self.Spear.Hitbox) temp_cube = Cuboid(vector.Vector3(0, 0, 0), self.current_weapon.Hitbox.mPos.copy(), vector.Vector2(48, 4)) # temp_cube = Cuboid(vector.Vector3(0, 0, 0), self.current_weapon.Hitbox.mPos.copy(), vector.Vector2(self.current_weapon.Hitbox.mExtents[0] * 2, self.current_weapon.Hitbox.mExtents[1] * 2)) temp_cube.mAngle = self.current_weapon.Hitbox.mAngle temp_vec = camera.apply(temp_cube.mPos) temp_cube.mPos = temp_vec # ##--Lane(Weapon_drawing)--## if self.current_weapon.weapon_drawn is True: # if weapon_drawn is True then draw weapon hit box if self.sprite_row == 4 or self.sprite_row == 1 or self.sprite_row == 2 or self.sprite_row == 3 or self.sprite_row == 0: x = temp_cube.mPos.x - self.current_weapon.rotated_weap_img.get_width()//2 y = temp_cube.mPos.y - self.current_weapon.rotated_weap_img.get_height()//2 surf.blit(self.current_weapon.rotated_weap_img, (x, y)) #temp_cube.drawPygame(surf) temp_rect = camera.apply(self.current_pos) # create temporary list to protect the current position # converts from world coord to screen coords # Drawing the actor from the sprite sheet using known attributes, and offsets the sprite so current_pos is the # ... center of the sprite surf.blit(self.sprite_sheet, (temp_rect[0] - (self.sprite_size // 2), temp_rect[1] - (self.sprite_size // 2)), (self.sprite_column * self.sprite_size + self.sprite_offset[0], self.sprite_row * self.sprite_size + self.sprite_offset[1], self.sprite_size, self.sprite_size)) # ##--Lane(Weapon_drawing)--## if self.current_weapon.weapon_drawn is True: # if weapon_drawn is True then draw weapon hit box if self.sprite_row == 5 or self.sprite_row == 6 or self.sprite_row == 7: x = temp_cube.mPos.x - self.current_weapon.rotated_weap_img.get_width()//2 y = temp_cube.mPos.y - self.current_weapon.rotated_weap_img.get_height()//2 surf.blit(self.current_weapon.rotated_weap_img, (x, y)) pygame.draw.rect(surf, (0, 0, 0), (temp_rect[0] - 20, temp_rect[1] - 20, 40, 3), 0) pygame.draw.rect(surf, (255, 255, 0), (temp_rect[0] - 20, temp_rect[1] - 20, 40 * (self.health/self.max_health), 3), 0)
def transition(self, filename, spawn_id): self.map = open(filename + ".txt", "r") self.mapFile = filename self.tileData = [] self.layerNumber = 0 for line in self.map: line = line.strip() if "[layer]" in line: self.layerNumber += 1 self.map.close() self.map = open(self.mapFile + ".txt", "r") self.mapWidthTile = 0 self.mapHeightTile = 0 self.tileWidth = 0 self.tileHeight = 0 self.mapWidthPixel = 0 self.mapHeightPixel = 0 self.Orientation = 0 self.backgroundColor = 0 self.tileSet = 0 self.LastTile = [] ####################################################################### # [not done] # Someone figure out if this should be load_extended or not... # Note that the load extensions will have to be changed with assets are saved in a specific file folder. # self.alpha_sheet = pygame.image.load_extended("../GoodEvilRPG/good_bad_RPG_art/ProjectUtumno.png").convert() self.alpha_sheet10 = pygame.image.load( "Assets/Tilesets/" + "ProjectUtumno.png").convert_alpha() ####################################################################### self.anim_timer = 0 self.timer = 0 self.TileX = 0 self.TileY = 0 self.alphas = {} self.alpha_sheets = {} for i in range(0, 11): self.alpha_sheets[i] = pygame.image.load("Assets/Tilesets/" + "ProjectUtumno" + str(i * 10) + ".png") ############################################# # Jonathan L self.enemies = [] if filename == "Final": if self.player.g_player.boss_counter > self.player.b_player.boss_counter: if self.player.b_player.is_active: self.player.swap_active() self.enemies.append( actor.Enemy([380, 350], [], 0, vector.Vector2(0, 1), "Evil", "Boss")) else: if self.player.g_player.is_active: self.player.swap_active() self.enemies.append( actor.Enemy([380, 350], [], 0, vector.Vector2(0, 1), "Good", "Boss")) self.transitions = [] self.player_spawns = [] self.generate_tiled_objects(self.mapFile + ".tmx") self.is_paused = 0 for spawn in self.player_spawns: if spawn_id == int(spawn[2]): self.player.current_pos = vector.Vector2(spawn[0], spawn[1]) ############################################# self.create_tiledata() self.create_attributes() self.CreateAlphaImages()
class Fish: "Fish(location) -> Fish" HOW_WIDE = 6 # Width of the fish HOW_LONG = 12 # Length of the fish MAX_FORCE = 0.05 # Maximum directional steering force MAX_SPEED = 60.0 # Maximum speed at which to travel SEP_FACTOR = 1.5 # Arbitrary separation mutliplier ALI_FACTOR = 1.0 # Arbitrary alignment mutliplier COH_FACTOR = 1.0 # Arbitrary cohesion mutliplier DESIRED_SEPARATION = 7 # Turn from each other when closer NEIGHBOR_DISTANCE = 17 # Maximum distance for interactions ######################################################################## # DO NOT CHANGE THE FOLLOWING SECTION limits = math.hypot(HOW_LONG, HOW_WIDE) radius = limits / 2 DESIRED_SEPARATION += limits NEIGHBOR_DISTANCE += limits TOP = 0 - radius LEFT = 0 - radius RIGHT = WIDTH + radius BOTTOM = HEIGHT + radius SHAPE = processing.Polygon(vector.Vector2(HOW_LONG / +2, 0), vector.Vector2(HOW_LONG / -2, HOW_WIDE / +2), vector.Vector2(HOW_LONG / -2, HOW_WIDE / -2)) del limits, radius, HOW_LONG, HOW_WIDE __slots__ = 'location', 'velocity', 'steering', 'body_color', 'trim_color' # END OF PRECALCULATED FISH VARIABLES ######################################################################## def __init__(self, location): "Initialize the fish with several vectors and colors." self.location = location.copy() self.velocity = vector.Polar2(random.random() * self.MAX_SPEED, random.random() * 360) self.body_color = '' self.trim_color = '' def paint(self, body_color, trim_color): "Assign colors to the fish's body and trim (outline)." self.body_color = body_color self.trim_color = trim_color def render(self, graphics): "Draw the fish's shape on the given graphics context." polygon = self.SHAPE.copy() polygon.rotate(self.velocity.direction) polygon.translate(self.location) graphics.draw(polygon, self.body_color, self.trim_color) def run_AI(self, school): "Execute the three boid rules and store in steering." self.steering = vector.Vector2(0, 0) # Follow rules of separation, alignment, and cohesion. separation = vector.Vector2(0, 0) alignment = vector.Vector2(0, 0) cohesion = vector.Vector2(0, 0) # Track fish that are too close along with neighbours. too_close = False neighbors = 0 # Loop over all other fish from the school fish is in. for fish in school: if fish is not self: # Get the difference in location and distance. offset = self.location - fish.location length = offset.magnitude # Find fish that are too close to current one. if length < self.DESIRED_SEPARATION: separation += offset.normalize() / length too_close = True # Try joining fish in fish's present vicinity. if length < self.NEIGHBOR_DISTANCE: alignment += fish.velocity cohesion += fish.location neighbors += 1 # Steer away from fish in this school that are nearby. if too_close: self.steering += self.correction(separation) * self.SEP_FACTOR # Gather with and align to schoolmates detected above. if neighbors: self.steering += self.correction(alignment) * self.ALI_FACTOR cohesion /= neighbors cohesion -= self.location self.steering += self.correction(cohesion) * self.ALI_FACTOR def correction(self, target): "Create a force towards the direction of the target." target.magnitude = self.MAX_SPEED return (target - self.velocity).limit(self.MAX_FORCE) def update(self, interval): "Change velocity and location with respect to time." self.velocity += self.steering / interval self.location += self.velocity.limit(self.MAX_SPEED) * interval self.wraparound() def wraparound(self): "Move the fish to wrap around the edges of the screen." if self.location.y < self.TOP: self.location.y = self.BOTTOM elif self.location.y > self.BOTTOM: self.location.y = self.TOP if self.location.x < self.LEFT: self.location.x = self.RIGHT elif self.location.x > self.RIGHT: self.location.x = self.LEFT
def mouse_pressed(self, event): "Create fish at cursor and add to the smallest school." new_fish = Fish(vector.Vector2(event.x, event.y)) min(self.schools, key=School.size).add_fish(new_fish)
Main_Menu_Music = pygame.mixer.Sound("Assets/Sounds/MainMusic.wav") Start_Button = pygame.mixer.Sound("Assets/Sounds/Main_Menu_Effect_1.wav") Menu_Sound = pygame.mixer.Sound("Assets/Sounds/Menu_Sounds.wav") Good_Image = pygame.image.load("Assets/Good_Image.png") Evil_Image = pygame.image.load("Assets/Evil_Image.png") Title = pygame.font.SysFont("Arial", 70) Start = pygame.font.SysFont("Arial", 45) Quit = pygame.font.SysFont("Arial", 45) Select = pygame.font.SysFont("Arial", 55) Text = Title.render("Journey To Vauss", True, (255, 215, 0)) Start_Object = Start.render("Start", True, (255, 215, 0)) Quit_Object = Quit.render("Quit", True, (255, 215, 0)) Select = Select.render("Select your destiny ...it's your choice.", True, (255, 215, 0)) Start_Bounds = Cuboid(vector.Vector3(0, 0, 0), vector.Vector2(485, 465), vector.Vector2(90, 40)) Quit_Bounds = Cuboid(vector.Vector3(255, 255, 255), vector.Vector2(485, 515), vector.Vector2(90, 40)) Good_Bounds = Cuboid(vector.Vector3(255, 255, 255), vector.Vector2(200, 300), vector.Vector2(390, 590)) Evil_Bounds = Cuboid(vector.Vector3(0, 0, 0), vector.Vector2(600, 300), vector.Vector2(390, 590)) Sword_Image = pygame.image.load('Assets/Sword_Image.png').convert_alpha() theMap = m.Map("Test_map") done = 0 game_won = 0 In_Menu = 1