Skip to content

Commit f6cf31c

Browse files
committed
Trying to implemente channels
1 parent ad1276a commit f6cf31c

File tree

2 files changed

+31
-11
lines changed

2 files changed

+31
-11
lines changed

game-engine/src/framework.rs

+15-7
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use std::sync::mpsc::Sender;
2+
13
pub struct BotContainer {
24
is_active: bool,
35
bot: Box<dyn Bot>,
@@ -20,23 +22,26 @@ pub trait Actor {
2022
fn update(&mut self);
2123
}
2224

23-
#[derive(Default)]
25+
// #[derive(Default)]
2426
#[allow(dead_code)]
2527
pub struct Game {
2628
// width: f32,
2729
// height: f32,
2830
size: Size,
2931
actors: Vec<Box<dyn Actor>>,
3032
bots_container: Vec<BotContainer>,
33+
sender: Sender<String>,
3134
}
3235

3336
impl Game {
34-
// pub fn new() -> Self {
35-
// Game {
36-
// actors: Vec::new(),
37-
// size:Size::default()
38-
// }
39-
// }
37+
pub fn new(sender: Sender<String>) -> Self {
38+
Game {
39+
actors: Vec::new(),
40+
size: Size::default(),
41+
bots_container: Vec::new(),
42+
sender,
43+
}
44+
}
4045
pub fn add_actor(&mut self, actor: Box<dyn Actor>) {
4146
self.actors.push(actor);
4247
}
@@ -55,6 +60,9 @@ impl Game {
5560
}
5661
pub fn apply(&self) {
5762
for container in &self.bots_container {
63+
self.sender
64+
.send("A simple message...".to_string())
65+
.expect("Error in sending message into channel");
5866
if container.is_active {
5967
container.bot.apply();
6068
}

game-engine/src/main.rs

+16-4
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use std::{
2+
sync::mpsc::channel,
23
thread::{self, sleep},
34
time::Duration,
45
};
@@ -8,19 +9,30 @@ use framework::*;
89
mod framework;
910

1011
fn main() {
11-
// let mut game = Game::new();
12-
let mut game = Game::default();
12+
let (transmitter, receiver) = channel::<String>();
13+
14+
let mut game = Game::new(transmitter.clone());
15+
// let mut game = Game::default();
1316
let super_mario = Player::new(1, "Super Mario".to_string());
1417
let mushroom = Mushroom::new(2, 10);
1518
game.add_actor(Box::new(super_mario));
1619
game.add_actor(Box::new(mushroom));
1720

1821
let mega_mind = MindController::default();
1922
game.add_bot(Box::new(mega_mind));
20-
2123
game.add_bot(Box::new(Confuser::default()));
2224

25+
// GameEngine::run(&game);
26+
2327
game.apply();
28+
game.draw();
29+
game.update();
30+
31+
// drop(transmitter);
32+
// Not: Sürekli dinlemede kalınacağı için loop döngüsü hiçbir zaman başlamaz.
33+
for r in receiver {
34+
println!("{}", r);
35+
}
2436

2537
loop {
2638
sleep(Duration::from_secs(2));
@@ -35,7 +47,7 @@ struct MindController {}
3547

3648
impl Bot for MindController {
3749
fn apply(&self) {
38-
thread::spawn(|| {
50+
thread::spawn(move || {
3951
loop {
4052
println!("\tApplying simulation...{:?}", thread::current().id());
4153
sleep(Duration::from_secs(5));

0 commit comments

Comments
 (0)