21xrx.com
2025-04-02 15:30:58 Wednesday
文章检索 我的文章 写文章
C++吃豆人游戏源代码
2023-07-08 12:36:37 深夜i     7     0
C++ 吃豆人 游戏 源代码

作为一款经典的游戏,《吃豆人》一直是很多程序员和游戏爱好者喜欢制作的对象之一。而使用C++开发《吃豆人》游戏,无疑是很多人理想的实现方式。下面是一个简单的C++吃豆人游戏源代码,希望对各位开发者有所帮助。

源代码如下:

#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;
bool gameOver;
const int width = 20;
const int height = 20;
int x, y, fruitX, fruitY, score;
int tailX[100], tailY[100];
int nTail;
enum eDirection DOWN ;
eDirection dir;
void Setup()
{
  gameOver = false;
  dir = STOP;
  x = width / 2;
  y = height / 2;
  // 随机生成果子位置
  fruitX = rand() % width;
  fruitY = rand() % height;
  score = 0;
}
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 == y && j == x)
        cout << "O";
      else if (i == fruitY && j == fruitX)
        cout << "F";
      else
      {
        bool print = false;
        for (int k = 0; k < nTail; k++)
        {
          if (tailX[k] == j && tailY[k] == i)
          
            cout << "o";
            print = true;
          
        }
        if (!print)
          cout << " ";
      }
      if (j == width - 1)
        cout << "#";
    }
    cout << endl;
  }
  // 下边框
  for (int i = 0; i < width + 2; i++)
    cout << "#";
  cout << endl;
  // 操作提示和分数
  cout << "Score:" << score << endl;
  cout << "Press Q to quitgame" << endl;
}
void Input()
{
  if (_kbhit()) // 如果有键盘输入
  {
    switch (_getch())
    
    case 'a':
      dir = LEFT;
      break;
    case 'd':
      dir = RIGHT;
      break;
    case 'w':
      dir = UP;
      break;
    case 's':
      dir = DOWN;
      break;
    case 'q':
      gameOver = true;
      break;
    
  }
}
void Logic()
{
  // 记录尾部的位置
  int prevX = tailX[0];
  int prevY = tailY[0];
  int prev2X, prev2Y;
  tailX[0] = x;
  tailY[0] = y;
  for (int i = 1; i < nTail; i++)
  {
    prev2X = tailX[i];
    prev2Y = tailY[i];
    tailX[i] = prevX;
    tailY[i] = prevY;
    prevX = prev2X;
    prevY = prev2Y;
  }
  switch (dir)
  {
  case LEFT:
    x--;
    break;
  case RIGHT:
    x++;
    break;
  case UP:
    y--;
    break;
  case DOWN:
    y++;
    break;
  }
  // 超出边界或撞到自己,游戏结束
  if (x < 0 || x >= width || y < 0 || y >= height)
    gameOver = true;
  for (int i = 0; i < nTail; i++)
    if (tailX[i] == x && tailY[i] == y)
      gameOver = true;
  // 吃到果子
  if (x == fruitX && y == fruitY)
  {
    score += 10;
    fruitX = rand() % width;
    fruitY = rand() % height;
    nTail++;
  }
}
int main()
{
  Setup();
  while (!gameOver)
  {
    Draw();
    Input();
    Logic();
    Sleep(50); // 控制运行速度
  }
  return 0;
}

这个代码实现了一个简单的吃豆人游戏,通过使用方向键来控制吃豆人的移动,通过吃果子来增加分数,撞墙或者撞到自己则游戏结束。其中,Setup函数负责游戏的初始化,Draw函数负责绘制游戏画面,Input函数负责获取键盘输入,Logic函数负责处理游戏逻辑。通过这个简单的源代码,开发者可以更好地理解C++语言的语法和运用方法,同时也能够有所启示,从而能够更好地开发自己的吃豆人游戏。

  
  

评论区