Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change terminal cursor position in Rust

Tags:

rust

In order to write a game, I need to write some characters at different positions in the terminal. I used

println!("{c:>width$}", c="*", width=x);

It's almost OK with the x position, but I want to change the y position, when I press space. Is there any way to do it?

like image 895
Saeed M. Avatar asked Nov 04 '16 15:11

Saeed M.


3 Answers

For terminal control I would recommend using a crate such as Termion. With Termion it looks something like:

fn main() {
    let mut stdout = stdout().into_raw_mode().unwrap();

    writeln!(stdout, "{}Placed at 3,7",
       termion::cursor::Goto(3, 7));
}

See the examples.

like image 169
Chris Emerson Avatar answered Oct 08 '22 23:10

Chris Emerson


You could also use ncurses-rs, which is a thin wrapper around the ncurse library, or Cursive, which is a bit higher level and allow you to create various widgets in the Terminal.

like image 36
Xavier T. Avatar answered Oct 09 '22 00:10

Xavier T.


You could use crossterm_cursor for this, it provides you a way to deal with cursor movement and a lot of other cross-platform stuff.

use crossterm::cursor;

let mut cursor = cursor();

/// Moving the cursor
// Set the cursor to position X: 10, Y: 5 in the terminal
cursor.goto(10,5);

// Move the cursor up,right,down,left 3 cells.
cursor.move_up(3);
cursor.move_right(3);
cursor.move_down(3);
cursor.move_left(3);

/// Safe the current cursor position to recall later
// Goto X: 5 Y: 5
cursor.goto(5,5);
// Safe cursor position: X: 5 Y: 5
cursor.save_position();
// Goto X: 5 Y: 20
cursor.goto(5,20);
// Print at X: 5 Y: 20.
print!("Yea!");
// Reset back to X: 5 Y: 5.
cursor.reset_position();
// Print 'Back' at X: 5 Y: 5.
print!("Back");

// hide cursor
cursor.hide();
// show cursor
cursor.show();
// blink or not blinking of the cursor (not widely supported)
cursor.blink(true)

You might as well use crossterm to do this, but that will include non-cursor related functionalities as well. An other possibility is, to use the command api. Please check out the examples for more information about the cursor functionalities.

like image 1
Timon Post Avatar answered Oct 09 '22 00:10

Timon Post