Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add Dorf Hero AI example! #17

Draft
wants to merge 16 commits into
base: main
Choose a base branch
from
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
/target
target
Cargo.lock
1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,3 @@ homepage = "https://github.com/zkat/big-brain"

[dependencies]
bevy = "0.5.0"

12 changes: 12 additions & 0 deletions examples/dorf_hero/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[package]
name = "dorf_hero"
version = "0.1.0"
authors = ["Kat Marchán <[email protected]>"]
edition = "2018"

[dependencies]
bevy_tilemap = "0.4.0"
rand = "0.8.3"
pathfinding = "2.1.2"
bevy = "0.5.0"
big-brain = { path = "../../" }
27 changes: 27 additions & 0 deletions examples/dorf_hero/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
This example is based on one from bevy_tilemap, found here:
https://github.com/joshuajbouw/bevy_tilemap/blob/9e19adb/examples/examples/random_dungeon.rs

It, and the other assets in this subproject, include the following license,
reproduced here in accordance with its requirements:

MIT License

Copyright (c) 2020 Joshua J. Bouw

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Binary file added examples/dorf_hero/assets/textures/dwarf.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/dorf_hero/assets/textures/square-dwarf.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/dorf_hero/assets/textures/square-floor.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/dorf_hero/assets/textures/square-wall.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
69 changes: 69 additions & 0 deletions examples/dorf_hero/src/ai/actions/chase.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
use bevy::prelude::*;
use bevy_tilemap::Tilemap;
use big_brain::prelude::*;

use crate::components::{Position, Render};
use crate::resources::GameState;

// Let's define our "default" action, which will be used whenever there's nothing in particular getting our dorf's attention.
#[derive(Default, Debug, Clone)]
pub struct ChaseBuilder;

#[derive(Debug, Default, Clone)]
pub struct Chase {

}

impl Chase {
pub fn build() -> ChaseBuilder {
ChaseBuilder
}
}

impl ActionBuilder for ChaseBuilder {
fn build(&self, cmd: &mut Commands, action: Entity, _actor: Entity) {
cmd.entity(action).insert(Chase::default());
}
}

pub fn meander_action(
mut game_state: ResMut<GameState>,
time: Res<Time>,
mut map_query: Query<(&mut Tilemap, &mut Timer)>,
mut location_query: Query<(&mut Position, &Render)>,
mut action_q: Query<(&mut Chase, &Actor, &mut ActionState)>,
) {
for (mut map, mut timer) in map_query.iter_mut() {
timer.tick(time.delta());
if !timer.finished() {
continue;
}
for (mut chase, Actor(actor), mut state) in action_q.iter_mut() {
match *state {
ActionState::Cancelled => {
// *ALWAYS* handle Cancelled, even if you're doing a single-tick action. Your action might end up hanging otherwise.
*state = ActionState::Success;
continue;
}
ActionState::Init | ActionState::Success | ActionState::Failure => {
continue;
}
// These two fall through to logic :)
ActionState::Requested => {
*state = ActionState::Executing;
}
ActionState::Executing => {}
}
if let Ok((mut pos, render)) = location_query.get_mut(*actor) {
if (chase.dx == 0 && chase.dy == 0)
|| !game_state.try_move(&mut *map, render, &mut pos, (chase.dx, chase.dy))
{
let mut rng = rand::thread_rng();
chase.dx = rng.gen_range(-1..=1);
chase.dy = rng.gen_range(-1..=1);
}
}
}
}
}

69 changes: 69 additions & 0 deletions examples/dorf_hero/src/ai/actions/meander.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
use bevy::prelude::*;
use bevy_tilemap::Tilemap;
use big_brain::prelude::*;
use rand::Rng;

use crate::components::{Position, Render};
use crate::resources::GameState;
// Let's define our "default" action, which will be used whenever there's nothing in particular getting our dorf's attention.
#[derive(Default, Debug, Clone)]
pub struct MeanderBuilder;

#[derive(Debug, Default, Clone)]
pub struct Meander {
dx: i32,
dy: i32,
}

impl Meander {
pub fn build() -> MeanderBuilder {
MeanderBuilder
}
}

impl ActionBuilder for MeanderBuilder {
fn build(&self, cmd: &mut Commands, action: Entity, _actor: Entity) {
cmd.entity(action).insert(Meander::default());
}
}

pub fn meander_action(
mut game_state: ResMut<GameState>,
time: Res<Time>,
mut map_query: Query<(&mut Tilemap, &mut Timer)>,
mut location_query: Query<(&mut Position, &Render)>,
mut action_q: Query<(&mut Meander, &Actor, &mut ActionState)>,
) {
for (mut map, mut timer) in map_query.iter_mut() {
timer.tick(time.delta());
if !timer.finished() {
continue;
}
for (mut meander, Actor(actor), mut state) in action_q.iter_mut() {
match *state {
ActionState::Cancelled => {
// *ALWAYS* handle Cancelled, even if you're doing a single-tick action. Your action might end up hanging otherwise.
*state = ActionState::Success;
continue;
}
ActionState::Init | ActionState::Success | ActionState::Failure => {
continue;
}
// These two fall through to logic :)
ActionState::Requested => {
*state = ActionState::Executing;
}
ActionState::Executing => {}
}
if let Ok((mut pos, render)) = location_query.get_mut(*actor) {
if (meander.dx == 0 && meander.dy == 0)
|| !game_state.try_move(&mut *map, render, &mut pos, (meander.dx, meander.dy))
{
let mut rng = rand::thread_rng();
meander.dx = rng.gen_range(-1..=1);
meander.dy = rng.gen_range(-1..=1);
}
}
}
}
}
2 changes: 2 additions & 0 deletions examples/dorf_hero/src/ai/actions/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pub mod chase;
pub mod meander;
16 changes: 16 additions & 0 deletions examples/dorf_hero/src/ai/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
use bevy::prelude::*;
use big_brain::prelude::*;

pub mod actions;
pub mod scorers;

pub struct DorfHeroAiPlugin;

impl Plugin for DorfHeroAiPlugin {
fn build(&self, app: &mut bevy::prelude::AppBuilder) {
app.add_plugin(BigBrainPlugin)
.add_system(scorers::enemy_distance::enemy_distance.system())
.add_system(scorers::fear_of_death::fear_of_death.system())
.add_system(actions::meander::meander_action.system());
}
}
80 changes: 80 additions & 0 deletions examples/dorf_hero/src/ai/scorers/enemy_distance.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
use bevy::prelude::*;
use big_brain::{
evaluators::{Evaluator, LinearEvaluator},
prelude::*,
};

use crate::components::{EvilDorf, Hero, Position};
use crate::util;

#[derive(Debug, Default)]
pub struct EnemyDistanceBuilder {
within: f32,
}

impl EnemyDistanceBuilder {
pub fn within(mut self, within: f32) -> Self {
self.within = within;
self
}
}

impl ScorerBuilder for EnemyDistanceBuilder {
fn build(&self, cmd: &mut Commands, scorer: Entity, _actor: Entity) {
cmd.entity(scorer).insert(EnemyDistance {
within: self.within,
evaluator: LinearEvaluator::new_ranged(self.within, 0.0),
});
}
}

#[derive(Debug)]
pub struct EnemyDistance {
within: f32,
evaluator: LinearEvaluator,
}

impl EnemyDistance {
pub fn build() -> EnemyDistanceBuilder {
EnemyDistanceBuilder::default()
}
}

pub fn enemy_distance(
enemy_q: Query<&Position, With<EvilDorf>>,
hero_q: Query<&Position, With<Hero>>,
mut scorer_q: Query<(&Actor, &mut Score, &EnemyDistance)>,
) {
for (Actor(actor), mut score, enemy_distance) in scorer_q.iter_mut() {
if let Ok(enemy_pos) = enemy_q.get(*actor) {
if let Ok(hero_pos) = hero_q.single() {
let distance = util::euclidean_distance(enemy_pos, hero_pos);
if distance <= enemy_distance.within {
score.set(
enemy_distance
.evaluator
.evaluate(distance / enemy_distance.within),
);
} else {
score.set(0.0);
}
}
}
if let Ok(hero_pos) = hero_q.get(*actor) {
let mut max = 0.;
for enemy_pos in enemy_q.iter() {
let distance = util::euclidean_distance(enemy_pos, hero_pos);
if distance <= enemy_distance.within {
let val = enemy_distance.evaluator.evaluate(distance / enemy_distance.within);
if val > max {
max = val;
}
if max >= 1.0 {
break;
}
}
}
score.set(max);
}
}
}
36 changes: 36 additions & 0 deletions examples/dorf_hero/src/ai/scorers/fear_of_death.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
use bevy::prelude::*;
use big_brain::{
evaluators::{Evaluator, PowerEvaluator},
prelude::*,
};

use crate::components::Hp;

pub struct FearOfDeath {
evaluator: PowerEvaluator,
}

impl FearOfDeath {
pub fn build() -> FearOfDeathBuilder {
FearOfDeathBuilder::default()
}
}
#[derive(Debug, Default)]
pub struct FearOfDeathBuilder;

impl ScorerBuilder for FearOfDeathBuilder {
fn build(&self, cmd: &mut Commands, scorer: Entity, _actor: Entity) {
cmd.entity(scorer).insert(FearOfDeath {
evaluator: PowerEvaluator::new_ranged(2., 1.0, 0.0),
});
}
}

pub fn fear_of_death(hp_q: Query<&Hp>, mut scorer_q: Query<(&Actor, &mut Score, &FearOfDeath)>) {
for (Actor(actor), mut score, fear) in scorer_q.iter_mut() {
if let Ok(hp) = hp_q.get(*actor) {
let perc = hp.current as f32 / hp.max as f32;
score.set(fear.evaluator.evaluate(perc));
}
}
}
2 changes: 2 additions & 0 deletions examples/dorf_hero/src/ai/scorers/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pub mod enemy_distance;
pub mod fear_of_death;
1 change: 1 addition & 0 deletions examples/dorf_hero/src/components/evil_dorf.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub struct EvilDorf;
3 changes: 3 additions & 0 deletions examples/dorf_hero/src/components/hero.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#[derive(Default)]
pub struct Hero;

10 changes: 10 additions & 0 deletions examples/dorf_hero/src/components/hp.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
pub struct Hp {
pub current: u32,
pub max: u32,
}

impl Hp {
pub fn new(max: u32) -> Self {
Hp { current: max, max }
}
}
11 changes: 11 additions & 0 deletions examples/dorf_hero/src/components/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
pub use evil_dorf::*;
pub use hero::*;
pub use hp::*;
pub use position::*;
pub use render::*;

mod evil_dorf;
mod hero;
mod hp;
mod position;
mod render;
5 changes: 5 additions & 0 deletions examples/dorf_hero/src/components/position.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#[derive(Default, Copy, Clone, PartialEq)]
pub struct Position {
pub x: i32,
pub y: i32,
}
6 changes: 6 additions & 0 deletions examples/dorf_hero/src/components/render.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#[derive(Default)]
pub struct Render {
pub sprite_index: usize,
pub sprite_order: usize,
}

Loading