刷题:数码管和按键计数,按键缓存如何清理?

x33g5p2x  于2022-06-20 转载在 其他  
字(2.8k)|赞(0)|评价(0)|浏览(356)

【题目】一个启动键、一个打击键,数码管4位,显示数字从0循环显示到99, 每0.5秒增加一个数字,中间随时按下按键,按下按键时若恰好循环数字尾数为3和4,每成功一次计1分,1次循环结束,分值大于10分则显示 (C 分值 倒C) 表示胜利,否则显示FALE表示失败。

【代码】基本实现题目需要,但是碰到一个问题:按键缓存影响计数,如何解决?

  1. #include<stdio.h>
  2. #include<conio.h>
  3. #include<windows.h>
  4. void gotoXY(int x, int y)
  5. {
  6. COORD coord = {(short)x, (short)y};
  7. SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
  8. }
  9. void saymsg(int x, int y, char*s)
  10. {
  11. gotoXY(x,y);
  12. printf("%s",s);
  13. }
  14. void display(int x, int y, int n)
  15. {
  16. char num[16][6][6] = {
  17. {{" ___ "},{"| |"},{"| |"},{"| |"},{"|___|"}},
  18. {{" "},{" |"},{" |"},{" |"},{" |"}},
  19. {{" ___ "},{" |"},{" ___|"},{"| "},{"|___ "}},
  20. {{" ___ "},{" |"},{" ___|"},{" |"},{" ___|"}},
  21. {{" "},{"| |"},{"|___|"},{" |"},{" |"}},
  22. {{" ___ "},{"| "},{"|___ "},{" |"},{" ___|"}},
  23. {{" ___ "},{"| "},{"|___ "},{"| |"},{"|___|"}},
  24. {{" ___ "},{" |"},{" |"},{" |"},{" |"}},
  25. {{" ___ "},{"| |"},{"|___|"},{"| |"},{"|___|"}},
  26. {{" ___ "},{"| |"},{"|___|"},{" |"},{" ___|"}},
  27. {{" ___ "},{"| "},{"| "},{"| "},{"|___ "}},
  28. {{" ___ "},{" |"},{" |"},{" |"},{" ___|"}},
  29. {{" ___ "},{"| "},{"|___ "},{"| "},{"| "}},
  30. {{" ___ "},{"| |"},{"|___|"},{"| |"},{"| |"}},
  31. {{" "},{"| "},{"| "},{"| "},{"|___ "}},
  32. {{" ___ "},{"| "},{"|___ "},{"| "},{"|___ "}},
  33. };
  34. for (int i=0;i<5;i++)
  35. saymsg(x,y+i,num[n][i]);
  36. }
  37. int main()
  38. {
  39. int x = 30, y = 8, key;
  40. int scores = 0;
  41. display(x,y,10);
  42. display(x+6,y,0);
  43. display(x+12,y,0);
  44. display(x+18,y,11);
  45. saymsg(x,y+6,(char*)"回车键开始,空格键计数");
  46. while (1){
  47. if (kbhit()){
  48. key = getch();
  49. if (key==13)
  50. break;
  51. }
  52. }
  53. for (int i=0;i<10;i++){
  54. display(x+6,y,i);
  55. for (int j=0;j<10;j++){
  56. display(x+12,y,j);
  57. if (kbhit()) {
  58. key = getch();
  59. fflush(stdin);
  60. //按键缓存影响计数如何解决?
  61. if(key==32 && (j==3||j==4))
  62. scores++;
  63. key = 0;
  64. //以下两行测试用
  65. gotoXY(x,y+9);
  66. printf("%d",scores);
  67. }
  68. Sleep(500);
  69. }
  70. }
  71. if (scores>10){
  72. display(x+6,y,11);
  73. display(x+12,y,11);
  74. saymsg(x,y+9,(char*)"Victory!\n");
  75. }
  76. else{
  77. for (int i=0;i<4;i++)
  78. display(x+i*6,y,i+12);
  79. saymsg(x,y+9,(char*)"FAIL\n");
  80. }
  81. return 0;
  82. }

关于清理按键缓存除了用

fflush(stdin);

还试了:

rewind(stdin);
setbuf(stdin, NULL);

甚至还试了中断:

union REGS regs;
regs.h.ah = 0x0c;
regs.h.al = 0;
intdos(&regs, &regs);

好像都不管用,试了很多个办法都没成功,经过的达人来指点一下吧。

相关文章