def make_game_state(self, rng: SeededRandomNumberGenerator) -> GameState: comms = self.get_matchcomms() self.grader.set_match_comms(comms) return GameState( ball=BallState(physics=Physics(location=Vector3(0, 0, 92.75), velocity=Vector3(0, 0, 0), angular_velocity=Vector3(0, 0, 0))), cars={ 0: CarState(physics=Physics(location=Vector3( self.car_start_x, 3000, 0), rotation=Rotator(0, -pi / 2, 0), velocity=Vector3(0, 0, 0), angular_velocity=Vector3(0, 0, 0)), jumped=False, double_jumped=False, boost_amount=0) }, boosts={i: BoostState(0) for i in range(34)}, )
def reset(self): ball_start = Vec3( x=random.randint(-1365, 1365), y=random.randint(-1280, -1200), z=random.randint(50, 100), ) ball_end = Vec3( x=random.randint(-800, 800), y=random.randint(-5125, -5120), z=random.randint(50, 100), ) ball_speed = (ball_end-ball_start).normalized() * random.randint(1600, 1800) car_start = Vec3( x=random.randint(-440, 440), y=random.randint(-5560, -5120), z=50, ) car_rot = Rotator( pitch=0, yaw=math.pi/2 + (random.random()-0.5)*math.pi/6, roll=0, ) self.set_game_state(GameState( ball=BallState(physics=Physics( location=ball_start.to_vector3(), velocity=ball_speed.to_vector3(), )), cars={0: CarState(physics=Physics( location=car_start.to_vector3(), rotation=car_rot, velocity=Vector3(0, 0, 0), angular_velocity=Vector3(0, 0, 0) ), boost_amount=random.randint(60, 90), )}, game_info=GameInfoState( game_speed=self.speed ) ))
def checkState(self): if self.state.expired: self.state.reset( ) #If our state has expired, reset it and choose the next available state car = CarState(boost_amount=100, physics=Physics(velocity=vector3(0, 0, 0), angular_velocity=vector3(0, 0, 0), location=vector3(400, 3000, 20), rotation=Rotator(0, math.pi / 2, 0))) ball = BallState(physics=Physics(location=vector3(-3000, 1000, 94), velocity=vector3(1500, 0, 0))) game = GameState(ball=ball, cars={self.index: car}) self.set_game_state(game) flag = True for item in self.states: if item.available() == True: self.state = item flag = False if flag: #If no states are available do this: self.state = wait()
def make_game_state(self, rng: SeededRandomNumberGenerator) -> GameState: self.grader.graders[1].max_duration_seconds = 5 return GameState( game_info=GameInfoState(game_speed=1), ball=BallState( physics=Physics(location=Vector3(rng.uniform(-500, 500), rng.uniform(-500, 500), 94), velocity=Vector3(0, rng.uniform(-300, 500), rng.uniform(0, 600)), angular_velocity=Vector3(0, 0, 0))), cars={ 0: CarState(physics=Physics(location=Vector3( rng.uniform(-100, -90), -2200, 25), rotation=Rotator(0, pi / 2, 0), velocity=Vector3(0, 1000, 0), angular_velocity=Vector3(0, 0, 0)), boost_amount=80), 1: CarState(physics=Physics( location=Vector3(10000, 10000, 10000))) }, )
def initialize_agent(self): random_position = Vector3(random.uniform(-3000, 3000), random.uniform(-4000, 4000), 18) random_velocity = Vector3(random.uniform(-1000, 1000), random.uniform(-1000, 1000), 0) random_rotation = Rotator(0, random.uniform(-math.pi, math.pi), 0) car_physics = Physics(location=random_position, velocity=random_velocity, rotation=random_rotation, angular_velocity=Vector3(0, 0, 0)) boost = random.uniform(0, 50) car_state = CarState(boost_amount=boost, physics=car_physics) game_state = GameState(cars={self.index: car_state}) self.set_game_state(game_state) self.initialization_time = self.info.time self.action.reset_status()
def make_game_state(self, rng: SeededRandomNumberGenerator) -> GameState: car_pos = Vector3(0, 2500, 25) ball_pos = Vector3(rng.uniform(-200, 200), rng.uniform(0, -1500), 100) ball_state = BallState( Physics(location=ball_pos, velocity=Vector3(0, -1250, 0), angular_velocity=Vector3(0, 0, 0))) car_state = CarState(boost_amount=87, jumped=True, double_jumped=True, physics=Physics(location=car_pos, rotation=Rotator(0, -pi / 2, 0), velocity=Vector3(0, 0, 0), angular_velocity=Vector3(0, 0, 0))) enemy_car = CarState(physics=Physics( location=Vector3(10000, 10000, 10000))) game_state = GameState(ball=ball_state, cars={ 0: car_state, 1: enemy_car }) return game_state
def set_state_test(self, game_tick_packet: GameTickPacket): my_car = game_tick_packet.game_cars[self.index] car_location = my_car.physics.location car_state = CarState() if math.fabs(car_location.x) > 2000 and car_location.z < 100: car_state = CarState(Physics(velocity=Vector3(z=500, x=-car_location.x * .5), rotation=Rotator(math.pi / 2, 0, 0), angular_velocity=Vector3(0, 0, 0)), jumped=False, double_jumped=False, boost_amount=87) ball_phys = game_tick_packet.game_ball.physics ball_state = BallState() if ball_phys.location.z < 500: ball_state = BallState( Physics(location=Vector3(0, 0, 800), velocity=Vector3(0, 0, 1000))) if math.fabs(car_location.x) > 1000: boost_states = {i: BoostState(1.0) for i in range(34)} else: boost_states = {i: BoostState(0.0) for i in range(34)} game_info_state = GameInfoState( world_gravity_z=-(ball_phys.location.z - 1200), game_speed=0.5) game_state = GameState(ball=ball_state, cars={self.index: car_state}, boosts=boost_states, game_info=game_info_state) self.set_game_state(game_state)
def reset_state(self): # If car is moving backwards, set it on the front goal, and vice versa if self.throttle_list[self.throttle_index] <= 0: speed_multiplier = 1 else: speed_multiplier = -1 car_state = CarState( boost_amount=100, physics=Physics( velocity=Vector3(0, 10000 * speed_multiplier, 0), location=Vector3(x=0, y=0), rotation=Rotator(0, math.pi / 2, 0), angular_velocity=Vector3(0, 0, 0), ), ) # Setting the run start time self.reset_time = 0 ball_state = BallState(Physics(location=Vector3(z=3000))) game_state = GameState(ball=ball_state, cars={self.index: car_state}) self.set_game_state(game_state)
def make_game_state(self, rng: SeededRandomNumberGenerator) -> GameState: minboost = self.boost if self.minboost is None else self.minboost maxboost = self.boost if self.maxboost is None else self.maxboost return GameState( ball=BallState(physics=Physics( location=Vector3(self.ball_x, self.ball_y, self.ball_z), velocity=Vector3(self.ball_vx, self.ball_vy, self.ball_vz), angular_velocity=Vector3(self.ball_sx, self.ball_sy, self.ball_sz))), cars={ 0: CarState(physics=Physics(location=Vector3( self.car_x, self.car_y, self.car_z), rotation=Rotator(0, self.car_spin, 0), velocity=Vector3(0, 0, 0), angular_velocity=Vector3(0, 0, 0)), jumped=False, double_jumped=False, boost_amount=rng.uniform(minboost, maxboost)) }, boosts={i: BoostState(0) for i in range(34)}, # Is this needed. )
def rotator_from_dir(dir: Vector3): yaw = math.atan(dir.y / dir.x) pitch = math.asin(dir.z / magnitude(dir)) if dir.x < 0: yaw = (yaw + math.pi) % (2 * math.pi) return Rotator(pitch, yaw, 0)
def get_output(self, packet: GameTickPacket) -> SimpleControllerState: self.game.read_game_information(packet, self.get_rigid_body_tick(), self.get_field_info()) self.controls = SimpleControllerState() next_state = self.state if self.state == State.RESET: self.timer = 0.0 # put the car in the middle of the field car_state = CarState(physics=Physics(location=Vector3(0, 0, 18), velocity=Vector3(0, 0, 0), rotation=Rotator(0, 0, 0), angular_velocity=Vector3( 0, 0, 0)), jumped=False, double_jumped=False) theta = random.uniform(0, 6.28) pos = Vector3(sin(theta) * 1000.0, cos(theta) * 1000.0, 100.0) # put the ball somewhere out of the way ball_state = BallState( physics=Physics(location=pos, velocity=Vector3(0, 0, 0), rotation=Rotator(0, 0, 0), angular_velocity=Vector3(0, 0, 0))) self.set_game_state( GameState(ball=ball_state, cars={self.game.id: car_state})) next_state = State.WAIT if self.state == State.WAIT: if self.timer > 0.2: next_state = State.INITIALIZE if self.state == State.INITIALIZE: self.action = Dodge(self.game.my_car) self.action.duration = 0.1 self.action.direction = vec2(self.game.ball.location) next_state = State.RUNNING if self.state == State.RUNNING: self.action.step(self.game.time_delta) self.controls = self.action.controls print(self.controls.jump) if self.timer > self.timeout: next_state = State.RESET self.timer += self.game.time_delta self.state = next_state return self.controls
def get_output(self, packet: GameTickPacket) -> SimpleControllerState: #Original Code my_car = packet.game_cars[self.index] ball_location = Vector2(packet.game_ball.physics.location.x, packet.game_ball.physics.location.y) car_location = Vector2(my_car.physics.location.x, my_car.physics.location.y) car_direction = get_car_facing_vector(my_car) car_to_ball = ball_location - car_location #update class data self.car.update(packet.game_cars[self.index]) self.ball.update(packet.game_ball) self.CoordinateSystems.update(self.car, self.ball) self.BallController.update(packet.game_ball) self.ball.x = packet.game_ball.physics.location.x self.ball.y = packet.game_ball.physics.location.y self.ball.z = packet.game_ball.physics.location.z # t = packet.game_info.seconds_elapsed #print(packet.game_cars[self.index]) carBallAngle = getAngle( packet.game_ball.physics.location.x - self.car.x, packet.game_ball.physics.location.z - self.car.z, 0, 0) # print('z:', self.car.z, 'vz:', self.car.vz, 'y:', self.car.y, 'vy:', self.car.vy, 'x:', self.car.x, 'vx:', self.car.vx, 'pitch:', self.car.pitch, 'roll: ', self.car.roll, 'yaw:', self.car.yaw) #fixing pitch since RL uses euler angles pi = math.pi p = float(self.car.pitch) r = float(self.car.roll) y = float(self.car.yaw) curang = float(getXZangle(p, r, y)) # print('actual pitchL', actualPitch[0]) #Create desired and current vectors [x, z, theta, vx, vz, omegay] # self.current = np.matrix([self.car.z, self.car.x, actualPitch, self.car.vz, self.car.vx, self.car.wy]) # self.desired = np.matrix([800, self.car.x, math.pi/4, self.car.vz, self.car.vx, self.car.wy]) self.current = np.matrix([curang, self.car.wy]) self.desired1 = np.matrix([-1 * float(carBallAngle[0]), 0]) self.desired2 = self.desired1 #np.matrix([-2, 0]) #calculate Adesired As = 900 #uu/s2 Ag = np.matrix([0, -650]) theta = carBallAngle Adesired = np.matrix([(As * math.cos(theta)), (As * math.sin(theta))]) Aa = Adesired - Ag Ax = float(Aa.item(0)) Az = float(Aa.item(1)) Ax2 = math.pow(Ax, 2) Az2 = math.pow(Az, 2) A = (math.sqrt(Ax2 + Az2)) boostPercent = A / 991.666 * 100 boostPercent = max(min(boostPercent, 100), 0) thetaActual = getAngle(Aa.item(0), Aa.item(1), 0, 0) # print('Theta actual:', thetaActual, 'Aactual: ', Aa, 'boost percent: ', boostPercent) thetaDesired = np.matrix([-1 * float(thetaActual), 0]) #Quaternion stuff q0 = Quaternion(axis=[1., 0., 0.], radians=self.car.roll) q1 = Quaternion(axis=[0., 1., 0.], radians=self.car.pitch) q2 = Quaternion(axis=[0., 0., 1.], radians=-1 * self.car.yaw) q3 = q0 * q1 * q2 xprime = q3.rotate([1, 0, 0]) qcar = q3.rotate([1., 0., 0.]) # print('xprime: ', xprime, 'q3:', q3) #get point vectors for car and ball ux = np.array([1., 0., 0.]) uy = np.array([0., 1., 0.]) uz = np.array([0., 0., 1.]) Pb = np.array([ packet.game_ball.physics.location.x, packet.game_ball.physics.location.y, packet.game_ball.physics.location.z ]) Pc = np.array([ self.car.x, self.car.y, self.car.z ]) #negate z because z axis for car is pointed downwards Pbc = np.subtract(Pb, Pc) #Get vector to ball from car in car coordinates xyz = np.cross( ux, Pbc) #xyz of quaternion is rotation between Pbc and unit x vector w = math.sqrt(1 * ( (Pbc.item(0)**2) + (Pbc.item(1)**2) + (Pbc.item(2)**2))) + np.dot(ux, Pbc) #scalr of quaternion qbcworld = Quaternion(w=w, x=xyz.item(0), y=xyz.item(1), z=xyz.item(2)) eulerAngles = toEulerAngle( qbcworld.unit) #convert quaternion to euler angles #getting quaternion describing car orientation qw2c = Quaternion(w=0, x=self.car.roll, y=self.car.pitch, z=self.car.yaw) # Pcar = qw2c.unit.rotate(ux) q0 = Quaternion(axis=[1., 0., 0.], radians=self.car.roll) q1 = Quaternion(axis=[0., 1., 0.], radians=self.car.pitch) q2 = Quaternion(axis=[0., 0., -1.], radians=self.car.yaw) q3 = q0.unit * q1.unit * q2.unit Pcar = q3.unit.rotate(ux) # print('pcar', xprime, 'pitch', self.car.pitch) xyzCar = np.cross( ux, Pcar) #xyz of quaternion is rotation between Pbc and unit x vector wCar = math.sqrt(1 * ( (Pcar.item(0)**2) + (Pcar.item(1)**2) + (Pcar.item(2)**2))) + np.dot(ux, Pcar) #scalr of quaternion qcarworld = Quaternion(w=wCar, x=xyzCar.item(0), y=xyzCar.item(1), z=xyzCar.item(2)) #Angular Velocity Inputs to the control algorithm omegades = np.matrix([0, 0, 0]) omegacur = self.CoordinateSystems.w_car #get current position of trajectory time = packet.game_info.seconds_elapsed Pdes, Vdes = self.Trajectory.circularTrajectory(1000, .5, time, 1500) #A, w, t, height # Pdes = np.array([self.ball.x, self.ball.y, self.ball.z]) # Vdes = np.array([self.ball.vx, self.ball.vy, self.ball.vz]) #CONTROL SYSTEM ALGORITHMS #get acceleration vector Pcur = np.array([self.car.x, self.car.y, self.car.z]) Vcur = np.array([self.car.vx, self.car.vy, self.car.vz]) acc, accMagnitude = getAccelerationVector(Pdes, Pcur, Vdes, Vcur) accfix = np.array([-1 * acc.item(0), acc.item(1), acc.item(2)]) boostPercent = accMagnitude / 991.666 * 100 boostPercent = max(min(boostPercent, 100), 0) # print('acc:', acc, 'accmag', accMagnitude) Qworld_to_acceleration_vector = self.CoordinateSystems.createQuaternion_world_at_car( accfix) torques = getTorques(self.CoordinateSystems.Qworld_to_car, Qworld_to_acceleration_vector, omegades, omegacur) #True Proportionanl navigation #Send Data to feedbackcontroller #self.car.printVals(); if (self.counter.count < self.counter.lap1): self.fbController.pitchControl(thetaDesired, self.current) #try only controlling z velocity # self.fbController.pitchControl(self.car.z, self.car.x, self.car.pitch, self.car.vz, self.car.vx, self.car.wz, self.car.z, self.car.x, self.car.pitch, self.car.vz, self.car.vx, self.car.wz) self.counter.increment() if (self.counter.count >= self.counter.lap1) and (self.counter.count < self.counter.lap2): self.fbController.pitchControl(thetaDesired, self.current) # self.fbController.pitchControl(0, 0, 0, 10, 0, 0, self.car.z, self.car.x, self.car.pitch, self.car.vz, self.car.vx, self.car.wz) self.counter.increment() if (self.counter.count >= self.counter.lap2): self.counter.reset() #Setting Controller state from values in controller #boost value # self.controller_state.boost = self.boostCounter.boost(60) # self.controller_state.boost = 1 self.controller_state.boost = self.boostCounter.boost(boostPercent) # # #roll, pitch, yaw values self.controller_state.pitch = max(min(torques.item(1), 1), -1) self.controller_state.roll = max(min(torques.item(0), 1), -1) self.controller_state.yaw = -1 * max( min(torques.item(2), 1), -1 ) #changes in rotations about coordinate system cause z axis changes # self.controller_state.pitch = 0 # self.controller_state.roll = 0 # self.controller_state.yaw = 0 #changes in rotations about coordinate system cause z axis changes # self.controller_state.pitch = 0.0#max(min(torques.item(1), 1), -1) #self.fbController.pitchPercent # self.controller_state.roll = 0.0#max(min(torques.item(0), 1), -1) # self.controller_state.yaw = 1#max(min(torques.item(2), 1), -1) #Make car jump if its on the floor if (packet.game_cars[self.index].has_wheel_contact): self.controller_state.jump = True else: self.controller_state.jump = False #Contol ball for testing functions x, y, z, vi = self.BallController.bounce(500, 500, 300, 1500) Vt = self.BallController.rotateAboutZ(np.matrix([0, 0, 0]), math.pi / 10) p = np.array([-1000, -1000, 100]) v = np.array([800, 0, 1500]) ballpos, ballvel = self.BallController.projectileMotion(p, v) # vx = self.BallController.oscillateX(-1500, 0, 1000) vx = Vt.item(0) vy = Vt.item(1) # vz = 0 #Set ball and car states to set game state for testing ball_state1 = BallState( Physics(location=Vector3(x, y, z), velocity=Vector3(0, 0, vi))) ball_state2 = BallState( Physics(location=Vector3(ballpos[0], ballpos[1], ballpos[2]), velocity=Vector3(ballvel[0], ballvel[1], ballvel[2]))) # ball_state = BallState(Physics(velocity = Vector3(vx, vy, 1))) # , # car_state = CarState(jumped=True, double_jumped=False, boost_amount=0, # physics=Physics(location = Vector3(-1000, 0, 500),velocity=Vector3(0, 0, 0), rotation = Rotator(pitch = eulerAngles.item(1), yaw = eulerAngles.item(2), roll = eulerAngles.item(0)))) car_state = CarState(jumped=True, double_jumped=False, boost_amount=1, physics=Physics( location=Vector3(-500, -1500, 500), velocity=Vector3(0, 0, 0), rotation=Rotator(pitch=math.pi / 1.9, yaw=0.1, roll=0), angular_velocity=Vector3(0, 0, 0))) # car_state2 = CarState(jumped=True, double_jumped=False, boost_amount=0, # physics=Physics(location = Vector3(00, 0, 500),velocity=Vector3(0, 0, 0))) #Pointed down car state for maximum initial error # car_state = CarState(jumped=True, double_jumped=False, boost_amount=1, # physics=Physics(location = Vector3(500, 0, 500),velocity=Vector3(0, 0, 1100), rotation = Rotator(yaw = math.pi/2, pitch = -1*math.pi/2, roll = math.pi/2))) if (self.BallController.release == 0): game_state = GameState(ball=ball_state2, cars={self.index: car_state}) self.set_game_state(game_state) # game_state = GameState(ball = ball_state)#, cars = {self.index: car_state}) # self.set_game_state(game_state) #PREDICTIONS #torque coefficients T_r = 36.07956616966136 # torque coefficient for roll T_p = 12.14599781908070 # torque coefficient for pitch T_y = 8.91962804287785 # torque coefficient for yaw #boost vector in car coordinates boostVector = np.array([self.controller_state.boost * 991.666, 0, 0]) #Get values at tk and tk - 1 self.t0 = self.t1 self.t1 = packet.game_info.seconds_elapsed self.p0 = self.p1 #position vector at initial time self.p1 = self.car.position #position vector at tk+1 self.v0 = self.v1 #velocity at prior frame self.v1 = self.car.velocity self.q0 = self.q1 #Orientation at prior frame self.q1 = self.CoordinateSystems.Qworld_to_car.conjugate.normalised self.w0 = self.w1 #angular velocity at prior frame self.w1 = self.car.angular_velocity self.a0 = self.a1 #accelreation vector at prior frame self.a1 = self.CoordinateSystems.toWorldCoordinates(boostVector) self.T0 = self.T1 #Torque vector at prior frame self.T1 = np.array([ self.controller_state.roll * T_r, self.controller_state.pitch * T_p, self.controller_state.yaw * -1 * T_y ]) aavg = (self.a1 + self.a0) / 2 vavg = (self.v1 + self.v0 / 2) predictedp1, predictedv1 = Predictions.predict(self.p0, self.v0, self.q0, self.w0, aavg, self.T0, self.t0, self.t1) errorv = (predictedv1 - self.v1)**2 errorp = (predictedp1 - self.p1)**2 # print("error^2 v:", errorv, "error^2 p:", errorp) # print("z actual:", self.car.z, "z predicted:", predictedp1[2]) self.data.add(self.v1[0], predictedv1[0], errorv[0], self.t1) #PLOTTING if (self.plotTime0 == None): self.plotTime0 = packet.game_info.seconds_elapsed else: self.plotTime1 = packet.game_info.seconds_elapsed if (self.plotTime1 != None): if ((self.plotTime1 - self.plotTime0) > 10): # self.plotData(self.data) None #RENDERING # self.renderer.begin_rendering() # # #helpful vectors for rendering # car = np.array([self.car.x, self.car.y, self.car.z]).flatten() # ball = np.array([self.ball.x, self.ball.y, self.ball.z]).flatten() # origin = np.array([0,0,0]) # #World coordinate system # self.renderer.draw_line_3d(np.array([0,0,0]), np.array([500,0,0]), self.renderer.red()) # self.renderer.draw_line_3d(np.array([0,0,0]), np.array([0,500,0]), self.renderer.green()) # self.renderer.draw_line_3d(np.array([0,0,0]), np.array([0,0,500]), self.renderer.blue()) # # #Car coordinate system # headingx = 100*self.CoordinateSystems.toWorldCoordinates(np.array([1,0,0])) #multiply by 100 to make line longer # headingy = 100*self.CoordinateSystems.toWorldCoordinates(np.array([0,1,0])) # headingz = 100*self.CoordinateSystems.toWorldCoordinates(np.array([0,0,1])) # self.renderer.draw_line_3d(np.array([self.car.x, self.car.y, self.car.z]), np.array([self.car.x + headingx.item(0), self.car.y + headingx.item(1), self.car.z + headingx.item(2)]), self.renderer.red()) # self.renderer.draw_line_3d(np.array([self.car.x, self.car.y, self.car.z]), np.array([self.car.x + headingy.item(0), self.car.y + headingy.item(1), self.car.z + headingy.item(2)]), self.renderer.green()) # self.renderer.draw_line_3d(np.array([self.car.x, self.car.y, self.car.z]), np.array([self.car.x + headingz.item(0), self.car.y + headingz.item(1), self.car.z + headingz.item(2)]), self.renderer.blue()) # # #Car direction vector on world coordinate system # self.renderer.draw_line_3d(np.array([0,0,0]), np.array([headingx.item(0), headingx.item(1), headingx.item(2)]), self.renderer.red()) # self.renderer.draw_line_3d(np.array([0,0,0]), np.array([headingy.item(0), headingy.item(1), headingy.item(2)]), self.renderer.green()) # self.renderer.draw_line_3d(np.array([0,0,0]), np.array([headingz.item(0), headingz.item(1), headingz.item(2)]), self.renderer.blue()) # # #Draw position of ball after converting from Pball_car to Pball_world # # desired = np.array(self.CoordinateSystems.getVectorToBall_world()).flatten() # # self.renderer.draw_line_3d(car, car + desired, self.renderer.yellow()) # # #Car to ball vector # # # self.renderer.draw_rect_3d(car+desired, 100, 100, 0, self.renderer.teal()) # # #Acceleration vector # a = np.array([accfix.item(0), -1*accfix.item(1),-1*accfix.item(2)]) # self.renderer.draw_line_3d(car, car + a/10, self.renderer.pink()) # # #trajectory vector # self.renderer.draw_line_3d(origin, Pdes, self.renderer.orange()) # # #error rectangles velocities # self.renderer.draw_rect_2d(10,10,int(errorv[0]**(1/2)), 50, True, self.renderer.cyan()) # self.renderer.draw_rect_2d(10,60,int(errorv[1]**(1/2)), 50, True, self.renderer.cyan()) # self.renderer.draw_rect_2d(10,110,int(errorv[2]**(1/2)), 50, True, self.renderer.cyan()) # #text for velocity errors # self.renderer.draw_string_2d(10, 10, 1, 1, "X velocity Error: " + str(errorv[0]**(1/2)), self.renderer.white()) # self.renderer.draw_string_2d(10, 60, 1, 1, "Y velocity Error: " + str(errorv[1]**(1/2)), self.renderer.white()) # self.renderer.draw_string_2d(10, 110, 1, 1, "Z velocity Error: " + str(errorv[2]**(1/2)), self.renderer.white()) # #positions # self.renderer.draw_rect_2d(10,160,int(errorp[0]**(1/2)), 50, True, self.renderer.red()) # self.renderer.draw_rect_2d(10,210,int(errorp[1]**(1/2)), 50, True, self.renderer.red()) # self.renderer.draw_rect_2d(10,260,int(errorp[2]**(1/2)), 50, True, self.renderer.red()) # # self.renderer.draw_string_2d(10, 160, 1, 1, 'X position Error: ' + str(errorp[0]**(1/2)), self.renderer.white()) # self.renderer.draw_string_2d(10, 210, 1, 1, "Y position Error: " + str(errorp[1]**(1/2)), self.renderer.white()) # self.renderer.draw_string_2d(10, 260, 1, 1, "Z position Error: " + str(errorp[2]**(1/2)), self.renderer.white()) # # self.renderer.end_rendering() #printing # print('wx:', self.car.wx, 'wy:', self.car.wy, 'wz:', self.car.wz) return self.controller_state
def get_output(self, packet: GameTickPacket) -> SimpleControllerState: #Setting up data... if C1DB.ticks == 0: while len(C1DB.carLoc) != len(packet.game_cars): C1DB.carLoc.append(Vec3(0, 0, 0)) C1DB.carVel.append(Vec3(0, 0, 0)) C1DB.carRot.append(Rotator(0, 0, 0)) C1DB.carAVel.append(Vec3(0, 0, 0)) C1DB.carPrevVel.append(Vec3(0, 0, 0)) #reimplement for lag compensation # else: # C1DB.deltaTime = time.perf_counter() - C1DB.pastTime # if C1DB.deltaTime < 0: # C1DB.deltaTime += 1 C1DB.pastTime = time.perf_counter() C1DB.ballLoc.covtVecFrom(packet.game_ball.physics.location) C1DB.ballVel.covtVecFrom(packet.game_ball.physics.velocity) C1DB.ballRot = packet.game_ball.physics.rotation C1DB.ballAVel.covtVecFrom(packet.game_ball.physics.angular_velocity) C1DB.index = self.index for i in range(0, len(packet.game_cars)): C1DB.carLoc[i].covtVecFrom(packet.game_cars[i].physics.location) C1DB.carVel[i].covtVecFrom(packet.game_cars[i].physics.velocity) C1DB.carRot[i] = packet.game_cars[i].physics.rotation C1DB.carAVel[i].covtVecFrom(packet.game_cars[i].physics.angular_velocity) C1DB.CBVec = C1DB.ballLoc - C1DB.carLoc[C1DB.index] #updating past values C1DB.myCarPrevLocs[C1DB.ticks%C1DB.memoryTicks] = copy.copy(C1DB.carLoc[C1DB.index]) C1DB.myCarPrevVels[C1DB.ticks%C1DB.memoryTicks] = copy.copy(C1DB.carVel[C1DB.index]) C1DB.myCarPrevRots[C1DB.ticks%C1DB.memoryTicks] = Rotator(C1DB.carRot[C1DB.index].pitch, C1DB.carRot[C1DB.index].yaw, C1DB.carRot[C1DB.index].roll) C1DB.myCarPrevAVels[C1DB.ticks%C1DB.memoryTicks] = copy.copy(C1DB.carAVel[C1DB.index]) # Setting car kinematic arrays # car_location = [Vec3(packet.game_cars[0].physics.location.x, # packet.game_cars[0].physics.location.y, # packet.game_cars[0].physics.location.z)] # car_velocity = [Vec3(packet.game_cars[0].physics.velocity.x, # packet.game_cars[0].physics.velocity.y, # packet.game_cars[0].physics.velocity.z)] # car_direction = [get_car_facing_vector(packet.game_cars[0])] # for i in range(1, packet.num_cars): # car_location.append(Vec3(packet.game_cars[i].physics.location.x, packet.game_cars[i].physics.location.y, # packet.game_cars[i].physics.location.z)) # car_velocity.append(Vec3(packet.game_cars[i].physics.velocity.x, packet.game_cars[i].physics.velocity.y, # packet.game_cars[i].physics.velocity.z)) # car_direction.append(get_car_facing_vector(packet.game_cars[i])) # C1DB.CBvec = ball_location - car_location[self.index] #State outputs if C1DB.debugOut and C1DB.ticks % 40 == 0: # int(1/C1DB.deltaTime) print("ball location: ") print(C1DB.ballLoc.x) print("ball speed: ") print(C1DB.ballVel.mag3()) print("self index: ") print(self.index) print("number of players: ") print(len(packet.game_cars)) print("car 1's pos: ") print(C1DB.carLoc[1].x) print(C1DB.carLoc[1].y) print(C1DB.carLoc[1].z) print("car 1's Vel") print(C1DB.carVel[1].x/60) print(C1DB.carVel[1].y/60) print(C1DB.carVel[1].z/60) print("car 1's Previous Vel") print(C1DB.carPrevVel[1].x/60) print(C1DB.carPrevVel[1].y/60) print(C1DB.carPrevVel[1].z/60) print() print("car 0's pos: ") print(C1DB.carLoc[0].x) print(C1DB.carLoc[0].y) print(C1DB.carLoc[0].z) print("car 0's rot: ") print(C1DB.carRot[0].pitch) print(C1DB.carRot[0].yaw) print(C1DB.carRot[0].roll) print() print("delta Time:") print(C1DB.deltaTime) print() # --- AI Start --- ball_prediction = self.get_ball_prediction_struct() if ball_prediction is not None: for i in range(ball_prediction.num_slices - 5, ball_prediction.num_slices): prediction_slice = ball_prediction.slices[i] location = prediction_slice.physics.location # if C1DB.debugOut and C1DB.ticks % int(10*1/C1DB.deltaTime) == 0: # self.logger.info("At time {}, the ball will be at ({}, {}, {})" # .format(prediction_slice.game_seconds, location.x, location.y, location.z)) #debugTracks: if C1DB.debugTrack == 0: pathFinder(self.controller_state, packet, C1DB, Target(C1DB.ballLoc, 2400, Rotator(0, -math.pi/2, 0), 0)) elif C1DB.debugTrack == 1: pathFinder(self.controller_state, packet, C1DB, Target(Vec3(2180, 3090, 17), 0, Rotator(0, -0.8, 0), 0)) if (C1DB.carLoc[C1DB.index] - Vec3(2180, 3090, 17)).mag3() < C1DB.targetSize: C1DB.debugTrack = 2 elif C1DB.debugTrack == 2: pathFinder(self.controller_state, packet, C1DB, Target(Vec3(0, 0, 17), 1400, Rotator(0, -2.356, 0), 0)) if (C1DB.carLoc[C1DB.index] - Vec3(0, 0, 17)).mag3() < C1DB.targetSize: C1DB.debugTrack = 3 elif C1DB.debugTrack == 3: pathFinder(self.controller_state, packet, C1DB, Target(Vec3(-2180, -3090, 17), 700, Rotator(0, -0.8, 0), 0)) if (C1DB.carLoc[C1DB.index] - Vec3(-2180, -3090, 17)).mag3() < C1DB.targetSize: C1DB.debugTrack = 4 elif C1DB.debugTrack == 4: pathFinder(self.controller_state, packet, C1DB, Target(Vec3(2180, -3090, 17), 1000, Rotator(0, 0.8, 0), 0)) if (C1DB.carLoc[C1DB.index] - Vec3(2180, -3090, 17)).mag3() < C1DB.targetSize: C1DB.debugTrack = 5 elif C1DB.debugTrack == 5: pathFinder(self.controller_state, packet, C1DB, Target(Vec3(0, 0, 17), 2000, Rotator(0, 2.356, 0), 0)) if (C1DB.carLoc[C1DB.index] - Vec3(0, 0, 17)).mag3() < C1DB.targetSize: C1DB.debugTrack = 6 elif C1DB.debugTrack == 6: pathFinder(self.controller_state, packet, C1DB, Target(Vec3(-2180, 3090, 17), 1400, Rotator(0, 0.8, 0), 0)) if (C1DB.carLoc[C1DB.index] - Vec3(-2180, 3090, 17)).mag3() < C1DB.targetSize: C1DB.debugTrack = 1 if C1DB.debugTrack == 7: if packet.game_cars[0].double_jumped == 1: C1DB.debugTrack = 8 else: #controller: self.controller_state.steer = 0.8 # if C1DB.ticks % 3000 < 2350: # targetVel = C1DB.ticks % 3000 # else: # targetVel = 0 targetVel = 2300 self.controller_state.throttle = 1 if C1DB.carVel[C1DB.index].mag2() > targetVel: self.controller_state.throttle = 0 self.controller_state.boost = 0 elif C1DB.carVel[C1DB.index].mag2() > 0: # 1220 self.controller_state.boost = 1 #analysis: if packet.game_cars[self.index].physics.location.z < 25: out = str(C1DB.carVel[C1DB.index].mag2()) denominator = (C1DB.carVel[self.index].x*(C1DB.myCarPrevVels[C1DB.ticks%C1DB.memoryTicks].y - C1DB.myCarPrevVels[(C1DB.ticks-1)%C1DB.memoryTicks].y)/C1DB.deltaTime - C1DB.carVel[self.index].y*(C1DB.myCarPrevVels[C1DB.ticks%C1DB.memoryTicks].x - C1DB.myCarPrevVels[(C1DB.ticks-1)%C1DB.memoryTicks].x)/C1DB.deltaTime) if(denominator != 0): out = out + " " + str((C1DB.carVel[self.index].x**2 + C1DB.carVel[self.index].y**2)**(3/2)/ denominator) else: out = out + " inf" # print("car to car: " + str((C1DB.carLoc[0] - C1DB.carLoc[1]).mag2())) out = out + " " + str(targetVel) + " " + str(C1DB.deltaTime) + "\n" print(out) debugOut = open("debug.txt", "a+") debugOut.write(out) debugOut.close() else: print("too high") elif C1DB.debugTrack == 8: if packet.game_cars[0].double_jumped == 0: C1DB.debugTrack = 9 elif C1DB.debugTrack == 9: pathFinder(self.controller_state, packet, C1DB, Target(Vec3(0, 0, 0), 0, Rotator(0, 0, 0), 1)) if (C1DB.carLoc[C1DB.index] - Vec3(0, 0, 0)).mag3() < C1DB.targetSize: C1DB.testTicks = 0 C1DB.debugTrack = 7 action_display = "temp" #draws ground path if available if C1DB.debugVisual == 1: drawPolarPath(self.renderer, C1DB) elif C1DB.debugVisual == 2: drawCirclePath(self.renderer, C1DB) # draw_debug(self.renderer, packet.game_cars[self.index], packet.game_ball, action_display) # --- Tick end data management --- # updates time C1DB.ticks += 1 if C1DB.ticks == 1000000: C1DB.ticks = 0 #update path tester if C1DB.ticks%100 == 99: C1DB.testTicks += 1 # updates data base for i in range(0, len(C1DB.carVel)): C1DB.carPrevVel[i] = copy.copy(C1DB.carVel[i]) C1DB.ballPrevVel = copy.copy(C1DB.ballVel) C1DB.prevInput = SimpleControllerState(self.controller_state.steer, self.controller_state.throttle, self.controller_state.pitch, self.controller_state.yaw, self.controller_state.roll, self.controller_state.jump, self.controller_state.boost, self.controller_state.handbrake) return self.controller_state
def spawn_car_in_showroom(loadout_config: LoadoutConfig, team: int, showcase_type: str, map_name: str, launcher_prefs: RocketLeagueLauncherPreference): match_config = MatchConfig() match_config.game_mode = 'Soccer' match_config.game_map = map_name match_config.instant_start = True match_config.existing_match_behavior = 'Continue And Spawn' match_config.networking_role = NetworkingRole.none match_config.enable_state_setting = True match_config.skip_replays = True bot_config = PlayerConfig() bot_config.bot = True bot_config.rlbot_controlled = True bot_config.team = team bot_config.name = "Showroom" bot_config.loadout_config = loadout_config match_config.player_configs = [bot_config] match_config.mutators = MutatorConfig() match_config.mutators.boost_amount = 'Unlimited' match_config.mutators.match_length = 'Unlimited' global sm if sm is None: sm = SetupManager() sm.connect_to_game(launcher_preference=launcher_prefs) sm.load_match_config(match_config) sm.start_match() game_state = GameState( cars={0: CarState(physics=Physics( location=Vector3(0, 0, 20), velocity=Vector3(0, 0, 0), angular_velocity=Vector3(0, 0, 0), rotation=Rotator(0, 0, 0) ))}, ball=BallState(physics=Physics( location=Vector3(0, 0, -100), velocity=Vector3(0, 0, 0), angular_velocity=Vector3(0, 0, 0) )) ) player_input = PlayerInput() team_sign = -1 if team == 0 else 1 if showcase_type == "boost": player_input.boost = True player_input.steer = 1 game_state.cars[0].physics.location.y = -1140 game_state.cars[0].physics.velocity.x = 2300 game_state.cars[0].physics.angular_velocity.z = 3.5 elif showcase_type == "throttle": player_input.throttle = 1 player_input.steer = 0.56 game_state.cars[0].physics.location.y = -1140 game_state.cars[0].physics.velocity.x = 1410 game_state.cars[0].physics.angular_velocity.z = 1.5 elif showcase_type == "back-center-kickoff": game_state.cars[0].physics.location.y = 4608 * team_sign game_state.cars[0].physics.rotation.yaw = -0.5 * pi * team_sign elif showcase_type == "goal-explosion": game_state.cars[0].physics.location.y = -2000 * team_sign game_state.cars[0].physics.rotation.yaw = -0.5 * pi * team_sign game_state.cars[0].physics.velocity.y = -2300 * team_sign game_state.ball.physics.location = Vector3(0, -3500 * team_sign, 93) sm.game_interface.update_player_input(player_input, 0) sm.game_interface.set_game_state(game_state)
def r(r_: Rotator) -> Rotator: return Rotator(r_.pitch, r_.yaw, r_.roll)
def get_output(self, packet: GameTickPacket) -> SimpleControllerState: self.game.read_game_information(packet, self.get_rigid_body_tick(), self.get_field_info()) self.controls = SimpleControllerState() next_state = self.state if self.state == State.RESET: self.timer = 0.0 # put the car in the middle of the field car_state = CarState(physics=Physics( location=Vector3(-2000, 0, 18), velocity=Vector3(0, 0, 0), rotation=Rotator(0, 0, 0), angular_velocity=Vector3(0, 0, 0)), jumped=False, double_jumped=False) # put the ball somewhere out of the way ball_state = BallState( physics=Physics(location=Vector3(0, 5000, 0), velocity=Vector3(0, 0, 0), rotation=Rotator(0, 0, 0), angular_velocity=Vector3(0, 0, 0))) self.set_game_state( GameState(ball=ball_state, cars={self.game.id: car_state})) next_state = State.WAIT if self.state == State.WAIT: if self.timer > 0.2: next_state = State.INITIALIZE if self.state == State.INITIALIZE: self.dodge = Dodge(self.game.my_car) self.turn = AerialTurn(self.game.my_car) f = self.game.my_car.forward() l = self.game.my_car.left() u = self.game.my_car.up() # musty flick if self.counter % 3 == 0: self.name = "Musty Flick" self.dodge.duration = 0.2 self.dodge.delay = 0.8 self.dodge.direction = vec2(f) self.dodge.preorientation = look_at(-0.1 * f - u, -1.0 * u) # diagonal forward dodge if self.counter % 3 == 1: self.name = "Fast Forward Dodge" self.dodge.duration = 0.15 self.dodge.delay = 0.4 self.dodge.direction = vec2(1.0, 0.0) self.dodge.preorientation = dot( axis_to_rotation(vec3(0, 0, 3)), self.game.my_car.rotation) # diagonal twist if self.counter % 3 == 2: self.name = "Air-Roll Dodge hit" self.dodge.duration = 0.15 self.dodge.delay = 0.5 self.dodge.direction = vec2(f - 0.3 * l) self.dodge.preorientation = dot( self.game.my_car.rotation, axis_to_rotation(vec3(-0.8, -0.4, 0))) self.counter += 1 next_state = State.RUNNING if self.state == State.RUNNING: if self.timer > 1.2: self.turn.target = look_at(xy(self.game.my_car.velocity), vec3(0, 0, 1)) self.turn.step(self.game.time_delta) self.controls = self.turn.controls else: self.dodge.step(self.game.time_delta) self.controls = self.dodge.controls if self.timer > self.timeout: next_state = State.RESET self.game.my_car.last_input.roll = self.controls.roll self.game.my_car.last_input.pitch = self.controls.pitch self.game.my_car.last_input.yaw = self.controls.yaw self.timer += self.game.time_delta self.state = next_state if self.name: self.renderer.begin_rendering() self.renderer.draw_string_2d(50, 50, 6, 6, self.name, self.renderer.red()) self.renderer.end_rendering() return self.controls
def space_x(self): if self.current_state == 'Reset': self.controller.jump = 0 self.controller.pitch = 0 self.controller.boost = 0 car_state = CarState(physics=Physics(velocity=V3(0, 0, 0), rotation=Rotator((math.pi/2) + 0.5, 0, 0), angular_velocity=V3(0, 0, 0), location=V3(0, 0, 100))) game_state = GameState(cars={self.index: car_state}) self.set_game_state(game_state) self.tR = time.time() #self.next_state = 'Boost' elif self.current_state == 'Timeout': if time.time() > self.tR+self.timeoutR: self.next_state = 'Jump' elif self.current_state == 'Jump': self.sas(math.pi/2) # TODO make math.pi/2 a var? self.controller.jump = 1 if self.me.rotation.x > (math.pi/2 - 0.05): self.next_state = 'Boost' elif self.current_state == 'Boost': self.sas(math.pi/2) self.controller.boost = 1 if self.me.pos.z > 800: self.launch_time = time.time() self.next_state = 'Falling' elif self.current_state == 'Falling': self.sas(math.pi/2) self.controller.boost = 0 self.time_burn = burn_time(self.me, self.land_height) if self.time_burn < 0: self.next_state = 'Suicide_burn' elif self.current_state == 'Suicide_burn': self.sas(math.pi/2) self.controller.boost = 1 if self.me.pos.z < 48+self.land_height: self.next_state = 'Land' elif self.current_state == 'Land': self.sas(math.pi/2) self.controller.boost = 0 elif self.current_state == 'Idle': self.controller.jump = 0 self.controller.pitch = 0 self.controller.boost = 0 self.next_state = 'Idle' self.current_state = self.next_state
def car_stop(self): self._changed = True self.car.physics.angular_velocity = Vector3(0, 0, 0) self.car.physics.velocity = Vector3(0, 0, 0) self.car.physics.rotation = Rotator(0, None, 0)
def drift_test(self): """Runs the drift tests.""" self.tests = 500 # Number of tests. yaw = np.pi / self.tests # Change in yaw. test_vel = 1400 # Starting velocity. if self.active: # Sets ball position out of bounds so it doesn't interfere. pos = Vector3(0, 0, 2200) ball_state = BallState(physics=Physics(location=pos)) # If the number of completed tests is less or equal to the number of tests, run tests. if self.count <= self.tests: # Save the previous test and restart timer. if self.timer > 5.0: # Converting data to numpy array. data = np.array( [self.position, self.velocity, self.rotation]) # Saving data to file. I used absolute location because I was lazy. np.save( f'D:/RLBot/ViliamVadocz/TestBot/data/test_{self.count:03}.npy', data) self.timer = 0.0 self.count += 1 # Setup next test. if self.timer == 0.0: # Sets the car's physics for the next test. pos = Vector3(2500, -2300, 17.01) vel = Vector3(0, test_vel, 0) rot = Rotator(None, np.pi / 2 + yaw * self.count, 0) ang_vel = Vector3(0, 0, 0) car_state = { self.index: CarState(physics=Physics(location=pos, velocity=vel, rotation=rot, angular_velocity=ang_vel)) } # Initialises data lists. (Not using numpy arrays here because I'd have to guess the approximate size) self.position = [] self.velocity = [] self.rotation = [] # Starts collecting data. (comparing to 0.1 here instead of just using else, juse to make sure that the test has restarted.) elif self.timer > 0.05: car_state = {self.index: CarState()} self.position.append(self.agent.pos) self.velocity.append(self.agent.vel) self.rotation.append(self.agent.rot) else: # End of testing. self.ctrl.throttle = False self.ctrl.handbrake = False car_state = {self.index: CarState()} # Increments timer. self.timer += self.dt # Sets game state. game_state = GameState(ball=ball_state, cars=car_state) # I set it multiple times because apparently if you just do it once # it sometimes doesn't work and it doesn't hurt to set it more than once. self.set_game_state(game_state) self.set_game_state(game_state) self.set_game_state(game_state) self.set_game_state(game_state) self.set_game_state(game_state)
def empty(): return SimPhysics(Vec3(0, 0, 0), Vec3(0, 0, 0), Vec3(0, 0, 0), Rotator(0, 0, 0))
def get_output(self, packet: GameTickPacket) -> SimpleControllerState: self.game.read_game_information(packet, self.get_rigid_body_tick(), self.get_field_info()) self.controls = SimpleControllerState() next_state = self.state if self.state == State.RESET: self.timer = 0.0 b_position = Vector3(random.uniform(-1500, 1500), random.uniform( 2500, 3500), random.uniform( 300, 500)) b_velocity = Vector3(random.uniform(-300, 300), random.uniform(-100, 100), random.uniform(1000, 1500)) ball_state = BallState(physics=Physics( location=b_position, velocity=b_velocity, rotation=Rotator(0, 0, 0), angular_velocity=Vector3(0, 0, 0) )) # this just initializes the car and ball # to different starting points each time c_position = Vector3(b_position.x, 0 * random.uniform(-1500, -1000), 25) #c_position = Vector3(200, -1000, 25) car_state = CarState(physics=Physics( location=c_position, velocity=Vector3(0, 800, 0), rotation=Rotator(0, 1.6, 0), angular_velocity=Vector3(0, 0, 0) ), boost_amount=100) self.set_game_state(GameState( ball=ball_state, cars={self.game.id: car_state}) ) next_state = State.WAIT if self.state == State.WAIT: if self.timer > 0.2: next_state = State.INITIALIZE if self.state == State.INITIALIZE: self.aerial = Aerial(self.game.my_car) # self.aerial.up = normalize(vec3( # random.uniform(-1, 1), # random.uniform(-1, 1), # random.uniform(-1, 1))) self.turn = AerialTurn(self.game.my_car) # predict where the ball will be prediction = Ball(self.game.ball) self.ball_predictions = [vec3(prediction.location)] for i in range(100): prediction.step(0.016666) prediction.step(0.016666) self.ball_predictions.append(vec3(prediction.location)) # if the ball is in the air if prediction.location[2] > 500: self.aerial.target = prediction.location self.aerial.arrival_time = prediction.time simulation = self.aerial.simulate() # # check if we can reach it by an aerial if norm(simulation.location - self.aerial.target) < 100: prediction.step(0.016666) prediction.step(0.016666) self.aerial.target = prediction.location self.aerial.arrival_time = prediction.time self.target_ball = Ball(prediction) break next_state = State.RUNNING if self.state == State.RUNNING: self.log.write(f"{{\"car\":{self.game.my_car.to_json()}," f"\"ball\":{self.game.ball.to_json()}}}\n") self.aerial.step(self.game.time_delta) self.controls = self.aerial.controls if self.timer > self.timeout: next_state = State.RESET self.aerial = None self.turn = None self.timer += self.game.time_delta self.state = next_state self.renderer.begin_rendering() red = self.renderer.create_color(255, 230, 30, 30) purple = self.renderer.create_color(255, 230, 30, 230) white = self.renderer.create_color(255, 230, 230, 230) if self.aerial: r = 200 x = vec3(r, 0, 0) y = vec3(0, r, 0) z = vec3(0, 0, r) target = self.aerial.target self.renderer.draw_line_3d(target - x, target + x, purple) self.renderer.draw_line_3d(target - y, target + y, purple) self.renderer.draw_line_3d(target - z, target + z, purple) if self.ball_predictions: self.renderer.draw_polyline_3d(self.ball_predictions, purple) self.renderer.end_rendering() return self.controls
def rotation_to_euler(theta: mat3) -> Rotator: return Rotator(atan2(theta[2, 0], norm(vec2(theta[0, 0], theta[1, 0]))), atan2(theta[1, 0], theta[0, 0]), atan2(-theta[2, 1], theta[2, 2]))
from typing import Dict, Any, Optional, List, Union from rlbot.matchconfig.match_config import PlayerConfig, Team from rlbot.utils.game_state_util import GameState, Physics, BallState, Vector3, Rotator, CarState, BoostState from rlbottraining.common_exercises.common_base_exercises import StrikerExercise, GoalieExercise from rlbottraining.common_graders.compound_grader import CompoundGrader from rlbottraining.common_graders.goal_grader import ( PassOnGoalForAllyTeam, StrikerGrader, PassOnBallGoingAwayFromGoal, GoalieGrader) from rlbottraining.match_configs import make_empty_match_config from rlbottraining.rng import SeededRandomNumberGenerator from rlbot_gui.rlbottrainingpack.math_parser import parse_item V0 = Vector3(0, 0, 0) R0 = Rotator(0, pi / 2, 0) def as_cls(cls, arg): if not isinstance(arg, cls): return cls(*arg) return arg class JSONExercise: boosts: list description: str def __init__(self): self.name = self.description + token_hex(5) self.match_config = None
def rot_mat_to_rot(theta: mat3) -> Rotator: pitch = atan2(theta[(2, 0)], norm(rlu_vec2(theta[(0, 0)], theta[(1, 0)]))) yaw = atan2(theta[(1, 0)], theta[(0, 0)]) roll = atan2(-theta[(2, 1)], theta[(2, 2)]) return Rotator(pitch, yaw, roll)
def to_rotator(self) -> Rotator: return Rotator(self.pitch, self.yaw, self.roll)
def get_output(self, packet: GameTickPacket) -> SimpleControllerState: self.renderer.begin_rendering() self.game.read_game_information(packet, self.get_rigid_body_tick(), self.get_field_info()) if self.lastReset + 300 < self.currentTick: if self.tests > 0: score = min(300, self.currentTick - self.lastDoneTick) self.totalScore += score print(self.tests, score, round(self.totalScore / self.tests, 2)) self.tests += 1 self.lastReset = self.currentTick self.target = vec3(2 * random() - 1, 2 * random() - 1, 2 * random() - 1) self.up = orthogonalize( vec3(2 * random() - 1, 2 * random() - 1, 2 * random() - 1), self.target) self.targetOrientation = look_at(self.target, self.up) car_state = CarState( physics=Physics(location=Vector3(0, 1000, 17), velocity=Vector3(0, 0, 0), rotation=Rotator(0, 0, 0), angular_velocity=Vector3(0, 0, 0))) self.set_game_state(GameState(cars={self.index: car_state})) self.stage = 0 self.lastDodgeTick = -math.inf # print("TELEPORT TO GROUND") return self.controls else: car_state = CarState(physics=Physics(location=Vector3(0, 0, 400), velocity=Vector3(0, 0, 0))) self.set_game_state(GameState(cars={self.index: car_state})) if self.stage <= 5: self.stage += 1 if self.stage == 6: self.dodgeDirection = normalize(vec2(0, 2 * random() - 1)) self.controls.jump = True #random() > 0.5 if self.controls.jump: self.lastDodgeTick = self.currentTick self.controls.roll, self.controls.pitch, self.controls.yaw = self.dodgeDirection[ 0], self.dodgeDirection[1], 0 self.stage += 1 return self.controls else: self.controls.jump = False self.packet = packet self.handleTime() car = packet.game_cars[self.index] position = vec3(car.physics.location.x, car.physics.location.y, car.physics.location.z) self.renderer.draw_line_3d(car.physics.location, position + 300 * normalize(self.target), self.renderer.yellow()) self.renderer.draw_line_3d(car.physics.location, position + 300 * normalize(self.up), self.renderer.pink()) carOrientation = rotationToOrientation(car.physics.rotation) ang = parseVector(car.physics.angular_velocity) if angle_between(carOrientation, self.targetOrientation) > 1 / 180 * math.pi: self.lastDoneTick = self.currentTick o_rlu = dot(transpose(self.targetOrientation), carOrientation) w_rlu = dot(transpose(self.targetOrientation), ang) o = torch.tensor([[o_rlu[i, j] for j in range(3)] for i in range(3)])[None, :].float().to(device) w = torch.tensor([w_rlu[i] for i in range(3)])[None, :].float().to(device) noPitchTime = max(0, (self.lastDodgeTick - self.currentTick) / 120 + .95) dodgeTime = max(0, (self.lastDodgeTick - self.currentTick) / 120 + .65) if dodgeTime == 0: self.dodgeDirection = vec2(0, 0) noPitchTime = torch.tensor([noPitchTime]).float().to(device) dodgeTime = torch.tensor([dodgeTime]).float().to(device) dodgeDirection = torch.tensor([ self.dodgeDirection[i] for i in range(2) ])[None, :].float().to(device) # if self.simulation.o is not None and self.simulation.w is not None: # print("=====================================") # print("-------------------------------------") # print(self.simulation.o, o) # print(self.simulation.w, w) # print(self.simulation.noPitchTime, noPitchTime) # print(self.simulation.dodgeTime, dodgeTime) # print(self.simulation.dodgeDirection, dodgeDirection) # self.simulation.step(self.ticksNowPassed / 120) # print(self.simulation.o, o) # print(self.simulation.w, w) # print(self.simulation.noPitchTime, noPitchTime) # print(self.simulation.dodgeTime, dodgeTime) # print(self.simulation.dodgeDirection, dodgeDirection) self.simulation.o = o self.simulation.w = w self.simulation.noPitchTime = noPitchTime self.simulation.dodgeTime = dodgeTime self.simulation.dodgeDirection = dodgeDirection if True: rpy = self.policy(self.simulation.o.permute(0, 2, 1), self.simulation.w_local(), self.simulation.noPitchTime, self.simulation.dodgeTime, self.simulation.dodgeDirection)[0] self.controls.roll, self.controls.pitch, self.controls.yaw = rpy else: self.reorientML.target_orientation = self.targetOrientation self.reorientML.step(1 / self.FPS) self.controls.roll, self.controls.pitch, self.controls.yaw = self.reorientML.controls.roll, self.reorientML.controls.pitch, self.reorientML.controls.yaw if self.simulation.error()[0].item() < 0.01: self.frames_done += 1 else: self.frames_done = 0 if self.frames_done >= 10: self.finished = True self.renderer.end_rendering() return self.controls
def setup_std_kickoff(self, packet): car_states = {} rand1 = np.random.random() for p in range(packet.num_cars): car = packet.game_cars[p] if car.team == 0: if rand1 < 1 / 5: pos = Vector3(-2048, -2560, 17) yaw = np.pi * 0.25 elif rand1 < 2 / 5: pos = Vector3(2048, -2560, 17) yaw = np.pi * 0.75 elif rand1 < 3 / 5: pos = Vector3(-256.0, -3840, 17) yaw = np.pi * 0.5 elif rand1 < 4 / 5: pos = Vector3(256.0, -3840, 17) yaw = np.pi * 0.5 elif rand1 < 5 / 5: pos = Vector3(0.0, -4608, 17) yaw = np.pi * 0.5 car_state = CarState(boost_amount=33.3, physics=Physics(location=pos, rotation=Rotator(yaw=yaw, pitch=0, roll=0), velocity=Vector3(0, 0, 0), angular_velocity=Vector3( 0, 0, 0))) car_states[p] = car_state elif car.team == 1: if rand1 < 1 / 5: pos = Vector3(2048, 2560, 17) yaw = np.pi * -0.75 elif rand1 < 2 / 5: pos = Vector3(-2048, 2560, 17) yaw = np.pi * -0.25 elif rand1 < 3 / 5: pos = Vector3(256.0, 3840, 17) yaw = np.pi * -0.5 elif rand1 < 4 / 5: pos = Vector3(-256.0, 3840, 17) yaw = np.pi * -0.5 elif rand1 < 5 / 5: pos = Vector3(0.0, 4608, 17) yaw = np.pi * -0.5 car_state = CarState(boost_amount=33.3, physics=Physics(location=pos, rotation=Rotator(yaw=yaw, pitch=0, roll=0), velocity=Vector3(0, 0, 0), angular_velocity=Vector3( 0, 0, 0))) car_states[p] = car_state if self.horz_ball_var == 'Off': ball_vel_x = ball_vel_y = 0 elif self.horz_ball_var == 'On': ball_vel_x = (np.random.random() * 2 - 1) * 500 ball_vel_y = (np.random.random() * 2 - 1) * 300 if self.vert_ball_var == 'Off': ball_vel_z = -1 ball_pos_z = 93 elif self.vert_ball_var == 'On': ball_vel_z = np.random.random() * 360 - 460 ball_pos_z = np.random.random() * 200 + 500 self.paused_car_states = car_states ball_state = BallState( Physics(location=Vector3(0, 0, ball_pos_z), velocity=Vector3(ball_vel_x, ball_vel_y, ball_vel_z))) self.game_state = GameState(ball=ball_state, cars=car_states) self.set_game_state(self.game_state) self.prev_time = self.cur_time self.game_phase = -1
from rlbot.utils.game_state_util import GameState, BallState, CarState, Physics, Vector3, Rotator BALL = BallState(physics=Physics(location=Vector3(0, 0, 93), velocity=Vector3(0, 0, 0), rotation=Rotator(0, 0, 0), angular_velocity=Vector3(0, 0, 0))) CARS = { 0: CarState(physics=Physics(location=Vector3(-2000, -3000, 500), velocity=Vector3(100, 100, 2300), rotation=Rotator(0, 0, 0), angular_velocity=Vector3(0, 0, 0))) } GAME_STATE = GameState(ball=BALL, cars=CARS)
def get_output(self, packet: GameTickPacket) -> SimpleControllerState: # 100 frames per individual, 10 individuals per generation, 100 generations, or reset before a goal happens if self.frame == (100 + self.generation * 2) or self.frame == 0 or ( -893 <= packet.game_ball.physics.location.x <= 893 and packet.game_ball.physics.location.y > 5115): if self.frame != 0: self.fitness_queue.put(self.percent_progress) self.frame = 0 self.individual += 1 self.percent_progress = 0.0 # set a random game state so the bot doesn't start memorizing saves car_state = CarState( jumped=False, double_jumped=False, boost_amount=100, physics=Physics(velocity=Vector3(x=0, y=0, z=0), rotation=Rotator( 0, math.pi * -1.5 + random.uniform(-0.5, 0.5), 0), angular_velocity=Vector3(0, 0, 0), location=Vector3(x=random.uniform(-1000, 1000), y=random.uniform(2000, 4000), z=0))) ball_state = BallState( Physics(location=Vector3(x=random.uniform(-800, 800), y=random.uniform(-1000, 1000), z=0), rotation=Rotator(0, 0, 0), velocity=Vector3(x=0, y=random.uniform(1000, 1500), z=random.uniform(0, 500)))) game_state = GameState( ball=ball_state, cars={self.index: car_state}, ) self.set_game_state(game_state) if self.individual == self.max_individuals: self.individual = 0 self.generation += 1 # wait for NEAT to have the next network ready self.network = self.net_queue.get() # run all code below on every frame self.frame += 1 ball = packet.game_ball bot = packet.game_cars[self.index] # if first frame, record the original ball distance, otherwise try to get best distance to ball distance = math.sqrt( (bot.physics.location.x - ball.physics.location.x)**2 + (bot.physics.location.y - ball.physics.location.y)**2 + (bot.physics.location.z - ball.physics.location.z)**2) if self.frame == 10: self.initial_distance = distance if self.frame >= 10: self.percent_progress = max(self.percent_progress, (self.initial_distance - distance) / self.initial_distance) # feature input vector that is used to train our neural network input = [] input.append(bot.physics.location.x) input.append(bot.physics.location.y) input.append(bot.physics.location.z) #input.append(bot.physics.rotation.pitch) input.append(bot.physics.rotation.yaw) #input.append(bot.physics.rotation.roll) input.append(bot.physics.velocity.x) input.append(bot.physics.velocity.y) input.append(bot.physics.velocity.z) input.append(bot.physics.angular_velocity.x) input.append(bot.physics.angular_velocity.y) #input.append(bot.physics.angular_velocity.z) input.append(bot.boost) input.append(bot.jumped) input.append(bot.double_jumped) input.append(bot.has_wheel_contact) input.append(ball.physics.location.x) input.append(ball.physics.location.y) input.append(ball.physics.location.z) #input.append(ball.physics.rotation.pitch) #input.append(ball.physics.rotation.yaw) #input.append(ball.physics.rotation.roll) input.append(ball.physics.velocity.x) input.append(ball.physics.velocity.y) input.append(ball.physics.velocity.z) #input.append(ball.physics.angular_velocity.x) #input.append(ball.physics.angular_velocity.y) #input.append(ball.physics.angular_velocity.z) # use self.network (from NEAT) with input to derive a usable output def sigmoid(x): if x >= 0: z = math.e**-x return 1. / (1. + z) else: z = math.e**x return z / (1. + z) def activate(x): return sigmoid(x / 3000) * 2 - 1 output = self.network.activate(input) self.controller_state.throttle = activate(output[0]) self.controller_state.steer = activate(output[1]) self.controller_state.boost = True if activate( output[2]) > 0.75 else False #self.controller_state.pitch = activate(output[2]) #self.controller_state.yaw = activate(output[3]) #self.controller_state.roll = activate(output[4]) #self.controller_state.jump = True if activate(output[5]) > 0.75 else False #self.controller_state.handbrake = True if activate(output[7]) > 0.75 else False if self.frame >= 10: self.renderer.begin_rendering() self.renderer.draw_string_2d( 20, 20, 2, 2, "Generation: " + str(self.generation) + " [Bot: " + str(self.individual) + "/" + str(self.max_individuals - 1) + " | " + str(self.frame) + " frames]", self.renderer.white()) self.renderer.draw_string_2d( 20, 50, 2, 2, "Best percent progress: " + str(round(self.percent_progress * 100)) + "%", self.renderer.white()) self.renderer.draw_string_2d( 20, 80, 2, 2, "Current percent progress: " + str( round((self.initial_distance - distance) / self.initial_distance * 100)) + "%", self.renderer.white()) self.renderer.draw_string_2d( 20, 110, 2, 2, "Steer: " + str(self.controller_state.steer), self.renderer.white()) self.renderer.draw_string_2d( 20, 140, 2, 2, "Throttle: " + str(self.controller_state.throttle), self.renderer.white()) self.renderer.draw_string_2d( 20, 170, 2, 2, "Boost: " + str(self.controller_state.boost), self.renderer.white()) #self.renderer.draw_string_2d(20,170, 2, 2, "Pitch: " + str(self.controller_state.pitch), self.renderer.white()) #self.renderer.draw_string_2d(20,200, 2, 2, "Yaw: " + str(self.controller_state.yaw), self.renderer.white()) #self.renderer.draw_string_2d(20,230, 2, 2, "Roll: " + str(self.controller_state.roll), self.renderer.white()) #self.renderer.draw_string_2d(20,260, 2, 2, "Powerslide: " + str(self.controller_state.handbrake), self.renderer.white()) #self.renderer.draw_string_2d(20,290, 2, 2, "Jump: " + str(self.controller_state.jump), self.renderer.white()) self.renderer.end_rendering() #print(self.controller_state.__dict__) return self.controller_state
def hel_jump(self): if self.current_state == 'Jump': self.controller.throttle = 0 self.controller.jump = 1 self.next_state = 'Tilt' elif self.current_state == 'Tilt': self.controller.jump = 0 self.controller.handbrake = 1 self.controller.pitch = -0.3 #self.controller.boost = 1 if self.me.rotation.x < -math.pi/6: self.next_state = 'WaitJump2' elif self.current_state == 'WaitJump2': self.controller.pitch = 0 self.controller.boost = 1 if self.me.rotation.x > -0.35: self.next_state = 'Jump2' elif self.current_state == 'Jump2': self.controller.jump = 1 self.second_jump_time = time.time() self.next_state = 'Boost' elif self.current_state == 'Boost': self.controller.boost = 1 if self.me.pos.z > 500: self.controller.boost = 0 if self.me.rotation.x < (math.pi/2 - 0.5): self.controller.pitch = 0.2 else: self.controller.pitch = 0 if time.time() > self.second_jump_time+self.second_timeout: self.next_state = 'SecondJump' elif self.current_state == 'SecondJump': self.controller.boost = 0 self.controller.jump = 1 self.controller.pitch = 1 self.next_state = 'Idle' elif self.current_state == 'Reset': self.controller.jump = 0 self.controller.handbrake = 0 self.controller.pitch = 0 self.controller.boost = 0 car_state = CarState(physics=Physics(velocity=Vector3(0, 0, 0), rotation=Rotator(0, 0, 0), angular_velocity=Vector3(0, 0, 0), location=Vector3(0, 0, 16.6))) game_state = GameState(cars={self.index: car_state}) self.set_game_state(game_state) self.tR = time.time() self.next_state = 'Timeout' elif self.current_state == 'Timeout': if time.time() > self.tR+self.timeoutR: self.next_state = 'Jump' elif self.current_state == 'Idle': self.controller.jump = 0 self.controller.handbrake = 0 self.controller.pitch = 0 self.controller.boost = 0 self.next_state = 'Idle' self.current_state = self.next_state