error[E0499]: cannot borrow *self as mutable more than once at a time
--> src\main.rs:31:46
|
31 | self.current_state().on_event(event, self);
| ---- -------- ^^^^ second mutable borrow occurs here
| | |
| | first borrow later used by call
| first mutable borrow occurs here
For more information about this error, try rustc --explain E0499.
Assistant
你遇到的錯誤:
code
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> src\main.rs:31:46
|
31 | self.current_state().on_event(event, self);
| ---- -------- ^^^^ second mutable borrow occurs here
| | |
| | first borrow later used by call
| first mutable borrow occurs here
use std::fmt::Debug;
trait State: Debug {
fn on_event(&mut self, event: &str, machine: &mut StateMachine);
fn name(&self) -> &str;
}
#[derive(Debug)]
struct StateMachine {
stack: Vec<Box<dyn State>>,
}
impl StateMachine {
fn new(initial_state: Box<dyn State>) -> Self {
Self {
stack: vec![initial_state],
}
}
fn current_state(&mut self) -> &mut Box<dyn State> {
self.stack.last_mut().expect("state stack should never be empty")
}
fn on_event(&mut self, event: &str) {
println!("Event '{}' received in state '{}'", event, self.current_state().name());
// 新增區塊scope,讓可變借用不重疊
{
let state = self.current_state();
state.on_event(event, self);
}
// 這裡 state 可變借用已經釋放,可以安全借用 self
}
fn push_state(&mut self, state: Box<dyn State>) {
println!("Pushing state '{}'", state.name());
self.stack.push(state);
}
fn pop_state(&mut self) {
if self.stack.len() > 1 {
let popped = self.stack.pop().unwrap();
println!("Popped state '{}', now state is '{}'", popped.name(), self.current_state().name());
} else {
println!("Cannot pop the last state!");
}
}
}
#[derive(Debug)]
struct Idle;
impl State for Idle {
fn on_event(&mut self, event: &str, machine: &mut StateMachine) {
match event {
"walk" => machine.push_state(Box::new(Walking)),
"run" => machine.push_state(Box::new(Running)),
_ => println!("Idle: Event '{}' ignored", event),
}
}
fn name(&self) -> &str {
"Idle"
}
}
#[derive(Debug)]
struct Walking;
impl State for Walking {
fn on_event(&mut self, event: &str, machine: &mut StateMachine) {
match event {
"stop" => machine.pop_state(),
"run" => {
machine.pop_state();
machine.push_state(Box::new(Running));
}
_ => println!("Walking: Event '{}' ignored", event),
}
}
fn name(&self) -> &str {
"Walking"
}
}
#[derive(Debug)]
struct Running;
impl State for Running {
fn on_event(&mut self, event: &str, machine: &mut StateMachine) {
match event {
"stop" => machine.pop_state(),
"walk" => {
machine.pop_state();
machine.push_state(Box::new(Walking));
}
_ => println!("Running: Event '{}' ignored", event),
}
}
fn name(&self) -> &str {
"Running"
}
}
fn main() {
let mut sm = StateMachine::new(Box::new(Idle));
sm.on_event("walk");
sm.on_event("run");
sm.on_event("stop");
sm.on_event("stop");
sm.on_event("run");
sm.on_event("stop");
sm.on_event("stop");
}
User
error[E0499]: cannot borrow *self as mutable more than once at a time
--> src\main.rs:29:35
|
28 | let state = self.current_state();
| ---- first mutable borrow occurs here
29 | state.on_event(event, self);
| -------- ^^^^ second mutable borrow occurs here
| |
| first borrow later used by call
For more information about this error, try rustc --explain E0499.
error[E0308]: mismatched types
--> src\main.rs:518:21
|
518 | if let Some(Button::Mouse(button)) = event.button_args() {
| ^^^^^^^^^^^^^^^^^^^^^ ------------------- this expression has type Option<ButtonArgs>
| |
| expected ButtonArgs, found Button
For more information about this error, try rustc --explain E0308.
Assistant
這個錯誤是在說:
rust
if let Some(Button::Mouse(button)) = event.button_args() {
if let Some(button_args) = event.button_args() {
if let Button::Mouse(mouse_button) = button_args.button {
// 使用 mouse_button
}
}
或是用一層 match:
rust
if let Some(button_args) = event.button_args() {
match button_args.button {
Button::Mouse(mouse_button) => {
// 這裡處理 mouse_button
}
_ => {}
}
}
修改你程式中 main 的部分:
rust
while let Some(event) = window.next() {
if let Some(button) = event.press_args() {
state_stack.input(button);
}
if let Some(button_args) = event.button_args() {
if let Button::Mouse(mouse_button) = button_args.button {
if let Some(cursor_pos) = event.mouse_cursor_args() {
state_stack.mouse_input(cursor_pos, mouse_button);
}
}
}
if let Some(args) = event.update_args() {
state_stack.update(&args);
}
window.draw_2d(&event, |c, g, device| {
state_stack.render(c, g, &mut glyphs);
glyphs.factory.encoder.flush(device);
});
if state_stack.is_empty() {
break;
}
}
error[E0277]: (dyn State + 'static) doesn't implement Debug
--> src\main.rs:18:10
|
16 | #[derive(Debug)]
| ----- in this derive macro expansion
17 | enum StateCommand {
18 | Push(Box),
| ^^^^^^^^^^^^^^ (dyn State + 'static) cannot be formatted using {:?} because it doesn't implement Debug
|
= help: the trait Debug is not implemented for (dyn State + 'static)
= help: the following other types implement trait Debug:
dyn Any + Send + Sync
dyn Any + Send
dyn Any
error[E0277]: (dyn State + 'static) doesn't implement Debug
--> src\main.rs:20:13
|
16 | #[derive(Debug)]
| ----- in this derive macro expansion
...
20 | Replace(Box),
| ^^^^^^^^^^^^^^ (dyn State + 'static) cannot be formatted using {:?} because it doesn't implement Debug
|
= help: the trait Debug is not implemented for (dyn State + 'static)
= help: the following other types implement trait Debug:
dyn Any + Send + Sync
dyn Any + Send
dyn Any
For more information about this error, try rustc --explain E0277.
Event 'walk' received in state 'Idle'
Pushing state 'Walking'
Event 'run' received in state 'Walking'
Popped state 'Walking', now state is 'Idle'
Pushing state 'Running'
Event 'stop' received in state 'Running'
Popped state 'Running', now state is 'Idle'
Event 'stop' received in state 'Idle'
Idle: Event 'stop' ignored
Event 'run' received in state 'Idle'
Pushing state 'Running'
Event 'stop' received in state 'Running'
Popped state 'Running', now state is 'Idle'
Event 'stop' received in state 'Idle'
Idle: Event 'stop' ignored
說明
StateMachine 的 stack 是狀態堆疊,用來保存目前與過去狀態。
每個狀態實作了 State trait,能對事件反應,根據事件控制狀態入棧(push_state)或出棧(pop_state)。
use std::fmt::Debug;
// 狀態切換指令列舉
#[derive(Debug)]
enum Action {
None,
Push(Box<dyn State>),
Pop,
Replace(Box<dyn State>),
}
// 狀態 Trait
trait State: Debug {
// 接收事件,回傳指令給狀態機做狀態操作
fn on_event(&mut self, event: &str) -> Action;
fn name(&self) -> &str;
}
// 狀態機定義
struct StateMachine {
stack: Vec<Box<dyn State>>,
}
impl StateMachine {
fn new(initial_state: Box<dyn State>) -> Self {
Self {
stack: vec![initial_state],
}
}
fn current_state(&self) -> &Box<dyn State> {
self.stack.last().expect("state stack is empty")
}
fn current_state_mut(&mut self) -> &mut Box<dyn State> {
self.stack.last_mut().expect("state stack is empty")
}
fn on_event(&mut self, event: &str) {
let state_name = self.current_state().name();
println!("Event '{}' received in state '{}'", event, state_name);
// 將事件傳給目前狀態,取得要執行的指令
let action = self.current_state_mut().on_event(event);
// 根據指令操作狀態堆疊
match action {
Action::None => {
// 不做變動
}
Action::Push(state) => {
println!("Pushing state '{}'", state.name());
self.stack.push(state);
}
Action::Pop => {
if self.stack.len() > 1 {
let popped = self.stack.pop().unwrap();
println!("Popped state '{}', now state is '{}'", popped.name(), self.current_state().name());
} else {
println!("Cannot pop the last state!");
}
}
Action::Replace(state) => {
let old = self.stack.pop().unwrap();
println!("Replacing state '{}' with '{}'", old.name(), state.name());
self.stack.push(state);
}
}
}
}
// ----------- 具體狀態實作 -----------
#[derive(Debug)]
struct Idle;
impl State for Idle {
fn on_event(&mut self, event: &str) -> Action {
match event {
"walk" => Action::Push(Box::new(Walking)),
"run" => Action::Push(Box::new(Running)),
_ => {
println!("Idle: Event '{}' ignored", event);
Action::None
}
}
}
fn name(&self) -> &str { "Idle" }
}
#[derive(Debug)]
struct Walking;
impl State for Walking {
fn on_event(&mut self, event: &str) -> Action {
match event {
"stop" => Action::Pop,
"run" => Action::Replace(Box::new(Running)),
_ => {
println!("Walking: Event '{}' ignored", event);
Action::None
}
}
}
fn name(&self) -> &str { "Walking" }
}
#[derive(Debug)]
struct Running;
impl State for Running {
fn on_event(&mut self, event: &str) -> Action {
match event {
"stop" => Action::Pop,
"walk" => Action::Replace(Box::new(Walking)),
_ => {
println!("Running: Event '{}' ignored", event);
Action::None
}
}
}
fn name(&self) -> &str { "Running" }
}
// ----------- 主程式 -----------
fn main() {
let mut sm = StateMachine::new(Box::new(Idle));
sm.on_event("walk");
sm.on_event("run");
sm.on_event("stop");
sm.on_event("stop");
sm.on_event("run");
sm.on_event("stop");
sm.on_event("stop");
}
執行結果
code
Event 'walk' received in state 'Idle'
Pushing state 'Walking'
Event 'run' received in state 'Walking'
Replacing state 'Walking' with 'Running'
Event 'stop' received in state 'Running'
Popped state 'Running', now state is 'Idle'
Event 'stop' received in state 'Idle'
Idle: Event 'stop' ignored
Event 'run' received in state 'Idle'
Pushing state 'Running'
Event 'stop' received in state 'Running'
Popped state 'Running', now state is 'Idle'
Event 'stop' received in state 'Idle'
Idle: Event 'stop' ignored
extern crate piston_window;
use piston_window::*;
use find_folder;
// 頁面識別
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
enum PageId {
Main = 1,
Second = 2,
Third = 3,
}
// 狀態切換指令
enum StateCommand {
Push(Box<dyn State>),
Pop,
Replace(Box<dyn State>),
SwitchPage(PageId),
None,
}
// 狀態 Trait
trait State {
fn update(&mut self, _args: &UpdateArgs) {}
fn input(&mut self, button: Button) -> Option<StateCommand>;
fn mouse_input(&mut self, _cursor: [f64; 2], _button: MouseButton) -> Option<StateCommand> {
None
}
fn render(&mut self, c: Context, g: &mut G2d, glyphs: &mut Glyphs);
}
// 輔助 trait 用於標記頁面ID
trait Page {
fn page_id(&self) -> PageId;
}
// 狀態堆疊結構
struct StateStack {
stack: Vec<Box<dyn State>>,
}
impl StateStack {
fn new(initial_state: Box<dyn State>) -> Self {
Self {
stack: vec![initial_state],
}
}
fn input(&mut self, button: Button) {
if let Some(top) = self.stack.last_mut() {
if let Some(cmd) = top.input(button) {
self.handle_command(cmd);
}
}
}
fn mouse_input(&mut self, cursor: [f64; 2], button: MouseButton) {
if let Some(top) = self.stack.last_mut() {
if let Some(cmd) = top.mouse_input(cursor, button) {
self.handle_command(cmd);
}
}
}
fn handle_command(&mut self, cmd: StateCommand) {
match cmd {
StateCommand::Push(state) => self.push(state),
StateCommand::Pop => self.pop(),
StateCommand::Replace(state) => {
self.stack.pop();
self.stack.push(state);
}
StateCommand::SwitchPage(page) => {
// 回到初始主頁,清空後加推新頁
while self.stack.len() > 1 {
self.pop();
}
match page {
PageId::Main => {}
PageId::Second => self.push(Box::new(SecondPage::new())),
PageId::Third => self.push(Box::new(ThirdPage::new())),
}
}
StateCommand::None => {}
}
}
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 update(&mut self, args: &UpdateArgs) {
if let Some(top) = self.stack.last_mut() {
top.update(args);
}
}
fn render(&mut self, c: Context, g: &mut G2d, glyphs: &mut Glyphs) {
for state in &mut self.stack {
state.render(c, g, glyphs);
}
}
fn is_empty(&self) -> bool {
self.stack.is_empty()
}
}
// =================== MainPage ===================
struct MainPage {
circle_x: f64,
circle_direction: f64,
fps_timer: f64,
fps_count: u32,
fps: u32,
}
impl MainPage {
fn new() -> Self {
Self {
circle_x: 320.0,
circle_direction: 100.0,
fps_timer: 0.0,
fps_count: 0,
fps: 0,
}
}
}
impl Page for MainPage {
fn page_id(&self) -> PageId {
PageId::Main
}
}
impl State for MainPage {
fn update(&mut self, args: &UpdateArgs) {
self.circle_x += self.circle_direction * args.dt;
if self.circle_x > 600.0 {
self.circle_x = 600.0;
self.circle_direction = -self.circle_direction;
} else if self.circle_x < 40.0 {
self.circle_x = 40.0;
self.circle_direction = -self.circle_direction;
}
self.fps_timer += args.dt;
self.fps_count += 1;
if self.fps_timer >= 1.0 {
self.fps = self.fps_count;
self.fps_count = 0;
self.fps_timer -= 1.0;
}
}
fn input(&mut self, button: Button) -> Option<StateCommand> {
if let Button::Keyboard(key) = button {
match key {
Key::M => Some(StateCommand::Push(Box::new(ModalWindow::new()))),
Key::Right => Some(StateCommand::Push(Box::new(SecondPage::new()))),
_ => None,
}
} else {
None
}
}
fn mouse_input(&mut self, cursor: [f64; 2], button: MouseButton) -> Option<StateCommand> {
if button == MouseButton::Left {
let x = cursor[0];
let y = cursor[1];
if x >= 5.0 && x <= 50.0 {
for (i, page) in [PageId::Main, PageId::Second, PageId::Third].iter().enumerate() {
let y_start = 5.0 + (i as f64) * 30.0;
if y >= y_start && y <= y_start + 28.0 {
if *page != self.page_id() {
return Some(StateCommand::SwitchPage(*page));
}
}
}
}
}
None
}
fn render(&mut self, c: Context, g: &mut G2d, glyphs: &mut Glyphs) {
clear([0.8, 0.8, 1.0, 1.0], g);
draw_text_centered("主頁面(按 M 彈出視窗)", c, g, glyphs, 240.0);
graphics::ellipse(
[1.0, 0.0, 0.0, 1.0],
[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([0.0, 0.0, 0.0, 1.0], 24);
text_obj
.draw(
&fps_text,
glyphs,
&graphics::DrawState::default(),
c.transform.trans(10.0, 460.0),
g,
)
.unwrap();
draw_page_numbers(c, g, glyphs, self.page_id());
}
}
// =================== SecondPage ===================
struct SecondPage {
circle_y: f64,
direction: f64,
}
impl SecondPage {
fn new() -> Self {
Self {
circle_y: 240.0,
direction: 120.0,
}
}
}
impl Page for SecondPage {
fn page_id(&self) -> PageId {
PageId::Second
}
}
impl State for SecondPage {
fn update(&mut self, args: &UpdateArgs) {
self.circle_y += self.direction * args.dt;
if self.circle_y > 440.0 {
self.circle_y = 440.0;
self.direction = -self.direction;
} else if self.circle_y < 40.0 {
self.circle_y = 40.0;
self.direction = -self.direction;
}
}
fn input(&mut self, button: Button) -> Option<StateCommand> {
if let Button::Keyboard(key) = button {
match key {
Key::Escape => Some(StateCommand::Pop),
Key::Left => Some(StateCommand::Pop),
_ => None,
}
} else {
None
}
}
fn mouse_input(&mut self, cursor: [f64; 2], button: MouseButton) -> Option<StateCommand> {
if button == MouseButton::Left {
let x = cursor[0];
let y = cursor[1];
if x >= 5.0 && x <= 50.0 {
for (i, page) in [PageId::Main, PageId::Second, PageId::Third].iter().enumerate() {
let y_start = 5.0 + (i as f64) * 30.0;
if y >= y_start && y <= y_start + 28.0 {
if *page != self.page_id() {
return Some(StateCommand::SwitchPage(*page));
}
}
}
}
}
None
}
fn render(&mut self, c: Context, g: &mut G2d, glyphs: &mut Glyphs) {
clear([0.9, 1.0, 0.9, 1.0], g);
draw_text_centered("第二頁(綠色球上下跑)", c, g, glyphs, 240.0);
graphics::ellipse(
[0.0, 0.8, 0.0, 1.0],
[320.0 - 20.0, self.circle_y - 20.0, 40.0, 40.0],
c.transform,
g,
);
draw_page_numbers(c, g, glyphs, self.page_id());
}
}
// =================== ThirdPage ===================
struct ThirdPage {
circle_y: f64,
direction: f64,
}
impl ThirdPage {
fn new() -> Self {
Self {
circle_y: 480.0,
direction: -100.0,
}
}
}
impl Page for ThirdPage {
fn page_id(&self) -> PageId {
PageId::Third
}
}
impl State for ThirdPage {
fn update(&mut self, args: &UpdateArgs) {
self.circle_y += self.direction * args.dt;
if self.circle_y < 40.0 {
self.circle_y = 40.0;
self.direction = -self.direction;
} else if self.circle_y > 480.0 {
self.circle_y = 480.0;
self.direction = -self.direction;
}
}
fn input(&mut self, button: Button) -> Option<StateCommand> {
if let Button::Keyboard(key) = button {
match key {
Key::Escape => Some(StateCommand::Pop),
Key::Left => Some(StateCommand::Pop),
_ => None,
}
} else {
None
}
}
fn mouse_input(&mut self, cursor: [f64; 2], button: MouseButton) -> Option<StateCommand> {
if button == MouseButton::Left {
let x = cursor[0];
let y = cursor[1];
if x >= 5.0 && x <= 50.0 {
for (i, page) in [PageId::Main, PageId::Second, PageId::Third].iter().enumerate() {
let y_start = 5.0 + (i as f64) * 30.0;
if y >= y_start && y <= y_start + 28.0 {
if *page != self.page_id() {
return Some(StateCommand::SwitchPage(*page));
}
}
}
}
}
None
}
fn render(&mut self, c: Context, g: &mut G2d, glyphs: &mut Glyphs) {
clear([0.95, 0.9, 1.0, 1.0], g);
draw_text_centered("第三頁(紫色球由下往上跑)", c, g, glyphs, 240.0);
graphics::ellipse(
[0.6, 0.0, 0.8, 1.0],
[320.0 - 20.0, self.circle_y - 20.0, 40.0, 40.0],
c.transform,
g,
);
draw_page_numbers(c, g, glyphs, self.page_id());
}
}
// =================== ModalWindow ===================
struct ModalWindow {
counter: usize,
}
impl ModalWindow {
fn new() -> Self {
Self { counter: 0 }
}
}
impl State for ModalWindow {
fn input(&mut self, button: Button) -> Option<StateCommand> {
if let Button::Keyboard(key) = button {
match key {
Key::Escape => Some(StateCommand::Pop),
Key::Space => {
self.counter += 1;
println!("計數器增加到 {}", self.counter);
Some(StateCommand::None)
}
_ => None,
}
} else {
None
}
}
fn render(&mut self, c: Context, g: &mut G2d, glyphs: &mut Glyphs) {
graphics::rectangle([0.0, 0.0, 0.0, 0.5], [0.0, 0.0, 640.0, 480.0], c.transform, g);
let rect = [120.0, 140.0, 400.0, 240.0];
graphics::rectangle([1.0, 1.0, 1.0, 1.0], rect, c.transform, g);
let text_obj = graphics::text::Text::new_color([0.0, 0.0, 0.0, 1.0], 32);
text_obj
.draw(
"這是彈出視窗",
glyphs,
&graphics::DrawState::default(),
c.transform.trans(180.0, 200.0),
g,
)
.unwrap();
text_obj
.draw(
"按 ESC 關閉,按空白鍵增加計數器",
glyphs,
&graphics::DrawState::default(),
c.transform.trans(120.0, 240.0),
g,
)
.unwrap();
let counter_str = format!("空白鍵按下次數: {}", self.counter);
text_obj
.draw(
&counter_str,
glyphs,
&graphics::DrawState::default(),
c.transform.trans(180.0, 280.0),
g,
)
.unwrap();
}
}
// =================== 工具函數 ===================
fn draw_text_centered(
text_str: &str,
c: Context,
g: &mut G2d,
glyphs: &mut Glyphs,
y: f64,
) {
use graphics::Transformed;
let text_width = text_str.len() as f64 * 24.0 / 2.0;
let x = 320.0 - text_width;
let transform = c.transform.trans(x, y);
let text_obj = graphics::text::Text::new_color([0.0, 0.0, 0.0, 1.0], 48);
text_obj
.draw(text_str, glyphs, &graphics::DrawState::default(), transform, g)
.unwrap();
}
// 左上角頁碼顯示與互動區域
fn draw_page_numbers(c: Context, g: &mut G2d, glyphs: &mut Glyphs, current: PageId) {
let pages = [
(PageId::Main, "主頁"),
(PageId::Second, "第二頁"),
(PageId::Third, "第三頁"),
];
for (i, (id, name)) in pages.iter().enumerate() {
let y = 5.0 + (i as f64) * 30.0;
let color = if *id == current {
[0.0, 0.0, 1.0, 1.0] // 當前頁藍色標示
} else {
[0.0, 0.0, 0.0, 1.0]
};
let text_obj = graphics::text::Text::new_color(color, 24);
text_obj
.draw(name, glyphs, &graphics::DrawState::default(), c.transform.trans(5.0, y + 20.0), g)
.unwrap();
}
}
// =================== 主程序 ===================
fn main() {
let mut window: PistonWindow = WindowSettings::new("狀態堆疊示例", [640, 480])
.exit_on_esc(true)
.build()
.unwrap();
let assets = find_folder::Search::ParentsThenKids(3, 3)
.for_folder("assets")
.expect("找不到 assets 資料夾");
let font_path = assets.join("mingliu.ttc");
let mut glyphs = window.load_font(font_path).expect("無法載入字型");
let mut state_stack = StateStack::new(Box::new(MainPage::new()));
while let Some(event) = window.next() {
if let Some(button) = event.press_args() {
state_stack.input(button);
}
if let Some(Button::Mouse(button)) = event.button_args() {
if let Some(cursor_pos) = event.mouse_cursor_args() {
state_stack.mouse_input(cursor_pos, button);
}
}
if let Some(args) = event.update_args() {
state_stack.update(&args);
}
window.draw_2d(&event, |c, g, device| {
state_stack.render(c, g, &mut glyphs);
glyphs.factory.encoder.flush(device);
});
if state_stack.is_empty() {
break;
}
}
}
使用說明
左上頁碼可用滑鼠左鍵點擊切換頁面(主頁、第二頁、第三頁)
主頁有紅色圓點左右移動,按 M 開啟 Modal
第二頁有綠色圓點上下移動,ESC 或左鍵返回上一頁(主頁)
第三頁有紫色圓點自底部往上跑,ESC 或左鍵返回上一頁
彈出 Modal 視窗可按空白鍵計數,ESC 關閉
這樣你就有多頁多動畫的互動範例了!若想要我講解或擴充細節,隨時告訴我!祝你開發愉快 🎉🚀
extern crate piston_window;
use piston_window::*;
use find_folder;
// 頁面識別
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
enum PageId {
Main = 1,
Second = 2,
Third = 3,
}
// 狀態切換指令
enum StateCommand {
Push(Box<dyn State>),
Pop,
Replace(Box<dyn State>),
SwitchPage(PageId),
None,
}
// 狀態 Trait
trait State {
fn update(&mut self, _args: &UpdateArgs) {}
fn input(&mut self, button: Button) -> Option<StateCommand>;
fn mouse_input(&mut self, _cursor: [f64; 2], _button: MouseButton) -> Option<StateCommand> {
None
}
fn render(&mut self, c: Context, g: &mut G2d, glyphs: &mut Glyphs);
}
// 輔助 trait 用於標記頁面ID
trait Page {
fn page_id(&self) -> PageId;
}
// 狀態堆疊結構
struct StateStack {
stack: Vec<Box<dyn State>>,
}
impl StateStack {
fn new(initial_state: Box<dyn State>) -> Self {
Self {
stack: vec![initial_state],
}
}
fn input(&mut self, button: Button) {
if let Some(top) = self.stack.last_mut() {
if let Some(cmd) = top.input(button) {
self.handle_command(cmd);
}
}
}
fn mouse_input(&mut self, cursor: [f64; 2], button: MouseButton) {
if let Some(top) = self.stack.last_mut() {
if let Some(cmd) = top.mouse_input(cursor, button) {
self.handle_command(cmd);
}
}
}
fn handle_command(&mut self, cmd: StateCommand) {
match cmd {
StateCommand::Push(state) => self.push(state),
StateCommand::Pop => self.pop(),
StateCommand::Replace(state) => {
self.stack.pop();
self.stack.push(state);
}
StateCommand::SwitchPage(page) => {
// 回到初始主頁,清空後加推新頁
while self.stack.len() > 1 {
self.pop();
}
match page {
PageId::Main => {}
PageId::Second => self.push(Box::new(SecondPage::new())),
PageId::Third => self.push(Box::new(ThirdPage::new())),
}
}
StateCommand::None => {}
}
}
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 update(&mut self, args: &UpdateArgs) {
if let Some(top) = self.stack.last_mut() {
top.update(args);
}
}
fn render(&mut self, c: Context, g: &mut G2d, glyphs: &mut Glyphs) {
for state in &mut self.stack {
state.render(c, g, glyphs);
}
}
fn is_empty(&self) -> bool {
self.stack.is_empty()
}
}
// =================== MainPage ===================
struct MainPage {
circle_x: f64,
circle_direction: f64,
fps_timer: f64,
fps_count: u32,
fps: u32,
}
impl MainPage {
fn new() -> Self {
Self {
circle_x: 320.0,
circle_direction: 100.0,
fps_timer: 0.0,
fps_count: 0,
fps: 0,
}
}
}
impl Page for MainPage {
fn page_id(&self) -> PageId {
PageId::Main
}
}
impl State for MainPage {
fn update(&mut self, args: &UpdateArgs) {
self.circle_x += self.circle_direction * args.dt;
if self.circle_x > 600.0 {
self.circle_x = 600.0;
self.circle_direction = -self.circle_direction;
} else if self.circle_x < 40.0 {
self.circle_x = 40.0;
self.circle_direction = -self.circle_direction;
}
self.fps_timer += args.dt;
self.fps_count += 1;
if self.fps_timer >= 1.0 {
self.fps = self.fps_count;
self.fps_count = 0;
self.fps_timer -= 1.0;
}
}
fn input(&mut self, button: Button) -> Option<StateCommand> {
if let Button::Keyboard(key) = button {
match key {
Key::M => Some(StateCommand::Push(Box::new(ModalWindow::new()))),
Key::Right => Some(StateCommand::Push(Box::new(SecondPage::new()))),
_ => None,
}
} else {
None
}
}
fn mouse_input(&mut self, cursor: [f64; 2], button: MouseButton) -> Option<StateCommand> {
if button == MouseButton::Left {
let x = cursor[0];
let y = cursor[1];
if x >= 5.0 && x <= 50.0 {
for (i, page) in [PageId::Main, PageId::Second, PageId::Third].iter().enumerate() {
let y_start = 5.0 + (i as f64) * 30.0;
if y >= y_start && y <= y_start + 28.0 {
if *page != self.page_id() {
return Some(StateCommand::SwitchPage(*page));
}
}
}
}
}
None
}
fn render(&mut self, c: Context, g: &mut G2d, glyphs: &mut Glyphs) {
clear([0.8, 0.8, 1.0, 1.0], g);
draw_text_centered("主頁面(按 M 彈出視窗)", c, g, glyphs, 240.0);
graphics::ellipse(
[1.0, 0.0, 0.0, 1.0],
[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([0.0, 0.0, 0.0, 1.0], 24);
text_obj
.draw(
&fps_text,
glyphs,
&graphics::DrawState::default(),
c.transform.trans(10.0, 460.0),
g,
)
.unwrap();
draw_page_numbers(c, g, glyphs, self.page_id());
}
}
// =================== SecondPage ===================
struct SecondPage {
circle_y: f64,
direction: f64,
}
impl SecondPage {
fn new() -> Self {
Self {
circle_y: 240.0,
direction: 120.0,
}
}
}
impl Page for SecondPage {
fn page_id(&self) -> PageId {
PageId::Second
}
}
impl State for SecondPage {
fn update(&mut self, args: &UpdateArgs) {
self.circle_y += self.direction * args.dt;
if self.circle_y > 440.0 {
self.circle_y = 440.0;
self.direction = -self.direction;
} else if self.circle_y < 40.0 {
self.circle_y = 40.0;
self.direction = -self.direction;
}
}
fn input(&mut self, button: Button) -> Option<StateCommand> {
if let Button::Keyboard(key) = button {
match key {
Key::Escape => Some(StateCommand::Pop),
Key::Left => Some(StateCommand::Pop),
_ => None,
}
} else {
None
}
}
fn mouse_input(&mut self, cursor: [f64; 2], button: MouseButton) -> Option<StateCommand> {
if button == MouseButton::Left {
let x = cursor[0];
let y = cursor[1];
if x >= 5.0 && x <= 50.0 {
for (i, page) in [PageId::Main, PageId::Second, PageId::Third].iter().enumerate() {
let y_start = 5.0 + (i as f64) * 30.0;
if y >= y_start && y <= y_start + 28.0 {
if *page != self.page_id() {
return Some(StateCommand::SwitchPage(*page));
}
}
}
}
}
None
}
fn render(&mut self, c: Context, g: &mut G2d, glyphs: &mut Glyphs) {
clear([0.9, 1.0, 0.9, 1.0], g);
draw_text_centered("第二頁(綠色球上下跑)", c, g, glyphs, 240.0);
graphics::ellipse(
[0.0, 0.8, 0.0, 1.0],
[320.0 - 20.0, self.circle_y - 20.0, 40.0, 40.0],
c.transform,
g,
);
draw_page_numbers(c, g, glyphs, self.page_id());
}
}
// =================== ThirdPage ===================
struct ThirdPage {
circle_y: f64,
direction: f64,
}
impl ThirdPage {
fn new() -> Self {
Self {
circle_y: 480.0,
direction: -100.0,
}
}
}
impl Page for ThirdPage {
fn page_id(&self) -> PageId {
PageId::Third
}
}
impl State for ThirdPage {
fn update(&mut self, args: &UpdateArgs) {
self.circle_y += self.direction * args.dt;
if self.circle_y < 40.0 {
self.circle_y = 40.0;
self.direction = -self.direction;
} else if self.circle_y > 480.0 {
self.circle_y = 480.0;
self.direction = -self.direction;
}
}
fn input(&mut self, button: Button) -> Option<StateCommand> {
if let Button::Keyboard(key) = button {
match key {
Key::Escape => Some(StateCommand::Pop),
Key::Left => Some(StateCommand::Pop),
_ => None,
}
} else {
None
}
}
fn mouse_input(&mut self, cursor: [f64; 2], button: MouseButton) -> Option<StateCommand> {
if button == MouseButton::Left {
let x = cursor[0];
let y = cursor[1];
if x >= 5.0 && x <= 50.0 {
for (i, page) in [PageId::Main, PageId::Second, PageId::Third].iter().enumerate() {
let y_start = 5.0 + (i as f64) * 30.0;
if y >= y_start && y <= y_start + 28.0 {
if *page != self.page_id() {
return Some(StateCommand::SwitchPage(*page));
}
}
}
}
}
None
}
fn render(&mut self, c: Context, g: &mut G2d, glyphs: &mut Glyphs) {
clear([0.95, 0.9, 1.0, 1.0], g);
draw_text_centered("第三頁(紫色球由下往上跑)", c, g, glyphs, 240.0);
graphics::ellipse(
[0.6, 0.0, 0.8, 1.0],
[320.0 - 20.0, self.circle_y - 20.0, 40.0, 40.0],
c.transform,
g,
);
draw_page_numbers(c, g, glyphs, self.page_id());
}
}
// =================== ModalWindow ===================
struct ModalWindow {
counter: usize,
}
impl ModalWindow {
fn new() -> Self {
Self { counter: 0 }
}
}
impl State for ModalWindow {
fn input(&mut self, button: Button) -> Option<StateCommand> {
if let Button::Keyboard(key) = button {
match key {
Key::Escape => Some(StateCommand::Pop),
Key::Space => {
self.counter += 1;
println!("計數器增加到 {}", self.counter);
Some(StateCommand::None)
}
_ => None,
}
} else {
None
}
}
fn render(&mut self, c: Context, g: &mut G2d, glyphs: &mut Glyphs) {
graphics::rectangle([0.0, 0.0, 0.0, 0.5], [0.0, 0.0, 640.0, 480.0], c.transform, g);
let rect = [120.0, 140.0, 400.0, 240.0];
graphics::rectangle([1.0, 1.0, 1.0, 1.0], rect, c.transform, g);
let text_obj = graphics::text::Text::new_color([0.0, 0.0, 0.0, 1.0], 32);
text_obj
.draw(
"這是彈出視窗",
glyphs,
&graphics::DrawState::default(),
c.transform.trans(180.0, 200.0),
g,
)
.unwrap();
text_obj
.draw(
"按 ESC 關閉,按空白鍵增加計數器",
glyphs,
&graphics::DrawState::default(),
c.transform.trans(120.0, 240.0),
g,
)
.unwrap();
let counter_str = format!("空白鍵按下次數: {}", self.counter);
text_obj
.draw(
&counter_str,
glyphs,
&graphics::DrawState::default(),
c.transform.trans(180.0, 280.0),
g,
)
.unwrap();
}
}
// =================== 工具函數 ===================
fn draw_text_centered(
text_str: &str,
c: Context,
g: &mut G2d,
glyphs: &mut Glyphs,
y: f64,
) {
use graphics::Transformed;
let text_width = text_str.len() as f64 * 24.0 / 2.0;
let x = 320.0 - text_width;
let transform = c.transform.trans(x, y);
let text_obj = graphics::text::Text::new_color([0.0, 0.0, 0.0, 1.0], 48);
text_obj
.draw(text_str, glyphs, &graphics::DrawState::default(), transform, g)
.unwrap();
}
// 左上角頁碼顯示與互動區域
fn draw_page_numbers(c: Context, g: &mut G2d, glyphs: &mut Glyphs, current: PageId) {
let pages = [
(PageId::Main, "主頁"),
(PageId::Second, "第二頁"),
(PageId::Third, "第三頁"),
];
for (i, (id, name)) in pages.iter().enumerate() {
let y = 5.0 + (i as f64) * 30.0;
let color = if *id == current {
[0.0, 0.0, 1.0, 1.0] // 當前頁藍色標示
} else {
[0.0, 0.0, 0.0, 1.0]
};
let text_obj = graphics::text::Text::new_color(color, 24);
text_obj
.draw(name, glyphs, &graphics::DrawState::default(), c.transform.trans(5.0, y + 20.0), g)
.unwrap();
}
}
// =================== 主程序 ===================
fn main() {
let mut window: PistonWindow = WindowSettings::new("狀態堆疊示例", [640, 480])
.exit_on_esc(true)
.build()
.unwrap();
let assets = find_folder::Search::ParentsThenKids(3, 3)
.for_folder("assets")
.expect("找不到 assets 資料夾");
let font_path = assets.join("mingliu.ttc");
let mut glyphs = window.load_font(font_path).expect("無法載入字型");
let mut state_stack = StateStack::new(Box::new(MainPage::new()));
while let Some(event) = window.next() {
if let Some(button) = event.press_args() {
state_stack.input(button);
}
if let Some(button_args) = event.button_args() {
if let Button::Mouse(mouse_button) = button_args.button {
if let Some(cursor_pos) = event.mouse_cursor_args() {
state_stack.mouse_input(cursor_pos, mouse_button);
}
}
}
if let Some(args) = event.update_args() {
state_stack.update(&args);
}
window.draw_2d(&event, |c, g, device| {
state_stack.render(c, g, &mut glyphs);
glyphs.factory.encoder.flush(device);
});
if state_stack.is_empty() {
break;
}
}
}
需要先擴充 State trait 支援 as_any:
rust
use std::any::Any;
trait State {
fn as_any(&self) -> &dyn Any;
// 其他函式省略
}
impl<T: 'static + State> State for T {
fn as_any(&self) -> &dyn Any {
self
}
}