本文主要是介绍C/C++项目实战-接球游戏,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
/********************************************************************
* *
* 程序名称:接球游戏 *
* 编译环境:Microsoft Visual Studio Professional 201 9版本 16.6.3 *
* && EasyX_20200520(beta) *
* 作者相关:Jay *
* 最后修改:2020.07.28 *
* *
*********************************************************************/#include <stdio.h>//C语言标准库函数
#include <time.h>//C语言时间库函数
#include <conio.h>//一个控制台输入输出库函数
#include <graphics.h>//EasyX图形库头文件// 定义常量
#define NUM 10
#define KEYLEFT ((GetAsyncKeyState(VK_LEFT) & 0x8000) ? 1 : 0)//检测左按键
#define KEYRIGHT ((GetAsyncKeyState(VK_RIGHT) & 0x8000) ? 1 : 0)//检测右按键
#define KEYESC ((GetAsyncKeyState(VK_ESCAPE) & 0x8000) ? 1 : 0)//检测ESC按键int box_x = 10;
int box_y = 420;// 定义球的结构体
struct Ball
{int x, y, v;
};
// 介绍
void menu()
{line(449, 0, 449, 480); //这个函数用于画直线。还可以用 linerel 和 lineto 画直线。settextcolor(WHITE);//这个函数用于设置当前文字颜色。outtextxy(450, 50, _T("按方向键控制盒子移动接住"));outtextxy(450, 160,_T("接到的球的数量:"));outtextxy(450, 280,_T("作者:Jay"));
}// 产生随机球
void ballRandom(Ball ball[], int i)
{ball[i].x = 16 + 45 * i;ball[i].y = 8 + rand() % 32;//产生8-32的随机数ball[i].v = 1 + rand() % 5; //产生1 - 5的随机数
}// 画球,并计算得分
void calculateScore(Ball ball[], int& score){for (int i = 0; i < NUM; i++){fillcircle(ball[i].x, ball[i].y, 8);if (ball[i].y >= 472){ballRandom(ball, i);continue;}if (box_x + 8 <= ball[i].x && ball[i].x <= box_x + 72 && ball[i].y >= 412){score++;ballRandom(ball, i);}}
}int main(void) {// 初始化initgraph(640, 480);//初始化画布srand((int)time(NULL));//选取种子文件setlinecolor(WHITE);//这个函数用于设置当前设备画线颜色。menu();Ball ball[NUM];int score = 0;int i=0;int dx=0;bool flag = true;for (i = 0; i < NUM; i++){ballRandom(ball, i);}while (flag){// 显示得分char strScore[10];_itoa_s(score, strScore, 10);//itoa 取整数输入值,并将其转换为相应进制数字的字符串。itoa(i ,num ,10 );outtextxy(570, 160, strScore);//打印得分// 画球,并计算得分calculateScore(ball, score);// 画盒子fillrectangle(box_x, box_y, box_x + 80, box_y + 60);//这个函数用于画有边框的填充矩形。// 获取用户控制命令if (KEYLEFT)dx = -10;if (KEYRIGHT) dx = 10;if (KEYESC) flag = false;//if (!Time(t)) flag = false;Sleep(20);// 擦除游戏区clearrectangle(0, 0, 448, 480);// 计算球的新坐标for (i = 0; i < NUM; i++) {ball[i].y += ball[i].v;}// 移动盒子box_x += dx;if (box_x < 0) box_x = 0;if (box_x > 368) box_x = 368;//if ((box_x > 0) && (box_x < 368)) box_x = dx;dx = 0;}// 按任意键退出_getch();closegraph();return 0;}
游戏界面:
这篇关于C/C++项目实战-接球游戏的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!