How to eliminate screen flickering caused by system("cls") in the console game?
Assistant
User
How to modify the existing snake game code to implement double buffering while preserving the original game mechanics and preventing memory leaks during screen resizing events?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
2. Cập nhật có chọn lọc (Chỉ vẽ lại phần thay đổi)
cpp
// Thay thế system("cls") bằng hàm này
void SmartClear() {
static CHAR_INFO clearBuffer[(width + 2) * (height + 3)];
memset(clearBuffer, 0, sizeof(clearBuffer));
WriteConsoleOutput(hStdOut, clearBuffer, bufferSize, bufferCoord, &writeRegion);
}
// Trong hàm Draw:
void Draw() {
ClearBuffer();
// Vẽ tường và các thành phần game vào buffer
for (int i = 0; i < width + 2; i++) {
DrawToBuffer(i, 0, L'#');
DrawToBuffer(i, height + 1, L'#');
}
// Vẽ rắn và thức ăn...
Render(); // Hiển thị buffer
}
3. Sử dụng Console Virtual Terminal Sequences (Windows 10+)
cpp
void EnableVTMode() {
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD dwMode = 0;
GetConsoleMode(hOut, &dwMode);
dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
SetConsoleMode(hOut, dwMode);
}
// Trong Draw():
cout << "\x1b[H"; // Di chuyển con trỏ về góc trên cùng bên trái
// Vẽ frame mới
Chọn phương pháp phù hợp nhất với phiên bản Windows và trình biên dịch của bạn. Phương pháp Double Buffering thường mang lại kết quả tốt nhất cho các game console phức tạp.
Đây là cách triển khai Double Buffering cho game rắn săn mồi với các cải tiến về quản lý bộ nhớ và xử lý thay đổi kích thước màn hình:
cpp
#include <iostream>
#include <conio.h>
#include <windows.h>
#include <vector>
#include <memory>
using namespace std;
const int width = 40;
const int height = 20;
enum Direction { STOP = 0, LEFT, RIGHT, UP, DOWN };
Direction dir;
struct Point {
int x, y;
};
// Double Buffer components
HANDLE hStdOut;
unique_ptr<CHAR_INFO[]> buffer;
COORD bufferSize;
SMALL_RECT writeRegion;
void InitConsole() {
hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
// Cố định kích thước cửa sổ
COORD coord = { (SHORT)(width + 2), (SHORT)(height + 3) };
SetConsoleScreenBufferSize(hStdOut, coord);
SetConsoleWindowInfo(hStdOut, TRUE, &{ 0, 0, (SHORT)(width + 1), (SHORT)(height + 2) });
// Ẩn con trỏ và scrollbar
CONSOLE_CURSOR_INFO cursorInfo = { 1, FALSE };
SetConsoleCursorInfo(hStdOut, &cursorInfo);
}
void InitBuffer() {
bufferSize = { (SHORT)(width + 2), (SHORT)(height + 3) };
buffer = make_unique<CHAR_INFO[]>(bufferSize.X * bufferSize.Y);
writeRegion = { 0, 0, (SHORT)(width + 1), (SHORT)(height + 2) };
}
void ClearBuffer() {
for (int i = 0; i < bufferSize.X * bufferSize.Y; ++i) {
buffer[i].Char.UnicodeChar = L' ';
buffer[i].Attributes = FOREGROUND_GREEN | FOREGROUND_INTENSITY;
}
}
void DrawToBuffer(int x, int y, wchar_t c, WORD attr = FOREGROUND_GREEN | FOREGROUND_INTENSITY) {
if (x >= 0 && x < bufferSize.X && y >= 0 && y < bufferSize.Y) {
buffer[y * bufferSize.X + x].Char.UnicodeChar = c;
buffer[y * bufferSize.X + x].Attributes = attr;
}
}
void Render() {
WriteConsoleOutput(hStdOut, buffer.get(), bufferSize, { 0, 0 }, &writeRegion);
}
// Game components
bool gameOver;
Point head;
vector<Point> body;
Point fruit;
int score;
void Setup() {
gameOver = false;
dir = STOP;
head = { width / 2, height / 2 };
fruit = { rand() % width, rand() % height };
score = 0;
body.clear();
}
void Draw() {
ClearBuffer();
// Vẽ tường
for (int x = 0; x < width + 2; x++) {
DrawToBuffer(x, 0, L'#');
DrawToBuffer(x, height + 1, L'#');
}
// Vẽ rắn
DrawToBuffer(head.x + 1, head.y + 1, L'O');
for (auto &segment : body) {
DrawToBuffer(segment.x + 1, segment.y + 1, L'o');
}
// Vẽ thức ăn
DrawToBuffer(fruit.x + 1, fruit.y + 1, L'F');
// Vẽ điểm
string scoreStr = "Score: " + to_string(score);
for (size_t i = 0; i < scoreStr.size(); ++i) {
DrawToBuffer(i, height + 2, scoreStr[i]);
}
Render();
}
void Input() {
if (_kbhit()) {
switch (_getch()) {
case 72: if (dir != DOWN) dir = UP; break;
case 80: if (dir != UP) dir = DOWN; break;
case 75: if (dir != RIGHT) dir = LEFT; break;
case 77: if (dir != LEFT) dir = RIGHT; break;
case 'x': gameOver = true; break;
}
}
}
void Logic() {
if (!body.empty()) {
body.insert(body.begin(), head);
body.pop_back();
}
switch (dir) {
case LEFT: head.x--; break;
case RIGHT: head.x++; break;
case UP: head.y--; break;
case DOWN: head.y++; break;
}
if (head.x < 0 || head.x >= width || head.y < 0 || head.y >= height)
gameOver = true;
if (head.x == fruit.x && head.y == fruit.y) {
score += 10;
body.push_back(head);
fruit = { rand() % width, rand() % height };
}
for (auto &segment : body)
if (segment.x == head.x && segment.y == head.y)
gameOver = true;
}
int main() {
InitConsole();
InitBuffer();
Setup();
while (!gameOver) {
Draw();
Input();
Logic();
Sleep(100);
}
// Cleanup
string gameOverText = "GAME OVER! Final Score: " + to_string(score);
ClearBuffer();
for (size_t i = 0; i < gameOverText.size(); ++i) {
DrawToBuffer(i, height / 2 + 1, gameOverText[i]);
}
Render();
Sleep(2000);
return 0;
}
Những cải tiến chính trong phiên bản này:
Quản lý bộ nhớ an toàn:
Sử dụng unique_ptr cho buffer để tự động giải phóng bộ nhớ
Khởi tạo buffer một lần duy nhất khi bắt đầu chương trình
Xử lý thay đổi kích thước màn hình:
Cố định kích thước console bằng SetConsoleScreenBufferSize
Vô hiệu hóa scrollbar
Sử dụng buffer có kích thước cố định phù hợp với game
Tối ưu hóa hiệu năng:
Loại bỏ hoàn toàn system("cls)
Giảm số lần gọi API Windows
Sử dụng thao tác buffer hiệu quả
Cấu trúc lại code:
Tách biệt phần xử lý đồ họa và game logic
Dễ dàng mở rộng các thành phần đồ họa
Hỗ trợ thêm màu sắc và ký tự Unicode
Xử lý thoát game an toàn:
Dọn dẹp buffer trước khi hiển thị thông báo kết thúc
Tự động giải phóng tài nguyên khi kết thúc chương trình
Để sử dụng code này:
Biên dịch với C++17 hoặc mới hơn
Chạy trên Windows 10/11
Đảm bảo console sử dụng font hỗ trợ Unicode (Consolas hoặc Lucida Console)
Các phím điều khiển và game logic được giữ nguyên so với phiên bản gốc, chỉ thay đổi phần xử lý đồ họa để triển khai double buffering.