> 技术文档 > 【c++】超好玩游戏

【c++】超好玩游戏

#include #include #include #include #include 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> 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(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 <= paddleX && j < paddleX + PADDLE_WIDTH)  cout << \"=\"; // 绘制砖块 else if (i  0 && j < WIDTH - 1 && bricks[i][j-1])  cout << \"■\"; else  cout << \" \"; 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; else cout << \"游戏结束!按R重新开始,按Q退出\" < 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 = WIDTH - 1) ballDirX *= -1; // 检测上边界碰撞 if (ballY = HEIGHT) { gameOver = true; return; } // 检测挡板碰撞 if (ballY == HEIGHT - 1 && ballX >= paddleX && ballX < paddleX + PADDLE_WIDTH) ballDirY *= -1; // 检测砖块碰撞 if (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♪(・ω・)ノ