21xrx.com
2025-04-07 22:48:33 Monday
文章检索 我的文章 写文章
C++小游戏编程代码:让你趣味编程不再寂寞!
2023-07-05 21:45:16 深夜i     10     0
C++编程 小游戏 代码 趣味 不寂寞

在编程的世界里,“寂寞”一词可谓是一个老生常谈的话题了。虽然代码可以实现我们想要的各种功能,但是和人互动和交流还是缺乏了些。这时,编写小游戏便成了一种非常好的选择。今天,我们将介绍一款C++小游戏编程代码,让你感受趣味编程的乐趣!

首先,让我们来了解一下这个小游戏的背景和规则。这是一款简单的飞机射击小游戏,主角是“刺猬”,他需要驾驶自己的战斗机消灭逼近的敌机。玩家需要控制小刺猬的战斗机来进行射击,同时也要躲避敌机的攻击,游戏中敌机的数量会逐渐增加,难度也会逐渐加大。当然,你也可以根据自己的兴趣和需求来进行改编和扩展这个小游戏,让它更加有趣和有挑战性。

接下来,让我们来看一下这个小游戏的代码。由于篇幅限制,我们只展示其中的部分代码,供读者参考。

#include<iostream>
#include<conio.h>
#include<cstdlib>
#include<Windows.h>
#include<ctime>
using namespace std;
void gotoxy(int x, int y) //光标移动函数
{
  COORD pos;
  pos.X = x;
  pos.Y = y;
  SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}
void draw_man(int x, int y, char c) //画人物函数
{
  gotoxy(x, y - 2); cout << " " << c << " ";
  gotoxy(x, y - 1); cout << c << c << c;
  gotoxy(x - 1, y); cout << c << " " << c;
  gotoxy(x + 1, y); cout << c << c << c;
}
void erase_man(int x, int y) //清除人物函数
{
  gotoxy(x, y - 2); cout << "  ";
  gotoxy(x, y - 1); cout << "  ";
  gotoxy(x - 1, y); cout << "  ";
  gotoxy(x + 1, y); cout << "  ";
}
void draw_enemy(int x, int y, char c) //画敌机函数
{
  gotoxy(x, y - 1); cout << c << c << c;
  gotoxy(x, y); cout << c << c << c<<c<<c;
  gotoxy(x, y + 1); cout << c << c << c;
}
void erase_enemy(int x, int y) //清除敌机函数
{
  gotoxy(x, y - 1); cout << "  ";
  gotoxy(x, y); cout << "   ";
  gotoxy(x, y + 1); cout << "  ";
}
int main() //主函数
{
  srand((unsigned int)time(NULL));
  char man = 'A';
  int man_x = 40, man_y = 26;
  int key = 0;
  int enemy_x = rand() % 60 + 10;
  int enemy_y = 1;
  int score = 0;
  bool is_game_over = false;
  while (!is_game_over) //游戏循环
  {
    if (_kbhit()) //检测是否有键盘输入
    {
      key = _getch();
      if (key == 'a' && man_x > 0) man_x--; //左移
      if (key == 'd' && man_x < 80) man_x++; //右移
    }
    erase_man(man_x, man_y); //清除人物
    if (score % 10 == 0) enemy_y++; //每得10分敌机下降一行
    if (enemy_y > 27) //敌机到达底部,游戏结束
    
      is_game_over = true;
    
    erase_enemy(enemy_x, enemy_y); //清除敌机
    enemy_y++;
    if (enemy_y == man_y && enemy_x >= man_x - 1 && enemy_x <= man_x + 1) //检测撞击
    
      is_game_over = true;
    
    draw_man(man_x,man_y,man); //画人物
    if (enemy_y == 25) //到达玩家所在行,重新生成敌机
    {
      enemy_x = rand() % 60 + 10;
      enemy_y = 1;
      score++;
    }
    draw_enemy(enemy_x, enemy_y, 'V'); //画敌机
    Sleep(50); //暂停50毫秒
  }
  gotoxy(35, 13);
  cout << "Game Over! Your Score is: " << score << endl;
  return 0;
}

通过上述的代码,我们可以看到游戏中实现了人物的移动、敌机的下落、撞击检测、得分计算和游戏结束的提示等功能。当然,这只是其中的一部分代码,如果你有兴趣,可以下载完整代码并进行学习和改编。

虽然编程是一项比较孤独的工作,但是通过编写小游戏,我们可以实现代码和人的互动和交流,更加轻松和有趣地体验编程的乐趣。希望你也能够通过这个C++小游戏编程代码,感受到趣味编程的无穷魅力!

  
  

评论区