1
1
// Conways game of life
2
2
3
+ extern crate libc;
4
+
5
+ use libc:: { fcntl, F_GETFL , F_SETFL , O_NONBLOCK } ;
3
6
use std:: io:: Stdout ;
4
7
use std:: io:: { stdout, Read , Write } ;
8
+ use std:: os:: unix:: io:: AsRawFd ;
5
9
use std:: sync:: mpsc;
6
10
use std:: thread;
7
11
use termion:: clear;
@@ -21,29 +25,36 @@ fn main() {
21
25
let height = height as usize ;
22
26
let mut world = World :: new ( width, height) ;
23
27
24
- let mut buffer = [ 0u8 ; 1 ] ;
25
-
26
- let ( tx, rx) = mpsc:: channel ( ) ;
27
-
28
- let input_thread = thread:: spawn ( move || {
29
- loop {
30
- match stdin. read ( & mut buffer) {
31
- Ok ( 0 ) => { } // No input available, continue the loop
32
- Ok ( _) => {
33
- tx. send ( buffer[ 0 ] ) . unwrap ( ) ;
34
- }
35
- Err ( e) => eprintln ! ( "Error reading from stdin: {}" , e) ,
36
- }
28
+ // Set stdin to non-blocking
29
+ unsafe {
30
+ let fd = std:: io:: stdin ( ) . as_raw_fd ( ) ;
31
+ let flags = fcntl ( fd, F_GETFL , 0 ) ;
32
+ if flags != -1 {
33
+ fcntl ( fd, F_SETFL , flags | O_NONBLOCK ) ;
37
34
}
38
- } ) ;
35
+ }
36
+
37
+ let mut buffer = [ 0u8 ; 1 ] ;
39
38
40
39
let mut on = false ;
40
+ let read_char_time = 100 ;
41
+ let mut read_char_timer = 0 ;
42
+ let mut read_char = true ;
41
43
world. randomize ( ) ;
42
44
home ( width, height, & mut stdout) ;
43
45
loop {
44
- match rx. try_recv ( ) {
45
- Ok ( input) => {
46
- match input {
46
+ read_char_timer -= 1 ;
47
+ if read_char_timer <= 0 {
48
+ read_char = true ;
49
+ read_char_timer = read_char_time;
50
+ }
51
+ if read_char {
52
+ match std:: io:: stdin ( ) . read ( & mut buffer) {
53
+ Ok ( 0 ) => {
54
+ // std::thread::sleep(std::time::Duration::from_millis(100));
55
+ }
56
+ Ok ( _) => {
57
+ match buffer[ 0 ] {
47
58
b'q' => break , // Exit the loop when 'q' is pressed.
48
59
b'r' => world. randomize ( ) , // Randomize the world when 'r' is pressed
49
60
b' ' => on = !on, // Start/stop the world when 's' is pressed
@@ -53,9 +64,12 @@ fn main() {
53
64
, // Home screen when 'h' is pressed
54
65
_ => { } // Ignore other inputs
55
66
}
67
+ }
68
+ Err ( e) => {
69
+ // eprintln!("Error reading from stdin: {}", e);
70
+ // std::thread::sleep(std::time::Duration::from_millis(100));
71
+ }
56
72
}
57
- Err ( mpsc:: TryRecvError :: Empty ) => { } // No input available, continue the loop
58
- Err ( mpsc:: TryRecvError :: Disconnected ) => break , // Input thread has terminated, exit the loop
59
73
}
60
74
61
75
// when user presses q, exit the loop
0 commit comments