Skip to content

Instantly share code, notes, and snippets.

@hexagit
Created May 22, 2023 09:51
Show Gist options
  • Save hexagit/925de192e8b0f5d5ab58e320494c9991 to your computer and use it in GitHub Desktop.
Save hexagit/925de192e8b0f5d5ab58e320494c9991 to your computer and use it in GitHub Desktop.
simpleなrustのサンプル
trait Task {
fn update(&mut self);
fn is_died(&self)->bool;
fn spawn(&self)->Box<dyn Task>;
}
struct UnitA {
name : String,
life : i32,
}
struct UnitB {
name : String,
revival : i32,
}
impl Task for UnitA{
fn update(&mut self){
self.life -= 1;
println!("{}'s life remain {}", self.name, self.life);
}
fn is_died(&self)->bool {
self.life <= 0
}
fn spawn(&self)->Box<dyn Task>{
println!("UnitA spawn UnitB");
Box::new(UnitB::new())
}
}
impl Task for UnitB{
fn update(& mut self){
self.revival -= 1;
println!("{}'s will revive {}", self.name, self.revival);
}
fn is_died(&self)->bool {
self.revival <= 0
}
fn spawn(&self)->Box<dyn Task>{
println!("UnitB spawn UnitA");
Box::new(UnitA::new())
}
}
impl UnitA{
fn new()->Self{
UnitA{name: "human".to_string(), life: 50}
}
}
impl UnitB{
fn new()->Self{
UnitB{name: "zombie".to_string(), revival: 40}
}
}
fn main() {
let mut units: Vec<Box<dyn Task>> = vec![
Box::new(UnitA::new()),
Box::new(UnitB::new())
];
// ゲームループ想定で処理を回します
loop{
let mut i = 0;
while i < units.len(){
let unit = units[i].as_mut();
unit.update();
if unit.is_died(){
println!("unit is died remove");
let new_unit = unit.spawn();
units.push(new_unit);
units.remove(i);
}
else{
i += 1;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment