use anyhow::Result; use gilrs::{Axis, Button, EventType}; use io::Write; use std::{io, thread, time::Duration}; fn main() -> Result<()> { use gilrs::{Button, Event, Gilrs}; let mut gilrs = Gilrs::new().unwrap(); // Iterate over all connected gamepads for (_id, gamepad) in gilrs.gamepads() { eprintln!("{} is {:?}", gamepad.name(), gamepad.power_info()); } let mut alter_x: f32 = 0.; let mut alter_y: f32 = 0.; let mut old_alter_y: f32 = 0.; let mut last_v: f32 = 0.; let mut was_x = false; let mut is_one = false; let mut is_jump = false; let mut velocity = 1.0; let mut active_gamepad = None; loop { let mut line = String::new(); io::stdin().read_line(&mut line)?; let frame: Vec<(f32, f32, u32)> = serde_json::from_str(&line)?; // Examine new events if let Some(Event { id, event, time }) = gilrs.next_event() { // eprintln!("{:?} New event from {}: {:?}", time, id, event); active_gamepad = Some(id); // match event { // EventType::AxisChanged(axis, v, _code) => { // if axis == Axis::LeftStickX { // alter_x -= 1.; // // was_x = true; // } else if axis == Axis::LeftStickY { // alter_y -= 1.; // // was_x = false; // } // } // _ => {} // } } // if is_one { // if was_x { // alter_x -= 1.0; // } else { // alter_y -= 1.0; // } // } if let Some(active_gamepad) = active_gamepad { let gp = gilrs.gamepad(active_gamepad); { let velocity = 0.5; let (sx, sy) = (gp.value(Axis::LeftStickX), gp.value(Axis::LeftStickY)); if sx.abs() > 0.5 || sy.abs() > 0.5 { if sx.abs() > 0.5 { alter_x -= velocity * sx.signum(); } if !is_jump { if sy.abs() > 0.5 { alter_y -= velocity * sy.signum(); } } } } if gp.is_pressed(Button::South) && !is_jump { is_jump = true; old_alter_y = alter_y; velocity = 1.0; } } if is_jump { if velocity >= -1. { alter_y -= velocity; velocity -= 0.05; } else { is_jump = false; alter_y = old_alter_y; } eprintln!("Jump: alter_y: {:?}", alter_y); } let altered_frame: Vec<(f32, f32, u32)> = frame .iter() .map(|(x, y, color)| { let mut new_x = if *x + alter_x * 10. >= 800. { 800. } else { *x + alter_x * 10. }; let mut new_y = if *y + alter_y * 10. >= 800. { 800. } else { *y + alter_y * 10. }; if new_x < 0. { new_x = 0.; } if new_y < 0. { new_y = 0.; } (new_x, new_y, *color) }) .collect(); serde_json::to_writer(io::stdout(), &altered_frame)?; io::stdout().write(b"\n")?; io::stdout().flush()?; // serde_json::to_writer(io::stderr(), &altered_frame)?; // io::stderr().write(b"\n")?; // io::stderr().flush()?; } }