Watch
1
Fork
You've already forked adversarial_foraging
0

Compare commits

..
Author SHA1 Message Date
aef4cffd43
enlarged kill radius 2026-11-09 16:28:58 -05:00
17551f2ae2
kill beam 2026-11-09 16:14:41 -05:00
596db89430
define mortality 2026-11-09 15:50:07 -05:00
3d9f957c4f
multi-run 2026-11-09 15:04:16 -05:00
bd9412e54a
randomize playing field 2026-11-09 14:55:30 -05:00
5e72d94080
keep score 2026-11-09 14:42:01 -05:00
6ebb6753fd
unified teams 2026-11-09 14:18:53 -05:00
1319968095
red vs blue 2026-11-09 14:06:27 -05:00
b279cc91d7
food collection 2026-11-09 11:42:22 -05:00
4bc18b26ff
kin visuals 2026-11-09 01:01:26 -05:00

View file

@ -1,4 +1,9 @@
use std::cmp::min; use std::cmp::min;
use std::collections::HashMap;
use std::f32::consts::TAU;
use std::ptr;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use macroquad::prelude::*; use macroquad::prelude::*;
use parry2d::math::Pose; use parry2d::math::Pose;
@ -12,16 +17,50 @@ use parry2d::shape::Shape;
const VIEW_DIST: f32 = 180.0; const VIEW_DIST: f32 = 180.0;
const BOT_RADIUS: f32 = 16.0; const BOT_RADIUS: f32 = 16.0;
const KILL_RADIUS: f32 = 140.0;
trait Mortal {
fn collider(&self) -> (&Pose, &dyn Shape);
fn kill(&self);
fn living(&self) -> bool;
fn draw(&self);
}
struct Robot { struct Robot {
pose: Pose, pose: Pose,
alive: bool, alive: AtomicBool,
collider: Ball,
sensor: Sensor,
team: Color,
}
impl Mortal for Robot {
fn draw(&self) {
let tl = self.pose.translation;
let tl2 = self.view_end();
draw_circle(tl.x, tl.y, BOT_RADIUS, BLACK);
draw_line(tl.x, tl.y, tl2.x, tl2.y, 2.0, BLUE);
draw_circle(tl.x, tl.y, BOT_RADIUS-1.0, self.team);
}
fn collider(&self) -> (&Pose, &dyn Shape) {
(&self.pose, &self.collider)
}
fn kill (&self) {
self.alive.store(false, Ordering::Relaxed);
}
fn living(&self) -> bool {
self.alive.load(Ordering::Relaxed)
}
} }
impl Robot { impl Robot {
fn new(position: Vec2) -> Self { fn new(position: Vec2, team: Color) -> Self {
let pose:Pose = Pose::from_translation(position.to_array().into()); let rand_angle = rand::gen_range(0, 1000) as f32 * TAU / 1000.0;
Self { pose, alive: true } let pose:Pose = Pose::from_parts(position.to_array().into(), Rot2::from_angle(rand_angle));
Self { pose, alive: AtomicBool::new(true), collider: Ball::new(BOT_RADIUS), sensor: Sensor::None, team}
} }
fn move_step(&mut self, forward: f32, right: f32) { fn move_step(&mut self, forward: f32, right: f32) {
@ -33,18 +72,11 @@ impl Robot {
Vec2::new(self.pose.rotation.re, self.pose.rotation.im) Vec2::new(self.pose.rotation.re, self.pose.rotation.im)
} }
pub fn draw(&self) {
let tl = self.pose.translation;
let tl2 = self.view_end();
draw_circle(tl.x, tl.y, BOT_RADIUS, BLACK);
draw_line(tl.x, tl.y, tl2.x, tl2.y, 2.0, BLUE);
draw_circle(tl.x, tl.y, BOT_RADIUS-1.0, RED);
}
fn view_end(&self) -> Vec2 { fn view_end(&self) -> Vec2 {
self.pose.translation + self.ahead() * VIEW_DIST self.pose.translation + self.ahead() * VIEW_DIST
} }
fn detect<'a>(&self, things: impl Iterator<Item = (&'a Pose, &'a dyn Shape)>) -> Option<f32> { fn detect<'a>(&self, things: impl Iterator<Item = (&'a Pose, &'a dyn Shape)>) -> Option<f32> {
let collider = Segment::new(self.pose.translation, self.view_end()); let collider = Segment::new(self.pose.translation, self.view_end());
things things
@ -52,73 +84,212 @@ impl Robot {
.map(|contact| contact.point1.distance(self.pose.translation)).reduce(|x: f32,y: f32| x.min(y)) .map(|contact| contact.point1.distance(self.pose.translation)).reduce(|x: f32,y: f32| x.min(y))
} }
pub fn policy(&mut self, sensor: Sensor){ fn draw_weapon(&self) {
let tl = self.pose.translation;
draw_circle(tl.x, tl.y, KILL_RADIUS, ORANGE);
}
fn weapon<'a>(&self, peers: impl Iterator<Item = &'a dyn Mortal>) {
let weapon = Ball::new(KILL_RADIUS);
for peer in peers {
let (p_p, p_c) = peer.collider();
if let Some(_) = contact(&self.pose, &weapon, p_p , p_c, 0.0).unwrap() {
peer.kill();
}
}
}
pub fn policy(&mut self, sensor: &Sensor) -> bool{
match sensor { match sensor {
Sensor::Food => self.move_step(1.0, 0.0), Sensor::Food => self.move_step(1.0, 0.0),
Sensor::None => self.move_step(1.0, 0.01), Sensor::Kin => self.move_step(-0.3, 0.02),
Sensor::NonKin => self.move_step(0.3, -0.02),
Sensor::None => self.move_step(0.3, 0.01),
} }
return *sensor == Sensor::NonKin;
} }
} }
struct Food { struct Food {
pose: Pose, pose: Pose,
collider: Ball, collider: Ball,
alive: bool, alive: AtomicBool,
} }
#[derive(PartialEq, Eq)]
enum Sensor { enum Sensor {
Food, Food,
Kin,
NonKin,
None None
} }
impl Food { impl Mortal for Food {
fn new(position: Vec2) -> Self { fn draw(&self) {
let pose:Pose = Pose::from_translation(position.to_array().into());
Self { pose, alive: true, collider: Ball::new(BOT_RADIUS) }
}
pub fn draw(&self) {
let tl = self.pose.translation; let tl = self.pose.translation;
draw_circle(tl.x, tl.y, BOT_RADIUS, BLACK); draw_circle(tl.x, tl.y, BOT_RADIUS, BLACK);
draw_circle(tl.x, tl.y, BOT_RADIUS-1.0, GREEN); draw_circle(tl.x, tl.y, BOT_RADIUS-1.0, GREEN);
} }
pub fn collider(&self) -> (&Pose, &dyn Shape) { fn collider(&self) -> (&Pose, &dyn Shape) {
(&self.pose, &self.collider) (&self.pose, &self.collider)
} }
fn kill (&self) {
self.alive.store(false, Ordering::Relaxed);
}
fn living(&self) -> bool {
self.alive.load(Ordering::Relaxed)
}
}
impl Food {
fn new(position: Vec2) -> Self {
let pose:Pose = Pose::from_translation(position.to_array().into());
Self { pose, alive: AtomicBool::new(true), collider: Ball::new(BOT_RADIUS) }
}
fn detect<'a>(&self, things: impl Iterator<Item = &'a Robot>) -> Option<Color> {
things
.map(|robot| contact(&self.pose, &self.collider, &robot.pose, &robot.collider, 0.0).unwrap().map(|a| (a,robot.team))).flatten()
.map(|(contact,team)| (contact.point1.distance(self.pose.translation),team)).reduce(|x ,y| if x.0 < y.0 {x} else{y} ).map(|(_, team)| team)
}
}
async fn run_simulation() -> (i32, i32) {
let mut watchdog = 0; // iterations since something interesting
let mut robots = Vec::new();
let mut score = HashMap::new();
for i in 5..20 {
robots.push(Robot::new(Vec2 { x: 100.0, y: i as f32*50.0 }, BLUE));
robots.push(Robot::new(Vec2 { x: 1200.0, y: i as f32*50.0 }, RED));
}
let mut food = Vec::new();
for i in 0..120 {
let x = rand::gen_range(200, 1100) as f32;
let y = rand::gen_range(200, 900) as f32;
food.push(Food::new(Vec2 { x, y }));
}
//for j in 5..20 {
// for i in 5..20 {
// food.push(Food::new(Vec2 { x: i as f32*60.0, y: j as f32*50.0 }));
// }
//}
fn color_hash(color: Color) -> [u32; 4] {
color.to_vec().to_array().map(|f| f.to_bits())
}
let mut loo = 0;
loop {
let rendered = loo %90 == 0;
//let rendered = false;
clear_background(LIGHTGRAY);
for food in &mut food{
if let Some(team) = food.detect(robots.iter()) {
if food.living() {
score.entry(color_hash(team)).and_modify(|s| *s +=1 ).or_insert(1);
food.kill();
watchdog = 0;
}
}
if rendered { food.draw(); }
}
food = food.into_iter().filter(Mortal::living).collect(); // remove dead food
robots = robots.into_iter().filter(Mortal::living).collect(); // remove dead robots
let mut sensors = Vec::new();
for robot in &*robots {
let detect_food = robot.detect(food.iter().map(Food::collider));
let detect_kin = robot.detect(robots.iter().filter(|o| o.team == robot.team).filter(|r| !ptr::eq(&**r , &**&robot)).map(Robot::collider));
let detect_non_kin = robot.detect(robots.iter().filter(|o| o.team != robot.team).filter(|r| !ptr::eq(&**r , &**&robot)).map(Robot::collider));
let mut sensor = Sensor::None;
let mut closest: Option<f32> = None;
for (dist, detection) in [(detect_food, Sensor::Food), (detect_kin, Sensor::Kin), (detect_non_kin, Sensor::NonKin)] {
if let (Some(close), Some(dist)) = (closest, dist) {
if close < dist {continue;}
}
if let Some(_) = dist {
sensor = detection;
closest = dist;
}
}
sensors.push(sensor);
}
for idx in 0..robots.len() {
let (before, after) = robots.split_at_mut(idx);
let (robot, after) = after.split_first_mut().unwrap();
let robots = before.iter().chain(after.iter());
let robots = robots.map(|r| r as &dyn Mortal);
let peers = robots.chain(food.iter().map(|f| f as &dyn Mortal));
let mut death = robot.policy(&sensors[idx]);
if robot.team == BLUE {
death = false; // pacifists
}
if death {
if true {robot.draw_weapon();}
robot.weapon(peers);
}
if rendered { robot.draw();}
}
if rendered {
draw_text(format!("RED: {}", score.get(&color_hash(RED)).unwrap_or(&0)), 20.0, 20.0, 30.0, DARKGRAY);
draw_text(format!("BLUE: {}", score.get(&color_hash(BLUE)).unwrap_or(&0)), 20.0, 40.0, 30.0, DARKGRAY);
}
loo += 1;
if rendered {
next_frame().await // TODO: framerate cap
}
watchdog += 1;
if food.is_empty() || watchdog > 1000 {
let red = score.get(&color_hash(RED)).unwrap_or(&0);
let blu = score.get(&color_hash(BLUE)).unwrap_or(&0);
return (*red, *blu);
}
}
} }
#[macroquad::main("Adversarial Foraging Simulator")] #[macroquad::main("Adversarial Foraging Simulator")]
async fn main() { async fn main() {
let mut robots = Vec::new(); let mut rtot = 0;
robots.push(Robot::new(Vec2 { x: 100.0, y: 100.0 })); let mut btot = 0;
robots.push(Robot::new(Vec2 { x: 140.0, y: 100.0 })); for i in 0..100 {
robots.push(Robot::new(Vec2 { x: 140.0, y: 200.0 })); rand::srand(i);
robots.push(Robot::new(Vec2 { x: 180.0, y: 150.0 }));
let mut food = Vec::new(); let (red, blu) = run_simulation().await;
food.push(Food::new(Vec2 { x: 160.0, y: 100.0 }));
food.push(Food::new(Vec2 { x: 360.0, y: 100.0 }));
food.push(Food::new(Vec2 { x: 360.0, y: 300.0 }));
loop { rtot += red;
clear_background(LIGHTGRAY); btot += blu;
for food in &food{ println!("{} wins! RED: {red}, BLU: {blu}", if red > blu {"red"} else {"blue"});
food.draw();
}
for robot in &mut robots {
println!("loop");
let detect = robot.detect(food.iter().map(Food::collider));
let sensor = if detect.is_some() {Sensor::Food} else {Sensor::None};
robot.policy(sensor);
println!("Food detection: {:?}",detect);
robot.draw();
}
draw_text("HELLO", 20.0, 20.0, 30.0, DARKGRAY);
next_frame().await // TODO: framerate cap
} }
let red = rtot / 100;
let blu = btot / 100;
println!("{} wins on average! RED: {red}, BLU: {blu}", if red > blu {"red"} else {"blue"});
} }