#include <iostream>
#include <vector>
#include <conio.h>
#include <windows.h>
#include <time.h>using namespace std;// 游戲常量
const int WIDTH = 40;
const int HEIGHT = 20;
const int PADDLE_WIDTH = 5;// 方向枚舉
enum Direction { STOP = 0, LEFT, RIGHT };class BreakoutGame {
private:int ballX, ballY; // 球的位置int ballDirX, ballDirY; // 球的方向int paddleX; // 擋板位置int score; // 分數bool gameOver; // 游戲結束標志vector<vector<bool>> bricks; // 磚塊矩陣public:BreakoutGame() {// 初始化游戲狀態resetGame();}// 重置游戲void resetGame() {ballX = WIDTH / 2;ballY = HEIGHT - 5;ballDirX = 1;ballDirY = -1;paddleX = (WIDTH - PADDLE_WIDTH) / 2;score = 0;gameOver = false;// 初始化磚塊bricks.resize(5, vector<bool>(WIDTH - 2, true));}// 繪制游戲界面void draw() {system("cls"); // 清屏// 繪制頂部邊界for (int i = 0; i < WIDTH + 2; i++)cout << "#";cout << endl;// 繪制游戲區域for (int i = 0; i < HEIGHT; i++) {for (int j = 0; j < WIDTH; j++) {if (j == 0)cout << "#"; // 左邊界// 繪制球if (i == ballY && j == ballX)cout << "O";// 繪制擋板else if (i == HEIGHT - 1 && j >= paddleX && j < paddleX + PADDLE_WIDTH)cout << "=";// 繪制磚塊else if (i < 5 && j > 0 && j < WIDTH - 1 && bricks[i][j-1])cout << "■";elsecout << " ";if (j == WIDTH - 1)cout << "#"; // 右邊界}cout << endl;}// 繪制底部邊界for (int i = 0; i < WIDTH + 2; i++)cout << "#";cout << endl;// 顯示分數cout << "分數: " << score << endl;if (gameOver) {if (score == (WIDTH - 2) * 5)cout << "恭喜你贏了!按R重新開始,按Q退出" << endl;elsecout << "游戲結束!按R重新開始,按Q退出" << endl;}}// 處理用戶輸入void input() {if (_kbhit()) {switch (_getch()) {case 'a':if (paddleX > 0)paddleX--;break;case 'd':if (paddleX + PADDLE_WIDTH < WIDTH)paddleX++;break;case 'q':gameOver = true;break;case 'r':resetGame();break;default:break;}}}// 更新游戲狀態void update() {if (gameOver) return;// 移動球ballX += ballDirX;ballY += ballDirY;// 檢測左右邊界碰撞if (ballX <= 0 || ballX >= WIDTH - 1)ballDirX *= -1;// 檢測上邊界碰撞if (ballY <= 0)ballDirY *= -1;// 檢測下邊界(游戲結束)if (ballY >= HEIGHT) {gameOver = true;return;}// 檢測擋板碰撞if (ballY == HEIGHT - 1 && ballX >= paddleX && ballX < paddleX + PADDLE_WIDTH)ballDirY *= -1;// 檢測磚塊碰撞if (ballY < 5 && ballY >= 0 && ballX > 0 && ballX < WIDTH - 1) {int brickX = ballX - 1;int brickY = ballY;if (bricks[brickY][brickX]) {bricks[brickY][brickX] = false;score++;ballDirY *= -1;// 檢查是否所有磚塊都被消除bool allCleared = true;for (int i = 0; i < 5; i++) {for (int j = 0; j < WIDTH - 2; j++) {if (bricks[i][j]) {allCleared = false;break;}}if (!allCleared) break;}if (allCleared)gameOver = true;}}}// 運行游戲主循環void run() {while (!gameOver) {draw();input();update();Sleep(60); // 控制游戲速度}}
};int main() {cout << "簡易打磚塊游戲" << endl;cout << "使用A和D鍵移動擋板,Q鍵退出,R鍵重新開始" << endl;cout << "按任意鍵開始游戲..." << endl;_getch();BreakoutGame game;game.run();return 0;
}
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?結語
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?希望你也能學會ヾ(?°?°?)ノ゙
? ? ? ? ? ? ? ? ? ? ? ? ?制作不易,點個贊吧!Thanks?(・ω・)ノ