11// Conways game of life
22
3+ extern crate libc;
4+
5+ use libc:: { fcntl, F_GETFL , F_SETFL , O_NONBLOCK } ;
36use std:: io:: Stdout ;
47use std:: io:: { stdout, Read , Write } ;
8+ use std:: os:: unix:: io:: AsRawFd ;
59use std:: sync:: mpsc;
610use std:: thread;
711use termion:: clear;
@@ -21,29 +25,36 @@ fn main() {
2125 let height = height as usize ;
2226 let mut world = World :: new ( width, height) ;
2327
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 ) ;
3734 }
38- } ) ;
35+ }
36+
37+ let mut buffer = [ 0u8 ; 1 ] ;
3938
4039 let mut on = false ;
40+ let read_char_time = 100 ;
41+ let mut read_char_timer = 0 ;
42+ let mut read_char = true ;
4143 world. randomize ( ) ;
4244 home ( width, height, & mut stdout) ;
4345 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 ] {
4758 b'q' => break , // Exit the loop when 'q' is pressed.
4859 b'r' => world. randomize ( ) , // Randomize the world when 'r' is pressed
4960 b' ' => on = !on, // Start/stop the world when 's' is pressed
@@ -53,9 +64,12 @@ fn main() {
5364 , // Home screen when 'h' is pressed
5465 _ => { } // Ignore other inputs
5566 }
67+ }
68+ Err ( e) => {
69+ // eprintln!("Error reading from stdin: {}", e);
70+ // std::thread::sleep(std::time::Duration::from_millis(100));
71+ }
5672 }
57- Err ( mpsc:: TryRecvError :: Empty ) => { } // No input available, continue the loop
58- Err ( mpsc:: TryRecvError :: Disconnected ) => break , // Input thread has terminated, exit the loop
5973 }
6074
6175 // when user presses q, exit the loop
0 commit comments