def __init__(self, obsX, obsY, obsWidth, obsHeight): self.obsX = obsX self.obsY = obsY self.obsWidth = obsWidth self.obsHeight = obsHeight self.collider = Collision(self.obsX, self.obsY, self.obsWidth, self.obsHeight) self.obsColor = self.OBS_COLOR[int(random(0,len(self.OBS_COLOR) ) )]
def __init__(self, positions, main): self._players = [ Player("Ninja", "ninja", positions[1], self, 0), Player("Pirate", "pirate", positions[0], self, 1) ] self._collision = Collision(self._players[0], self._players[1]) self._eventOccured = [ False, False ] self._soundManager = SoundManager() self._elapsedTime = 0; self.main = main
def drawSelf(self): pushMatrix() rectMode(CENTER) fill(self.obsColor) strokeWeight(3) stroke(self.OBS_STROKE) rect(self.obsX, self.obsY, self.obsWidth, self.obsHeight) self.collider = Collision(self.obsX, self.obsY, self.obsWidth, self.obsHeight) popMatrix()
def __init__(self, tyres, sensors=[], cameras=[], timeframe=0.1, car_speed=50): logger.debug("Car4W.__init__()") self.action_id = 0 self.t = None self.camera = None self.timeframe = timeframe self.car_speed = car_speed if len(tyres) != 4: raise EnvironmentError("Car4W required four tyres") self.state = 0 self.frontRight = tyres[0][1] self.frontLeft = tyres[1][1] self.backRight = tyres[2][1] self.backLeft = tyres[3][1] self.stop() # Stop the car, reset pins. self.collision = Collision(sensors) self.collision.start() logger.debug("Waiting to collision sensor to get ready") while not self.collision.ready: sleep(0.5) logger.info("Collision sensors are ready.") logger.debug("Waiting to camera to get ready") self.cameras = cameras for camera in self.cameras: camera[1].start() logger.debug("Camera start called") for camera in self.cameras: while not camera[1].more(): sleep(0.5) logger.debug(camera[0] + " is ready.") logger.info("Cameras are ready.")
def __init__(self, playerX, playerY, borderSize, playerSize=PLAYER_SIZE): self.xVariance = random(0, 4) self.yVariance = random(0, 4) self.PLAYER_SIZE = playerSize self.playerX = playerX - self.PLAYER_SIZE / 2 self.playerY = playerY - self.PLAYER_SIZE / 2 self.playerYBot = height - borderSize - self.PLAYER_SIZE / 2 self.playerYTop = borderSize + self.PLAYER_SIZE / 2 self.collider = Collision(self.playerX, self.playerY, self.PLAYER_SIZE, self.PLAYER_SIZE)
def drawPlayer(self): pushMatrix() fill(self.PLAYER_COLOR) strokeWeight(3) if (self.PLAYER_SIZE == 50): stroke(self.PLAYER_STROKE) else: noStroke() self.collider = Collision(self.playerX, self.playerY, self.PLAYER_SIZE, self.PLAYER_SIZE) rect(self.playerX, self.playerY, self.PLAYER_SIZE, self.PLAYER_SIZE) popMatrix()
def applyImpulses(self): for b in self.orbitingBodies: collidedThisFrame = False for other in self.orbitingBodies: imp = Collision.getCollisionImpulse(b, other, self.elasticity) if (imp.x != 0 or imp.y != 0 or imp.z != 0): collidedThisFrame = True elif (imp.x == 123.4 and imp.y == 123.4 and imp.z == 123.4): collidedThisFrame = True else: b.addImpulse(imp) ''' for other in self.playerBodies: if other != "empty": imp = Collision.getCollisionImpulse(b, other, self.elasticity) if (imp.x != 0 or imp.y != 0 or imp.z != 0): collidedThisFrame = True elif (imp.x == 123.4 and imp.y == 123.4 and imp.z == 123.4): collidedThisFrame = True else: b.addImpulse(imp) ''' # Don't want to apply impulses multiple times if collidedThisFrame: b.colliding = True; else: b.colliding = False
def read_source_file(file_name, hour_file_name): with open(file_name, 'r') as readCollision: # r represent read model print("Start to read file: " + file_name + ". This may take a while...") file = csv.reader(readCollision) for row in file: if "COLLISION_ID" not in row[0]: collision = Collision() collision.collision_id = row[0] collision.location_key = row[1] collision.hour_key = row[2] collision.weather_key = row[3] collision.environment = row[4] collision.light = row[5] collision.surface_condition = row[6] collision.traffic_control = row[7] collision.traffic_control_condition = row[8] collision.collision_classification = row[9] collision.impace_type = row[10] collision.no_of_pedestrians = row[11] collision.date = row[12] collision.location = row[13] collision.is_intersection = row[14] collisions.append(collision) readCollision.close() with open(hour_file_name, 'r') as readHour: # r represent read model print("Start to read file: " + hour_file_name + ". This may take a while...") file = csv.reader(readHour) for row in file: if "EVENT_ID" not in row[0]: event = Event() event.event_id = row[0] event.event_name = row[1] event.event_start_date = row[2] event.event_end_date = row[3] if int(event.event_start_date.split("-")[0]) > int( event.event_end_date.split("-")[0]): raise Exception( "Wrong event time - event starting date must be earlier than event ending date: " "START:" + event.event_start_date + " compare to END:" + event.event_end_date) if int(event.event_start_date.split("-")[1]) > int( event.event_end_date.split("-")[1]): raise Exception( "Wrong event time - event starting date must be earlier than event ending date: " "START:" + event.event_start_date + " compare to END:" + event.event_end_date) events.append(event) readHour.close()
def read_source_file(file_name, locoation_file_name): with open(file_name, 'r') as readCollision: # r represent read model print("Start to read file: " + file_name + ". This may take a while...") file = csv.reader(readCollision) for row in file: if "COLLISION_ID" not in row[0]: collision = Collision() collision.collision_id = row[0] collision.location_id = row[1] collision.hour_key = row[2] collision.environment = row[3] collision.light = row[4] collision.surface_condition = row[5] collision.traffic_control = row[6] collision.traffic_control_condition = row[7] collision.collision_classification = row[8] collision.impace_type = row[9] collision.no_of_pedestrians = row[10] collision.date = row[11] collisions.append(collision) readCollision.close() with open(locoation_file_name, 'r') as readLocation: # r represent read model print("Start to read file: " + locoation_file_name + ". This may take a while...") file = csv.reader(readLocation) for row in file: if "LOCATION_ID" not in row[0]: location = Location() location.location_id = row[0] location.street_name = row[1] location.intersection_one = row[2] location.intersection_two = row[3] location.longitude = row[4] location.latitude = row[5] location.neighborhood = row[6] location.closest_weather_station = row[7] locations.append(location) readLocation.close()
inputThread.start() ship = Ship(12, 12) width=25*3 height=25*2 canvas = verts = [["E" for x in range(width)] for y in range(height)] mObjects = [] mObjects.append(ship) explosions = [] astroidSpawner = AstroidSpawner(width, height) collision = Collision() string = "" lost = "not lost" def collideWall(): if(ship.posX >= width - 6 + ship.width - 1 or ship.posX <= 2): return True if(ship.posY >= height - 4 + ship.height - 1 or ship.posY <= 1): return True return False def fillCanvas(): #Clear canvas y = 0
while run: clock.tick(27) if shoot_loop > 0: shoot_loop += 1 if shoot_loop > 3: shoot_loop = 0 for event in pygame.event.get(): if event.type == pygame.QUIT: run = False for bullet in map.bullets: for enemy in map.emenies: if not enemy.visible: map.remove_enemy(enemy) if Collision.bullet_and_target(bullet, enemy): enemy.hit() map.hero.score += 1 map.remove_bullet(bullet) if bullet.x < 1280 and bullet.x > 0: bullet.x += bullet.vel else: map.remove_bullet(bullet) for block in map.blocks: if Collision.hero_on_block(block, map.hero) and not map.hero.is_jump: map.hero.y = block.hitbox[1] - 52 map.hero.faling = False else: map.hero.faling = True if Collision.hero_under_block(block, map.hero):
def process_collision_table(): list = collision_processor("2014collisionsfinal.xls.csv") list1 = collision_processor("2016collisionsfinal.xls.csv") list2 = collision_processor("2015collisionsfinal.xls.csv") collisions = [] with open("h2017collisionsfinal.csv", 'r') as readData: # r represent read model print( "Start to read file: h2017collisionsfinal.csv. This may take a while..." ) file = csv.reader(readData) key_ctr = 0 for row in file: if "Record" not in row[0]: collision = Collision() collision.collision_id = key_ctr key_ctr = key_ctr + 1 collision.location = row[1] collision.longtitude = row[4] collision.latitude = row[5] collision.date = row[7] collision.time = row[8] environment = row[9] if row[9] == "": environment = "Unknown" collision.environment = remove_prefix(environment, "Unknown") light = row[13] if row[13] == "": light = "Unknown" collision.light = remove_prefix(light, "Unknown") surface_condition = row[10] if row[10] == "": surface_condition = "Unknown" collision.surface_condition = remove_prefix( surface_condition, "Unknown") traffic_control = row[11] if row[11] == "": traffic_control = "Unknown" collision.traffic_control = remove_prefix( traffic_control, "Unknown") collision.traffic_control_condition = "N/A" collision_classification = row[14] if row[14] == "": collision_classification = "Unknown" collision.collision_classification = remove_prefix( collision_classification, "Unknown") impact_type = row[15] if row[15] == "": impact_type = "Unknown" collision.impace_type = remove_prefix(impact_type, "Unknown") collision.no_of_pedestrians = "N/A" collisions.append(collision) readData.close() # with open("2017collisionsfinal.xls.csv", 'w', newline='') as csvFile: # print("Prepare to write the data into the file: h2017collisionsfinal.csv. It might take a while...") # writer = csv.writer(csvFile) # writer.writerow(["COLLISION_ID", "LOCATION", "LONGITUDE", "LATITUDE", "DATE", "TIME", "ENVIRONMENT", # "LIGHT", "SURFACE_CONDITION", "TRAFFIC_CONTROL", "TRAFFIC_CONTROL_CONDITION", # "COLLISION_CLASSIFICATION", "IMPACT_TYPE", "NO_OF_PEDESTRIANS"]) # for collision in collisions: # writer.writerow([collision.collision_id, collision.location, collision.longtitude, collision.latitude, # collision.date, collision.time, collision.environment, collision.light, # collision.surface_condition, collision.traffic_control, # collision.traffic_control_condition, collision.collision_classification, # collision.impace_type, collision.no_of_pedestrians]) # csvFile.close() list.extend(list1) list.extend(list2) list.extend(collisions) output_collision_data_from_list_to_new_csv("Collision_Table", list)
test2.add_component("physics", (20, 0, 0.005, True, False)) test3.add_component("image_renderer", "assets/block.png") test3.add_component("collider", (test3.transform.position.x - test3.renderer.to_render.surface.get_width() / 2, test3.transform.position.y + test3.renderer.to_render.surface.get_height() / 2, test3.renderer.to_render.surface.get_width(), test3.renderer.to_render.surface.get_height())) test3.add_component("physics", (20, 0, 0.005, True, False)) test.add_component("physics", (20, 0, 0.005, False, True)) polygon = Collision( [ (-16, 16), # (16, 16), (16, -16), (-16, -16) ], pygame) nope = Collision( [ # (-16, 16), (16, 16), (16, -16), (-16, -16) ], pygame) print(polygon.origin) camera.target = test2 running = True
def read_source_file(file_name, hour_file_name): with open(file_name, 'r') as readCollision: # r represent read model print("Start to read file: " + file_name + ". This may take a while...") file = csv.reader(readCollision) for row in file: if "COLLISION_ID" not in row[0]: collision = Collision() collision.collision_id = row[0] collision.location_id = row[1] collision.hour_id = row[2] collision.environment = row[3] collision.light = row[4] collision.surface_condition = row[5] collision.traffic_control = row[6] collision.traffic_control_condition = row[7] collision.collision_classification = row[8] collision.impace_type = row[9] collision.no_of_pedestrians = row[10] collisions.append(collision) readCollision.close() with open(hour_file_name, 'r') as readHour: # r represent read model print("Start to read file: " + hour_file_name + ". This may take a while...") file = csv.reader(readHour) for row in file: if "HOUR_ID" not in row[0]: hour = Hour() hour.hour_id = row[0] hour.hour_start = row[1] hour.hour_end = row[2] hour.date = row[3] hour.day_of_week = row[4] hour.day = row[5] hour.month = row[6] hour.year = row[7] hour.weekend = row[8] hour.holiday = row[9] hour.holiday_name = row[10] hours.append(hour) readHour.close()
class Scene: def __init__(self, positions, main): self._players = [ Player("Ninja", "ninja", positions[1], self, 0), Player("Pirate", "pirate", positions[0], self, 1) ] self._collision = Collision(self._players[0], self._players[1]) self._eventOccured = [ False, False ] self._soundManager = SoundManager() self._elapsedTime = 0; self.main = main def _decelerate(self, playerIndex, elapsedTime, ratio=1.0): player = self._players[playerIndex] for i in range(0,2): speed = player.speed()[i] if speed < epsilon and speed > -epsilon: speed = 0 else: if speed > 0: speed -= (acceleration + deceleration) * elapsedTime * ratio else: speed += (acceleration + deceleration) * elapsedTime * ratio player.setSpeed(speed, i) def newFrame(self, elapsedTime): for playerIndex in range(0, 2): player = self._players[playerIndex] if not self._eventOccured[playerIndex]: if player.isJumping: ratio = 0.5 else: ratio = 1.0 self._decelerate(playerIndex, elapsedTime, ratio) self._eventOccured = [ False, False ] self._elapsedTime = elapsedTime for player in self._players: player.update(elapsedTime) for playerIndex in range(0, 2): self._collision.moveForward(playerIndex, self._players[playerIndex].speed()[0] * self._elapsedTime) self._collision.moveSide(playerIndex, self._players[playerIndex].speed()[1] * self._elapsedTime) def _move(self, playerIndex, elapsedTime, axe, delta): self._eventOccured[playerIndex] = True accel = delta * elapsedTime * acceleration decel = delta * elapsedTime * deceleration self._decelerate(playerIndex, elapsedTime, 0.08) consMaxSpeed = maxSpeed if axe == 1: dist = 0.5 + (self._collision.getDistance() / maxDist) / 2 consMaxSpeed *= dist if delta * self._players[playerIndex].speed()[axe] < 0: if axe == 0: self._players[playerIndex].incrementSpeed(accel + decel, 0) else: self._players[playerIndex].incrementSpeed(0, decel + accel) if delta * self._players[playerIndex].speed()[axe] < consMaxSpeed: if axe == 0: self._players[playerIndex].incrementSpeed(accel, 0) else: self._players[playerIndex].incrementSpeed(0, accel) if delta * self._players[playerIndex].speed()[axe] > consMaxSpeed: self._players[playerIndex].setSpeed(delta * consMaxSpeed, axe) def moveForward(self, playerIndex, elapsedTime): isJumping = self._players[playerIndex].isJumping() if isJumping: self._decelerate(playerIndex, elapsedTime, 0.15) elapsedTime /= 1.8 self._move(playerIndex, elapsedTime, 0, 1) def moveBackward(self, playerIndex, elapsedTime): isJumping = self._players[playerIndex].isJumping() if isJumping: self._decelerate(playerIndex, elapsedTime, 0.15) elapsedTime /= 1.8 self._move(playerIndex, elapsedTime, 0, -1) def moveRight(self, playerIndex, elapsedTime): isJumping = self._players[playerIndex].isJumping() if isJumping: self._decelerate(playerIndex, elapsedTime, 0.25) elapsedTime /= 2.5 self._move(playerIndex, elapsedTime, 1, 1) def moveLeft(self, playerIndex, elapsedTime): isJumping = self._players[playerIndex].isJumping() if isJumping: self._decelerate(playerIndex, elapsedTime, 0.25) elapsedTime /= 2.5 self._move(playerIndex, elapsedTime, 1, -1) def jump(self, playerIndex, elapsedTime): self._players[playerIndex].jump(elapsedTime) def attack(self, playerIndex, elapsedTime): self._players[playerIndex].attack(elapsedTime, self._collision.getDistance()) def getOtherPlayer(self, player): if player == self._players[0]: return self._players[1] else: return self._players[0] def getPlayer(self, playerId): """ retourne le joueur playerId. playerId vaut 0 ou 1 """ return self._players[playerId] def getCollision(self): return self._collision def introEnd(self): self._soundManager.introEnd() def getSoundManager(self): return self._soundManager;
def findCollisions(self, entityIDs): """Returns a bool indicating if the two entities collided and a collision class which records the two entities and the lambda at which they collide""" collisions = [] for e1id, e2id in combinations(entityIDs, 2): if ((self.collsionComponents[e1id].category, self.collsionComponents[e2id].category) in self.interestingCollisions or (self.collsionComponents[e2id].category, self.collsionComponents[e1id].category) in self.interestingCollisions): continue da_x = 0 da_y = 0 dv_x = 0 dv_y = 0 if e1id in self.accelerationComponents.keys(): da_x += self.accelerationComponents[e1id].ax da_y += self.accelerationComponents[e1id].ay dv_x += self.velocityComponents[e1id].vx dv_y += self.velocityComponents[e1id].vy elif e1id in self.velocityComponents.keys(): dv_x += self.velocityComponents[e1id].vx dv_y += self.velocityComponents[e1id].vy if e2id in self.accelerationComponents.keys(): da_x -= self.accelerationComponents[e2id].ax da_y -= self.accelerationComponents[e2id].ay dv_x -= self.velocityComponents[e2id].vx dv_y -= self.velocityComponents[e2id].vy elif eid in self.velocityComponents.keys(): dv_x -= self.velocityComponents[e2id].vx dv_y -= self.velocityComponents[e2id].vy loc1 = self.positionComponents[e1id] loc2 = self.positionComponents[e2id] geom1 = self.geometryComponents[e1id] geom2 = self.geometryComponents[e2id] dx0_rl = (loc1.x + geom1.width) - loc2.x dx0_lr = loc1.x - (loc2.x + geom2.width) dy0_tb = loc1.y - (loc2.y + geom1.height) dy0_bt = (loc1.y + geom1.height) - loc2.y if da_x != 0: test, lx = self.__findLForAccel(da_x, dv_x, dx0_lr, dx0_rl) elif dv_x != 0: test, lx = self.__findLForVel(dv_x, dx0_lr, dx0_rl) else: test, lx = self.__findLForPos(dx0_lr, dx0_rl) if test == False: continue if da_y != 0: test, ly = self.__findLForAccel(da_y, dv_y, dy0_tb, dy0_bt) elif dv_y != 0: test, ly = self.__findLForVel(dv_y, dy0_tb, dy0_bt) else: test, ly = self.__findLForPos(dy0_tb, dy0_bt) if test == False: continue L = 10 # L > 1 impies no collision for l1 in lx: if l1[0] > 1 or l1[1] < 0: continue for l2 in ly: if l2[0] > 1 or l2[1] < 0: continue if l1[0] <= l2[0] <= l1[1]: L = min(L, l2[0]) axis = "y" if l2[0] <= l1[0] <= l2[1]: L = min(L, l1[0]) axis = "x" if L < 0 or L > 1: continue else: print "collision found!!!" collisions.append(Collision(e1id, e2id, L, axis)) return collisions
def findCollision(dt, e1, e2): """Returns a bool indicating if the two entities collided and a collision class which records the two entities and the lambda at which they collide""" da_x = 0 da_y = 0 if hasattr(e1.state, "accelerationComponent"): da_x += e1.state.accelerationComponent.ax da_y += e1.state.accelerationComponent.ay if hasattr(e2.state, "accelerationComponent"): da_x -= e2.state.accelerationComponent.ax da_y -= e2.state.accelerationComponent.ay dv_x = 0 dv_y = 0 if hasattr(e1.state, "velocityComponent"): dv_x += e1.state.velocityComponent.vx dv_y += e1.state.velocityComponent.vy if hasattr(e2.state, "velocityComponent"): dv_x -= e2.state.velocityComponent.vx dv_y -= e2.state.velocityComponent.vy dx0_rl = (e1.state.geometryComponent.location[0] + e1.state.geometryComponent.width) - e2.state.geometryComponent.location[0] dx0_lr = e1.state.geometryComponent.location[0] - (e2.state.geometryComponent.location[0] + e2.state.geometryComponent.width) dy0_tb = e1.state.geometryComponent.location[1] - (e2.state.geometryComponent.location[1] + e2.state.geometryComponent.height) dy0_bt = (e1.state.geometryComponent.location[1] + e1.state.geometryComponent.height) - e2.state.geometryComponent.location[1] if da_x != 0: test, lx = __findLForAccel(dt, da_x, dv_x, dx0_lr, dx0_rl) elif dv_x != 0: test, lx = __findLForVel(dt, dv_x, dx0_lr, dx0_rl) else: test, lx = __findLForPos(dt, dx0_lr, dx0_rl) if test == False: return False, None if da_y != 0: test, ly = __findLForAccel(dt, da_y, dv_y, dy0_tb, dy0_bt) elif dv_y != 0: test, ly = __findLForVel(dt, dv_y, dy0_tb, dy0_bt) else: test, ly = __findLForPos(dt, dy0_tb, dy0_bt) if test == False: return False, None L = 10 # L > 1 impies no collision for l1 in lx: if l1[0] > 1 or l1[1]<0: continue for l2 in ly: if l2[0] > 1 or l2[1]<0: continue if l1[0] <= l2[0] <= l1[1]: L = min(L, l2[0]) axis = "y" if l2[0] <= l1[0] <= l2[1]: L = min(L, l1[0]) axis = "x" if L < 0 or L > 1: return False, None else: print "collision found!!!" return True, Collision(e1, e2, L, axis)
def tick(self, player, camera): speed = 2 jump_speed = 45 self.tickTimer += 1 if self.tickTimer % 3 == 0: player.dv.add(self.accelerationDownwards.add(Vector(0, 1))) player.dv.y = 15 if player.dv.y > 10 else player.dv.y if self.tickTimer % 3 == 0: if player.pos.y + (player.w / 2) * 2 < camera.map_dimensions.y - ( camera.map_dimensions.y - camera.span[1]): player.dv.add(self.accelerationDownwards.add(Vector(0, 1))) player.dv.y = 15 if player.dv.y > 10 else player.dv.y elif player.pos.y + (player.w / 2) < camera.map_dimensions.y: camera.dv.add(self.accelerationDownwards.add(Vector(0, 1))) player.dv.add(self.accelerationDownwards.add(Vector(0, 1))) player.dv.y = 15 if player.dv.y > 10 else player.dv.y camera.dv.y = 15 if player.dv.y > 10 else player.dv.y else: # If the player has fallen off the map: player.revive(camera) interaction = Collision(player) interaction.update() if interaction.inCollisionDown: self.down = False player.dv.y = 0 if self.left and player.pos.x - (player.w / 2) > camera.furthest + ( player.w / 2) + 20: player.set_state(player.RUNNING) player.direction = player.LEFT player.dv.add(Vector(-speed, 0)) camera.dv.add(Vector(-speed, 0)) if camera.pos.x <= camera.furthest: camera.dv.x = 0 camera.pos.x = camera.furthest elif self.left: self.accelerationDownwards = Vector(0, 0.5) player.dv.x = 0 player.pos.x = camera.furthest + (player.w / 2) + 20 camera.dv.x = 0 camera.pos.x = camera.furthest if self.right and player.pos.x + ( player.w / 2) < camera.furthest + camera.span[0]: player.set_state(player.RUNNING) player.direction = player.RIGHT if player.pos.x < camera.furthest + camera.span[0] / 2: player.dv.add(Vector(speed, 0)) else: player.dv.add(Vector(speed, 0)) camera.dv.add(Vector(speed, 0)) if camera.pos.x >= camera.map_dimensions.x - camera.span[0] - ( Unit.UNIT * 2): camera.dv.x = 0 camera.pos.x = camera.map_dimensions.x - camera.span[0] - ( Unit.UNIT * 2) elif self.right and camera.map_dimensions.x - 20: self.accelerationDownwards = Vector(0, 0.5) player.dv.x = 0 player.pos.x = ( (camera.furthest + camera.span[0]) - player.w / 2) - 20 camera.dv.add(Vector(speed, 0)) elif self.right: self.accelerationDownwards = Vector(0, 0.5) player.dv.x = 0 player.pos.x = camera.dimensions.x - 20 camera.pos.x = camera.dimensions.x - camera.span[0] if self.up and player.pos.y - (player.w / 2) > 1 and player.grounded: player.set_state(player.JUMPING) player.grounded = False self.up = False self.accelerationDownwards = Vector(0, 0.5) player.dv.add(Vector(0, -jump_speed)) camera.dv.add(Vector(0, -jump_speed)) if camera.pos.y <= 0: camera.dv.y = 0 camera.pos.y = 0 elif not (player.pos.y - (player.w / 2) > 1): self.accelerationDownwards = Vector(0, 0.5) player.dv.y = 0 player.pos.y = 1 + (player.w / 2) camera.dv.y = 0 if not (self.right or self.up or self.left) and player.grounded: player.set_state(player.IDLE) player.sprite_index = player.IDLE_START if not player.grounded and player.state != player.JUMPING: player.set_state(player.JUMPING) player.dv *= 0.8 camera.dv *= 0.8
def collision_processor(file_name): """ Retrieve data about the time, in hour, of the ottawa's collision record from a csv file. :param file_name: the file to retrieve data """ global total_record global total_valid_record collisions = [] key_ctr = 0 with open(file_name, 'r') as readData: # r represent read model print("Start to read file: " + file_name + ". This may take a while...") file = csv.reader(readData) canada_holiday = holidays.CA() for row in file: if "COLLISION_ID" not in row[0]: collision = Collision() collision.collision_id = key_ctr key_ctr = key_ctr + 1 collision.location = row[1] collision.longtitude = row[4] collision.latitude = row[5] collision.date = row[6] collision.time = row[7] environment = row[8] if row[8] == "": environment = "Unknown" collision.environment = remove_prefix(environment, "Unknown") light = row[9] if row[9] == "": light = "Unknown" collision.light = remove_prefix(light, "Unknown") surface_condition = row[10] if row[10] == "": surface_condition = "Unknown" collision.surface_condition = remove_prefix( surface_condition, "Unknown") traffic_control = row[11] if row[11] == "": traffic_control = "Unknown" collision.traffic_control = remove_prefix( traffic_control, "Unknown") traffic_control_condition = row[12] if row[12] == "": if collision.traffic_control == "No control": traffic_control_condition = "N/A" collision.traffic_control_condition = traffic_control_condition else: traffic_control_condition = "Unknown" collision.traffic_control_condition = traffic_control_condition else: collision.traffic_control_condition = remove_prefix( traffic_control_condition, "Unknown") collision_classification = row[13] if row[13] == "": collision_classification = "Unknown" collision.collision_classification = remove_prefix( collision_classification, "Unknown") impact_type = row[14] if row[14] == "": impact_type = "Unknown" collision.impace_type = remove_prefix(impact_type, "Unknown") no_of_pedestrians = row[15] if row[14] == "": no_of_pedestrians = -1 collision.no_of_pedestrians = no_of_pedestrians collisions.append(collision) return collisions
def accident_processor(collision_file_name, hour_file_name, location_file_name): """ Retrieve data about the time, in hour, of the ottawa's collision record from a csv file. :param collision_file_name: The name of the collision file, which has been generated from preprocessor :param hour_file_name: The processed hour table file :param location_file_name: the processed location table file """ global total_record global total_valid_record hours = [] locations = [] collisions = [] with open(hour_file_name, 'r') as readHour: # r represent read model print("Start to read file: " + hour_file_name + ". This may take a while...") file = csv.reader(readHour) for row in file: if "HOUR_ID" not in row[0]: hour_id = row[0] hours.append(hour_id) readHour.close() print("Finished reading data from hour table") with open(location_file_name, 'r') as readLocation: # r represent read model print("Start to read file: " + location_file_name + ". This may take a while...") file = csv.reader(readLocation) for row in file: if "LOCATION_ID" not in row[0]: location_id = row[0] locations.append(location_id) readLocation.close() print("Finished reading data from location table") with open(collision_file_name, 'r') as readCollision: # r represent read model print("Start to read file: " + collision_file_name + ". This may take a while...") file = csv.reader(readCollision) ptr = 0 for row in file: if "COLLISION_ID" not in row[0]: collision = Collision() collision.collision_id = row[0] collision.location_id = locations[ptr] # append corresponding id collision.hour_id = hours[ptr] # append corresponding id collision.environment = row[6] collision.light = row[7] collision.surface_condition = row[8] collision.traffic_control = row[9] collision.traffic_control_condition = row[10] collision.collision_classification = row[11] collision.impace_type = row[12] collision.no_of_pedestrians = row[13] ptr = ptr + 1 collisions.append(collision) readCollision.close() print("Finished processing collision table") return collisions
def read_source_file(file_name, weather_file_name): with open(file_name, 'r') as readCollision: # r represent read model print("Start to read file: " + file_name + ". This may take a while...") file = csv.reader(readCollision) for row in file: if "COLLISION_ID" not in row[0]: collision = Collision() collision.collision_id = row[0] collision.location_key = row[1] collision.hour_key = row[2] collision.environment = row[3] collision.light = row[4] collision.surface_condition = row[5] collision.traffic_control = row[6] collision.traffic_control_condition = row[7] collision.collision_classification = row[8] collision.impace_type = row[9] collision.no_of_pedestrians = row[10] collision.date = row[11] collision.location = row[12] collision.is_intersection = row[13] collisions.append(collision) readCollision.close() with open(weather_file_name, 'r') as readWeather: # r represent read model print("Start to read file: " + weather_file_name + ". This may take a while...") file = csv.reader(readWeather) key_ctr = 0 for row in file: weathers.append(row) # print(row[0]+" @ "+row[24]) readWeather.close()
def run(self): nrLevel = 0 pygame.init() sound = pygame.mixer.Sound("music/BackGround.wav") soundLose = pygame.mixer.Sound("music/Lose.wav") soundWin = pygame.mixer.Sound("music/Win.wav") sound.play(1) screen = pygame.display.set_mode(Setting.resolution, pygame.FULLSCREEN) pygame.display.set_caption('Croko') clock = pygame.time.Clock() main_loop = True collision = Collision() player = Player("img/PlayerUP.png", 1) players = pygame.sprite.Group() players.add(player) level = LevelHandler() level.loadFile(Setting.LEVELS[nrLevel]) level.gen() playerBullets = pygame.sprite.Group() enemyBullets = pygame.sprite.Group() enemy = TigerTank(Setting.EnemySpawn[0]) enemy1 = GhostTank(Setting.EnemySpawn[1]) enemy2 = Enemy(Setting.EnemySpawn[2]) enemy3 = Enemy(Setting.EnemySpawn[3]) enem = EnemyHandler(enemyBullets) enem.tanks.add(enemy) enem.tanks.add(enemy1) enem.tanks.add(enemy2) enem.tanks.add(enemy3) credit = Credits() self.blocks = pygame.sprite.Group() self.blocks.remove(self.blocks) self.blocks = level.map() while main_loop: pygame.mouse.set_visible(False) player.getBlocks(self.blocks) enem.getBlocks(self.blocks) enem.getEnemyTanks() if (enem.count <= 0): if nrLevel is not Setting.LAST_LEVEL: nrLevel += 1 self.blocks.remove(self.blocks) level.loadFile(Setting.LEVELS[nrLevel]) level.gen() enem.reset() else: sound.stop() soundWin.play(1) pygame.time.wait(4500) credit.run() main_loop = False if (player.live <= 0): sound.stop() soundLose.play(1) pygame.time.wait(4500) main_loop = False for block in self.blocks: if isinstance(block, EaglBlock): if block.life <= 0: sound.stop() soundLose.play(1) pygame.time.wait(4500) main_loop = False for event in pygame.event.get(): if event.type == pygame.QUIT: main_loop = False sound.stop() else: player.reaction(event, playerBullets) if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: main_loop = False sound.stop() screen.fill(CZARNY) collision.playerCollisionWithEnemy(players, enem.tanks) collision.SelfbulletsCollisionWithEnemy(enem.tanks, enemyBullets) collision.bulletsCollisionWithPlayer(players, enemyBullets) collision.bulletCollisionWithBlocks(playerBullets, self.blocks) collision.bulletCollisionWithBlocks(enemyBullets, self.blocks) collision.bulletsCollisionWithBullets(enemyBullets, playerBullets) enem.bulletsCollisionWithSelf(playerBullets) players.draw(screen) players.update() playerBullets.update() playerBullets.draw(screen) enem.tanks.draw(screen) enem.shot() enem.tanks.update() enemyBullets.draw(screen) enemyBullets.update() self.blocks.draw(screen) pygame.display.flip() clock.tick(30)
def display_redraw(self): # redraw board and players # draw static background self.draw_background() ### if test mode is on, draw additional markers on screen if self.test_mode: # draw sectors around ball and players for obj in self.players: sector_num = int(obj.size * 4 / self.sector_size) for i in range( int(obj.p.x / self.sector_size) - sector_num, int(obj.p.x / self.sector_size) + sector_num + 1): for j in range( int(obj.p.y / self.sector_size) - sector_num, int(obj.p.y / self.sector_size) + sector_num + 1): pygame.draw.rect( self.screen, (0, 255 - ((i + j) % 2) * 50, 0), (i * self.sector_size, j * self.sector_size, int(self.sector_size), int(self.sector_size))) for obj in self.balls: sector_num = int(obj.size * 4 / self.sector_size) for i in range( int(obj.p.x / self.sector_size) - sector_num, int(obj.p.x / self.sector_size) + sector_num + 1): for j in range( int(obj.p.y / self.sector_size) - sector_num, int(obj.p.y / self.sector_size) + sector_num + 1): pygame.draw.rect( self.screen, (0, 255 - ((i + j) % 2) * 50, 0), (int(obj.p.x / self.sector_size) * self.sector_size, int(obj.p.y / self.sector_size) * self.sector_size, int( self.sector_size), int(self.sector_size))) # draw hitboxes for obj in self.players: pygame.gfxdraw.aacircle(self.screen, int(obj.p.x), int(obj.p.y), obj.hitbox, (0, 0, 255)) for obj in self.balls: pygame.gfxdraw.aacircle(self.screen, int(obj.p.x), int(obj.p.y), obj.hitbox, (0, 0, 255)) # check collisions and redraw all players for obj in self.players: Collision.collide(obj) pygame.gfxdraw.filled_circle(self.screen, int(obj.p.x), int(obj.p.y), obj.size, obj.color) pygame.gfxdraw.aacircle(self.screen, int(obj.p.x), int(obj.p.y), obj.size, obj.border_color) pygame.gfxdraw.aacircle(self.screen, int(obj.p.x), int(obj.p.y), obj.size - 1, obj.border_color) # check collisions with posts self.goal_left.goal_collide() self.goal_right.goal_collide() # draw graphics on top of the screen self.draw_graphics()
def goal_collide(self): Collision.collide(self.post_up) Collision.collide(self.post_down)
def walls_collision(self, obj): Collision.walls_collision(obj, self)
map.draw(score_activate=(car.last_score + 1) % 8) car.draw() label.text = str(car.score) label.draw() global glob_frame glob_frame += 1 label2.text = str(glob_frame) label2.draw() if not car.player_play: f = car.rays(ai, net, map.in_map, map.out_map, True) keys.ai_keys(f) # print f fps_display.draw() if __name__ == "__main__": fps_display = FPSDisplay(window) map = CarMap() ai = Ai() net = Net() device = torch.device('cpu') net.load_state_dict( torch.load('models/' + car_model + '.txt', map_location=device)) net.double() car = Car() keys = Keyboard_helper() collision = Collision() pyglet.clock.schedule_interval(update_frames, 1 / 24.0) pyglet.app.run()
class Car4W: def __init__(self, tyres, sensors=[], cameras=[], timeframe=0.1, car_speed=50): logger.debug("Car4W.__init__()") self.action_id = 0 self.t = None self.camera = None self.timeframe = timeframe self.car_speed = car_speed if len(tyres) != 4: raise EnvironmentError("Car4W required four tyres") self.state = 0 self.frontRight = tyres[0][1] self.frontLeft = tyres[1][1] self.backRight = tyres[2][1] self.backLeft = tyres[3][1] self.stop() # Stop the car, reset pins. self.collision = Collision(sensors) self.collision.start() logger.debug("Waiting to collision sensor to get ready") while not self.collision.ready: sleep(0.5) logger.info("Collision sensors are ready.") logger.debug("Waiting to camera to get ready") self.cameras = cameras for camera in self.cameras: camera[1].start() logger.debug("Camera start called") for camera in self.cameras: while not camera[1].more(): sleep(0.5) logger.debug(camera[0] + " is ready.") logger.info("Cameras are ready.") def speed(self, speedup=1.5): percent = self.car_speed * speedup if percent > 100: percent = 100 self.frontRight.speed(percent) self.frontLeft.speed(percent) self.backRight.speed(percent) self.backLeft.speed(percent) def set_timeframe(self, timeframe): self.timeframe = timeframe def is_idle(self): return self.state in (State.IDLE, State.STOPPED) def take_action(self, method_name): logger.debug("Taking action, " + method_name) #self.action_id += 1 # This function is called from Websocket method = getattr(self, method_name) method() def get_state(self): return self.state def get_state_vector( self, latest=False, for_network=None ): # for_network convert numpy to list because it is faster for pickle start_time = time.time() state = {} # ADDING: Sensors details sensors = self.collision.get(latest) state['sensors'] = sensors # ADDING: Camera data fps = [] for camera in self.cameras: name = camera[0] fps.append([camera[1].fps, camera[1].Q.qsize()]) frame = camera[1].get_frame(latest) if for_network == False: # It is for Desktop GUI (Python) frame = [ str(frame.dtype), base64.b64encode(frame).decode("utf-8"), frame.shape ] elif for_network == True: stream = cStringIO.StringIO() frame = frame[:, :, ::-1] #frame = np.roll(frame, 1, axis=-1) # BGR to RGB frame = Image.fromarray(frame, 'RGB') # Takes 150 ms - Slow RPS frame.save(stream, format="JPEG") frame = base64.b64encode(stream.getvalue()).decode("utf-8") state[name] = frame logger.debug("All Camera Info [FPS, QSize]: {}".format(fps)) logger.debug("Received State in {} seconds".format(time.time() - start_time)) return state # converted to pickle in State.py def forward(self): self.speed(1) self.state = State.FORWARD self.frontLeft.forward() self.frontRight.forward() self.backLeft.forward() self.backRight.forward() def backward(self): self.speed(1) self.state = State.BACKWARD self.frontLeft.backward() self.frontRight.backward() self.backLeft.backward() self.backRight.backward() def idle(self): self.state = State.IDLE self.stop() def stop(self): self.speed(1) self.state = State.STOPPED self.frontLeft.stop() self.frontRight.stop() self.backLeft.stop() self.backRight.stop() def forwardRight(self): self.speed(1.5) self.frontLeft.forward() self.backLeft.forward() self.frontRight.backward() self.backRight.backward() self.state = State.FORWARD_RIGHT def forwardLeft(self): self.speed(1.5) self.frontRight.forward() self.backRight.forward() self.frontLeft.backward() self.backLeft.backward() self.state = State.FORWARD_LEFT def backwardRight(self): self.speed(1.5) self.state = State.BACKWARD_RIGHT self.frontLeft.backward() self.backLeft.backward() self.frontRight.forward() self.backRight.forward() def backwardLeft(self): self.speed(1.5) self.state = State.BACKWARD_LEFT self.frontRight.backward() self.backRight.backward() self.frontLeft.forward() self.backLeft.forward() def close(self): self.stop() self.collision.stop() for camera in self.cameras: camera[1].stop() def test(self): from time import sleep self.forward() sleep(0.5) self.stop() sleep(1) self.backward() sleep(0.5) self.stop() sleep(1) self.forwardRight() sleep(0.5) self.stop() sleep(1) self.forwardLeft() sleep(0.5) self.stop() sleep(1) self.backwardLeft() sleep(1) self.stop() sleep(1) self.backwardRight() sleep(1) self.stop() def __del__(self): GPIO.cleanup()