use piston_window::*; use findfolder; trait State { fn input(&mut…
- User
use piston_window::*; use find_folder;
trait State { fn input(&mut self,button:Button)->Option; fn update(&mut self,_args:&UpdateArgs); fn render(&mut self,c:Context,g:&mut G2d,glyphs:&mut Glyphs); }
enum StateCommand{ Push(Box), Pop, None, }
struct StateStack{ stack:Vec<Box> } impl StateStack{
codefn new(initial_state:Box<dyn State>)->Self{ Self { stack: vec![initial_state] } } fn push(&mut self,state:Box<dyn State>){ self.stack.push(state); } fn pop(&mut self){ if self.stack.is_empty(){ return; } self.stack.pop(); if self.stack.is_empty(){ println!("堆疊結束") } } fn render(&mut self,c:Context,g:&mut G2d,glyphs:&mut Glyphs){ for state in &mut self.stack{ state.render(c, g, glyphs); } } fn input(&mut self,button:Button){ if let Some(top)=self.stack.last_mut(){ if let Some(cmd) = top.input(button) { match cmd { StateCommand::Push(state)=>self.push(state), StateCommand::Pop=>self.pop(), StateCommand::None=>{} } } } } fn is_empty(&self)->bool{ self.stack.is_empty() } fn update(&mut self,args:&UpdateArgs){ if let Some(top)=self.stack.last_mut(){ top.update(args); } }}
struct MainPage{ circle_x:f64, direction:f64, fps_timer:f64, fps_count:u32, fps:u32, } impl MainPage{ fn new()->Self{ Self { circle_x: 320.0, direction: 100.0, fps_timer: 0.0, fps_count: 0, fps:0 } } } struct ModalWindow{ count:usize } impl ModalWindow{ fn new()->Self{ Self { count: 0 } } } impl State for MainPage { fn update(&mut self,args:&UpdateArgs) { self.circle_x +=self.direction*args.dt; if self.circle_x > 660.0 { self.circle_x=660.0; self.direction = -self.direction }else if self.circle_x< 40.0{ self.circle_x=40.0; self.direction = -self.direction; }; self.fps_timer +=args.dt; self.fps_count+=1; if self.fps_timer > 1.0 { self.fps=self.fps_count; self.fps_timer -=1.0; self.fps_count =0; } } fn input(&mut self,button:Button)->Option { if let Button::Keyboard(key)=button{ if key == Key::M { return Some(StateCommand::Push(Box::new(ModalWindow::new()))); } } None } fn render(&mut self,c:Context,g:&mut G2d,glyphs:&mut Glyphs) { clear([0.8,0.8,0.8,1.0], g); draw_text_centered( "主頁面", c, g, glyphs, 240.0); graphics::ellipse( [1.0;4], [self.circle_x-20.0,300.0-20.0,40.0,40.0], c.transform, g,); let fps_text=format!("Fps:{}",self.fps); let text_obj=graphics::text::Text::new_color([1.0;4], 24); text_obj.draw( &fps_text, glyphs, &graphics::DrawState::default(), c.transform.trans(10.0, 460.0), g).unwrap();
- Assistant