def __init__(self, position, map, infoTree, physics, renderer, activated): self.renderer = renderer self.physics = physics self.map = map self.activated = activated self.type = None self.life = 0 # 0-100?! self.points = 0 #for highscore self.alive = True self.position = Vector(position[0], position[1]) self.dimensions = [0, 0] self.velocity = Vector(0, 0) self.movespeed = None #util.Vector(3,0) self.jumpspeed = None #util.Vector(0,-13) self.jumplock = False self.jumpSound = None #util.load_sound('jump.wav') self.sprite = self.renderer.createSprite(self) self.colShape = self.physics.createColShape(self) if self.activated: self.activate() self._loadInfo(infoTree) self.sprite.setAni('idle')
def __init__(self, level: int, lsystem: Lsystem, update_callback, start_point=(0, 0, 0)): self._lsystem = lsystem self._level = level self._updater = FractalUpdate(self._lsystem.approx_steps(level), update_callback) self.position_stack = [Vector(*start_point)] self.rotation_stack = [Vector(0, 1, 0)] self.look_at_stack = [Vector(1, 0, 0)] self.verts_stack = [0] self.moved = False self.verts = [self.position_stack[-1].values] self.edges = [] self.stacks = [ self.position_stack, self.rotation_stack, self.look_at_stack, self.verts_stack ] self._timings = { x: 0 for x in ("Rotate", "Move", "Draw", "Push", "Pop") }
def score_candidate(self, init_time: float, candidate: Slice, car_physics: Physics, agent: DrawingAgent) -> (float, dict): """ Scores a candidate. < 0 => not considered a valid candidate >= 0 => valid candidate. Higher the number the better. """ # Calculate the time the ball and car will take to get # to get to the candidate point. Assume car is pointed # in the correct direction. ball_time = self.get_time(init_time, candidate) dist = car_physics.location.dist(Vector(candidate.physics.location)) car_time = dist / car_physics.velocity.length() delta = car_time - ball_time # < 0 means ball will get there after player # Check if we are able to turn to hit the ball? angle = get_angle(car_physics.rotation, car_physics.location, Vector(candidate.physics.location)) cost = angle / 10 if dist < self.DIST_THRESHOLD else 0 # If the car will get there too early, or the delta is too large, bail if (delta < 0 or delta > self.DELTA_T_THRESH): return (- abs(delta), {"delta": delta}) # Adjust the score to account for turning radius return ((self.DELTA_T_THRESH - delta) - cost, {"delta": delta})
def __init__(self, position, map, infoTree, physics, renderer, activated): self.renderer = renderer self.physics = physics self.map = map self.activated = activated self.type = 'player' self.life = 0 #0-100 self.score = 0 self.alive = True self.position = Vector(position[0], position[1]) self.dimensions = [0, 0] self.velocity = Vector(0, 0) self.movespeed = None #util.Vector(3,0) self.jumpspeed = None #util.Vector(0,-13) self.woundingLock = False self.woundTimer = 0 self.jumplock = False self.wLeft = False self.wRight = False self.sprite = self.renderer.createSprite(self) self.colShape = self.physics.createColShape(self) if self.activated: self.activate() self._loadInfo(infoTree) self.sprite.setAni('idle') #includes all objects, that collides at the moment with the player self.collideBusyList = []
def mapColWhileMoveDown(self, tilePos): oldPosition = self.position oldVelocity = self.velocity self.jumplock = False self.position = Vector( oldPosition[0], (((tilePos.y * constants.TILESIZE) - 1) - self.dimensions[1])) self.velocity = Vector(oldVelocity[0], 1)
def __init__(self, speed, graphicName): self.speed = Vector(speed, 0) self.image = Image(graphicName) self.scrollPosition = Vector(0, 0) #TODO: name improveable self.neededGraphics = 0 self._calcGraphicCount() self.oldPos = Vector(0, 0)
def mapColWhileMoveUp(self, tilePos): oldPosition = self.position oldVelocity = self.velocity self.position = Vector(oldPosition[0], ((tilePos.y + 1) * constants.TILESIZE) + 1) #when reaching the roof, instantly move downwards self.velocity.y = 0
def loc(self,item): """ if item is on the map, return tuple containing its coordinates, returns false otherwise """ for each in self.characters.items(): if item == each[1]: return Vector(each[0]) return False
def __init__(self, rotation): self.yaw = float(rotation.yaw) self.roll = float(rotation.roll) self.pitch = float(rotation.pitch) cr = math.cos(self.roll) sr = math.sin(self.roll) cp = math.cos(self.pitch) sp = math.sin(self.pitch) cy = math.cos(self.yaw) sy = math.sin(self.yaw) self.forward = Vector(cp * cy, cp * sy, sp) self.right = Vector(cy * sp * sr - cr * sy, sy * sp * sr + cr * cy, -cp * sr) self.up = Vector(-cr * cy * sp - sr * sy, -cr * sy * sp + sr * cy, cp * cr)
def checkEntityMapCollision(self, map): for colShape in self.colShapeList: #only the outer rect is getting checked #TODDO: check if rect.x or rect.left is the right midTop = Vector( (colShape.getOuterRect().midtop[0] // constants.TILESIZE), (colShape.getOuterRect().midtop[1] // constants.TILESIZE)) midBottom = Vector( (colShape.getOuterRect().midbottom[0] // constants.TILESIZE), (colShape.getOuterRect().midbottom[1] // constants.TILESIZE)) midRightSide = Vector( (colShape.getOuterRect().midright[0] // constants.TILESIZE), (colShape.getOuterRect().midright[1] // constants.TILESIZE)) midLeftSide = Vector( (colShape.getOuterRect().midleft[0] // constants.TILESIZE), (colShape.getOuterRect().midleft[1] // constants.TILESIZE)) #bewegt sich nach oben if colShape.entity.velocity[1] < 0: if map.getTileDangerousness(1, midTop) == True: colShape.entity.setDead() if map.getTileAccessibility(1, midTop) == True: colShape.entity.mapColWhileMoveUp(midTop) #bewegt sich nach unten elif colShape.entity.velocity[1] > 0: if map.getTileDangerousness(1, midBottom) == True: colShape.entity.setDead() if map.getTileAccessibility(1, midBottom) == True: colShape.entity.mapColWhileMoveDown(midBottom) #Bewegung nach rechts if colShape.entity.velocity[0] > 0: if map.getTileDangerousness(1, midRightSide) == True: colShape.entity.setDead() if map.getTileAccessibility(1, midRightSide) == True: colShape.entity.mapColWhileMoveRight(midRightSide) #Bewegung nach links elif colShape.entity.velocity[0] < 0: if map.getTileDangerousness(1, midLeftSide) == True: colShape.entity.setDead() if map.getTileAccessibility(1, midLeftSide) == True: colShape.entity.mapColWhileMoveLeft(midLeftSide)
def update(self, cameraPos): deltaPos = cameraPos - self.oldPos if deltaPos[0] < 0: self.scrollPosition -= self.speed elif deltaPos[0] > 0: self.scrollPosition += self.speed else: pass if self.scrollPosition[0] < 0: self.scrollPosition = Vector( self.scrollPosition[0] + self.getDimensions()[0], 0) elif self.scrollPosition[0] > self.getDimensions()[0]: self.scrollPosition = Vector( self.scrollPosition[0] - self.getDimensions()[0], 0) self.oldPos = Vector(cameraPos[0], cameraPos[1])
def _loadInfo(self, infoTree): self.type = str(infoTree.getAttribute("type")) for infoNode in infoTree.childNodes: if infoNode.nodeName == "points": self.points = int(infoNode.firstChild.data) elif infoNode.nodeName == "life": self.life = int(infoNode.firstChild.data) elif infoNode.nodeName == 'movespeed': self.movespeed = Vector(int(infoNode.firstChild.data),0) elif infoNode.nodeName == 'jumpspeed': self.jumpspeed = Vector(0,int(infoNode.firstChild.data)) elif infoNode.nodeName == 'jumpSound': for cNode in infoNode.childNodes: if cNode.nodeName == "soundFile": self.jumpSound = ressourceLoader.RessourceLoader.load_sound(str(cNode.firstChild.data)) elif infoNode.nodeName == 'colShape': for colRectNode in infoNode.childNodes: if colRectNode.nodeName == 'colRect': posUpperLeft = [0,0] dimensions = [0,0] isSpike = None isBody = None colRectIndex = int(colRectNode.getAttribute("index")) for colRectInfoNode in colRectNode.childNodes: if colRectInfoNode.nodeName == 'posUpperLeft': for posUpperLeftNode in colRectInfoNode.childNodes: if posUpperLeftNode.nodeName == 'horizontal': posUpperLeft[0] = int(posUpperLeftNode.firstChild.data) elif posUpperLeftNode.nodeName == 'vertical': posUpperLeft[1] = int(posUpperLeftNode.firstChild.data) elif colRectInfoNode.nodeName == 'dimensions': for dimensionsNode in colRectInfoNode.childNodes: if dimensionsNode.nodeName == 'horizontal': dimensions[0] = int(dimensionsNode.firstChild.data) elif dimensionsNode.nodeName == 'vertical': dimensions[1] = int(dimensionsNode.firstChild.data) elif colRectInfoNode.nodeName == 'isBody': isBody = util.string2bool(colRectInfoNode.firstChild.data) elif colRectInfoNode.nodeName == 'isSpike': isSpike = util.string2bool(colRectInfoNode.firstChild.data) self.colShape.addRect(posUpperLeft, dimensions, isBody, isSpike) self._calcDimensions()
def get_goal_overlap(self) -> Vector: ball_prediction = self.get_ball_prediction_struct() slices = list(map(lambda x : Vector(x.physics.location), ball_prediction.slices)) threshold = self.field_info.my_goal.location.y for (index, loc) in enumerate(slices): if abs(loc.y) < threshold: continue if index < len(slices) - 1 and abs(slices[index + 1].y) < threshold: continue return loc
def __init__(self, filename): instream = InStream(filename) n = instream.readInt() radius = instream.readFloat() draw.setCanvasSize() draw.setXscale(-radius, +radius) draw.setYscale(-radius, +radius) self._bodies = array.create1D(n) for i in range(n): rx = instream.readFloat() ry = instream.readFloat() vx = instream.readFloat() vy = instream.readFloat() mass = instream.readFloat() r = Vector([rx, ry]) v = Vector([vx, vy]) self._bodies[i] = Body(r, v, mass)
def handleInput(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.stateManager.endGame() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self.stateManager.endGame() elif event.key == pygame.K_SPACE: if not self.levelManager.curLevel.cutSceneState: self.levelManager.curLevel.player.jump() elif event.key == pygame.K_LEFT: if not self.levelManager.curLevel.cutSceneState: self.levelManager.curLevel.player.walkLeft() elif event.key == pygame.K_RIGHT: if not self.levelManager.curLevel.cutSceneState: self.levelManager.curLevel.player.walkRight() elif event.key == pygame.K_p: Event().raiseCstmEvent( Event.SWITCHSTATE, argDict={"state": StateManager.PAUSESTATE}) elif event.key == pygame.K_m: Event().raiseCstmEvent( Event.SWITCHSTATE, argDict={"state": StateManager.MENUSTATE}) elif event.type == pygame.KEYUP: if event.key == pygame.K_LEFT: if not self.levelManager.curLevel.cutSceneState: self.levelManager.curLevel.player.walkStop(dir=-1) elif event.key == pygame.K_RIGHT: if not self.levelManager.curLevel.cutSceneState: self.levelManager.curLevel.player.walkStop(dir=1) elif event.type == pygame.MOUSEBUTTONDOWN: if Options.getOption("ISDEBUG"): print "The current cursor position is: ", Vector( event.pos[0], event.pos[1]) + self.gameRenderer.getCamera() #custom events: elif event.type == Event().ACTIVATETRIGGER: self.levelManager.curLevel.triggerManager.addTrigger( event.tObject) elif event.type == Event().NEWDIALOG: self.interface.dialogManager.addDialog(event.msg, self) elif event.type == Event().LEVELFINISHED: self.levelManager.curLevel.setFinished() elif event.type == Event().SWITCHSTATE: self.stateManager.switchState(event.state) #Trigger input: if self.levelManager.curLevel.triggerManager.isNewEvents(): self.levelManager.curLevel.triggerManager.next().action()
def map2screen(self,pos): """ given map coordinates pos, returns the screen coordinates """ #calculate how many tiles should be visible on the screen xelements = self.screen_size[0] / self.tile_size[0] yelements = self.screen_size[1] / self.tile_size[1] print self.center_tile offset = Vector(pos) - self.center_tile print offset offset = Vector( ( offset[0]*self.tile_size[0], offset[1]*self.tile_size[1] ) ) print offset offset = Vector( ( offset[0]+self.screen_center[0], offset[1]+self.screen_center[1]) ) print offset #self.calc_range(self.center_tile,(xelements,yelements),self.x_range,self.y_range) #pos = ( pos[0]-self.x_range[0], pos[1]-self.y_range[0] ) #pos = ( pos[0]*100, pos[1]*81 ) return offset
def __init__(self,roguemap=None): """ """ self.size = ( roguemap.x, roguemap.y ) self._x = roguemap.x self._y = roguemap.y self.map = dict() self.characters = MultiDict( ) #all characters, pc's and npc's currently on the map self.gitems = MultiDict( ) #all game items currently on the map self.effects = MultiDict( ) #all graphic effect objects active on the map for i in range(0, roguemap.x ): for j in range(0, roguemap.y ): self.map[i,j] = Tile( i, j, roguemap.arr[i][j] ) self.map[i,j].x = i self.map[i,j].y = j #now that the dungeon map has been created, we can initialize the dungeon actor self.tile_size = Vector( (100,81) ) self.screen_size = Vector( (800,600) ) self.screen_center = Vector( (0,0) ) self.center_tile = Vector( (0,0) ) self.x_range = Vector( ) self.y_range = Vector( )
def initialize_boosts(self, game_info: FieldInfoPacket): raw_boosts = [ game_info.boost_pads[i] for i in range(game_info.num_boosts) ] self.boost_pads: List[BoostPad] = [ BoostPad(Vector(rb.location), rb.is_full_boost, False, 0) for rb in raw_boosts ] # Cache the list of full boosts since they're commonly requested. # They reference the same objects in the boost_pads list. self._full_boosts_only: List[BoostPad] = [ bp for bp in self.boost_pads if bp.is_full_boost ]
def __init__(self, screen): Renderer.__init__(self, screen) self.spriteList = [] self.camera = Vector(0, 0) self.dialogFont = RessourceLoader.load_font('courier_new.ttf', 15) self.dialogBackground = pygame.Surface((400, 100)) self.dialogBackground.fill((155, 155, 155)) self.blackBar = pygame.Surface((self.resolution[0], 25)) self.horiBorder = self.resolution[0] // 3 self.vertiBorder = self.resolution[1] // 3
def updateCamera(self, playerInstance): ''' @param playerInstance: instance of the current player object ''' cameraOffset = Vector(0, 0) playerPos = playerInstance.getPosition() if (playerPos[0] - self.camera[0]) > (self.resolution[0] - self.horiBorder): cameraOffset += Vector((playerPos[0] - self.camera[0]) - (self.resolution[0] - self.horiBorder), 0) elif (playerPos[0] - self.camera[0]) < (self.horiBorder): cameraOffset -= Vector( (self.horiBorder) - (playerPos[0] - self.camera[0]), 0) if (playerPos[1] - self.camera[1]) < (self.vertiBorder): cameraOffset -= Vector(0, (self.vertiBorder) - (playerPos[1] - self.camera[1])) elif (playerPos[1] - self.camera[1]) > (self.resolution[1] - self.vertiBorder): cameraOffset += Vector(0, (playerPos[1] - self.camera[1]) - (self.resolution[1] - self.vertiBorder)) self.camera += cameraOffset if playerPos[0] < self.horiBorder: self.camera = Vector(0, self.camera[1]) elif playerPos[0] > playerInstance.map.getDimensions( )[0] * constants.TILESIZE - self.horiBorder: self.camera = Vector( playerInstance.map.getDimensions()[0] * constants.TILESIZE - self.resolution[0], self.camera[1]) if playerPos[1] < self.vertiBorder: self.camera = Vector(self.camera[0], 0) elif playerPos[1] > playerInstance.map.getDimensions( )[1] * constants.TILESIZE - self.vertiBorder: self.camera = Vector( self.camera[0], playerInstance.map.getDimensions()[1] * constants.TILESIZE - self.resolution[1])
def plan(self, dungeon): """ given the environment the ego is currently in, author an Action object """ #if this character is dead, append generate a null action and return if not self._ego._alive: self.qaction.append(Action()) return #scan the dungeon for other character objects for char in dungeon.characters.items(): if self.friendorfoe(char[1]) < 0: target = char[1] targetloc = Vector((char[0][0], char[0][1])) elif char[1].name == self._ego.name: me = char[1] myloc = Vector((char[0][0], char[0][1])) dirVec = targetloc - myloc #calculate a vector to the target print 'dirVec', dirVec ###distance check#### #check abilities against current distance in order to determine what action to take # print "direction vec mag: %(magnitude)s" %{'magnitude': dirVec.magnitude() } # print myloc if dirVec.magnitude() < 2: action = Action() else: dirVec.normalized( ) #normalize and round to get a unit vector towards the target dirVec.ctint() action = Action(atype='move', actor=self._ego, stage=dungeon, target=dirVec, energy=1) print "MIND ACTION", action self._actionqueue.append(action)
def draw_state(self, parsed_packet: ParsedPacket, packet: rl.GameTickPacket): # Draw ball prediction line for where the ball is going to go ball_prediction = self.get_ball_prediction_struct() slices = list(map(lambda x : Vector(x.physics.location), ball_prediction.slices)) self.renderer.draw_polyline_3d(slices[::10], self.renderer.white()) # Write to the car the appropriate string self.write_string(parsed_packet.my_car.physics.location, self.display_on_car(parsed_packet, packet)) # Determine whether or not the ball is going to go into the goal goal_overlap: Vector = self.get_goal_overlap() if goal_overlap is not None: # The ball is going in self.draw_circle(goal_overlap, 100)
def relative_location(center: Vector, ori: Orientation, target: Vector) -> Vector: """ Returns target as a relative location from center's point of view, using the given orientation. The components of the returned vector describes: * x: how far in front * y: how far right * z: how far above """ x = (target - center).dot(ori.forward) y = (target - center).dot(ori.right) z = (target - center).dot(ori.up) return Vector(x, y, z)
def __init__(self, colShape, posUpperLeft, dimensions, isBody, isSpike): self.colShape = colShape #pos from the upperLeft corner of the rect referring to the position of the entity(it's upperLeft corner self.posUpperLeft = Vector(posUpperLeft[0], posUpperLeft[1]) self.dimensions = dimensions #if true, the entity is dead when it collides with the player self.isBody = isBody #if true, the player is dead when it collides with the player self.isSpike = isSpike #absolute position in the whole level self.absPos = self.colShape.entity.getPosition( ) + self.posUpperLeft self.rect = pygame.Rect(self.absPos.getTuple(), self.dimensions)
def renderMapLayer(self, layerIndex, map): ''' renders map Layer @param layerIndex: 0 => Layer1 : 1 => Layer2 ''' for y in range( max(self.camera[1] // constants.TILESIZE, 0), min(map.getDimensions()[1], (self.camera[1] + self.resolution[1]) // constants.TILESIZE + 1)): for x in range( max(self.camera[0] // constants.TILESIZE, 0), min(map.getDimensions()[0], (self.camera[0] + self.resolution[0]) // constants.TILESIZE + 1)): if not map.getMapGrid()[layerIndex][x][y] in [0, 1]: self.screen.blit( map.getTileGraphic(layerIndex, Vector(x, y)), (x * constants.TILESIZE - self.camera[0], y * constants.TILESIZE - self.camera[1]))
def steer_toward_target(car: PlayerInfo, target: Vector) -> float: relative = relative_location(Vector(car.physics.location), Orientation(car.physics.rotation), target) angle = math.atan2(relative.y, relative.x) return limit_to_safe_range(angle * 5)
def get_output(self, parsed_packet: ParsedPacket, packet: rl.GameTickPacket, agent: DrawingAgent) -> SimpleControllerState: # Gather some information about our car and the ball my_car = parsed_packet.my_car car_location = my_car.physics.location car_velocity = my_car.physics.velocity ball_location = parsed_packet.ball.physics.location ball_velocity = parsed_packet.ball.physics.velocity ball_prediction = agent.get_ball_prediction_struct() slices = list(map(lambda x : Vector(x.physics.location), ball_prediction.slices)) agent.draw_circle(parsed_packet.my_car.physics.location, self.STOP_AND_WAIT_RADIUS, agent.renderer.white(), False, 0) my_car_ori = Orientation(my_car.physics.rotation) car_to_ball = ball_location - car_location car_to_ball_angle = my_car_ori.forward.ang_to(car_to_ball) self.chooseContactPoint(ball_prediction.slices, my_car.physics, agent) if(self.contactSlice == None): flip_point = Vector(find_slice_at_time(ball_prediction, packet.game_info.seconds_elapsed + 1).physics.location) else: flip_point = Vector(self.contactSlice.physics.location) target_location = flip_point if not agent.prev_seq_done and agent.WRITE_FLIP_PHYSICS_TO_DB: agent.prev_seq_done = True agent.write_flip_physics(agent.current_flip_physics) if car_location.dist(flip_point) < 300 and self.contactSlice != None: if agent.WRITE_FLIP_PHYSICS_TO_DB == True: # record physics info at beginning of flip agent.current_flip_physics = {} # TODO: add slices here agent.current_flip_physics["car_ball_angle"] = car_to_ball_angle agent.current_flip_physics["car_ball_dist"] = car_location.dist(ball_location) agent.current_flip_physics["car_velo_x"] = car_velocity[0] agent.current_flip_physics["car_velo_y"] = car_velocity[1] agent.current_flip_physics["car_velo_z"] = car_velocity[2] agent.current_flip_physics["car_velo_mag"] = car_velocity.length() agent.current_flip_physics["car_loc_x"] = car_location[0] agent.current_flip_physics["car_loc_y"] = car_location[1] agent.current_flip_physics["car_loc_z"] = car_location[2] agent.current_flip_physics["ball_velo_x"] = ball_velocity[0] agent.current_flip_physics["ball_velo_y"] = ball_velocity[1] agent.current_flip_physics["ball_velo_z"] = ball_velocity[2] agent.current_flip_physics["ball_velo_mag"] = ball_velocity.length() agent.current_flip_physics["ball_loc_x"] = ball_location[0] agent.current_flip_physics["ball_loc_y"] = ball_location[1] agent.current_flip_physics["ball_loc_z"] = ball_location[2] agent.current_flip_physics["contact"] = False return agent.begin_front_flip(packet) # Draw target to show where the bot is attempting to go if (self.contactSlice == None): agent.draw_line_with_rect(car_location, target_location, 8, agent.renderer.cyan()) else: contactPt = Vector(self.contactSlice.physics.location) agent.draw_line_with_rect(contactPt, contactPt + get_post_collision_velocity(my_car.physics, Physics(self.contactSlice.physics)), 1, agent.renderer.red()) angle = get_angle(parsed_packet.my_car.physics.rotation, parsed_packet.my_car.physics.location, target_location) agent.write_string_2d(1000, 1000, f"{angle}") # Set the final controls based off of above decision making controls = SimpleControllerState() controls.steer = steer_toward_target(my_car, target_location) if(self.contactSlice != None or car_location.dist(ball_location) > self.STOP_AND_WAIT_RADIUS): controls.throttle = 1.0 else: controls.throttle = -1 if (angle > self.POWERSLIDE_THRESHOLD): controls.handbrake = True # You can set more controls if you want, like controls.boost. return controls
def mapColWhileMoveLeft(self, tilePos): oldPosition = self.position oldVelocity = self.velocity self.position = Vector((((tilePos.x + 1) * constants.TILESIZE) + 1), oldPosition[1])
def mapColWhileMoveRight(self, tilePos): oldPosition = self.position oldVelocity = self.velocity self.position = Vector( ((tilePos.x * constants.TILESIZE) - 1) - self.dimensions[0], oldPosition[1])
def mapColWhileMoveUp(self, tilePos): oldPosition = self.position oldVelocity = self.velocity self.position = Vector(oldPosition[0], ((tilePos.y + 1) * constants.TILESIZE) + 1)