WSL Ubuntu中fflush(stdout)无效,俄罗斯方块界面无法更新求助
解决俄罗斯方块游戏场地重复打印而非更新的问题
你的核心问题是:fflush(stdout)仅负责刷新输出缓冲区,让内容立刻显示,但不会清除终端中已打印的内容,所以每次调用printTetGame都会在原有输出后追加新的场地,导致重复打印。要实现场地更新,需要主动清除终端旧内容或让光标回到起始位置重写。
解决方案
以下是两种通用的处理方式,根据你的操作系统选择:
1. 使用ANSI转义序列(跨平台,适用于Linux/macOS/Windows 10+)
在打印场地前,输出ANSI清屏并定位光标到左上角的指令,这样新的场地会覆盖旧内容:
#include <stdio.h> void printTetGame(TetGame *tetg) { // 清屏并将光标移至终端左上角 printf("\033[H\033[2J"); TetField *tf = tetg->field; TetFigure *t = tetg->figure; for (int i = 0; i < tf->height; i++) { for (int j = 0; j < tf->width; j++) { int sym = 0; if (tf->blocks[i * tf->width + j].b != 0) sym = 1; else { int x = j - t->x; int y = i - t->y; if (x >= 0 && x < t->size && y >= 0 && y < t->size) if (t->blocks[y * t->size + x].b != 0) sym = 1; } printf("%d", sym); } // 每行结束添加换行,让场地结构更清晰 printf("\n"); } fflush(stdout); };
2. Windows专属清屏命令(适用于Windows 7及更早版本)
如果你的系统不支持ANSI转义序列,可以使用Windows自带的清屏命令:
#include <stdio.h> #include <stdlib.h> // 需包含头文件以使用system函数 void printTetGame(TetGame *tetg) { system("cls"); // Windows终端清屏命令 TetField *tf = tetg->field; TetFigure *t = tetg->figure; for (int i = 0; i < tf->height; i++) { for (int j = 0; j < tf->width; j++) { int sym = 0; if (tf->blocks[i * tf->width + j].b != 0) sym = 1; else { int x = j - t->x; int y = i - t->y; if (x >= 0 && x < t->size && y >= 0 && y < t->size) if (t->blocks[y * t->size + x].b != 0) sym = 1; } printf("%d", sym); } printf("\n"); } fflush(stdout); };
补充说明
- 原代码中没有每行换行,导致场地内容挤在一行,添加
printf("\n")可以让场地的行列结构正常显示。 fflush(stdout)仍然需要保留,确保每次打印的内容立刻输出到终端,避免因缓冲区延迟导致的显示滞后。
内容的提问来源于stack exchange,提问作者Иванов Леонид
相关产品推荐
相关产品推荐

