21xrx.com
2025-04-15 12:57:26 Tuesday
文章检索 我的文章 写文章
C++ 编写大鱼吃小鱼游戏的源代码
2023-07-04 19:12:45 深夜i     65     0
C++ 大鱼吃小鱼游戏 源代码 编写 游戏开发

大鱼吃小鱼游戏是一款非常经典的街机游戏,其玩法简单而富有乐趣,也是很多程序员喜欢用来练手的项目之一。在C++编程领域,实现大鱼吃小鱼游戏也是一个不错的练手项目,以下是一份简单的C++源代码。

#include<iostream>
#include<cstdlib>
#include<ctime>
#pragma warning(disable:4996)
using namespace std;
const int width = 20;
const int height = 20;
int x, y;
int fx, fy;
int score = 0;
bool eaten = true; //判断是否吃到食物
void Draw() //绘制游戏界面
{
  system("cls");
  for (int i = 0; i < height; i++)
  {
    for (int j = 0; j < width; j++)
    {
      if (i == 0 || i == height - 1 || j == 0 || j == width - 1)
        cout << "#";
      else if (i == y && j == x)
        cout << "O";
      else if (i == fy && j == fx)
        cout << "F";
      else
        cout << " ";
    }
    cout << endl;
  }
  cout << "Score:" << score << endl;
}
void Input() //接受用户输入
{
  if (_kbhit())
  {
    switch (_getch())
    {
    case 'a':
      x--; break;
    case 'd':
      x++; break;
    case 'w':
      y--; break;
    case 's':
      y++; break;
    }
  }
}
void Logic() //处理游戏逻辑
{
  if (x == fx && y == fy)
  {
    eaten = true;
    score += 10;
  }
  if (eaten)
  {
    srand((unsigned)time(NULL));
    fx = rand() % (width - 1) + 1;
    fy = rand() % (height - 1) + 1;
    eaten = false;
  }
  if (x == 0 || x == width - 1 || y == 0 || y == height - 1)
  {
    system("cls");
    cout << "Game Over!" << endl << "Your score:" << score << endl;
    exit(0);
  }
}
int main()
{
  x = width / 2;
  y = height / 2;
  srand((unsigned)time(NULL));
  fx = rand() % (width - 1) + 1;
  fy = rand() % (height - 1) + 1;
  while (1)
  {
    Draw();
    Input();
    Logic();
  }
  return 0;
}

以上代码实现了基础的大鱼吃小鱼游戏逻辑,其中定义了绘制游戏界面所需的数据,包括游戏区域宽度和高度、玩家和食物的坐标等。在绘制游戏界面时,利用循环语句遍历游戏区域,根据坐标绘制出界面元素。接受用户输入时,使用_kbhit()和_getch()函数来获取用户按键信息,并根据按键输入来改变玩家坐标。游戏逻辑部分主要处理玩家与食物的碰撞和游戏结束的判断,其中利用随机数生成食物的坐标,并记录玩家得分。

需要注意的是,以上代码仅为基础的游戏逻辑实现,游戏的玩法和操作方式可以根据个人需求进行更改和完善。

  
  

评论区