use std::fs::File;
use std::io::{Write, BufWriter};
enum PlayerAction {
Move(i32, i32),
Attack(String),
Defend(i32)
}
fn handle_player_action(action: PlayerAction) {
let log_file = File::create("game_log.txt").expect("Failed to create log file");
let mut log_writer = BufWriter::new(log_file);
match action {
PlayerAction::Move(x, y) => {
writeln!(log_writer, "Player moved to ({}, {})", x, y).expect("Failed to write to log");
println!("Player moved to ({}, {})", x, y);
},
PlayerAction::Attack(attack_type) => {
let attack_power = if attack_type == "special_attack" {
200 // 假设特殊攻击攻击力翻倍为200
} else {
100 // 普通攻击攻击力为100
};
writeln!(log_writer, "Player attacked with type: {}, power: {}", attack_type, attack_power).expect("Failed to write to log");
println!("Player attacked with type: {}, power: {}", attack_type, attack_power);
},
PlayerAction::Defend(power) => {
writeln!(log_writer, "Player defended with power: {}", power).expect("Failed to write to log");
println!("Player defended with power: {}", power);
}
}
}
高效匹配与处理的原因
- 模式匹配的高效性:Rust 的
match
语句采用了类似 switch - case
的高效匹配机制,在编译期会生成高效的跳转表(对于简单类型和枚举),所以匹配不同的 PlayerAction
变体时效率很高。
- 针对性处理:对于
Attack
动作,在匹配时直接判断攻击类型字符串,避免了额外的条件判断嵌套,代码逻辑清晰,提高了处理效率。
- 日志记录:在每个匹配分支中直接进行日志记录,保证了所有动作处理的即时记录,没有额外的性能开销。