Skip to content

Commit ad1276a

Browse files
committed
Fixed single thread problem
1 parent 58e498c commit ad1276a

File tree

2 files changed

+42
-7
lines changed

2 files changed

+42
-7
lines changed

game-engine/src/framework.rs

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,13 @@
1+
pub struct BotContainer {
2+
is_active: bool,
3+
bot: Box<dyn Bot>,
4+
}
5+
impl BotContainer {
6+
pub fn new(is_active: bool, bot: Box<dyn Bot>) -> Self {
7+
BotContainer { is_active, bot }
8+
}
9+
}
10+
111
pub trait Bot {
212
fn apply(&self) {
313
println!("Default AI movements");
@@ -17,7 +27,7 @@ pub struct Game {
1727
// height: f32,
1828
size: Size,
1929
actors: Vec<Box<dyn Actor>>,
20-
bots: Vec<Box<dyn Bot>>,
30+
bots_container: Vec<BotContainer>,
2131
}
2232

2333
impl Game {
@@ -36,14 +46,18 @@ impl Game {
3646
}
3747
}
3848
pub fn add_bot(&mut self, bot: Box<dyn Bot>) {
39-
self.bots.push(bot);
49+
self.bots_container.push(BotContainer::new(true, bot));
4050
}
4151
pub fn update(&mut self) {
4252
for actor in &mut self.actors {
4353
actor.update();
4454
}
45-
for bot in &self.bots {
46-
bot.apply();
55+
}
56+
pub fn apply(&self) {
57+
for container in &self.bots_container {
58+
if container.is_active {
59+
container.bot.apply();
60+
}
4761
}
4862
}
4963
}

game-engine/src/main.rs

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,14 @@ fn main() {
1414
let mushroom = Mushroom::new(2, 10);
1515
game.add_actor(Box::new(super_mario));
1616
game.add_actor(Box::new(mushroom));
17+
1718
let mega_mind = MindController::default();
1819
game.add_bot(Box::new(mega_mind));
1920

21+
game.add_bot(Box::new(Confuser::default()));
22+
23+
game.apply();
24+
2025
loop {
2126
sleep(Duration::from_secs(2));
2227
game.draw();
@@ -26,20 +31,36 @@ fn main() {
2631
}
2732

2833
#[derive(Default)]
29-
pub struct MindController {}
34+
struct MindController {}
3035

3136
impl Bot for MindController {
3237
fn apply(&self) {
33-
//todo@buraksenyurt Buradaki thread'in bir kere açılmasını garanti et
3438
thread::spawn(|| {
3539
loop {
36-
println!("Applying simulation...");
40+
println!("\tApplying simulation...{:?}", thread::current().id());
3741
sleep(Duration::from_secs(5));
3842
}
3943
});
4044
}
4145
}
4246

47+
#[derive(Default)]
48+
struct Confuser {}
49+
50+
impl Bot for Confuser {
51+
fn apply(&self) {
52+
thread::spawn(|| {
53+
loop {
54+
println!(
55+
"\t\tBrain confusing in progress...{:?}",
56+
thread::current().id()
57+
);
58+
sleep(Duration::from_secs(1));
59+
}
60+
});
61+
}
62+
}
63+
4364
#[allow(dead_code)]
4465
struct Player {
4566
id: u32,

0 commit comments

Comments
 (0)