diff --git a/module/keyboard.cpp b/module/keyboard.cpp index 9afb8c9..14a4257 100644 --- a/module/keyboard.cpp +++ b/module/keyboard.cpp @@ -10,22 +10,19 @@ #ifndef _WIN32 static struct termios init_termios; static struct termios new_termios; -static int peek_character=-1; +static int peek_char=-1; int kbhit(){ unsigned char ch=0; int nread=0; - if(peek_character!=-1) + if(peek_char!=-1) return 1; int flag=fcntl(0,F_GETFL); - flag|=O_NONBLOCK; - fcntl(0,F_SETFL,flag); + fcntl(0,F_SETFL,flag|O_NONBLOCK); nread=read(0,&ch,1); - flag&=(~O_NONBLOCK); fcntl(0,F_SETFL,flag); - if(nread==1) - { - peek_character=ch; + if(nread==1){ + peek_char=ch; return 1; } return 0; @@ -33,10 +30,9 @@ int kbhit(){ int getch(){ int ch=0; - if(peek_character!=-1) - { - ch=peek_character; - peek_character=-1; + if(peek_char!=-1){ + ch=peek_char; + peek_char=-1; return ch; } read(0,&ch,1); @@ -57,10 +53,13 @@ extern "C" nasal_ref nas_noblock(std::vector& args,nasal_gc& gc){ } extern "C" nasal_ref nas_init(std::vector& args,nasal_gc& gc){ #ifndef _WIN32 + tcflush(0,TCIOFLUSH); tcgetattr(0,&init_termios); new_termios=init_termios; new_termios.c_lflag&=~(ICANON|ECHO|ECHONL); - new_termios.c_cc[VMIN]=0; + // vmin=0 is nonblock input, but in wsl there is a bug that will block input + // so we use fcntl to write the nonblock input + new_termios.c_cc[VMIN]=1; new_termios.c_cc[VTIME]=0; tcsetattr(0,TCSANOW,&new_termios); #endif @@ -68,8 +67,8 @@ extern "C" nasal_ref nas_init(std::vector& args,nasal_gc& gc){ } extern "C" nasal_ref nas_close(std::vector& args,nasal_gc& gc){ #ifndef _WIN32 - tcsetattr(0,TCSANOW,&init_termios); tcflush(0,TCIOFLUSH); + tcsetattr(0,TCSANOW,&init_termios); #endif return nil; } \ No newline at end of file diff --git a/test/tetris.nas b/test/tetris.nas index b030590..f743401 100644 --- a/test/tetris.nas +++ b/test/tetris.nas @@ -260,6 +260,8 @@ var main=func(){ # windows use chcp 65001 to output unicode if(os.platform()=="windows") system("chcp 65001"); + + libkey.init(); print( "\ec\e[1:1H", "+-------------------------+\n", @@ -275,7 +277,6 @@ var main=func(){ rand(time(0)); var map=mapgen(mapx:12,mapy:15); - libkey.init(); libkey.getch(); print("\ec"); @@ -313,12 +314,13 @@ var main=func(){ } } libkey.close(); - print( map.gameover()? "\e[31mg\e[32ma\e[33mm\e[34me \e[35mo\e[36mv\e[94me\e[31mr \e[32m~\e[0m\n": "\e[31ms\e[32me\e[33me \e[34my\e[35mo\e[36mu \e[94m~\e[0m\n" ); + print("enter anything to quit...\n"); + input(); }; -main(); +main(); \ No newline at end of file