21xrx.com
2025-04-27 13:19:48 Sunday
文章检索 我的文章 写文章
【代码分享】用C++编写的小游戏
2023-06-23 22:54:03 深夜i     12     0
C++ 代码分享 小游戏

作为一种流行的编程语言,C++在游戏开发中的使用非常广泛。今天,我们来分享一款由C++编写的小游戏,它可以锻炼你的反应能力和手眼协调能力,同时也可以帮助你加深对C++语言的理解。

这款名为“球球大作战”的小游戏的玩法非常简单,玩家控制一个小球不断吃到其他球,以变得越来越大。但是,玩家在吃球时需要注意别碰到其他危险的球体,否则游戏就会结束。

让我们看一下这款游戏的核心代码。首先,我们定义了一个球对象,它包含了球的位置和大小信息:

class Ball
{
public:
  Ball(float x, float y, float radius)
  
    m_x = x;
    m_y = y;
    m_radius = radius;
  
  void draw()
  
    // 绘制球的代码
  
  float getX() const
  
    return m_x;
  
  float getY() const
  
    return m_y;
  
  float getRadius() const
  
    return m_radius;
  
private:
  float m_x;
  float m_y;
  float m_radius;
};

我们还定义了一个游戏对象,它包含了游戏的主要逻辑:

class Game
{
public:
  Game()
  
    // 初始化游戏的代码
  
  void run()
  {
    while (m_running)
    {
      handleEvents();
      update();
      draw();
    }
  }
  void handleEvents()
  
    // 处理用户输入的代码
  
  void update()
  
    // 更新游戏状态的代码
  
  void draw()
  
    // 绘制游戏画面的代码
  
private:
  bool m_running;
  Ball m_playerBall;
  std::vector<Ball> m_otherBalls;
};

在游戏的运行过程中,我们可以随时添加新的球体对象,以实现游戏环境的变化:

void Game::update()
{
  // 碰撞检测的代码
  for (auto& ball : m_otherBalls)
  {
    if (distance(m_playerBall, ball) <= m_playerBall.getRadius() + ball.getRadius())
    {
      if (m_playerBall.getRadius() >= ball.getRadius())
      {
        m_playerBall.setRadius(m_playerBall.getRadius() + ball.getRadius() * 0.1f);
        ball.setRadius(0);
      }
      else
      
        m_running = false;
      
    }
  }
  m_otherBalls.erase(std::remove_if(m_otherBalls.begin(), m_otherBalls.end(),
    [](const Ball& ball) { return ball.getRadius() == 0; }), m_otherBalls.end());
  // 添加新的球体的代码
  if (m_otherBalls.size() < MAX_BALLS)
  {
    // 随机生成新的球体的位置和大小
    float x = randFloat(0, SCREEN_WIDTH);
    float y = randFloat(0, SCREEN_HEIGHT);
    float r = randFloat(10, 30);
    m_otherBalls.push_back(Ball(x, y, r));
  }
}

最后,我们把所有的代码组合起来,就可以得到这款简单而又有趣的小游戏了:

int main()
{
  sf::RenderWindow window(sf::VideoMode(SCREEN_WIDTH, SCREEN_HEIGHT), "Ball Battle");
  Game game;
  game.run();
  return 0;
}

在编写这款游戏的过程中,我们不仅锻炼了自己的编程能力,还加深了对C++语言的理解。希望这款小游戏能够对初学者有所帮助,也希望大家多多分享自己的代码,让我们共同进步。

  
  

评论区