Accept multiple asteroids and shot-time input

This commit is contained in:
Leonora Tindall 2023-04-03 22:47:45 -05:00
parent 36da3483ae
commit e63fbf74ba
1 changed files with 100 additions and 92 deletions

View File

@ -7,6 +7,10 @@ use crate::{
nn::{ActivationFunc, NN}, nn::{ActivationFunc, NN},
HEIGHT, WIDTH, HEIGHT, WIDTH,
}; };
const NUM_KEYS: usize = 4;
const INPUTS_PER_ASTEROID: usize = 4;
const NUM_ASTEROIDS: usize = 1;
const INPUTS_FOR_SHIP: usize = 2;
#[derive(Default)] #[derive(Default)]
pub struct Player { pub struct Player {
pub pos: Vec2, pub pos: Vec2,
@ -16,11 +20,9 @@ pub struct Player {
rot: f32, rot: f32,
drag: f32, drag: f32,
bullets: Vec<Bullet>, bullets: Vec<Bullet>,
asteroid: Option<Asteroid>, asteroids: Vec<Option<Asteroid>>,
inputs: Vec<f32>, inputs: Vec<f32>,
pub outputs: Vec<f32>, pub outputs: Vec<f32>,
// asteroid_data: Vec<(f32, f32, f32)>,
raycasts: Vec<f32>,
last_shot: u32, last_shot: u32,
shot_interval: u32, shot_interval: u32,
pub brain: Option<NN>, pub brain: Option<NN>,
@ -40,9 +42,15 @@ impl Player {
Some(mut c) => { Some(mut c) => {
c.retain(|&x| x != 0); c.retain(|&x| x != 0);
// Number of inputs // Number of inputs
c.insert(0, 5); c.insert(
0,
(INPUTS_PER_ASTEROID * NUM_ASTEROIDS)
+ INPUTS_FOR_SHIP
);
// Number of outputs // Number of outputs
c.push(4); c.push(
NUM_KEYS
);
Some(NN::new(c, mut_rate.unwrap(), activ.unwrap())) Some(NN::new(c, mut_rate.unwrap(), activ.unwrap()))
} }
_ => None, _ => None,
@ -55,51 +63,17 @@ impl Player {
shot_interval: 18, shot_interval: 18,
alive: true, alive: true,
shots: 4, shots: 4,
outputs: vec![0.; 4], // 4 outputs
raycasts: vec![0.; 8], outputs: vec![0.; NUM_KEYS],
..Default::default() ..Default::default()
} }
} }
pub fn check_player_collision(&mut self, asteroid: &Asteroid) -> bool { pub fn check_player_collision(&mut self, asteroid: &Asteroid) -> bool {
// To give more near asteroids data: // Save the asteroid to our asteroids
self.asteroids.push(Some(asteroid.clone()));
// self.asteroid_data.push((
// ((asteroid.pos - self.pos).length() - asteroid.radius) / WIDTH,
// self.dir.angle_between(asteroid.pos - self.pos),
// (asteroid.vel - self.vel).length(),
// ));
// Single asteroid data:
if self.asteroid.is_none()
|| (asteroid.pos).distance_squared(self.pos)
< self
.asteroid
.as_ref()
.unwrap()
.pos
.distance_squared(self.pos)
{
self.asteroid = Some(asteroid.clone());
}
// Try raycasting below:
// let v = asteroid.pos - self.pos;
// for i in 0..4 {
// let dir = Vec2::from_angle(PI / 4. * i as f32).rotate(self.dir);
// let cross = v.perp_dot(dir);
// let dot = v.dot(dir);
// if cross.abs() <= asteroid.radius {
// self.raycasts[if dot >= 0. { i } else { i + 4 }] = *partial_max(
// &self.raycasts[if dot >= 0. { i } else { i + 4 }],
// &(100.
// / (dot.abs() - (asteroid.radius * asteroid.radius - cross * cross).sqrt())),
// )
// .unwrap();
// }
// }
if asteroid.check_collision(self.pos, 8.) || self.lifespan > 3600 && self.brain.is_some() { if asteroid.check_collision(self.pos, 8.) || self.lifespan > 3600 && self.brain.is_some() {
self.alive = false; self.alive = false;
return true; return true;
@ -107,12 +81,28 @@ impl Player {
false false
} }
pub fn consider_asteroids(pos: Vec2, asteroids: &mut Vec<Option<Asteroid>>) {
// Consider the closest asteroids first
asteroids.sort_by_key(|ast| match ast {
None => i32::MAX,
Some(ast) => (dist_wrapping(ast.pos, pos, ast.radius) * 100.) as i32,
});
// Cull if there are too may asteroids
*asteroids = asteroids.iter().cloned().take(NUM_ASTEROIDS).collect();
// Insert if there are not enought asteroids
if asteroids.len() < NUM_ASTEROIDS {
for _ in 0..NUM_ASTEROIDS - asteroids.len() {
asteroids.push(None);
}
}
assert_eq!(asteroids.len(), NUM_ASTEROIDS);
}
pub fn check_bullet_collisions(&mut self, asteroid: &mut Asteroid) -> bool { pub fn check_bullet_collisions(&mut self, asteroid: &mut Asteroid) -> bool {
for bullet in &mut self.bullets { for bullet in &mut self.bullets {
if asteroid.check_collision(bullet.pos, 0.) { if asteroid.check_collision(bullet.pos, 0.) {
asteroid.alive = false; asteroid.alive = false;
bullet.alive = false; bullet.alive = false;
self.asteroid = None;
return true; return true;
} }
} }
@ -125,46 +115,47 @@ impl Player {
self.acc = 0.; self.acc = 0.;
self.outputs = vec![0.; 4]; self.outputs = vec![0.; 4];
let mut keys = vec![false; 4]; let mut keys = vec![false; 4];
if let Some(ast) = self.asteroid.as_ref() { self.inputs = vec![];
self.inputs = vec![ // Insert all the asteroid data
(ast.pos - self.pos).length() / HEIGHT, Self::consider_asteroids(self.pos, &mut self.asteroids);
self.dir.angle_between(ast.pos - self.pos), for ast in &self.asteroids {
(ast.vel - self.vel).x * 0.6, if let Some(ast) = ast {
(ast.vel - self.vel).y * 0.6, self.inputs.extend_from_slice(&[
self.rot / TAU as f32, // Distance to asteroid
// self.vel.x / 8., dist_wrapping(ast.pos, self.pos, ast.radius),
// self.vel.y / 8., // Angle to asteroid
// self.rot / TAU as f32, self.dir.angle_between(ast.pos - self.pos),
]; // Asteroid velocity x
// self.inputs.append(self.raycasts.as_mut()); (ast.vel - self.vel).x * 0.6,
// Asteroid velocity y
// self.asteroid_data (ast.vel - self.vel).y * 0.6,
// .sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap()); ]);
// self.asteroid_data.resize(1, (0., 0., 0.)); } else {
// inputs.append( self.inputs.extend_from_slice(&[0., 0., 0., 0.]);
// &mut self
// .asteroid_data
// .iter()
// .map(|(d, a, h)| vec![*d, *a, *h])
// .flatten()
// .collect::<Vec<_>>(),
// );
if let Some(brain) = &self.brain {
self.outputs = brain.feed_forward(&self.inputs);
keys = self
.outputs
.iter()
.map(|&x| {
x > if brain.activ_func == ActivationFunc::Sigmoid {
0.85
} else {
0.
}
})
.collect();
} }
} }
assert_eq!(self.inputs.len(), NUM_ASTEROIDS * INPUTS_PER_ASTEROID);
// Insert the ship data
self.inputs.push(self.rot / TAU as f32);
self.inputs.push(
(self.shot_interval as f32 - self.last_shot as f32).max(0.) / self.shot_interval as f32,
);
// Run the brain
if let Some(brain) = &self.brain {
assert_eq!(self.inputs.len(), brain.config[0] - 1);
self.outputs = brain.feed_forward(&self.inputs);
keys = self
.outputs
.iter()
.map(|&x| {
x > if brain.activ_func == ActivationFunc::Sigmoid {
0.85
} else {
0.
}
})
.collect();
}
if keys[0] || self.brain.is_none() && is_key_down(KeyCode::Right) { if keys[0] || self.brain.is_none() && is_key_down(KeyCode::Right) {
// RIGHT // RIGHT
self.rot = (self.rot + 0.1 + TAU as f32) % TAU as f32; self.rot = (self.rot + 0.1 + TAU as f32) % TAU as f32;
@ -205,9 +196,7 @@ impl Player {
} }
self.bullets self.bullets
.retain(|b| b.alive && b.pos.x.abs() * 2. < WIDTH && b.pos.y.abs() * 2. < HEIGHT); .retain(|b| b.alive && b.pos.x.abs() * 2. < WIDTH && b.pos.y.abs() * 2. < HEIGHT);
self.asteroid = None; self.asteroids = vec![];
// self.asteroid_data.clear();
// self.raycasts = vec![0.; 8];
} }
pub fn draw(&self, color: Color, debug: bool) { pub fn draw(&self, color: Color, debug: bool) {
@ -226,13 +215,17 @@ impl Player {
draw_triangle_lines(p6, p7, p8, 2., color); draw_triangle_lines(p6, p7, p8, 2., color);
} }
if debug { if debug {
if let Some(ast) = self.asteroid.as_ref() { let mut debug_asteroids = self.asteroids.clone();
draw_circle_lines(ast.pos.x, ast.pos.y, ast.radius, 1., RED); Self::consider_asteroids(self.pos, &mut debug_asteroids);
// let p = self.pos for asteroid in &debug_asteroids {
// + self.dir.rotate(Vec2::from_angle(self.asteroid_data[0].1)) if let Some(ast) = asteroid {
// * self.asteroid_data[0].0 draw_circle_lines(ast.pos.x, ast.pos.y, ast.radius, 1., RED);
// * WIDTH; // let p = self.pos
draw_line(self.pos.x, self.pos.y, ast.pos.x, ast.pos.y, 1., RED); // + self.dir.rotate(Vec2::from_angle(self.asteroid_data[0].1))
// * self.asteroid_data[0].0
// * WIDTH;
draw_line(self.pos.x, self.pos.y, ast.pos.x, ast.pos.y, 1., RED);
}
} }
// Draw raycasts // Draw raycasts
@ -276,3 +269,18 @@ impl Bullet {
draw_circle(self.pos.x, self.pos.y, 2., Color::new(c.r, c.g, c.b, 0.9)); draw_circle(self.pos.x, self.pos.y, 2., Color::new(c.r, c.g, c.b, 0.9));
} }
} }
// Distance in a toroidal space:
// https://blog.demofox.org/2017/10/01/calculating-the-distance-between-points-in-wrap-around-toroidal-space/
fn dist_wrapping(a: Vec2, b: Vec2, r: f32) -> f32 {
let mut dx = (a.x - b.x).abs();
let mut dy = (a.y - b.y).abs();
if dx > (WIDTH as f32 / 2.) {
dx = WIDTH as f32 - dx;
}
if dy > (HEIGHT as f32 / 2.) {
dy = HEIGHT as f32 - dy;
}
((dx * dx + dy * dy).sqrt() - r) / (WIDTH * WIDTH + HEIGHT * HEIGHT).sqrt()
}