Small 2048 game in Rust
Commit 757e6cdd7477
tarball1 file changed+35-11
@@ -3,6 +3,39 @@ use std::io::{Read, stdin};
33
use std::os::unix::io::AsRawFd;44
use termios::*;55
6
+#[derive(Debug, Clone, Copy)]7
+pub struct TermMode {8
+ original: Termios,9
+ fd: i32,10
+}11
+12
+impl TermMode {13
+ pub fn new() -> Self {14
+ let fd = stdin().as_raw_fd();15
+16
+ let original = Termios::from_fd(fd).unwrap();17
+18
+ Self { original, fd }19
+ }20
+21
+ pub fn non_canon(&self) -> Self {22
+ let mut new = self.original.clone();23
+ new.c_lflag &= !(ECHO | ICANON);24
+ new.c_cc[VMIN] = 1;25
+ new.c_cc[VTIME] = 0;26
+27
+ tcsetattr(self.fd, TCSANOW, &new).unwrap();28
+29
+ *self30
+ }31
+32
+ pub fn put_back(&self) -> Self {33
+ tcsetattr(self.fd, TCSANOW, &self.original).unwrap();34
+35
+ *self36
+ }37
+}38
+639
#[derive(Debug, PartialEq)]740
enum Direction {841
Up,@@ -152,16 +185,7 @@ fn get_direction(input: u8) -> Option<Direction> {
152185
}153186
154187
fn main() {155
- let fd = stdin().as_raw_fd();156
-157
- let old = Termios::from_fd(fd).unwrap();158
- let mut new = old.clone();159
-160
- new.c_lflag &= !(ECHO | ICANON);161
- new.c_cc[VMIN] = 1;162
- new.c_cc[VTIME] = 0;163
-164
- tcsetattr(fd, TCSANOW, &new).unwrap();188
+ let mut term_mode = TermMode::new().non_canon();165189
166190
let mut field: [[u16; 4]; 4] = [[0; 4]; 4];167191
@@ -208,5 +232,5 @@ fn main() {
208232
print_field(field);209233
io::stdout().flush().unwrap();210234
211
- tcsetattr(fd, TCSANOW, &old).unwrap();235
+ term_mode.put_back();212236
}