Fork Copy #include #include #include #include #include #include using namespace std; char map[10][5]; int playerX = 2; int lives = 3; int score = 0; void initMap() { for (int i = 0; i < 10; i++) { for (int j = 0; j < 5; j++) { map[i][j] = ' '; } } map[9][playerX] = 'Y'; } void drawMap() { cout << "Lives: " << lives << " Score: " << score << endl; cout << "+-----+" << endl; for (int i = 0; i < 10; i++) { cout << "|"; for (int j = 0; j < 5; j++) { cout << map[i][j]; } cout << "|" << endl; } cout << "+-----+" << endl; cout << "--------------------" << endl; } void generateObstacle() { int col = rand() % 5; if (map[0][col] != 'X') { // Avoid overlapping if already there, but random so ok map[0][col] = 'X'; } } void moveDown() { for (int i = 8; i >= 0; i--) { for (int j = 0; j < 5; j++) { if (map[i][j] == 'X') { map[i][j] = ' '; map[i + 1][j] = 'X'; } } } } bool checkCollision() { return (map[9][playerX] == 'X'); } void movePlayer(char c) { map[9][playerX] = ' '; if ((c == 'A' || c == 'a') && playerX > 0) playerX--; else if ((c == 'D' || c == 'd') && playerX < 4) playerX++; map[9][playerX] = 'Y'; } int main() { srand(time(0)); initMap(); int k; cout << "hay nhap k: "; cin >> k; int turns = 0; cout << "Press A to move left, D to move right, Q to quit." << endl; while (true) { if (_kbhit()) { char c = _getch(); if (c == 'Q' || c == 'q') { cout << "Game quit." << endl; return 0; } movePlayer(c); } this_thread::sleep_for(chrono::milliseconds(500)); moveDown(); if (checkCollision()) { // Clear all X on bottom, including the collision one for (int j = 0; j < 5; j++) { if (map[9][j] == 'X') map[9][j] = ' '; } map[9][playerX] = 'Y'; lives--; if (lives <= 0) { system("cls"); drawMap(); cout << "you lose! Score: " << score << endl; return 0; } } else { // No collision, clear X on bottom for (int j = 0; j < 5; j++) { if (map[9][j] == 'X') map[9][j] = ' '; } score++; } generateObstacle(); turns++; if (turns >= k) { system("cls"); drawMap(); cout << "Thang cuoc Score: " << score << endl; return 0; } system("cls"); drawMap(); } return 0; }