use pistonwindow::{PistonWindow, WindowSettings}; use pistonwindow::{Button as…
- User
use piston_window::{PistonWindow, WindowSettings}; use piston_window::{Button as PistonButton, MouseButton, Key}; use piston_window::PressEvent; use piston_window::MouseCursorEvent; use piston_window::{Context, Graphics}; use piston_window::EventLoop; // 引入 EventLoop trait use serde::{Deserialize, Serialize}; use std::fs; use chrono::Local;
const PLAYER_SIZE: f64 = 40.0; const OBJECT_SIZE: f64 = 30.0; const WINDOW_WIDTH: f64 = 640.0; const WINDOW_HEIGHT: f64 = 480.0;
#[derive(Serialize, Deserialize, Clone)] struct GameData { player_x: f64, player_y: f64, objects_collected: [bool; 2], }
struct Button { rect: [f64; 4], // x, y, w, h label: String, last_saved_time: Option, }
impl Button { fn draw<G: Graphics>(&self, c: Context, g: &mut G) { piston_window::rectangle([0.7, 0.7, 0.7, 1.0], self.rect, c.transform, g); if let Some(time) = &self.last_saved_time { println!("{} 時間: {}", self.label, time); } }
codefn is_pressed(&self, x: f64, y: f64) -> bool { let [bx, by, bw, bh] = self.rect; x >= bx && x <= bx + bw && y >= by && y <= by + bh }}
struct Game { player_x: f64, player_y: f64, objects_collected: [bool; 2], buttons_save: [Button; 2], buttons_load: [Button; 2], loading: bool, loading_alpha: f32, }
impl Game { fn new() -> Self { Self { player_x: 100.0, player_y: 100.0, objects_collected: [false, false], buttons_save: [ Button { rect: [10.0, 400.0, 100.0, 40.0], label: "Save 1".to_string(), last_saved_time: None }, Button { rect: [130.0, 400.0, 100.0, 40.0], label: "Save 2".to_string(), last_saved_time: None }, ], buttons_load: [ Button { rect: [10.0, 450.0, 100.0, 40.0], label: "Load 1".to_string(), last_saved_time: None }, Button { rect: [130.0, 450.0, 100.0, 40.0], label: "Load 2".to_string(), last_saved_time: None }, ], loading: false, loading_alpha: 0.0, } }
code - Assistant
- User
完整的程式碼
- Assistant
- User
error[E0502]: cannot borrow
gameas mutable because it is also borrowed as immutable --> src\main.rs:200:21 | 198 | for (i, btn) in game.buttons_save.iter().enumerate() { | ------------------------------------ | | | immutable borrow occurs here | immutable borrow later used here 199 | if btn.is_pressed(x, y) { 200 | game.save(i); | ^^^^^^^^^^^^ mutable borrow occurs hereerror[E0502]: cannot borrow
gameas mutable because it is also borrowed as immutable --> src\main.rs:206:21 | 204 | for (i, btn) in game.buttons_load.iter().enumerate() { | ------------------------------------ | | | immutable borrow occurs here | immutable borrow later used here 205 | if btn.is_pressed(x, y) { 206 | game.load(i); | ^^^^^^^^^^^^ mutable borrow occurs hereFor more information about this error, try
rustc --explain E0502. error: could not compilemy_project(bin "my_project") due to 2 previous errors - Assistant
這個錯誤是 Rust 的借用檢查器 (borrow checker) 在告訴你:
- User
完整的程式碼
- Assistant