C语言的坦克大战源码

合集下载

C#坦克大战实现(可编辑)

C#坦克大战实现(可编辑)

C#坦克大战实现记记事事本本CC##坦坦克克大大战战实实现现2010-12-18 21:06 910人阅读评论 0 收藏举报记得在大学学java时,同学在下载了很多java的视频,看到里面有些是介绍简单游戏开发的,马士兵老师讲的,挺感兴趣的。

一起看了看视频写了写程序。

现在毕业了,因为工作中用的是C#,最近很想拿C#把以前写的坦克大战重写下,来熟悉熟悉C#的基本语法。

程序很简单,跟java代码相比没有多大改动实现方法如下1.在form中添加一个panel,在panel的 Paint方法中得到Graphics对象2.通过Graphics对象再panel画出坦克,子弹等相关内容3.添加timer控件来控制panel的重画实现坦克,子弹的运动4.根据电脑按下的方向键,确定出坦克的方向,panel重画时根据坦克的方向修改坦克的X,Y轴坐标,来实现坦克的移动5.通过Rectangle的IntersectsWith函数来进行碰撞检测,实现子弹打击坦克具体实现代码1.在项目里面添加枚举类型////// 表示方向的的枚举类型///public enum Direction L, U, D, R, STOP 2.添加子弹类的相关常量,属性////// 子弹X轴的速度,单位PX///public static int XSPEED 10;////// 子弹Y轴的速度,单位PX///public static int YSPEED 10;////// 子弹的宽度///public static int WIDTH 10;1////// 子弹的高度///public static int HEIGHT 10;////// 子弹的坐标///int x, y;////// 子弹的方向///Direction dir;////// 子弹的存活状态///private bool live true;////// TankClient窗体实例///private TankClient tankClient; ////// 敌我双方的标记///private bool good;3.添加draw方法来画出子弹public void Draw Graphics gif !livetankClve this ;2return;//通过画椭圆函数在界面上显示子弹g.FillEllipse Brushes.Black, x, y, Missile.WIDTH, Missile.HEIGHT ;Move ;4.添加子弹打击坦克的方法public bool HitTank Tank t//用IntersectsWith来检测两个矩形相碰撞if GetRectangle .IntersectsWith t.GetRectangle && t.Live && this.live && this.good! t.Goodt.Live false;this.live false;return true;return false;5.添加坦克类相关属性,常量////// 坦克x轴的速度///public static int XSPEED 5; ////// 坦克y轴的速度///public static int YSPEED 5;////// 坦克的宽度///public static int WIDTH 30;3////// 坦克的高度///public static int HEIGHT 30;////// 坦克的坐标///private int x, y;////// 标记上下左右键是否按下///private bool l false, u false, r false, d false;////// 坦克的方向///private Direction dir Direction.STOP ;////// 坦克炮筒方向///private Direction ptDir Direction.D ; ////// TankClient窗体实例///TankClient tankClient;////// 标记敌我双方///private bool good;///4/// 控制敌人坦克不规则运行时使用 ///private int step 0;////// 标记坦克的存活状态///private bool live true;6.在tank类中实现画坦克方法public void Draw Graphics g if !liveif !goodtankClve this ; return;if good//通过FillEllipse来画坦克g.FillEllipse Brushes.Red, x, y, WIDTH, HEIGHT ;elseg.FillEllipse Brushes.Blue, x, y, WIDTH, HEIGHT ;//根据炮筒坦克来画出坦克的炮筒switch ptDircase Direction.D:g.DrawLine Pens.Black, x + WIDTH / 2, y + HEIGHT / 2, x + WIDTH / 2, y + HEIGHT ;break;case Direction.U :g.DrawLine Pens.Black, x + WIDTH / 2, y + HEIGHT / 2, x + WIDTH / 2, y ;5break;case Direction.L:g.DrawLine Pens.Black, x + WIDTH / 2, y + HEIGHT / 2, x, y + HEIGHT / 2 ;break;case Direction.R:g.DrawLine Pens.Black, x + WIDTH / 2, y + HEIGHT / 2, x + WIDTH, y + HEIGHT / 2 ;break;Move ;7.键盘按键处理的相关代码public void KeyPressed KeyEventArgs eKeys key e.KeyCode; switch keycase Keys.Right: r true;break;case Keys.Left: l true;break;case Keys.Up:u true; break;case Keys.Down: d true; break;LocateDirection ;8.tank发子弹的方法public Missile Fireif !live return null;int x this.x + WIDTH / 2 - Missile.WIDTH / 2;6int y this.y + HEIGHT / 2 - Missile.HEIGHT / 2;Missile missile new Missile x, y, good, ptDir, tankClient ;tankCl missile ;return missile;9.主窗体类加入坦克myTank new Tank 50, 20, true, this ;//放到前面 this不能用 //y轴比java的减少了30for int i 0; i 15; i++//添加10个坦克x轴间距为40pxtanks.Add new Tank 50+40* i+1 ,20,false,this ; //y轴比java的减少了3010.主窗体类中调用子弹打击坦克的方法for int i 0; i missiles.Count; i++ Missile m missiles[i];m.HitTank myTank ;m.HitTanks tanks ;m.Draw g ;11.主窗体处理按键代码private void Form1_KeyDown object sender, KeyEventArgs emyTank.KeyPressed e ;12.控制重画代码private void timer1_Tick object sender, EventArgs e//间隔50毫秒控制panel的重画panel1.Invalidate ;13.这是主要代码基本完成,但是游戏会有闪烁问题可以通过双缓冲来解决,C#解决时很省事,一个函数就能解决7this.SetStyleControlStyles.OptimizedDoubleBuffer |ControlStyles.ResizeRedraw |ControlStyles.AllPaintingInWmPaint, true ;顺便改了个手机版本的但是手机版本的没能解决双缓冲问题,屏幕有些闪烁,朋友们可以自己改进代码下载如果你发现有什么不合理的,需要改进的地方,邮件联系328452421@ (常年不在线,邮件联系)朱晓。

C#版坦克大战

C#版坦克大战

福州教育学院()届毕业论文(设计)题目:系部:专业(方向):学号:姓名:提交日期:指导教师及职称:C#版坦克大战摘要:1985年推出的坦克大战(Battle City)由13×13大小的地图组成了35个关卡,地形包括砖墙、海水、钢板、森林、地板5种,玩家作为坦克军团仅存的一支精锐部队的指挥官,为了保卫基地不被摧毁而展开战斗。

游戏中可以获取有多种功能的宝物,敌人种类则包括装甲车、轻型坦克、反坦克炮、重型坦克4种。

游戏以其出色的游戏性感染的一代又一代的玩家。

现在我在以前的坦克大战的基础上增加了一些的新功能和新算法(例如:玩家自定义地图编辑功能和新的AI算法,并且将地图扩展到了20×20)使得游戏更加有趣。

目录第一章引言 (3)1.1C#语言的介绍 (3) FrameWork简介 (3)第二章游戏的设计 (3)2.1游戏的设计方案 (4)2.2游戏的开发所需的硬件和软件 (4)2.3 游戏中的中枢Level类 (4)2.4 游戏中的组件的基类Element类 (12)第三章游戏所涉及的技术问题 (14)3.1 GUI+与图像双缓冲技术 (14)3.2 多线程技术 (16)3.3 I/O技术实现地图的读取 (17)3.4 碰撞的检测 (19)3.5 接受用户的键盘输入 (19)第四章游戏界面与代码 (19)4.1 开始界面及代码 (19)4.2 游戏界面及代码 (21)第五章总结 (25)第一章引言1.1 C#语言的介绍C#(读做 "C sharp",中文译音暂时没有.专业人士一般读"C sharp",现在很多非专业一般读"C井"。

C#是微软公司发布的一种面向对象的、运行于.NET Framework之上的高级程序设计语言。

并定于在微软职业开发者论坛(PDC)上登台亮相。

C#是微软公司研究员Anders Hejlsberg的最新成果。

C大作业坦克大战

C大作业坦克大战

#include<iostream> #include<stdlib.h>#include<windows.h>#include<time.h>#include<conio.h> usingnamespacestd;HANDLEMutex=CreateMutex(NULL,FALSE,NULL);/互/ 斥对象intGameOver=0;intlevel=0;intmap[23][23];// 坦克种类,Normal 为玩家坦克#defineNormal0#defineRed1#defineBlue2#defineGreen3// 方向的宏定义#defineUp0#defineDown1#defineLeft2#defineRight3// 地图标记的宏定义#defineEmpty0#definePlayer1#definePlayerBullet2#defineEnemyBullet3#defineEnemy4intKill;intKillRed;intKillGreen;intEnemyExist;voidSetPos(inti,intj)// 设定光标位置{COORDpos={i,j};HANDLEOut=GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleCursorPosition(Out,pos);}voidHideCurSor(void)// 隐藏光标{CONSOLE_CURSOR_INFOinfo={1,0};HANDLEOut=GetStdHandle(STD_OUTPUT_HANDLE);SetConsoleCursorInfo(Out,&info);}intsharp[4][12]={0,1,1,0,1,1,1,2,2,0,2,2},{0,0,0,2,1,0,1,1,1,2,2,1},{0,1,0,2,1,0,1,1,2,1,2,2},{0,0,0,1,1,1,1,2,2,0,2,1},};// 此数组用来保存坦克各个方向的形状信息DWORDWINAPIBulletfly(LPVOIDlpParameter);// 子弹函数申明voidUpdata();// 更新界面信息函数申明classTank// 坦克类{private:intDirection;// 方向inthotpoint[2];// 活动点intSpeed;// 速度intFirePower;// 火力public:Tank(intdir,inthot1,inthot2,inttyp,intspe,intfirepow)// 构造函数{Direction=dir;hotpoint[0]=hot1;hotpoint[1]=hot2; }Type=typ;Speed=spe;FirePower=firepow;}intType;// 坦克的种类(详见宏定义) intID;// 坦克在MAP中的标记(详见宏定义) intFireEnable;// 是否可以开火intLife;// 生命值voidRunning();// 运行函数intJudge(intx,inty,intID);// 判断是否可以绘制坦克voidDrawTank();// 重绘坦克voidRedraw();// 擦除坦克intGetSpeed()// 获取速度{returnSpeed;}intGetFire()// 获取火力{returnFirePower;}intGetDirection()// 获取方向{returnDirection;}intGetHotX()// 获取活动点坐标{returnhotpoint[0];}intGetHotY(){returnhotpoint[1];}voidIncreaseFire()// 火力+{FirePower++;}voidIncreaseSpeed()// 速度+{Speed++;}voidChangeDirection(intnewD)//改变方向{Direction=newD;}voidChangePos(intx,inty)// 改变活动点{hotpoint[0]=x;hotpoint[1]=y;}};Tankplayer(Right,0,0,Normal,1,1);// 玩家Tankenemy(Left,20,0,Red,1,1);// 敌人voidTank::DrawTank()// 绘制坦克{inti;intnx,ny;if(Type==Red)SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY|FOREGROUND_RED);elseif(Type==Blue)SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY|FOREGROUND_BLUE);elseif(Type==Green)SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY|FOREGROUND_GREEN);elseif(Type==Normal)SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY|FOREGROUND_RED|FOREGROUND_GREEN|FOREG R OUND_BLUE);for(i=0;i<6;i++){nx=hotpoint[0]+sharp[Direction][i*2]; ny=hotpoint[1]+sharp[Direction][i*2+1];SetPos((ny+1)*2,nx+1);// 利用sharp 数组相对于点x,y 绘制形状map[nx][ny]=ID;cout<<" ■ ";}}voidTank::Redraw()// 擦除坦克,原理同上{inti;intnx,ny;}for(i=0;i<6;i++){ nx=hotpoint[0]+sharp[Direction][i*2]; ny=hotpoint[1]+sharp[Direction][i*2+1];map[nx][ny]=Empty;SetPos((ny+1)*2,nx+1); cout<<"";}}intTank::Judge(intx,inty,intdir)// 判断当前是否可以绘制坦克{inti;intnx,ny;for(i=0;i<6;i++){ nx=x+sharp[dir][i*2]; ny=y+sharp[dir][i*2+1];if(nx<0||nx>=23||ny<0||ny>=23||map[nx][ny]!=Empty)// 不能绘制,返回 1 return1;return0;}voidTank::Running()// 坦克运行函数{intnewD;// 坦克的运行while(1){if(Life==0){EnemyExist=0;// 敌人不存在return;} if(GameOver==1)return;if(FireEnable==1&&GameOver==0)// 如果可以开火{WaitForSingleObject(Mutex,INFINITE);// 线程拥有互斥对象FireEnable=0;// 设为不可开火HANDLEbullet=CreateThread(NULL,0,Bulletfly,&ID,0,NULL);/ / 创建子弹线程}}}CloseHandle(bullet); ReleaseMutex(Mutex);// 释放互斥对象Sleep(100);}WaitForSingleObject(Mutex,INFINITE);// 线程拥有互斥对象srand((int)time(0));newD=rand()%4;if(newD==Up)// 随机出新的方向并重新绘制坦克{Redraw();if(Judge(hotpoint[0]-1,hotpoint[1],newD)==0){hotpoint[0]--;Direction=newD;}else{if(Judge(hotpoint[0],hotpoint[1],newD)==0) Direction=newD;elseif(newD==Down){Redraw();if(Judge(hotpoint[0]+1,hotpoint[1],newD)==0) {hotpoint[0]++; Direction=newD;}else{ if(Judge(hotpoint[0],hotpoint[1],newD)==0)Direction=newD;}}elseif(newD==Left){Redraw();if(Judge(hotpoint[0],hotpoint[1]-1,newD)==0) {hotpoint[1]--; Direction=newD;}else{if(Judge(hotpoint[0],hotpoint[1],newD)==0) Direction=newD; }}elseif(newD==Right){Redraw();if(Judge(hotpoint[0],hotpoint[1]+1,newD)==0){hotpoint[1]++;Direction=newD;}else{if(Judge(hotpoint[0],hotpoint[1],newD)==0) Direction=newD; }}if(GameOver==0&&Life!=0)DrawTank();ReleaseMutex(Mutex);// 释放互斥对象 Sleep(500-80*Speed);}}/*********************DWORDWINAPIBulletfly(LPVOIDlpParameter){int*ID=(int*)lpParameter;//ID 用来获取发射子弹坦克的 intPos[2];// 子弹活动点 intdirection; intSpeed; inttype;inthit=0;// 击中标记intoldx,oldy;// 旧活动点 intflag=0;// 子弹是否有移动的标记 if(*ID==Player)// 如果是玩家坦克 {type=PlayerBullet; direction=player.GetDirection(); Speed=player.GetFire(); Pos[0]=player.GetHotX(); Pos[1]=player.GetHotY();子弹线程函数IDelseif(*ID==Enemy)// 如果是敌人坦克{type=EnemyBullet;direction=enemy.GetDirection();Speed=enemy.GetFire();Pos[0]=enemy.GetHotX();Pos[1]=enemy.GetHotY();}if(direction==Up)// 根据坦克的位置和方向确定子弹的初始坐标{Pos[0]--;Pos[1]++;}elseif(direction==Down){Pos[0]+=3;Pos[1]++;}elseif(direction==Left)Pos[0]++;Pos[1]--;}elseif(direction==Right){{Pos[0]++;Pos[1]+=3;}// 子弹的运行while(1){WaitForSingleObject(Mutex,INFINITE);//这个不再注释了。

C语言完整游戏项目坦克大战详细代码

C语言完整游戏项目坦克大战详细代码

C语⾔完整游戏项⽬坦克⼤战详细代码话不多说我们今天就来创造出属于我们⾃⼰的《坦克⼤战》,GOGOGO直接开始吧这次的源码⽐较详细,我分了好⼏个cpp⽂件,思路更加的清晰,请耐⼼⽤⼼的观看⾸先就是我们载⼊图⽚的函数tupian.cpp# include "tanke.h"障碍物void LaoWang(int * tilex, int * tiley){IMAGE img;loadimage(&img, _T("res\\tile.bmp"));putimage(*tilex, *tiley, 32 , 32 , &img, 32 * 5, 0 );}void tileHong(int * tilex, int * tiley){IMAGE img;loadimage(&img, _T("res\\tile.bmp"));putimage(*tilex, *tiley, 32, 32, &img, 32 * 0, 0 );return;}void tileLv(int * tilex, int * tiley){IMAGE img;loadimage(&img, _T("res\\tile.bmp"));putimage(*tilex, *tiley, 32, 32, &img, 32 * 2, 0 );return;}void tileBai(int * tilex, int * tiley){IMAGE img;loadimage(&img, _T("res\\tile.bmp"));putimage(*tilex, *tiley, 32, 32, &img, 32 * 1, 0 );return;}IMAGE img;loadimage(&img, _T("res\\tile.bmp"));putimage(*tilex, *tiley, 32, 32, &img, 32 * 3, 0 ); }//物品void FaZhang(int *wupinx, int *wupiny){IMAGE img;loadimage(&img, _T("res\\fazhang.jpg"));putimage(*wupinx, *wupiny, 24, 24, &img, 0, 0 ); }void ShouQiang(int *wupinx, int *wupiny){IMAGE img;loadimage(&img, _T("res\\shouqiang.jpg"));putimage(*wupinx, *wupiny, 24, 24, &img, 0, 0 ); }void ShangDian(int *wupinx, int *wupiny){IMAGE img;loadimage(&img,_T("res\\shangdian.jpg"));putimage(*wupinx, *wupiny, 32, 32, &img, 0, 0 ); }void YaoShui(int *wupinx, int *wupiny){IMAGE img;loadimage(&img, _T("res\\yaoshui.jpg"));putimage(*wupinx, *wupiny, 28, 28, &img, 0, 0 ); }void DunPai(int *wupinx, int *wupiny){IMAGE img;loadimage(&img, _T("res\\dunpai.jpg"));putimage(*wupinx, *wupiny, 28, 28, &img, 0, 0 ); }void XieZi(int *wupinx, int *wupiny){IMAGE img;loadimage(&img, _T("res\ iezi.jpg"));putimage(*wupinx, *wupiny, 28, 28, &img, 0, 0 ); }void Boss(int *wupinx, int *wupiny){IMAGE img;loadimage(&img, _T("res\\boss.jpg"));putimage(*wupinx, *wupiny, 32, 32, &img, 0, 0 ); }void BigBoss(int *wupinx, int *wupiny){IMAGE img;loadimage(&img, _T("res\\bigboss.jpg"));putimage(*wupinx, *wupiny, 32, 32, &img, 0, 0 ); }接下来是初始化的函数waiyuan.cpp# include "tanke.h"{setcolor(GREEN);settextstyle(0, 0, ("宋体"));char c2[20] = "⾃⼰⽣命值:";outtextxy(0, 20, c2);char c3[10] ;sprintf(c3, _T("%.1f"), 100* (60 - *j) / 60.0);outtextxy(90, 20, c3);}void DShengMing(int * d,int *k){setcolor(GREEN);settextstyle(0, 0, ("宋体"));char c2[20] = "敌⼈⽣命值:";outtextxy(0, 0, c2);char c3[10] ;sprintf(c3, _T("%.1f"), 100* (60 - *d) / 60.0);outtextxy(90, 0, c3);char c4[40] = "恭喜~! 现在起⾦币到2200有惊喜!";//胜利 if ( *k >= 8000 ){setcolor(YELLOW);settextstyle(30, 0, ("宋体"));outtextxy(150, 0, c4);}}void Gold(int * gold){setcolor(GREEN);settextstyle(0, 0, ("宋体"));char c2[20] = "⾦币:";outtextxy(0, 40, c2);char c3[10] ;sprintf(c3, _T("%d"), *gold);outtextxy(40, 40, c3);}void start(void){initgraph(200, 130);TCHAR s1[10]="坦克⼤战";TCHAR s2[30]="按A 开始游戏按B 退出游戏";TCHAR s3[30]="按W S A D控制⽅向";TCHAR s4[20]="按J 发射⼦弹";TCHAR s5[20]="按C 看攻略";outtextxy(70, 0, s1);outtextxy(0, 110, s2);outtextxy(60, 90, s5);outtextxy(55, 30, s4);outtextxy(35, 60, s3);while (true){Sleep(500);if (GetAsyncKeyState('A')){BeginBatchDraw();closegraph();initgraph(640, 480);Sleep(200);Quit();return ;}if (GetAsyncKeyState('C'))GongLue();}}}void GongLue(void){initgraph(450, 300);TCHAR s1[20]="游戏攻略:";TCHAR s2[50]="再打坦克之前先吃法杖打掉⽩⾊砖块,";TCHAR s3[50]="这样敌坦克打⽩⾊就不能回⾎了,boss更应如此。

C++实例编程:简单坦克大战_C/C++_IT哇咔_IT技术爱好者之家

C++实例编程:简单坦克大战_C/C++_IT哇咔_IT技术爱好者之家
case 4:line(100+x*20,50+y*20,100+x*20-9,50+y*20);break;/*左*/
}
}
void DrawAmy(int x,int y,int i)/*画敌人*/
{
if(amy[i].color==12)
bar(100+x*20-9,50+y*20-9,100+x*20+9,50+y*20+9);
}
void DrawBrick(int x,int y)/*画砖*/
{
setfillstyle(SOLID_FILL,6);
bar(100+x*20-9,50+y*20-9,100+x*20+9,50+y*20+9);
setcolor(15);
line(100+x*20-9,50+y*20-4,100+x*20+9,50+y*20-4);
line(100+x*20-9,50+y*20+4,100+x*20+9,50+y*20+4);
line(100+x*20-4,50+y*20-9,100+x*20-4,50+y*20+9);
setcolor(12);
else if(amy[i].color==13)
setcolor(13);
else/*这里是判断三种颜色的坦克*/
setcolor(14);
circle(100+x*20,50+y*20,7);

c语言坦克大战最新代码

c语言坦克大战最新代码
} key=bioskey(0);
judge_tank_my(map,key);/*判断己方坦克运动函数*/
} aaa: ; } void map_all(int map[15][15])/*初始化地图函数*/ { int i,j; for(i=0;i<15;i++)
for(j=0;j<15;j++) switch(map[j][i]) { case 0: break; case 5:map_wall(i,j);break;/*地形*/ case 6:map_steel(i,j);break; case 7:map_water(i,j);break; case 8:map_border(i,j);break; case 9:map_base(i,j);break; }
void uptank(int i,int j,int color);/*画坦克函数*/ void downtank(int i,int j,int color); void lefttank(int i,int j,int color); void righttank(int i,int j,int color);
/* Note:Your choice is C IDE */ #include "graphics.h" #include "stdlib.h" #include "stdio.h"
#define a_UP 0x4800/*定义A坦克按键*/ #define a_DOWN 0x5000 #define a_LEFT 0x4b00 #define a_RIGHT 0x4d00 #define a_shoot 0x1c0d
void judge_moveshootway(int map[15][15],int i);/*炮弹运动时判断炮弹方 向函数*/ void judge_shoot(int m,int map[15][15],int i);/*判断炮弹打中的物体函数 */ void judge_shootway(int map[15][15],int i);/*炮弹打中物体时判断方向函 数*/

c语言坦克大战源代码

c语言坦克大战源代码

c语言坦克大战源代码/*游戏的整体思路大概是这样的?首先是欢迎界面,然后进入游戏界面,最后是gameover的界面。

本来打算做单人游戏,后来发现让敌人自主移动比较困难,所以改成了双人游戏?layer1控制按键是up,down,left,right,enter,player2控制按键是a,s,d,w,space。

*/#include<stdio.h>#include<string.h>#include<stdlib.h>#include<graphics.h>/*定义鼠标键值常量*/#define ESC 0x011b/*玩家1坦克按键*/#define UP 0x4800#define DOWN 0x5000#define LEFT 0x4b00#define RIGHT 0x4d00#define ENTER 0x1c0d#define up 0x1177/*玩家2坦克按键*/#define down 0x1f73#define left 0x1e61#define right 0x2064#define fire 0x246a/*定义游戏常量*//*双人游戏*/#define NUM 2/*坦克宽度*/#define WIDTH 20/*坦克的数量,宽度*//*定义global变量*******************************************//*子弹的属性*/struct myboom{/*如果子弹life为0则代表子弹没有发射*/int life;int x,y;int direction;};/*子弹们的初始属性*/struct myboom iboom[NUM]={{0},{0}};/*坦克的属性*/struct mytank{int life;int x,y;int direction;};/*坦克们的初始属性*/struct mytank itank[NUM]={{3,10*WIDTH,22*WIDTH},{1,440,40}};pre[NUM][2]={{10*WIDTH,22*WIDTH},{440,40}};/*xy[0]代表自己的坦克; xy[1]及以后代表敌军; 坦克坐标*//*存被子弹覆盖的图像*/void *boom_save[NUM];/*malloc开辟图像空间的大小*/int size;/*动画显示*/void *save[NUM];/*后来加上的。

对战坦克大战(vc++)

对战坦克大战(vc++)

对战坦克大战本节将介绍一个和FC(Family Computer)上的经典游戏《坦克大战》类似的游戏——对战坦克大战。

这是一个4 人对战的坦克游戏,4 个玩家两两一组,率先攻击到对方鹰巢的一组玩家获胜。

对战坦克大战是一个C/S 结构的网络游戏,它的网络部分是用重叠I/O 的Socket 实现的。

它分成服务器端和客户端。

服务器端用来接受客户端连接,并对游戏作出控制。

先来看看服务器部分的实现。

4.10.1 对战坦克大战的服务器程序服务器程序界面如图4.15 所示。

图4.15 对战坦克大战的服务器程序服务器是一段Win32 程序。

程序入口WinMain 和前面游戏中介绍过的入口函数并无二样。

WndProc是WinMain 中定义的消息回调函数,代码如下:LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam){int cxChar, cyChar ;switch (message){case WM_CREATE :cxChar = LOWORD (GetDialogBaseUnits ()) ;cyChar = HIWORD (GetDialogBaseUnits ()) ;hwndList = CreateWindow (TEXT ("listbox"), NULL,WS_CHILDWINDOW|WS_VISIBLE | LBS_STANDARD ^LBS_SORT,cxChar, cyChar,cxChar * 44 + GetSystemMetrics (SM_CXVSCROLL), cyChar * 16,hwnd, (HMENU) ID_LIST,(HINSTANCE) GetWindowLong (hwnd, GWL_HINSTANCE), NULL) ;//初始化服务器if ( !InitServer() )第4 章网络游戏开发277PostQuitMessage (0) ;//创建socket 监听线程CreateThread( NULL, 0, AcceptThread, NULL, 0, NULL ); //创建socket 工作线程CreateThread( NULL, 0, WorkerThread, NULL, 0, NULL ); return 0 ;case WM_SETFOCUS :SetFocus (hwndList) ;return 0 ;case WM_DESTROY :TerminateServer();PostQuitMessage (0) ;return 0 ;}return DefWindowProc (hwnd, message, wParam, lParam) ;}WndProc 在创建消息中首先调用了InitServer,以初始化服务器。

c语言简单的坦克对战代码

c语言简单的坦克对战代码

c语言简单的坦克对战代码C语言简单的坦克对战代码介绍坦克对战游戏是一个经典的游戏,它可以锻炼玩家的反应能力和策略思维。

本文将介绍如何使用C语言编写一个简单的坦克对战游戏。

准备工作在开始编写代码之前,我们需要安装一些必要的工具。

首先,我们需要下载并安装一个C语言编译器。

常见的C语言编译器有GCC、Clang等。

其次,我们需要选择一个集成开发环境(IDE),例如Code::Blocks、Visual Studio等。

游戏规则在本文中,我们将实现一个基本的坦克对战游戏。

游戏规则如下:1. 游戏场景为一个20*20的方格。

2. 游戏中有两辆坦克,分别由玩家和电脑控制。

3. 玩家可以通过键盘控制自己的坦克移动和发射子弹。

4. 电脑会随机移动并发射子弹。

5. 当一辆坦克被击中时,游戏结束。

代码实现下面是实现上述规则所需的代码:头文件和宏定义```#include <stdio.h>#include <stdlib.h>#include <conio.h>#include <windows.h>#define WIDTH 20#define HEIGHT 20```其中,`WIDTH`和`HEIGHT`表示游戏场景的宽度和高度。

游戏场景的绘制void drawScene(char scene[WIDTH][HEIGHT]){int i, j;system("cls");for (i = 0; i < HEIGHT; i++) {for (j = 0; j < WIDTH; j++) {printf("%c", scene[i][j]);}printf("\n");}}```该函数用于绘制游戏场景。

参数`scene`是一个二维字符数组,用于表示游戏场景中每个位置的状态。

函数首先清空屏幕,然后遍历二维数组并输出对应的字符。

坦克大战源码

坦克大战源码

坦克大战源码根据韩顺平老师视频所作/**坦克大战* 防重叠*/package ;import .*;import .*;import class MyTankGame5 extends JFrame implements ActionListener{quals("newgame")){quals("exit")){quals("saveExit")){quals("continue")){etImage"/"));image2=().getImage"/"));image3=().getImage"/"));etNodesAndEnemy();etSpeed();etSpeed(0);etSpeed();etSpeed(0);边的矩形(x, y, 5, 30,false);边的矩形(x, y, 5, 30,false);etSpeed();etSpeed(0);etSpeed(esp1);;import Node{int x;int y;int direct;public Node(int x,int y,int direct){=x;=y;=direct;}}//记录坦克信息的类class Recorder{//记录敌人和我的坦克数量private static int enlife=20;private static int mylife=10;private static int deadenemy=0;private static FileWriter fw=null;private static BufferedWriter bw=null;private static FileReader fr=null;private static BufferedReader br=null;private static Vector<EnemyTank> ets=new Vector<EnemyTank>();//从文件恢复记录static Vector<Node> nodes=new Vector<Node>();//完成读取public Vector<Node> getNodesAndEnemy(){try {//创建fr=new FileReader("d:\\chen\\");br=new BufferedReader(fr);String n="";//先读取第一行n=();deadenemy=(n);//用split分割从第二行开始取while((n=())!=null){//字符串str中从第一个字符起,//每遇到一个空格则切割为一个元素,//放入[]xyd数组中String []xyd=(" ");//这里的空格数与keepRecAndEnemyTank()中//写入(String record=+" "++" "+;)//!!!!!!!!!!!!!! //的空格数要对应,否则会报错!Node node1=new Node(xyd[0]),(xyd[1]),(xyd[2]));(node1);}} catch (IOException e) {// TODO Auto-generated catch block();}finally{//关闭文件//谁先开,谁后关!try {();();} catch (IOException e) {// TODO Auto-generated catch block();}}return nodes;}public static Vector<EnemyTank> getEts() {return ets;}public static void setEts(Vector<EnemyTank> ets) { = ets;}//保存击毁敌人的数目和敌人坐标,存盘退出public static void keepRecAndEnemyTank(){try {//创建fw=new FileWriter("d:\\chen\\");bw=new BufferedWriter(fw);(deadenemy+"\r\n");//保存当前敌人的数目和坐标for(int i=0;i<();i++){//取出第一个坦克EnemyTank et=(i);//保存活的if{String record=+" "++" "+;//写入(record+"\r\n");}}} catch (IOException e) {// TODO Auto-generated catch block();}finally{//关闭文件//谁先开,谁后关!try {();();} catch (IOException e) {// TODO Auto-generated catch block();}}}//保存击毁的敌人数目public static void keepRecording(){try {//创建fw=new FileWriter("d:\\chen\\");bw=new BufferedWriter(fw);(deadenemy+"\r\n");} catch (IOException e) {// TODO Auto-generated catch block();}finally{//关闭文件//谁先开,谁后关!try {();();} catch (IOException e) {// TODO Auto-generated catch block();}}}//读取出上一局击毁的敌人数目public static void getRecording(){try {//创建fr=new FileReader("d:\\chen\\");br=new BufferedReader(fr);String n=();deadenemy=(n);} catch (IOException e) {// TODO Auto-generated catch block();}finally{//关闭文件//谁先开,谁后关!try {();();} catch (IOException e) {// TODO Auto-generated catch block();}}}public static int getEnlife() {return enlife;}public static void setEnlife(int enlife) {= enlife;}public static int getMylife() {return mylife;}public static void setMylife(int mylife) {= mylife;}//减少数量public static void reduceMylife() {;}public static void reduceEnlife() {;}public static void deadenemy() {++;public static int getDeadenemy() {return deadenemy;}}class Tank{//坦克的横坐标int x=0;//纵坐标int y=0;//暂停速度int tempspeed;public int getTempspeed() {return tempspeed;}public void setTempspeed(int tempspeed) { = tempspeed;}//颜色int color;boolean isLive=true;public boolean isLive() {return isLive;}public void setLive(boolean isLive) {= isLive;}public int getColor() {return color;}public void setColor(int color) {= color;public int getX() {return x;}public void setX(int x) {= x;}public int getY() {return y;}public void setY(int y) {= y;}public Tank (int x,int y){=x;=y;}//坦克方向//0上,1右,2下,3左int direct=0;public int getDirect() {return direct;}public void setDirect(int direct) {= direct;}//坦克的速度int speed=3;public int getSpeed() {return speed;}public void setSpeed(int speed) {= speed;}}//敌方坦克class EnemyTank extends Tank implements Runnable{//设敌人可以复活10次static int newlife=10;//计数器static int counter=0;//让坦克随机产生步数//每次走多少步int steps=(int)()*50+10);int sleeptime=200; //睡眠时间//定义一个向量存放敌人子弹Vector<Shot> ss1=new Vector<Shot>();//在敌人创建和子弹死亡后在创建子弹public EnemyTank(int x,int y){super(x,y);}//定义一个向量,访问MyPanel的所有敌人坦克Vector<EnemyTank> ets=new Vector<EnemyTank>();//得到MyPanel的所有敌人坦克public void setEts(Vector<EnemyTank> vv){=vv;}//判断是否撞到了别的敌人坦克public boolean isTouchotherEnemy(){boolean b=false;//判断switch{case 0://向上//取出敌人所有坦克for(int i=0;i<();i++){//取出第一个坦克EnemyTank et=(i);//如果不是自己if(et!=this){//如果敌人方向是向上或者向下if==0||==2){if>=&&<=+20&&>=&&<=+30){return true;}if+20>=&&+20<=+20&&>=&&<=+30){return true;}}//如果敌人方向是向左或者向右if==1||==3){if>=&&<=+30&&>=&&<=+20){return true;}if+20>=&&+20<=+30&&>=&&<=+20){return true;}}}}break;case 1://向右//取出敌人所有坦克for(int i=0;i<();i++){//取出第一个坦克EnemyTank et=(i);//如果不是自己if(et!=this){//如果敌人方向是向上或者向下if==0||==2){if+30>=&&+30<=+20&&>=&&<=+30){return true;}if+30>=&&+30<=+20&&+20>=&&+20<=+30){return true;}}//如果敌人方向是向左或者向右if==1||==3){if>=&&<=+30&&>=&&<=+20){return true;}if+30>=&&+30<=+30&&+20>=&&+20<=+20){return true;}}}}break;case 2://向下//取出敌人所有坦克for(int i=0;i<();i++){//取出第一个坦克EnemyTank et=(i);//如果不是自己if(et!=this){//如果敌人方向是向上或者向下if==0||==2){if>=&&<=+20&&+30>=&&+30<=+30){return true;}if+20>=&&+20<=+20&&+30>=&&+30<=+30){return true;}}//如果敌人方向是向左或者向右if==1||==3){if>=&&<=+30&&+30>=&&+30<=+20){return true;}if+20>=&&+20<=+30&&+30>=&&+30<=+20){return true;}}}}break;case 3://向左//取出敌人所有坦克for(int i=0;i<();i++){//取出第一个坦克EnemyTank et=(i);//如果不是自己if(et!=this){//如果敌人方向是向上或者向下if==0||==2){if>=&&<=+20&&>=&&<=+30){return true;}if>=&&<=+20&&+20>=&&+20<=+30){return true;}}//如果敌人方向是向左或者向右if==1||==3){if>=&&<=+30&&>=&&<=+20){return true;}if>=&&<=+30&&+20>=&&+20<=+20){return true;}}}}break;}return b;}public void run() {// TODO Auto-generated method stubwhile(true){switch{case 0://继续让他再走几步for(int i=0;i<steps;i++){if(y>0&&!isTouchotherEnemy()){y-=speed;}// //撞到墙或者队友就转弯||isTouchotherEnemy()// else if(y<=0)// {// //让坦克变向// =(direct+1)%4;// }try {(sleeptime);} catch (InterruptedException e) {// TODO Auto-generated catch block();}}break;case 1://继续让他再走几步for(int i=0;i<steps;i++){if(x<&&!isTouchotherEnemy()){x+=speed;}// //撞到墙或者队友就转弯// else if(x>=// {// //让坦克变向// =(direct+1)%4;// }try {(sleeptime);} catch (InterruptedException e) {// TODO Auto-generated catch block();}}break;case 2://继续让他再走几步for(int i=0;i<steps;i++){if(y<&&!isTouchotherEnemy()){y+=speed;}//撞到墙或者队友就转弯// else if(y>=// {// //让坦克变向// =(direct+1)%4;// }try {(sleeptime);} catch (InterruptedException e) {// TODO Auto-generated catch block();}}break;case 3://继续让他再走几步for(int i=0;i<steps;i++){if(x>0&&!isTouchotherEnemy()){x-=speed;}// //撞到墙或者队友就转弯// else if(x<=0)// {// //让坦克变向// =(direct+1)%4;// }try {(sleeptime);} catch (InterruptedException e) {// TODO Auto-generated catch block();}}break;}//判断是否死亡,是否暂停if==false||=={//退出线程break;}//让坦克随机产生方向=(int)()*4);}}}//我的坦克class Hero extends Tank{//设我可以复活3次static int newlife=10;//计数器static int counter=0;Vector<Shot> ss=new Vector<Shot>();//子弹Shot s=null;public Hero(int x,int y){super(x,y);}//开火public void shotEnemy(){switch{case 0:s=new Shot(x+9,y-10,0);(s);break;case 1:s=new Shot(x+35,y+9,1);(s);break;case 2:s=new Shot(x+10,y+35,2);(s);break;case 3:s=new Shot(x-9,y+9,3);(s);break;}//创建线程对象Thread t1=new Thread(s);//启动();}//坦克向上移动public void moveUp(){if(y>0&&{y-=speed;}}//坦克向右移动public void moveRight(){if(x<&&{x+=speed;}}//坦克向下移动public void moveDown(){if(y<&&{y+=speed;}}//坦克向左移动public void moveLeft(){if(x>0&&{x-=speed;}}}//炸弹类class Bomb{//定义炸弹坐标int x,y;//炸弹生命int life=3;boolean isLive=true;public Bomb(int x,int y){=x;=y;}//减少生命值public void lifeDown(){if(life>0){life--;}else{=false;}}}//子弹类class Shot implements Runnable{//坐标int x;int y;int direct;int speed=5;public int getDirect() {return direct;}public void setDirect(int direct) {= direct;}public int getSpeed() {return speed;}public void setSpeed(int speed) {= speed;}//是否还活着boolean isLive=true;public Shot(int x,int y,int direct){=x;=y;=direct;}public void run(){while(true){try {(50);} catch (InterruptedException e) {// TODO Auto-generated catch block();}switch(direct){case 0://上方向y-=speed;break;case 1://向右x+=speed;break;case 2://向下y+=speed;break;case 3://向左x-=speed;break;}//"子弹坐标:"+"("+x+","+y+")");//子弹何时死亡?//判断该子弹是否碰到窗口边缘if(x<0||x>||y<0||y>{=false;break;}}}}//播放声音的类class AePlayWave extends Thread {private String filename;public AePlayWave(String wavfile){filename = wavfile;}public void run() {File soundFile = new File(filename);AudioInputStream audioInputStream = null;try {audioInputStream = (soundFile);} catch (Exception e1) {();return;}AudioFormat format = ();SourceDataLine auline = null;info = new , format);try {auline = (SourceDataLine) (info);(format);} catch (Exception e) {();return;}();int nBytesRead = 0;//这是缓冲byte[] abData = new byte[512];try {while (nBytesRead != -1){nBytesRead = (abData, 0, ;if (nBytesRead >= 0)(abData, 0, nBytesRead);}} catch (IOException e) {();return;} finally {();();}}}。

C大作业坦克大战

C大作业坦克大战

C大作业坦克大战文档编制序号:[KKIDT-LLE0828-LLETD298-POI08]#include<iostream>#include<>#include<>#include<>#include<>usingnamespacestd;HANDLEMutex=CreateMutex(NULL,FALSE,NULL);//互斥对象intGameOver=0;intlevel=0;intmap[23][23];//坦克种类,Normal为玩家坦克#defineNormal0#defineRed1#defineBlue2#defineGreen3//方向的宏定义#defineUp0#defineDown1#defineLeft2#defineRight3//地图标记的宏定义#defineEmpty0#definePlayer1#definePlayerBullet2#defineEnemyBullet3#defineEnemy4intKill;intKillRed;intKillGreen;intEnemyExist;voidSetPos(inti,intj)//设定光标位置{COORDpos={i,j};HANDLEOut=GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleCursorPosition(Out,pos);}voidHideCurSor(void)//隐藏光标{CONSOLE_CURSOR_INFOinfo={1,0};HANDLEOut=GetStdHandle(STD_OUTPUT_HANDLE);SetConsoleCursorInfo(Out,&info);}intsharp[4][12]={{0,1,1,0,1,1,1,2,2,0,2,2},{0,0,0,2,1,0,1,1,1,2,2,1},{0,1,0,2,1,0,1,1,2,1,2,2},{0,0,0,1,1,1,1,2,2,0,2,1},};//此数组用来保存坦克各个方向的形状信息DWORDWINAPIBulletfly(LPVOIDlpParameter);//子弹函数申明voidUpdata();//更新界面信息函数申明classTank//坦克类{private:intDirection;//方向inthotpoint[2];//活动点intSpeed;//速度intFirePower;//火力public:Tank(intdir,inthot1,inthot2,inttyp,intspe,intfirepow)//构造函数{Direction=dir;hotpoint[0]=hot1;hotpoint[1]=hot2;Type=typ;Speed=spe;FirePower=firepow;}intType;//坦克的种类(详见宏定义)intID;//坦克在MAP中的标记(详见宏定义)intFireEnable;//是否可以开火intLife;//生命值voidRunning();//运行函数intJudge(intx,inty,intID);//判断是否可以绘制坦克voidDrawTank();//重绘坦克voidRedraw();//擦除坦克intGetSpeed()//获取速度{returnSpeed;}intGetFire()//获取火力{returnFirePower;}intGetDirection()//获取方向{returnDirection;}intGetHotX()//获取活动点坐标{returnhotpoint[0];}intGetHotY(){returnhotpoint[1];}voidIncreaseFire()//火力+{FirePower++;}voidIncreaseSpeed()//速度+{Speed++;}voidChangeDirection(intnewD)//改变方向{Direction=newD;}voidChangePos(intx,inty)//改变活动点{hotpoint[0]=x;hotpoint[1]=y;}};Tankplayer(Right,0,0,Normal,1,1);//玩家Tankenemy(Left,20,0,Red,1,1);//敌人voidTank::DrawTank()//绘制坦克{inti;intnx,ny;if(Type==Red)SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),FOREG ROUND_INTENSITY|FOREGROUND_RED);elseif(Type==Blue)SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),FOREG ROUND_INTENSITY|FOREGROUND_BLUE);elseif(Type==Green)SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),FOREG ROUND_INTENSITY|FOREGROUND_GREEN);elseif(Type==Normal)SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),FOREG ROUND_INTENSITY|FOREGROUND_RED|FOREGROUND_GREEN|FOREGRO UND_BLUE);for(i=0;i<6;i++){nx=hotpoint[0]+sharp[Direction][i*2];ny=hotpoint[1]+sharp[Direction][i*2+1];SetPos((ny+1)*2,nx+1);//利用sharp数组相对于点x,y绘制形状map[nx][ny]=ID;cout<<"■";}}voidTank::Redraw()//擦除坦克,原理同上{inti;intnx,ny;for(i=0;i<6;i++){nx=hotpoint[0]+sharp[Direction][i*2];ny=hotpoint[1]+sharp[Direction][i*2+1];map[nx][ny]=Empty;SetPos((ny+1)*2,nx+1);cout<<"";}}intTank::Judge(intx,inty,intdir)//判断当前是否可以绘制坦克{inti;intnx,ny;for(i=0;i<6;i++){nx=x+sharp[dir][i*2];ny=y+sharp[dir][i*2+1];if(nx<0||nx>=23||ny<0||ny>=23||map[nx][ny]!=Empty)//不能绘制,返回1return1;}return0;}voidTank::Running()//坦克运行函数{intnewD;//坦克的运行while(1){if(Life==0){EnemyExist=0;//敌人不存在return;}if(GameOver==1)return;if(FireEnable==1&&GameOver==0)//如果可以开火{WaitForSingleObject(Mutex,INFINITE);//线程拥有互斥对象FireEnable=0;//设为不可开火HANDLEbullet=CreateThread(NULL,0,Bulletfly,&ID,0,NULL);//创建子弹线程CloseHandle(bullet);ReleaseMutex(Mutex);//释放互斥对象Sleep(100);}WaitForSingleObject(Mutex,INFINITE);//线程拥有互斥对象srand((int)time(0));newD=rand()%4;if(newD==Up)//随机出新的方向并重新绘制坦克{Redraw();if(Judge(hotpoint[0]-1,hotpoint[1],newD)==0){hotpoint[0]--;Direction=newD;}else{if(Judge(hotpoint[0],hotpoint[1],newD)==0)Direction=newD;}}elseif(newD==Down){Redraw();if(Judge(hotpoint[0]+1,hotpoint[1],newD)==0){hotpoint[0]++;Direction=newD;}else{if(Judge(hotpoint[0],hotpoint[1],newD)==0)Direction=newD;}}elseif(newD==Left){Redraw();if(Judge(hotpoint[0],hotpoint[1]-1,newD)==0){hotpoint[1]--;Direction=newD;}else{if(Judge(hotpoint[0],hotpoint[1],newD)==0)Direction=newD;}}elseif(newD==Right){Redraw();if(Judge(hotpoint[0],hotpoint[1]+1,newD)==0){hotpoint[1]++;Direction=newD;}else{if(Judge(hotpoint[0],hotpoint[1],newD)==0)Direction=newD;}}if(GameOver==0&&Life!=0)DrawTank();ReleaseMutex(Mutex);//释放互斥对象Sleep(500-80*Speed);}}/*********************子弹线程函数*******************/ DWORDWINAPIBulletfly(LPVOIDlpParameter){int*ID=(int*)lpParameter;//ID用来获取发射子弹坦克的IDintPos[2];//子弹活动点intdirection;intSpeed;inttype;inthit=0;//击中标记intoldx,oldy;//旧活动点intflag=0;//子弹是否有移动的标记if(*ID==Player)//如果是玩家坦克{type=PlayerBullet;direction=();Speed=();Pos[0]=();Pos[1]=();}elseif(*ID==Enemy)//如果是敌人坦克{type=EnemyBullet;direction=();Speed=();Pos[0]=();Pos[1]=();}if(direction==Up)//根据坦克的位置和方向确定子弹的初始坐标{Pos[0]--;Pos[1]++;}elseif(direction==Down){Pos[0]+=3;Pos[1]++;}elseif(direction==Left){Pos[0]++;Pos[1]--;}elseif(direction==Right){Pos[0]++;Pos[1]+=3;}//子弹的运行while(1){WaitForSingleObject(Mutex,INFINITE);//这个不再注释了。

坦克大战的游戏代码

坦克大战的游戏代码

using System;using System.Collections.Generic;using System.Text;using System.Drawing; //addusing System.Collections;//addnamespace 坦克{class Tank{private int width; //坦克的宽度private int height; //坦克的高度private int top; //坦克位置的纵坐标private int left; //坦克位置的横坐标private int type; //坦克的类型(2---5敌方,6己方)private int direct; //0--上,1--下,2--左,3--右public ArrayList bList=new ArrayList();//子弹序列public Tank(int tank_type)//构造函数{Random r = new Random();this.direct = r.Next(0, 4);//产生0—3的数this.width = 32;this.height = 32;this.left = r.Next(0, 1);//产生0—9的数this.top = r.Next(0, 1);//产生0—9的数this.type = tank_type;}public int Top//Top属性{get{return top;}set{if (top >= 0 && top <= 9){top = value;//if (top == 0 || top == 9) newDirect();}}}public int Type//坦克的类型属性{get{return type;}set{if (top >= 1 && top <= 5){type = value;}}}public int Left//Left属性{get{return left;}set{if (left >= 0 && left <= 9){left = value;//if (left == 0 || left == 9) newDirect();}}}public int Direct//Direct属性(坦克方向){get{return direct;}set{direct = value;}}public void newDirect()//改变方向{Random r = new Random();int new_Direct=r.Next(0, 4);//产生0—3的数while(this.direct == new_Direct)new_Direct = r.Next(0, 4);//产生0—3的数this.direct = new_Direct;}public void Draw(Graphics g,int type)//根据坦克类型选择不同图片{Image tankImage = Image.FromFile("BMP/ETANK1.BMP");if (type == 2) tankImage = Image.FromFile("BMP/ETANK2.BMP");if (type == 3) tankImage = Image.FromFile("BMP/ETANK3.BMP");if (type == 4) tankImage = Image.FromFile("BMP/ETANK4.BMP");if (type == 5) tankImage = Image.FromFile("BMP/ETANK1.BMP");if (type == 6) tankImage = Image.FromFile("BMP/MYTANK.BMP");//得到绘制这个坦克图形的在游戏面板中的矩形区域Rectangle destRect = new Rectangle(this.left * width, this.top * height, width,height);Rectangle srcRect = new Rectangle(direct * width, 0, width, height);g.DrawImage(tankImage,destRect,srcRect,GraphicsUnit.Pixel );}public void Explore(Graphics g)//坦克爆炸动画{//得到绘制这个坦克图形的在游戏面板中的矩形区域Rectangle destRect = new Rectangle(this.left * width, this.top * height, width, height);Rectangle srcRect = new Rectangle(0, 0, width, height);Image tankImage = Image.FromFile("BMP/explode1.bmp");g.DrawImage(tankImage, destRect, srcRect, GraphicsUnit.Pixel);tankImage = Image.FromFile("BMP/explode1.bmp");g.DrawImage(tankImage, destRect, srcRect, GraphicsUnit.Pixel);tankImage = Image.FromFile("BMP/explode2.bmp");g.DrawImage(tankImage, destRect, srcRect, GraphicsUnit.Pixel);PlaySound.Play("Sound/Explode.wav");}public void fire(){bullet b = new bullet(this.type);//根据坦克产生不同子弹b.Direct = this.Direct;//坦克的朝向b.Top = this.Top;b.Left = this.Left;//b.move();bList.Add(b);if(this.type==6) PlaySound.Play("Sound/Shoot.wav");//己方发射出声}public void MoveBullet(ref int [,]Map){for (int i = bList.Count-1; i>=0; i--)//遍历子弹序列//for (int i = 0; i < bList.Count;i++ ){bullet t = ((bullet)bList[i]);//移动以前if (t.Left < 0 || t.Left > 9 || t.Top < 0 || t.Top > 9)//超出边界{bList.RemoveAt(i); continue;//删除此颗子弹}if (Map[t.Left, t.Top] != 0 && Map[t.Left, t.Top]!= this.type )//已遇到坦克和墙等障碍物{bList.RemoveAt(i);//删除此颗子弹if (t.hitE(Map[t.Left, t.Top]))//击中对方坦克Map[t.Left, t.Top] = -1;//此处坦克被打中continue;}t.move();//移动以后if (t.Left < 0 || t.Left > 9 || t.Top < 0 ||t.Top > 9)//超出边界{bList.RemoveAt(i);continue;//删除此颗子弹}if (Map[t.Left, t.Top] != 0)//已遇到物体{bList.RemoveAt(i);//删除此颗子弹if (t.hitE(Map[t.Left, t.Top]))//击中对方坦克Map[t.Left, t.Top] = -1;//此处坦克被打中continue;}}}public void DrawBullet(Graphics g,int [,]Map)//画子弹{MoveBullet(ref Map);foreach (bullet t in bList)//遍历子弹序列t.Draw(g);}//public void NewPosition()//产生新坐标//{// Random r = new Random();// this.left = r.Next(0, 10);//产生0—9的数// this.top = r.Next(0, 10);//产生0—9的数//}//public bool ComparePosition(Tank s)//比较坦克位置//{// if (this.left == s.left && this.top == s.top)// return true;// else// return false;//}}}。

c语言程序设计_坦克大战(提高篇)(funcode环境)

c语言程序设计_坦克大战(提高篇)(funcode环境)

C语言课程设计--坦克大战一、游戏介绍玩家坦克与敌方坦克在街道中进行巷战,玩家坦克被击中、玩家指挥部被击中或游戏时间到,一局游戏结束。

二、实验目的综合应用C语言知识和设计知识开发一款小游戏。

三、实验内容初始界面如下图。

按下空格键后游戏开始,“空格开始”消失,载入地图,并把玩家坦克设置在指挥部左侧。

游戏时间到,比如30秒,玩家坦克被敌方坦克摧毁,或者玩家指挥部被摧毁,一局游戏结束,游戏回到初始界面,并显示上一局的分数。

游戏区域为下图中最内部的黑色区域,左上角坐标[-26, -22],右下角坐标为[26, 22]。

墙为正方形,边长为4,坦克也是正方形,比墙略小一点。

玩家用WASD键控制坦克上、下、左、右运行,按J键开炮。

玩家坦克碰到墙就停下来,需要调转方向才能继续前进。

玩家坦克开炮,一炮就能摧毁一块墙,或者一辆敌方坦克。

玩家没摧毁一辆敌方坦克,加1分。

玩家指挥部被坦克或者炮弹(不管玩家还是敌方)碰上,都会被摧毁。

每隔几秒钟,比如3秒,就会产生一辆敌方坦克。

敌方坦克每隔一段时间,比如1秒,就自动开炮。

敌方坦克遇到墙就会停下来。

停下来的坦克,前方的墙如果被摧毁了,又能继续前进。

每隔几秒钟,比如2秒,敌方坦克就会顺时针变换一个方向前进。

四、实验准备本实验中可能用到的C语言标准库函数和FunCode APIStdio.h函数原型功能与返回值参数说明与应用举例int sprintf( char *buffer, const char *format,[ argument] … ) ; 把格式化的数组写入某个字符串。

返回值:字符串长度char szName[128];int i=0;sprintf(szName, ”feichong_%d”, i);将字符串”feichong_0”写入到szName中Math.h函数原型功能与返回值参数说明与应用举例double atan2( double y, double x ); 计算y/x的反正切值。

百度之星坦克大战代码

百度之星坦克大战代码

#include "Tank.h"#include <string.h>#include "main.cpp"//请勿修改以上头文件/* 您可以在这里添加您所需头文件*/#include "stdio.h"#include <vector>#include <set>using namespace std;/* 您可以在这里添加您的自定义函数*//* A*寻路算法*/// 所需结构定义typedef struct node // aStar 算法需要的动态表节点{int id;int father; // 父节点编号int cost; // 从初始位置到达此次的花费g(x)}node;static vector<node> openT; // open表static vector<node> closedT; // closed表static vector<int> path[MAX_TANK_NUM]; // 路径存储位置static set<int> targeted; // 标记目标矿点是否被己方锁定,存在则锁定int point2id(int row, int col) // 节点编号{int id = row * (MAP_WIDTH + 2) + col;return id;}Point id2point(int id) // 节点反编号{Point po;po.row = id / (MAP_WIDTH + 2);po.col = id % (MAP_WIDTH + 2);return po;}// 查找某vector表中是否有一节点int find(int id, vector<node> vet){if (vet.empty()){return -1;}for (int i = 0; i < vet.size(); i ++){if (id == vet[i].id){return i;}}return -1;}// 查找当然位置在path[myID]中的indexint findPathIdx(int id, vector<int> pathT){if (pathT.empty()){return -1;}for (int i = 0; i < pathT.size(); i ++){if (id == pathT[i]){return i;}}return -1;}// 返回从一节点到邻近节点的花费(坦克要走的步数)// 可通过PERVIOUS为1,BRICK为2,BREAKBRICK为3 int addcost(CellType type){switch(type) {case PERVIOUS:return 1;break;case BRICK:return 2;break;default:return 3;}}// 对给定扩展点进行检测添加void addExtNode(node tmpNode, int extid, CellType type){Point extPo;node extNode;extPo = id2point(extid);if ((-1 == find(extid, closedT)) && (STONE != type)) // 要扩展点不在closed表中,且不为石头则扩展{int idx = find(extid, openT); // 在open表中的索引if (-1 == idx) // 如果不在open表中则添加{extNode.id = extid;extNode.father = tmpNode.id;extNode.cost = tmpNode.cost + addcost(type);openT.push_back(extNode);}else // 如果在open表中,看新路径是否更近,近则修改{if (tmpNode.cost + addcost(type) < openT[idx].cost){openT[idx].father = tmpNode.id;openT[idx].cost = tmpNode.cost + addcost(type);}}}}// 得到本坦克的路径void getPath(int myID, int goalIdx){// id为myID的坦克路径存于path[myID]中path[myID].clear();node tmpNode = openT[goalIdx];path[myID].insert(path[myID].begin(), tmpNode.id);/*Point debug_po = id2point(tmpNode.id);printf("Path Star!\nGoal (%d, %d)\n", debug_po.row, debug_po.col);*/while (-1 != tmpNode.father){int tmpIdx = find(tmpNode.father, closedT);//printf("%d ", tmpIdx);if (-1 != tmpIdx){tmpNode = closedT[tmpIdx];/*Point debug_po = id2point(tmpNode.id);printf("(%d, %d)\n", debug_po.row, debug_po.col);*/path[myID].insert(path[myID].begin(), tmpNode.id);}else{path[myID].clear();return;}}}// 根据下一步目标返回:方向运动指令OrderType getOrder(FlagType myFlag, Point mySite, Point nextStep){int rowD = nextStep.row - mySite.row;printf("%d ",rowD);int colD = nextStep.col - mySite.col;printf("%d ",colD);switch(rowD){case -1:return GOUP;break;case 1:return GODOWN;break;default:;}switch(colD){case -1:return GOLEFT;break;case 1:return GORIGHT;break;default:;}return STOP;}// A*寻路算法,路径存储在path[myID]中void aStar(int myID, Point start, Point goal, MapCell map[][MAP_WIDTH +2]) {openT.clear();closedT.clear();path[myID].clear();// 1. 把初始节点放入openTnode tmpNode;tmpNode.id = point2id(start.row, start.col);tmpNode.father = -1; // 初始节点无父节点tmpNode.cost = 0;openT.push_back(tmpNode);// 2. 如果openT为空,搜索失败退出bool findGoal = false;while (! openT.empty() && ! findGoal){tmpNode = openT[0];int no = 0; // 记录最小f(x)的索引//3. 移除openT中f(x)值最小的Point p1 = id2point(tmpNode.id); // 当前考察点位置int hx1 = abs(goal.row - p1.row) + abs(goal.col - p1.col); // 当前路径costint fx1 = hx1 + tmpNode.cost;// 寻找f(x)最小的节点for (int i = 0; i < openT.size(); i ++){node tmpNode2 = openT[i];Point p2 = id2point(tmpNode2.id);int hx2 = abs(goal.row - p2.row) + abs(goal.col - p2.col);int fx2 = hx2 + tmpNode2.cost;if (fx1 > fx2){tmpNode = openT[i];no = i;}}// 如果节点为目标节点,则路径找到,返回路径if (point2id(goal.row, goal.col) == tmpNode.id){// 存储路径getPath(myID, no); // 当目标在open中,得到的最小f(x)的点是目标节点索引为no return;}// 从openT移节点如closedT中openT.erase(openT.begin() + no);closedT.push_back(tmpNode);//4. 从四个方向扩展节点Point tmpPo;tmpPo = id2point(tmpNode.id);int extid;CellType type;// 上extid = point2id(tmpPo.row - 1, tmpPo.col);type = (map[tmpPo.row - 1][tmpPo.col]).type;addExtNode(tmpNode, extid, type);// 下extid = point2id(tmpPo.row + 1, tmpPo.col);type = (map[tmpPo.row + 1][tmpPo.col]).type;addExtNode(tmpNode, extid, type);// 左extid = point2id(tmpPo.row, tmpPo.col - 1);type = (map[tmpPo.row][tmpPo.col - 1]).type;addExtNode(tmpNode, extid, type);// 右extid = point2id(tmpPo.row, tmpPo.col + 1);type = (map[tmpPo.row][tmpPo.col + 1]).type;addExtNode(tmpNode, extid, type);}}//平台0回合时调用此函数获取AI名称及坦克类型信息,请勿修改此函数声明。

坦克大战代码

坦克大战代码

坦克大战代码// 1、TTank.cpp: implementation of the TTank class.坦克类////////////////////////////////////////////////////////////////////////#include "stdafx.h"#include "TankWar.h"#include "TTank.h"#include "TWorld.h"#include "TExplode.h"#include "TBonus.h"#include "TBullet.h"//////////////////////////////////////////////////////////////////////// Construction/Destruction/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEnemyTank///////////////////////////////////////////////////////////////////EPG TEnemyTank::m_epg[3];//////////////////////////////////////////////////敌军坦克移动void TEnemyTank::Move(){if(!IsMyTime())return ;//防护小于0,还不死吗if(m_nShield < 0){Dead();//玩家增加经验值g_world.Player(0)->m_nExper += 10 + m_nType * 10;//加点爆炸效果g_world.ExplodeLink().Add(NEWTExplode(m_nX,m_nY,EXPLODE_TANK));}///////////////////////////////////////////////////////疯子要行动了,怎么动呢?用随机数来决定吧//玩家没进入范围,什么也不做if(ABS(m_nX-g_world.Player(0)->GetX())>500 ||ABS(m_nY-g_world.Player(0)->GetY())>500)return ;//产生0到100之间的随机数状态int status=Rand(0,100);//保存现在的位置坐标int x=m_nX,y=m_nY;//根据产生的状态行动if(status<2){//状态小于2,改变一下方向(概率是... 计算一下好像是: 2/100即0.02)m_dir =(DIRECTION) Rand(0,4);}else if(status <3){//状态小于3,开火(概率是... 计算一下好像是: (3-2)/100即0.01)switch(m_nType){case FIRE_TANK://火弹:射程100,威力20g_world.BulletLink().Add(NEWTBullet(m_nX,m_nY,m_dir,FIRE,20,100));break;case DOUBLE_MISSILE_TANK://火弹:射程250,威力15g_world.BulletLink().Add(NEWTBullet(m_nX,m_nY,m_dir,DMISSILE,15,250));break;case SINGLE_MISSILE_TANK://火弹:射程250,威力10g_world.BulletLink().Add(NEWTBullet(m_nX,m_nY,m_dir,SMISSILE,10,250));break;}}else{//其它的状态值就表示运行吧(概率是... 计算一下好像是: 100-3/100即0.97)//生命在于运动嘛:)m_nX+=g_nDirXY[m_dir][0];m_nY+=g_nDirXY[m_dir][1];}///////////////////////////////////////////////////////计算一下上面的移动是否有效//先假设移动有效BOOL canMove=TRUE;//取得自己的边框RECT rc;GetRect(rc);//////////////////////////////////////////////////////根据方向来计算是否与障碍地图上的障碍物碰撞if(m_dir==DIR_UP){//方向向上,只检查左上角及右上角坐标是否碰到障碍if(g_world.ObstacleMap(rc.left/OBSTACLE_WIDTH,rc.top/OBSTACLE_HEIG HT))canMove = FALSE;elseif(g_world.ObstacleMap(rc.right/OBSTACLE_WIDTH,rc.top/OBSTACLE_HEIGHT ))canMove = FALSE;}else if(m_dir==DIR_DOWN){//方向向下,只检查左下角及右下角坐标是否碰到障碍if(g_world.ObstacleMap(rc.left/OBSTACLE_WIDTH,rc.bottom/OBSTACLE_H EIGHT))canMove = FALSE;elseif(g_world.ObstacleMap(rc.right/OBSTACLE_WIDTH,rc.bottom/OBSTACLE_HEI GHT))canMove = FALSE;}else if(m_dir==DIR_RIGHT){//方向向右,只检查右下角及右上角坐标是否碰到障碍if(g_world.ObstacleMap(rc.right/OBSTACLE_WIDTH,rc.top/OBSTACLE_HEI GHT))canMove = FALSE;elseif(g_world.ObstacleMap(rc.right/OBSTACLE_WIDTH,rc.bottom/OBSTACLE_HEI GHT))canMove = FALSE;}else if(m_dir==DIR_LEFT){//方向向左,只检查左上角及左上角坐标是否碰到障碍if(g_world.ObstacleMap(rc.left/OBSTACLE_WIDTH,rc.top/OBSTACLE_HEIG HT))canMove = FALSE;elseif(g_world.ObstacleMap(rc.left/OBSTACLE_WIDTH,rc.bottom/OBSTACLE_HEIG HT))canMove = FALSE;}//总不能移到世界范围以外吧if(m_nY>g_world.GetHeight()-OBSTACLE_HEIGHT ||m_nX>g_world.GetWidth()-OBSTACLE_WIDTH ||m_nX<0 || m_nY<0)canMove = FALSE;//有没有碰到其它的NC坦克?不过要记住排除与自己相撞的情况//疯子也不会疯到这种程度吧if(g_world.EnemyTankLink().HitTestAll(this))//停下来,打个招呼canMove = FALSE;//撞到了其它障碍物(木箱、邪恶之源)了吗?if(g_world.ObstacleLink().HitTestAll(this))canMove = FALSE;//碰到玩家坦克了吗?if(g_world.Player(0)->HitTest(this))//当然不能动了canMove = FALSE;//移动无效,恢复原值if(canMove==FALSE)m_nX = x,m_nY=y;////////////////////////////计算当前动画帧m_nCurrentFrame=m_dir;}////////////////////////////////////////////////////画坦克void TEnemyTank::Draw(){POINT p;p.x = m_nX;p.y = m_nY;g_world.LPToDP(p);WGE_Surface.Blt(m_epg[m_nType],m_nCurrentFrame,p.x,p.y );}///////////////////////////////////////////取边框void TEnemyTank::GetRect(RECT& rc){rc.left = m_nX - m_epg[m_nType].GetFrame(m_nCurrentFrame)->m_nKeyX;rc.top = m_nY - m_epg[m_nType].GetFrame(m_nCurrentFrame)->m_nKeyY;rc.bottom = rc.top + m_epg[m_nType].GetFrame(m_nCurrentFrame)->m_dwHeight ;rc.right = rc.left + m_epg[m_nType].GetFrame(m_nCurrentFrame)->m_dwWidth ;}/////////////////////////////////////////////////TEnemyTank::TEnemyTank(int x, int y, int nType):TSprite(x,y,100,0,CLASS_TENEMYTANK),m_nType(nType){switch(nType){case FIRE_TANK://防护力100,速度1/(50/1000)m_nShield = 100;SetDelayTimer(50);break;case DOUBLE_MISSILE_TANK://防护力150,速度1/(70/1000)m_nShield = 150;SetDelayTimer(70);break;case SINGLE_MISSILE_TANK://防护力100,速度1/(30/1000)m_nShield = 200;SetDelayTimer(30);break;}}///////////////////////////////////////////////////////////碰撞是否有效BOOL TEnemyTank::HitBy(TObject * pObj){//////////////////////////////////////////////与参数对象碰撞if(HitTest(pObj)){////////////////////////////////////////////参数对象是一个子弹if(pObj->ClassType()==CLASS_TBULLET){//转变为子弹对象TBullet * pBullet = (TBullet*)pObj;if(pBullet->m_nType == LIGHT){//是光弹,防护减去光弹的力量m_nShield -= pBullet->m_nShield ;return TRUE;}}}return FALSE;}///////////////////////////////////////////////////////////////////////// TPlayerTank玩家///////////////////////////////////////////////////////////////////EPG TPlayerTank::m_epg[3];TPlayerTank::TPlayerTank(int x, int y, int nType):TSprite(x,y,100,0,CLASS_TPLAYERTANK),m_nType(nType),m_nExper(0),m_nMoney(0),m_nMaxShield(100){SetDelayTimer(1); //参考值40,这里是1}///////////////////////////////////////////////////碰撞是否有效BOOL TPlayerTank::HitBy(TObject * pObj){/////////////////////////////////////////////是否与参数对象碰撞if(HitTest(pObj)){if(pObj->ClassType()==CLASS_TBULLET){//参数对象炮弹TBullet * pBullet = (TBullet*)pObj;if(pBullet->m_nType == FIRE||pBullet->m_nType == DMISSILE||pBullet->m_nType == SMISSILE){//被火弹,双导弹,单导弹(都是敌方的炮弹)击中,减防护力// m_nShield -= pBullet->m_nShield ;m_nShield += pBullet->m_nShield ;return TRUE;}}else if(pObj->ClassType()==CLASS_TBONUS){//参数对象是奖励TBonus * pBonus = (TBonus*)pObj;switch(pBonus->m_nBonusType){case BONUS_RECOVER: //恢复物品m_nShield += 20; //恢复20点m_nShield = MIN(m_nShield+20,m_nMaxShield);break;case BONUS_EXPER: //经验物品//m_nExper += 10; //经验值加10m_nType = MIN((m_nExper/1000),2); //第1000点升一级m_nMaxShield = 100 + m_nExper/100; //调整最大防护m_dwDelayTimer -= m_dwDelayTimer*10/100; //速度提高10%break;case BONUS_MONEY:m_nMoney += 100; //得到100元}return TRUE;}}return FALSE;}///////////////////////////////////////////////////////玩家坦克移动void TPlayerTank::Move(){if(!IsMyTime())return ;/*if(m_nShield<0){Dead();g_world.ExplodeLink().Add(NEWTExplode(m_nX,m_nY,EXPLODE_PLAYER));return;}*//////////////////////////////////////////////////////响应键盘事件,移动坦克//保存原坐标int x=m_nX,y=m_nY;//处理按键if(WGE_Input.Key()[DIK_UP]){if(m_nY>0) m_nY -- ;m_dir = DIR_UP;}elseif(WGE_Input.Key()[DIK_DOWN]){if(m_nY<g_world.GetHeight()-OBSTACLE_HEIGHT)m_nY += 1;m_dir = DIR_DOWN;}elseif(WGE_Input.Key()[DIK_LEFT]){if(m_nX>0) m_nX -= 1;m_dir = DIR_LEFT;}elseif(WGE_Input.Key()[DIK_RIGHT]){if(m_nX<g_world.GetWidth()-OBSTACLE_WIDTH)m_nX += 1;m_dir = DIR_RIGHT;}///////////////////////////////////////////////////////////计算上面的移动是否有效BOOL canMove=TRUE; //假设有效先RECT rc;GetRect(rc);//是否碰撞地形障碍?方法和敌人坦克一样if(m_dir==DIR_UP){if(g_world.ObstacleMap(rc.left/OBSTACLE_WIDTH,rc.top/OBSTACLE_HEIG HT))canMove = TRUE;elseif(g_world.ObstacleMap(rc.right/OBSTACLE_WIDTH,rc.top/OBSTACLE_HEIGHT ))canMove = TRUE;}elseif(m_dir==DIR_DOWN){if(g_world.ObstacleMap(rc.left/OBSTACLE_WIDTH,rc.bottom/OBSTACLE_H EIGHT))canMove =TRUE;elseif(g_world.ObstacleMap(rc.right/OBSTACLE_WIDTH,rc.bottom/OBSTACLE_HEI GHT))canMove = TRUE;}elseif(m_dir==DIR_RIGHT){if(g_world.ObstacleMap(rc.right/OBSTACLE_WIDTH,rc.top/OBSTACLE_HEIGHT))canMove = TRUE;elseif(g_world.ObstacleMap(rc.right/OBSTACLE_WIDTH,rc.bottom/OBSTACLE_HEI GHT))canMove = TRUE;}elseif(m_dir==DIR_LEFT){if(g_world.ObstacleMap(rc.left/OBSTACLE_WIDTH,rc.top/OBSTACLE_HEIG HT))canMove = TRUE;elseif(g_world.ObstacleMap(rc.left/OBSTACLE_WIDTH,rc.bottom/OBSTACLE_HEIG HT))canMove = TRUE;}//碰到了敌人的坦克没有?if(g_world.EnemyTankLink().HitTestAll(this))canMove = FALSE;//是否碰到了障碍物(木箱或邪恶源)if(g_world.ObstacleLink().HitTestAll(this))canMove = FALSE;//移动无效,恢复原坐标if(canMove==FALSE)m_nX = x,m_nY=y;//计算当前动画帧m_nCurrentFrame=m_dir;//按左CTRL键开火,不过每100ms才能开一次,加弹总要花点时间吧:)static DWORD dwFireTick=GetTickCount();if(GetTickCount()-dwFireTick>10) //参考值100ms,这里是10ms{if(WGE_Input.Key()[DIK_LCONTROL]||WGE_Input.Key()[DIK_RCONTROL ]){g_world.BulletLink().Add(NEWTBullet(m_nX,m_nY,m_dir,LIGHT,10+m_nMoney/300,100+m_nType*25));}dwFireTick=GetTickCount();}//让玩家坦克处于可视区的中央g_world.GetViewportRect(rc);int height= rc.bottom - rc.top - OBSTACLE_HEIGHT;int width= rc.right - rc.left - OBSTACLE_WIDTH;g_world.SetViewport(m_nX-width/2,m_nY-height/2);}////////////////////////////////////////////////////////画玩家坦克void TPlayerTank::Draw(){POINT p;p.x = m_nX;p.y = m_nY;g_world.LPToDP(p);WGE_Surface.Blt(m_epg[m_nType],m_nCurrentFrame,p.x,p.y );}/////////////////////////////////////////////////返回坦克的边框void TPlayerTank::GetRect(RECT& rc){rc.left = m_nX - m_epg[m_nType].GetFrame(m_nCurrentFrame)->m_nKeyX;rc.top = m_nY - m_epg[m_nType].GetFrame(m_nCurrentFrame)->m_nKeyY;rc.bottom = rc.top + m_epg[m_nType].GetFrame(m_nCurrentFrame)->m_dwHeight ;rc.right = rc.left + m_epg[m_nType].GetFrame(m_nCurrentFrame)->m_dwWidth ;}//2、TBonus.cpp: implementation of the TBonus class.奖励类////////////////////////////////////////////////////////////////////////#include "stdafx.h"#include "TBonus.h"#include "TWorld.h"EPG TBonus::m_epg_bonus[3];ESound TBonus::m_sound[1];//////////////////////////////////////////////////////////////////////// Construction/Destruction//////////////////////////////////////////////////////////////////////TBonus::~TBonus(){}TBonus::TBonus(int x, int y, BONUS nBonusType):TObject(x,y,CLASS_TBONUS){m_nBonusType = nBonusType ;m_nCurrentFrame = 0;m_dwDelayTimer= 100;}void TBonus::Draw(){POINT p;p.x = m_nX;p.y = m_nY;g_world.LPToDP(p);WGE_Surface.Blt(m_epg_bonus[m_nBonusType],m_nCurrentFrame,p.x,p.y );}void TBonus::GetRect(RECT &rc){rc.left = m_nX - m_epg_bonus[m_nBonusType].GetFrame(m_nCurrentFrame)->m_nKeyX;rc.top = m_nY - m_epg_bonus[m_nBonusType].GetFrame(m_nCurrentFrame)->m_nKeyY;rc.bottom = rc.top + m_epg_bonus[m_nBonusType].GetFrame(m_nCurrentFrame)->m_dwHeight ;rc.right = rc.left + m_epg_bonus[m_nBonusType].GetFrame(m_nCurrentFrame)->m_dwWidth ;}void TBonus::Move(){if(!IsMyTime())return ;if(g_world.Player(0)->HitBy(this)){Dead();m_sound[0].Play();}++m_nCurrentFrame%=m_epg_bonus[m_nBonusType].GetFrameCount();}//3、TBullet.cpp: implementation of the TBullet class.子弹类////////////////////////////////////////////////////////////////////////#include "stdafx.h"#include "TBullet.h"#include "TExplode.h"#include "Tworld.h"ESound TBullet::m_sound[4];EPG TBullet::m_epg[4];//////////////////////////////////////////////////////////////////////// Construction/Destruction//////////////////////////////////////////////////////////////////////TBullet::TBullet(int x,int y,DIRECTION dir,BULLET_TYPE nType,int nShield,int nFireRange):TSprite(x,y,nShield,0,CLASS_TBULLET),m_nType(nType){SetDelayTimer(50);m_dir = dir;m_nFireRange = nFireRange;////////////////////////////////////////////计算音效的音量及均衡int valume,pan; //音量和均衡int w,h;//声源与玩家的距离w = x - g_world.Player(0)->GetX();h = y - g_world.Player(0)->GetY();//计算音效的音量及均衡valume = MAX(ABS(w),ABS(h)) * (-10000/800);pan = w * (10000/400);///////////////////////////////////////////////////跟据类型设置速度switch(nType){case LIGHT://玩家的子弹,总会听到声音的m_nSpeed = 15;//if(valume>-10000) //小于最小音量,没必要播放m_sound[2].Play(-1000,pan);break;case FIRE:m_nSpeed = 10;if(valume>-10000)m_sound[1].Play(valume,pan);break;case DMISSILE:m_nSpeed = 0; //导弹开始速度为0,然后利用加速度加速if(valume>-10000)m_sound[0].Play(valume,pan);break;case SMISSILE:m_nSpeed = 0;if(valume>-10000)m_sound[0].Play(valume,pan);break;}}TBullet::~TBullet(){}void TBullet::Move(){if(!IsMyTime())return ;TLinkNode * pNode;switch(m_nType){case FIRE: //火弹,由火坦克发射的炮弹//计算出当前动画帧m_nCurrentFrame = m_dir*3+(m_nCurrentFrame+1)%3;//超出射程范围,发出死亡信息if(m_nFireRange<0){Dead();}//击中玩家了吗?(即使死了也不让你好过)if(g_world.Player(0)->HitBy(this)){//击中目标,任务完成Dead();}//已经死亡,来个爆炸效果if(IsDead())g_world.ExplodeLink().Add(NEW TExplode(m_nX,m_nY,EXPLODE_FIRE));break;case DMISSILE: //双导弹,敌军的导弹m_nSpeed +=1; //以加速为1的速度运动m_nCurrentFrame = m_dir; //计算当前动画的帧//超出射程范围,发出死亡信息if(m_nFireRange<0)Dead();//击中玩家?if(g_world.Player(0)->HitBy(this))Dead();//死了if(IsDead()){///////////////////////////////////////////////////////双导弹当然是两个爆炸效果if(m_dir==DIR_RIGHT||m_dir==DIR_LEFT){g_world.ExplodeLink().Add(NEW TExplode(m_nX,m_nY+6,EXPLODE_MISSILE));g_world.ExplodeLink().Add(NEW TExplode(m_nX,m_nY-6,EXPLODE_MISSILE));}else{g_world.ExplodeLink().Add(NEW TExplode(m_nX+6,m_nY,EXPLODE_MISSILE));g_world.ExplodeLink().Add(NEW TExplode(m_nX-6,m_nY,EXPLODE_MISSILE));}}break;case SMISSILE: //单导弹,不用注释了吧m_nSpeed ++;m_nCurrentFrame = m_dir;if(m_nFireRange<0)Dead();if(g_world.Player(0)->HitBy(this))Dead();if(IsDead())g_world.ExplodeLink().Add(NEW TExplode(m_nX,m_nY,EXPLODE_MISSILE));break;case LIGHT: //我们的武器:)m_nCurrentFrame = 0;//////////////////////////////////////////////////////计算是否打中在链表中的敌军坦克//取得链表中的第一辆坦克pNode=g_world.EnemyTankLink().m_pHeader;while(pNode) //还不到链尾{//打中了吗?if(pNode->m_pObject->HitBy(this))//Ok,Mission completedDead();//取得下一辆坦克pNode = pNode->m_pNext;}//////////////////////////////////////////////////////计算是否打中障碍物pNode = g_world.ObstacleLink().m_pHeader ;while(pNode){if(pNode->m_pObject->HitBy(this))Dead();pNode = pNode->m_pNext;}if(m_nFireRange<0){//太远了,没办法Dead();}//???,为什么没有爆炸效果?break;default:TRACE(0,"Invalid bullet id");break;}//填加的代码//取得自己的边框RECT rc;GetRect(rc);if(m_nType==LIGHT||m_nType==FIRE||m_nType==SMISSILE||m_nType==D MISSILE){if(m_dir==DIR_UP){//方向向上,只检查左上角及右上角坐标是否碰到障碍if(g_world.ObstacleMap(rc.left/OBSTACLE_WIDTH,rc.top/OBSTACLE_HEIG HT))Dead(); //子弹消失elseif(g_world.ObstacleMap(rc.right/OBSTACLE_WIDTH,rc.top/OBSTACLE_HEIGHT ))Dead();}else if(m_dir==DIR_DOWN){//方向向下,只检查左下角及右下角坐标是否碰到障碍if(g_world.ObstacleMap(rc.left/OBSTACLE_WIDTH,rc.bottom/OBSTACLE_H EIGHT))Dead();elseif(g_world.ObstacleMap(rc.right/OBSTACLE_WIDTH,rc.bottom/OBSTACLE_HEI GHT))Dead();}else if(m_dir==DIR_RIGHT){//方向向右,只检查右下角及右上角坐标是否碰到障碍if(g_world.ObstacleMap(rc.right/OBSTACLE_WIDTH,rc.top/OBSTACLE_HEI GHT))Dead();elseif(g_world.ObstacleMap(rc.right/OBSTACLE_WIDTH,rc.bottom/OBSTACLE_HEI GHT))Dead();}else if(m_dir==DIR_LEFT){//方向向左,只检查左上角及左上角坐标是否碰到障碍if(g_world.ObstacleMap(rc.left/OBSTACLE_WIDTH,rc.top/OBSTACLE_HEIG HT))Dead();elseif(g_world.ObstacleMap(rc.left/OBSTACLE_WIDTH,rc.bottom/OBSTACLE_HEIG HT))Dead();}}//是不是死了?if(!IsDead()){//没死,那么继续移动//速度太快了!if(m_nSpeed>24)m_nSpeed = 24;//向前,向前,向前...m_nX+=g_nDirXY[m_dir][0]*m_nSpeed;m_nY+=g_nDirXY[m_dir][1]*m_nSpeed;//改变射程m_nFireRange -= m_nSpeed;}}////////////////////////////////////////////////画子弹void TBullet::Draw(){POINT p;p.x = m_nX;p.y = m_nY;g_world.LPToDP(p); //把世界逻辑坐标转换到设备坐标WGE_Surface.Blt(m_epg[m_nType],m_nCurrentFrame,p.x,p.y );/////////////////////////////////////////////////取得碰撞矩形void TBullet::GetRect(RECT& rc){rc.left = m_nX - m_epg[m_nType].GetFrame(m_nCurrentFrame)->m_nKeyX;rc.top = m_nY - m_epg[m_nType].GetFrame(m_nCurrentFrame)->m_nKeyY;rc.bottom = rc.top + m_epg[m_nType].GetFrame(m_nCurrentFrame)->m_dwHeight ;rc.right = rc.left + m_epg[m_nType].GetFrame(m_nCurrentFrame)->m_dwWidth ;}// TExplode.cpp: implementation of the TExplode class.////////////////////////////////////////////////////////////////////////#include "stdafx.h"#include "TExplode.h"#include "TWorld.h"EPG TExplode::m_epg[4];ESound TExplode::m_sound[3];//////////////////////////////////////////////////////////////////////// Construction/Destruction//////////////////////////////////////////////////////////////////////TExplode::TExplode(int x,int y,EXPLODE nType):TObject(x,y,CLASS_TEXPLODE),m_nType(nType),m_nCurrentFrame(0){SetDelayTimer(100);switch(nType){case EXPLODE_TANK:case EXPLODE_BOX:m_sound[0].Play();break;case EXPLODE_PLAYER://玩家爆炸动画慢一点,与声音配合SetDelayTimer(200);m_sound[0].Play();break;}}TExplode::~TExplode(){}/////////////////////////////////////////////////移动void TExplode::Move(){if(!IsMyTime())return ;/////////////////////////////////////////////计算if(m_nType==EXPLODE_PLAYER){//玩家爆炸应该壮烈一点if(m_nCurrentFrame>=m_epg[3].GetFrameCount()-1){//先来一个小爆炸m_sound[1].Play();//然后变成大爆炸m_nType = EXPLODE_TANK;m_nCurrentFrame = 0;return ;}}else{//一般爆炸就可以了if(m_nCurrentFrame>=m_epg[m_nType].GetFrameCount()-1){//爆炸消失Dead();return ;}}m_nCurrentFrame ++;}/////////////////////////////////////////////////画出爆炸void TExplode::Draw(){POINT p;p.x = m_nX;p.y = m_nY;g_world.LPToDP(p);if(m_nType==EXPLODE_PLAYER){WGE_Surface.Blt(m_epg[3],m_nCurrentFrame,p.x,p.y);}elseWGE_Surface.Blt(m_epg[m_nType],m_nCurrentFrame,p.x,p.y );}//////////////////////////////////////////////取得动画边框void TExplode::GetRect(RECT& rc){int i;if(m_nType==EXPLODE_PLAYER)i = 3;elsei = m_nType;rc.left = m_nX - m_epg[i].GetFrame(m_nCurrentFrame)->m_nKeyX;rc.top = m_nY - m_epg[i].GetFrame(m_nCurrentFrame)->m_nKeyY;rc.bottom = rc.top + m_epg[i].GetFrame(m_nCurrentFrame)->m_dwHeight ;rc.right = rc.left + m_epg[i].GetFrame(m_nCurrentFrame)->m_dwWidth ;}// 4、TLink.cpp: implementation of the TLink class.连接类////////////////////////////////////////////////////////////////////////#include "stdafx.h"#include "TLink.h"//////////////////////////////////////////////////////////////////////// Construction/Destruction//////////////////////////////////////////////////////////////////////TLink::TLink(){m_pHeader = NULL;}TLink::~TLink(){DeleteAll();}void TLink::AddHeader(TObject * pObject){ASSERT(pObject);TLinkNode * pAddNode = NEW TLinkNode(pObject);pAddNode->m_pNext = m_pHeader;m_pHeader = pAddNode;}void TLink::AddTail(TObject * pObject){ASSERT(pObject);TLinkNode * pAddNode = NEW TLinkNode(pObject);if(m_pHeader==NULL){m_pHeader = pAddNode ;m_pHeader->m_pNext = NULL;}else{TLinkNode * pNode = m_pHeader ;while(pNode->m_pNext){ASSERT(pObject!=pNode->m_pObject);pNode = pNode->m_pNext ;}pNode->m_pNext = pAddNode ;pAddNode->m_pNext = NULL;}}void TLink::Add(TObject * pObject){AddHeader(pObject);}void TLink::DeleteAll(){TLinkNode * pNode = m_pHeader;while(pNode){m_pHeader = pNode->m_pNext ;delete pNode ;pNode = m_pHeader;}}void TLink::Delete(TObject * pObject){TLinkNode * pPreNode = m_pHeader ;if(m_pHeader->m_pObject == pObject){m_pHeader = m_pHeader->m_pNext ;delete pPreNode ;return ;}TLinkNode * pNode = pPreNode->m_pNext ;while(pNode){if(pNode->m_pObject == pObject){pPreNode->m_pNext = pNode->m_pNext ;delete pNode;return ;}pPreNode = pNode ;pNode = pNode->m_pNext ;}}/////////////////////////////////画出链表中所有的对象void TLink::DrawAll(){TLinkNode * pNode = m_pHeader;while(pNode){pNode->m_pObject->Draw();pNode = pNode->m_pNext ;}}//////////////////////////////////////////////移动链表中所有的对象void TLink::MoveAll(){//取得第一个结点TLinkNode * pNode = m_pHeader;//循环整个链表while(pNode){if(pNode->m_pObject->IsDead()){//该对象已经被击毁,从链表中删除TObject * pDeleteObj = pNode->m_pObject;pNode = pNode->m_pNext ;Delete(pDeleteObj);}else{//调用该对象的Move()函数pNode->m_pObject->Move();pNode = pNode->m_pNext ;}}}BOOL TLink::HitTestAll(TObject * pObj){TLinkNode * pNode = m_pHeader;BOOL bHit = FALSE;while(pNode && bHit==FALSE){if(pNode->m_pObject != pObj)bHit=pNode->m_pObject->HitTest(pObj);pNode = pNode->m_pNext ;}return bHit;}//5、TObject.cpp: implementation of the TObject class.物体类////////////////////////////////////////////////////////////////////////#include "stdafx.h"#include "TObject.h"//////////////////////////////////////////////////////////////////////// Construction/Destruction//////////////////////////////////////////////////////////////////////TObject::TObject(int x,int y,CLASS_TYPE nClassType):m_nX(x),m_nY(y),m_dwLastTickCount(0),m_dwDelayTimer(0),m_nClassType(nClassType),m_bIsDead(FALSE){TObject::~TObject(){}///////////////////////////////////////////////该对象是否与另它对象碰撞BOOL TObject::HitTest(TObject* object){RECT rc1,rc2,temp;GetRect(rc1);object->GetRect(rc2);return IntersectRect(&temp,&rc1,&rc2);}////////////////////////////////////////////////是否该我动了?BOOL TObject::IsMyTime(){if(GetTickCount()-m_dwLastTickCount>=m_dwDelayTimer){m_dwLastTickCount = GetTickCount();return TRUE;}return FALSE;}//6、TObstacle.cpp: implementation of the TObstacle class.障碍物类////////////////////////////////////////////////////////////////////////#include "stdafx.h"#include "TObstacle.h"#include "TBonus.h"#include "TBullet.h"#include "TExplode.h"#include "TWorld.h"EPG TObstacle::m_epg[2];//////////////////////////////////////////////////////////////////////// Construction/Destruction//////////////////////////////////////////////////////////////////////TObstacle::TObstacle(int x,int y,OBSTACLE nType):TObject(x,y,CLASS_TOBSTACLE),m_nType(nType),m_nCurrentFrame(0) {SetDelayTimer(100);switch(m_nType){case OBSTACLE_BOX: //木箱//硬度100m_nHardiness = 100;break;case OBSTACLE_END: //邪恶源//硬度1000! ,非常硬m_nHardiness = 1000;break;}}TObstacle::~TObstacle(){}void TObstacle::Destroy(){m_epg[0].Destroy();m_epg[1].Destroy();}///////////////////////////////////////////////击中测试BOOL TObstacle::HitBy(TObject * pObj){if(HitTest(pObj)){////////////////////////////////////////只能被光弹击中if(pObj->ClassType()==CLASS_TBULLET){TBullet * pBullet = (TBullet*)pObj;if(pBullet->m_nType == LIGHT){m_nHardiness -= pBullet->m_nShield ;return TRUE;}}}return FALSE;}////////////////////////////////////////////移动void TObstacle::Move(){if(!IsMyTime())return ;//计算当前帧++m_nCurrentFrame%=m_epg[m_nType].GetFrameCount();if(m_nHardiness<0){//消失Dead();if(m_nType == OBSTACLE_END){//邪恶源被击毁,过关//强烈爆炸g_world.ExplodeLink().Add(NEW TExplode(m_nX,m_nY, EXPLODE_PLAYER));//经验值+1000g_world.Player(0)->m_nExper += 1000;//进入下一关g_game_status = GAME_STAGECLEAR;}else if(m_nType == OBSTACLE_BOX){//产生一个随机物品g_world.BonusLink().Add(NEW TBonus(m_nX,m_nY,(BONUS)Rand(0,3)));//然后爆炸g_world.ExplodeLink().Add(NEW TExplode(m_nX,m_nY, EXPLODE_BOX));}}}/////////////////////////////////////////////画出来void TObstacle::Draw(){POINT p;p.x = m_nX;p.y = m_nY;g_world.LPToDP(p);WGE_Surface.Blt(m_epg[m_nType],m_nCurrentFrame,p.x,p.y );}///////////////////////////////////////////////////////碰撞边框void TObstacle::GetRect(RECT& rc){rc.left = m_nX - m_epg[m_nType].GetFrame(m_nCurrentFrame)->m_nKeyX;rc.top = m_nY - m_epg[m_nType].GetFrame(m_nCurrentFrame)->m_nKeyY;rc.bottom = rc.top + m_epg[m_nType].GetFrame(m_nCurrentFrame)->m_dwHeight ;rc.right = rc.left + m_epg[m_nType].GetFrame(m_nCurrentFrame)->m_dwWidth ;}// TSprite.cpp: implementation of the TSprite class. 精灵类////////////////////////////////////////////////////////////////////////#include "stdafx.h"#include "TSprite.h"int g_nDirXY[4][2] ={{1,0} , {0,1},{-1,0},{0,-1}};//////////////////////////////////////////////////////////////////////// Construction/Destruction//////////////////////////////////////////////////////////////////////TSprite::TSprite(int x,int y,int nShield,int nStatus,CLASS_TYPE nClassType):TObject(x,y,nClassType),m_nShield(nShield),m_nStatus(nStatus),m_dir(DIR_LEFT) ,m_nCurrentFrame(0){}TSprite::~TSprite(){}// TWorld.cpp: implementation of the TWorld class. 世界类////////////////////////////////////////////////////////////////////////#include "stdafx.h"#include "TankWar.h"#include "TWorld.h"#include "TBonus.h"#include "TObstacle.h"TWorld g_world; //全局唯一的世界对象//////////////////////////////////////////////////////////////////////// Construction/Destruction//////////////////////////////////////////////////////////////////////EGroupPic TWorld::m_grp_terrain;EPG TWorld::m_epg_icon[3];TWorld::TWorld():m_pTerrainMap(NULL),m_pObstacleMap(NULL){}TWorld::~TWorld(){DestroyWorld();}//////////////////////////////////////////////////加载地形图像BOOL TWorld::LoadTerrainPicture(LPCSTR szGrpFile,EDataFile* pDat){if(m_grp_terrain.Load(szGrpFile,pDat)==FALSE){MessageBox(NULL,szGrpFile,"加载错误",MB_OK);return FALSE;}return TRUE;。

坦克大战程序代码

坦克大战程序代码

坦克大战程序代码This model paper was revised by the Standardization Office on December 10, 2020class f extends JFrame {f(String title) {(title) ;(608 , 630) ;(300 , 100) ;;MyTank mp = new MyTank() ;(mp) ;(mp) ;new Thread(mp).start() ;}public static void main(String[] args) { f h = new f("坦克大战(版本") ;(true) ;}}//主战坦克class MyTank extends JPanel implements KeyListener , Runnable { int x = 280, y = 280 ;//坦克的初始位置int op = 1 ;//坦克的移动方向int color = 0 ;int tankspeed = 8 ;//坦克的速度int tankbullet = 8 ;//坦克的子弹速度int tankfbullet = 4 ;//敌军的子弹速度int shengming = 100 ;//生命int fenshu = 0 ;int nandu = 5 ; //设置游戏难度//子弹int dx = 295 , dy = 295 ;int dx1 = 295 , dy1 = -10 ;int dx2 = 600 , dy2 = 295 ;int dx3 = 295 , dy3 = 600 ;int dx4 = -10 , dy4 = 295 ;//敌军坦克int num = 10 ;//敌军坦克数量,不能修改int[] xf = new int[num] ;int[] yf = new int[num] ;int[] opf = new int[num] ;int[] dxf = new int[num] ;int[] dyf = new int[num] ;int[] dxf1 = new int[num] ;int[] dyf1 = new int[num] ;int[] dxf2 = new int[num] ;int[] dyf2 = new int[num] ;int[] dxf3 = new int[num] ;int[] dyf3 = new int[num] ;int[] dxf4 = new int[num] ;int[] dyf4 = new int[num] ;//构造函数,初始化敌军坦克的位置和状态MyTank() {for (int i = 0; i<num; i++) {xf[i] = (int) () * 560) ;yf[i] = (int) () * 560) ;dxf[i] = xf[i] + 15 ;dyf[i] = yf[i] + 15 ;}for (int i = 0; i<num; i++) {dxf1[i] = 295 ; dyf1[i] = -10 ;dxf2[i] = 600 ; dyf2[i] = 295 ;dxf3[i] = 295 ; dyf3[i] = 600 ;dxf4[i] = -10 ; dyf4[i] = 295 ;}}//主面版public void paint(Graphics g) { (g) ;;;("生命:" , 10 , 20 ) ;(50 , 10 , shengming * 5 , 10) ;(50 , 10 , 500 , 10) ;("得分: "+ fenshu , 10 , 40) ;if(op == 1) {;(x , y , 40 , 40) ;switch (color % 6) {case 0: ; break;case 1: ; break;case 2: ; break;case 3: ; break;case 4: ; break;case 5: ; break;}(x - 5 , y - 5 , 10 , 10) ; (x - 5 , y + 5 , 10 , 10) ; (x - 5 , y + 15 , 10 , 10) ; (x - 5 , y + 25 , 10 , 10) ; (x - 5 , y + 35 , 10 , 10) ; (x + 35 , y - 5 , 10 , 10) ; (x + 35 , y + 5 , 10 , 10) ; (x + 35 , y + 15 , 10 , 10) ; (x + 35 , y + 25 , 10 , 10) ; (x + 35 , y + 35 , 10 , 10) ; ;(x + 15 , y - 20 , 10 , 40) ; switch (color % 20) {case 0: ; break; case 1: ; break; case 2: ; break; case 3: ; break; case 4: ; break; case 5: ; break; case 6: ; break; case 7: ; break; case 8: ; break; case 9: ; break; case 10: ; break; case 11: ; break; case 12: ; break; case 13: ; break; case 14: ; break; case 15: ; break;case 16: ; break;case 17: ; break;case 18: ; break;case 19: ; break; }(x + 5 , y + 30 , 10 , 10) ; (x + 25 , y + 30 , 10 , 10) ; }if(op == 2) {;(x , y , 40 , 40) ;switch (color % 6) {case 0: ; break;case 1: ; break;case 2: ; break;case 3: ; break;case 4: ; break;case 5: ; break;}(x - 5 , y - 5 , 10 , 10) ; (x + 5 , y - 5 , 10 , 10) ; (x + 15 , y - 5 , 10 , 10) ; (x + 25 , y - 5 , 10 , 10) ; (x + 35 , y - 5 , 10 , 10) ; (x - 5 , y+35 , 10 , 10) ; (x + 5 , y+35 , 10 , 10) ; (x + 15 , y+35 , 10 , 10) ; (x + 25 , y+35 , 10 , 10) ; (x + 35 , y+35 , 10 , 10) ; ;(x + 20 , y + 15 , 40 , 10) ; switch (color % 20) {case 1: ; break; case 2: ; break; case 3: ; break; case 4: ; break; case 5: ; break; case 6: ; break; case 7: ; break; case 8: ; break; case 9: ; break; case 10: ; break; case 11: ; break; case 12: ; break; case 13: ; break; case 14: ; break; case 15: ; break;case 17: ; break;case 18: ; break;case 19: ; break; }(x , y + 5 , 10 , 10) ;(x , y + 25 , 10 , 10) ;}if(op == 3) {;(x , y , 40 , 40) ;switch (color % 6) {case 0: ; break;case 1: ; break;case 2: ; break;case 3: ; break;case 5: ; break;}(x - 5 , y - 5 , 10 , 10) ; (x - 5 , y + 5 , 10 , 10) ; (x - 5 , y + 15 , 10 , 10) ; (x - 5 , y + 25 , 10 , 10) ; (x - 5 , y + 35 , 10 , 10) ; (x + 35 , y - 5 , 10 , 10) ; (x + 35 , y + 5 , 10 , 10) ; (x + 35 , y + 15 , 10 , 10) ; (x + 35 , y + 25 , 10 , 10) ; (x + 35 , y + 35 , 10 , 10) ; ;(x + 15 , y + 20 , 10 , 40) ; switch (color % 20) {case 1: ; break; case 2: ; break; case 3: ; break; case 4: ; break; case 5: ; break; case 6: ; break; case 7: ; break; case 8: ; break; case 9: ; break; case 10: ; break; case 11: ; break; case 12: ; break; case 13: ; break; case 14: ; break; case 15: ; break;case 17: ; break;case 18: ; break;case 19: ; break; }(x + 5 , y , 10 , 10) ;(x + 25 , y , 10 , 10) ;}if(op == 4) {;(x , y , 40 , 40) ;switch (color % 6) {case 0: ; break;case 1: ; break;case 2: ; break;case 3: ; break;case 5: ; break;}(x - 5 , y - 5 , 10 , 10) ; (x + 5 , y - 5 , 10 , 10) ; (x + 15 , y - 5 , 10 , 10) ; (x + 25 , y - 5 , 10 , 10) ; (x + 35 , y - 5 , 10 , 10) ; (x - 5 , y+35 , 10 , 10) ; (x + 5 , y+35 , 10 , 10) ; (x + 15 , y+35 , 10 , 10) ; (x + 25 , y+35 , 10 , 10) ; (x + 35 , y+35 , 10 , 10) ; ;(x - 20 , y + 15 , 40 , 10) ; switch (color % 20) {case 1: ; break; case 2: ; break; case 3: ; break; case 4: ; break; case 5: ; break; case 6: ; break; case 7: ; break; case 8: ; break; case 9: ; break; case 10: ; break; case 11: ; break; case 12: ; break; case 13: ; break; case 14: ; break; case 15: ; break;case 17: ; break;case 18: ; break;case 19: ; break; }(x + 30 , y + 5 , 10 , 10) ; (x + 30 , y + 25 , 10 , 10) ; };(dx , dy , 10 , 10) ;(dx1 , dy1 , 10 , 10) ;(dx2 , dy2 , 10 , 10) ;(dx3 , dy3 , 10 , 10) ;(dx4 , dy4 , 10 , 10) ;for (int i = 0; i<num; i++) { if(opf[i] == 1) {(xf[i] - 5 , yf[i] - 5 , 10 , 10) ; (xf[i] - 5 , yf[i] + 5 , 10 , 10) ; (xf[i] - 5 , yf[i] + 15 , 10 , 10) ; (xf[i] - 5 , yf[i] + 25 , 10 , 10) ; (xf[i] - 5 , yf[i] + 35 , 10 , 10) ; (xf[i] + 35 , yf[i] - 5 , 10 , 10) ; (xf[i] + 35 , yf[i] + 5 , 10 , 10) ; (xf[i] + 35 , yf[i] + 15 , 10 , 10) ; (xf[i] + 35 , yf[i] + 25 , 10 , 10) ; (xf[i] + 35 , yf[i] + 35 , 10 , 10) ; (xf[i] + 15 , yf[i] - 20 , 10 , 40) ; (xf[i] + 5 , yf[i] + 30 , 10 , 10) ; (xf[i] + 25 , yf[i] + 30 , 10 , 10) ; }if(opf[i] == 2) {(xf[i] - 5 , yf[i] - 5 , 10 , 10) ; (xf[i] + 5 , yf[i] - 5 , 10 , 10) ; (xf[i] + 15 , yf[i] - 5 , 10 , 10) ; (xf[i] + 25 , yf[i] - 5 , 10 , 10) ; (xf[i] + 35 , yf[i] - 5 , 10 , 10) ; (xf[i] - 5 , yf[i] + 35 , 10 , 10) ; (xf[i] + 5 , yf[i] + 35 , 10 , 10) ; (xf[i] + 15 , yf[i] + 35 , 10 , 10) ; (xf[i] + 25 , yf[i] + 35 , 10 , 10) ; (xf[i] + 35 , yf[i] + 35 , 10 , 10) ; (xf[i] + 20 , yf[i] + 15 , 40 , 10) ; (xf[i] , yf[i] + 5 , 10 , 10) ;(xf[i] , yf[i] + 25 , 10 , 10) ;}if(opf[i] == 3) {(xf[i] - 5 , yf[i] - 5 , 10 , 10) ; (xf[i] - 5 , yf[i] + 5 , 10 , 10) ; (xf[i] - 5 , yf[i] + 15 , 10 , 10) ; (xf[i] - 5 , yf[i] + 25 , 10 , 10) ; (xf[i] - 5 , yf[i] + 35 , 10 , 10) ; (xf[i] + 35 , yf[i] - 5 , 10 , 10) ; (xf[i] + 35 , yf[i] + 5 , 10 , 10) ; (xf[i] + 35 , yf[i] + 15 , 10 , 10) ; (xf[i] + 35 , yf[i] + 25 , 10 , 10) ; (xf[i] + 35 , yf[i] + 35 , 10 , 10) ; (xf[i] + 15 , yf[i] + 20 , 10 , 40) ; (xf[i] + 5 , yf[i] , 10 , 10) ;(xf[i] + 25 , yf[i] , 10 , 10) ;}if(opf[i] == 4) {(xf[i] - 5 , yf[i] - 5 , 10 , 10) ; (xf[i] + 5 , yf[i] - 5 , 10 , 10) ; (xf[i] + 15 , yf[i] - 5 , 10 , 10) ; (xf[i] + 25 , yf[i] - 5 , 10 , 10) ; (xf[i] + 35 , yf[i] - 5 , 10 , 10) ; (xf[i] - 5 , yf[i] + 35 , 10 , 10) ; (xf[i] + 5 , yf[i] + 35 , 10 , 10) ; (xf[i] + 15 , yf[i] + 35 , 10 , 10) ; (xf[i] + 25 , yf[i] + 35 , 10 , 10) ; (xf[i] + 35 , yf[i] + 35 , 10 , 10) ; (xf[i] - 20 , yf[i] + 15 , 40 , 10) ; (xf[i] + 30 , yf[i] + 5 , 10 , 10) ; (xf[i] + 30 , yf[i] + 25 , 10 , 10) ; }(dxf1[i] , dyf1[i] , 10 , 10 ) ;(dxf2[i] , dyf2[i] , 10 , 10 ) ; (dxf3[i] , dyf3[i] , 10 , 10 ) ; (dxf4[i] , dyf4[i] , 10 , 10 ) ;}}public void keyTyped(KeyEvent e) {}//键盘控制坦克的移动,发弹public void keyPressed(KeyEvent e) { color ++ ;if() == {op = 1 ;y = y - tankspeed ;dy = dy - tankspeed ;if(y <= 0) {y = y + tankspeed ;dy = dy + tankspeed ; }}if() == {op = 2 ;x = x + tankspeed ; dx = dx + tankspeed ; if(x >= 560) {x = x - tankspeed ; dx = dx - tankspeed ; }}if() == {op = 3 ;y = y + tankspeed ; dy = dy + tankspeed ;if(y >= 560) {y = y - tankspeed ; dy = dy - tankspeed ; }}if() == {op = 4 ;x = x - tankspeed ; dx = dx - tankspeed ; if(x <= 0) {x = x + tankspeed ; dx = dx + tankspeed ; }}if() == {if(op == 1) {dx1 = dx ; dy1 = dy ;}if(op == 2) {dx2 = dx ; dy2 = dy ;}if(op == 3) {dx3 = dx ; dy3 = dy ;}if(op == 4) {dx4 = dx ; dy4 = dy ;}}() ;}public void keyReleased(KeyEvent e) { }public void run() {for (int a = 0; a<60000; a++) {dy1 = dy1 - tankbullet ;dx2 = dx2 + tankbullet ;dy3 = dy3 + tankbullet ;dx4 = dx4 - tankbullet ;for (int i = 0; i<num; i++) {dyf1[i] = dyf1[i] - tankfbullet ;dxf2[i] = dxf2[i] + tankfbullet ;dyf3[i] = dyf3[i] + tankfbullet ;dxf4[i] = dxf4[i] - tankfbullet ;}//判断是否被击中for (int i = 0; i<num; i++) {if(dyf1[i]<y + 38 &&dyf1[i]>y +8 && dxf1[i]-x>-10 && dxf1[i]-x<40) { ("被1击中") ;dxf1[i] = dxf[i] ; dyf1[i] = dyf[i] ;shengming = shengming - nandu ;}if(dxf2[i]>x+2 &&dxf2[i]<x+32 &&dyf2[i] - y >-10 && dyf2[i] - y <40 ) { ("被2击中") ;dxf2[i] = dxf[i] ; dyf2[i] = dyf[i] ;shengming = shengming - nandu ;}if(dyf3[i]>y+2 && dyf3[i]< y+32 && dxf3[i]-x >-10&& dxf3[i]-x<40) {("被3击中") ;dxf3[i] = dxf[i] ; dyf3[i] = dyf[i] ;shengming = shengming - nandu ;}if(dxf4[i]>x+8 &&dxf4[i]<x+38 &&dyf4[i] - y >-10 && dyf4[i] - y <40 ) { ("被4击中") ;dxf4[i] = dxf[i] ; dyf4[i] = dyf[i] ;shengming = shengming - nandu ;}}//判断是否击中敌军for (int i = 0; i<num; i++) {if(dy1<yf[i] + 38 &&dy1>yf[i] +8 && dx1-xf[i]>-10 && dx1-xf[i]<40) {("1击中") ;fenshu = fenshu + 100 ;xf[i] = (int)() * 560 );yf[i] = (int)() * 560 );}if(dx2>xf[i]+2 &&dx2<xf[i]+32 &&dy2 - yf[i] >-10 && dy2 - yf[i] <40 ) { ("2击中") ;fenshu = fenshu + 100 ;xf[i] = (int)() * 560 );yf[i] = (int)() * 560 );}if(dy3>yf[i]+2 && dy3< yf[i]+32 && dx3-xf[i] >-10&& dx3-xf[i]<40) {("3击中") ;fenshu = fenshu + 100 ;xf[i] = (int)() * 560 );yf[i] = (int)() * 560 );}if(dx4>xf[i]+8 &&dx4<xf[i]+38 &&dy4 - yf[i] >-10 && dy4 - yf[i] <40 ) { ("4击中") ;fenshu = fenshu + 100 ;xf[i] = (int)() * 560 );yf[i] = (int)() * 560 );}dxf[i] = xf[i] + 15 ;dyf[i] = yf[i] + 15 ;}//坦克的移动for (int i = 0; i<num; i++) { switch (opf[i]) {case 1:{yf[i]-- ;dyf[i] -- ;for (int s = 0; s<num; s++) { if(yf[i] <= 0) {yf[i] ++ ;dyf[i] ++ ;}}break;}case 2:{xf[i]++ ;dxf[i]++ ;for (int s = 0; s<num; s++) { if(xf[i] >= 560){xf[i] -- ;dxf[i] -- ;}}break;}case 3:{yf[i]++ ;dyf[i]++ ;for (int s = 0; s<num ; s++) { if(yf[i] >= 560){yf[i] -- ;dyf[i] -- ;}}break;}case 4:{xf[i]-- ;dxf[i]-- ;for (int s = 0; s<num; s++) { if(xf[i] <= 0){xf[i] ++ ;dxf[i] ++ ;}}break;}}}try{(20) ;}catch(Exception e) {() ;}//坦克的开火if(a % 50 == 5) {if()>{for (int i = 0; i<2; i++) {if(opf[i] == 1) {dxf1[i] = dxf[i] ; dyf1[i] = dyf[i] ; }if(opf[i] == 2) {dxf2[i] = dxf[i] ; dyf2[i] = dyf[i] ; }if(opf[i] == 3) {dxf3[i] = dxf[i] ; dyf3[i] = dyf[i] ; }if(opf[i] == 4) {dxf4[i] = dxf[i] ; dyf4[i] = dyf[i] ; }}}}if(a % 50 == 15) {if()> {for (int i = 2; i<4; i++) {if(opf[i] == 1) {dxf1[i] = dxf[i] ; dyf1[i] = dyf[i] ; }if(opf[i] == 2) {dxf2[i] = dxf[i] ; dyf2[i] = dyf[i] ; }if(opf[i] == 3) {dxf3[i] = dxf[i] ; dyf3[i] = dyf[i] ; }if(opf[i] == 4) {dxf4[i] = dxf[i] ; dyf4[i] = dyf[i] ; }}}}if(a % 50 == 25) {if()>{for (int i = 4; i<6; i++) {if(opf[i] == 1) {dxf1[i] = dxf[i] ; dyf1[i] = dyf[i] ;}if(opf[i] == 2) {dxf2[i] = dxf[i] ; dyf2[i] = dyf[i] ; }if(opf[i] == 3) {dxf3[i] = dxf[i] ; dyf3[i] = dyf[i] ; }if(opf[i] == 4) {dxf4[i] = dxf[i] ; dyf4[i] = dyf[i] ; }}}}if(a % 50 == 35) {if()>{for (int i = 6; i<8; i++) {if(opf[i] == 1) {dxf1[i] = dxf[i] ; dyf1[i] = dyf[i] ; }if(opf[i] == 2) {dxf2[i] = dxf[i] ; dyf2[i] = dyf[i] ; }if(opf[i] == 3) {dxf3[i] = dxf[i] ; dyf3[i] = dyf[i] ; }if(opf[i] == 4) {dxf4[i] = dxf[i] ; dyf4[i] = dyf[i] ; }}}}if(a % 50 == 45) {if()> {for (int i = 8; i<10; i++) {if(opf[i] == 1) {dxf1[i] = dxf[i] ; dyf1[i] = dyf[i] ; }if(opf[i] == 2) {dxf2[i] = dxf[i] ; dyf2[i] = dyf[i] ; }if(opf[i] == 3) {dxf3[i] = dxf[i] ; dyf3[i] = dyf[i] ; }if(opf[i] == 4) {dxf4[i] = dxf[i] ; dyf4[i] = dyf[i] ; }}}}//坦克的随机移动if(a % 50 == 1 ) {for (int i = 0; i<2; i++) { if( () > ) {if() > {opf[i] = 1 ;}else{opf[i] = 2 ;}}else{if() > {opf[i] = 3 ;}else{opf[i] = 4 ;}}}}if(a % 50 == 11 ) {//坦克的随机移动for (int i = 2; i<4; i++) { if( () > ) {if() > {opf[i] = 1 ;}else{opf[i] = 2 ;}}else{if() > {opf[i] = 3 ;}else{}}}}if(a % 50 == 21 ) {//坦克的随机移动for (int i = 4; i<6; i++) { if( () > ) {if() > {opf[i] = 1 ;}else{opf[i] = 2 ;}}else{if() > {}else{opf[i] = 4 ;}}}}if(a % 50 == 31 ) {//坦克的随机移动for (int i = 6; i<8; i++) { if( () > ) {if() > {opf[i] = 1 ;}else{opf[i] = 2 ;}}else{if() > {opf[i] = 3 ;}else{opf[i] = 4 ;}}}}if(a % 50 == 41 ) {//坦克的随机移动for (int i = 8; i<10; i++) { if( () > ) {if() > {opf[i] = 1 ;}else{opf[i] = 2 ;}}else{if() > {opf[i] = 3 ;}else{opf[i] = 4 ;}}}}//重画if(shengming<=0){//弹出player1胜利对话框(null,"你结束了!!!","Game Over !", ; //结束游戏(0) ;}() ;}}}。

c语言简单的坦克对战代码

c语言简单的坦克对战代码

C语言简单的坦克对战代码引言在计算机科学领域,游戏开发一直是一个非常有趣和具有挑战性的领域。

本文将介绍如何使用C语言编写一个简单的坦克对战游戏代码。

通过这个例子,读者将学习到如何使用C语言的基本语法和数据结构来实现一个简单的游戏。

游戏规则在这个坦克对战游戏中,有两个玩家分别控制两辆坦克进行对战。

游戏地图是一个二维的矩形区域,玩家可以在地图上移动坦克,并且可以发射子弹来摧毁对方的坦克。

坦克可以向上、向下、向左、向右四个方向移动,子弹可以向上、向下、向左、向右四个方向发射。

游戏的主要目标是摧毁对方的坦克,当一方的坦克被击中后,游戏结束,另一方获胜。

游戏设计为了实现这个游戏,我们需要设计几个基本的数据结构和函数。

以下是游戏设计的主要部分:数据结构1.Tank结构体:表示一个坦克的位置和状态信息。

2.Bullet结构体:表示一颗子弹的位置和状态信息。

3.Map结构体:表示游戏地图的大小和当前状态。

函数1.init_map()函数:用于初始化游戏地图,并生成两辆坦克的初始位置。

2.move_tank()函数:用于移动坦克的位置。

3.shoot_bullet()函数:用于发射子弹。

4.update_map()函数:用于更新游戏地图的状态,包括坦克和子弹的位置。

5.check_collision()函数:用于检测子弹是否击中了坦克。

6.game_over()函数:用于判断游戏是否结束。

代码实现以下是使用C语言实现坦克对战游戏的代码:#include <stdio.h>#define MAP_SIZE 10typedef struct {int x;int y;} Position;typedef struct {Position position;int health;} Tank;typedef struct {Position position;int active;} Bullet;typedef struct {Tank player1;Tank player2;Bullet bullets[MAP_SIZE * MAP_SIZE];} Map;void init_map(Map* map) {map->player1.position.x = 0;map->player1.position.y = 0;map->player1.health = 100;map->player2.position.x = MAP_SIZE - 1;map->player2.position.y = MAP_SIZE - 1;map->player2.health = 100;for (int i = 0; i < MAP_SIZE * MAP_SIZE; i++) { map->bullets[i].active = 0;}}void move_tank(Tank* tank, int x, int y) {tank->position.x += x;tank->position.y += y;}void shoot_bullet(Map* map, Tank* tank) {for (int i = 0; i < MAP_SIZE * MAP_SIZE; i++) {if (!map->bullets[i].active) {map->bullets[i].active = 1;map->bullets[i].position.x = tank->position.x;map->bullets[i].position.y = tank->position.y;break;}}}void update_map(Map* map) {for (int i = 0; i < MAP_SIZE * MAP_SIZE; i++) {if (map->bullets[i].active) {Bullet* bullet = &map->bullets[i];bullet->position.x += 1;bullet->position.y += 1;}}}int check_collision(Map* map) {for (int i = 0; i < MAP_SIZE * MAP_SIZE; i++) {if (map->bullets[i].active) {Bullet* bullet = &map->bullets[i];if (bullet->position.x == map->player1.position.x && bullet->position.y == map->player1.position.y) { map->player1.health -= 10;bullet->active = 0;}if (bullet->position.x == map->player2.position.x && bullet->position.y == map->player2.position.y) { map->player2.health -= 10;bullet->active = 0;}}}}int game_over(Map* map) {if (map->player1.health <= 0 || map->player2.health <= 0) {return 1;} else {return 0;}}int main() {Map map;init_map(&map);while (!game_over(&map)) {// 获取玩家输入,移动坦克或发射子弹update_map(&map);check_collision(&map);}// 游戏结束,显示获胜方return 0;}总结通过本文的介绍,读者可以了解到如何使用C语言编写一个简单的坦克对战游戏代码。

c语言编写坦克大战源代码

c语言编写坦克大战源代码

#include "tank.h"#include "ConOperator.h"#include <time.h>#include <windows.h>#include <conio.h>#include <iostream>using namespace std;TankGame::TankGame(int w, int h){// 设定当前关数no = 1;// 设定游戏整体高宽wide = w;high = h;HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);COORD sizePos = {2 * wide, high};SetConsoleScreenBufferSize(hStdOut, sizePos);// 分配游戏空间状态表gameSpace = new GameSpace*[high];for (int i = 0; i != high; i++)gameSpace[i] = new GameSpace[wide];// 添加围墙wall = new Wall(gameSpace, wide, high);wall->draw();}void TankGame::load_init(){// 初始化游戏空间for (int y = 1; y != high-1; y++) {for (int x = 1; x != wide-1; x++) {gameSpace[y][x].have = false;gameSpace[y][x].kind = 0;gameSpace[y][x].no = 0;}}// 添加地图map.load(gameSpace, no);// 初始化自己坦克me.init_xy();me.trans_direction(1);me.set_no(0);me.init_move(gameSpace, wide / 2 - 2, high - 5);// 按顺序诞生敌人坦克creatPlace = 0;for (int i = 0; i != 3; i++) {freezeTime[i] = REBIRTHTIME;enemy[i].init_xy();enemy[i].set_kind(2);enemy[i].set_no(i+1);reset(enemy[i]);}// 数目初始化leftCount = 17;existCount = 3;// 显示图片me.draw_tank();for (int i = 0; i != 3; i++)enemy[i].draw_tank();map.draw();}TankGame::~TankGame(){if (wall)delete wall;if (gameSpace) {for (int i = 0; i != high; i++)delete[] gameSpace[i];delete[] gameSpace;}}void TankGame::reset(Tank& tank){bool success = false;int t = 3;while (t && !success) {creatPlace++;if (creatPlace == 4)creatPlace = 1;// 诞生地点选择switch (creatPlace) {case 1:tank.trans_direction(3); //朝下if (tank.reset(gameSpace,1,1))success = true;break;case 2:tank.trans_direction(3);if (tank.reset(gameSpace,wide / 2 - 2, 1))success = true;break;case 3:tank.trans_direction(3);if (tank.reset(gameSpace,wide - 4, 1))success = true;break;}if (!success)t--;}}void TankGame::start(){char command;enter_picture(command);if (command != ENTER)return;while (me.blood > 0) {// init data for runingload_init();// run a taskruning_a_task();// determine why returnif (me.blood > 0) {no++;if (no > map.total) {success_gameover();break;}char command;turn_to_next_task(command);if (command != ENTER)break;}else game_over();}}//voidvoid TankGame::runing_a_task(){while ((leftCount || existCount) && me.blood) {clock_t now = clock();char command = -1; // 主人命令while (clock() - now < TIME_UNIT) // 小于一个时间片,暂停update_keyBoard_char(command);/*更新敌人坦克*/for (int i = 0; i != 3; i++) {if (enemy[i].blood == 0)continue;if (enemy[i].freezeTime == 0) {enemy[i].rand_direction(gameSpace); // 产生随机方向}else {if (enemy[i].speed == 0) {enemy[i].move(gameSpace);if (bullet[i+1].disapper) {int shot = -1;bullet[i+1] = enemy[i].rand_shot(gameSpace,i+1, shot);if (shot == 0)me.be_shot(gameSpace);bullet[i+1].registration(gameSpace);}enemy[i].freezeTime--;} else {enemy[i].speed--;}}}/*更新自己坦克*/if (command >=0 && command < 4) {me.trans_to_direction(command);me.move(gameSpace);}/*更新子弹*/for (int i = 0; i !=4; i++) {if (!bullet[i].disapper) { // 存在的子弹int shot;bullet[i].move(gameSpace, shot); // 运行,是否射中if (shot == 0)me.be_shot(gameSpace);else if (shot >= 1 && shot <= 3) {enemy[shot-1].be_shot(gameSpace);existCount--;} else if (shot >= 7 && shot <= 10) {bullet[shot-7].unregistration(gameSpace);bullet[shot-7].clear();bullet[shot-7].init(bullet[shot-7].kind);}}}/*自己产生子弹*/if (bullet[0].disapper) {if (command == 32) {int shot;bullet[0] = me.make_bullet(gameSpace,0, shot);if (shot >= 1 && shot <= 3) {enemy[shot-1].be_shot(gameSpace);existCount--;}bullet[0].registration(gameSpace);}}/*诞生缺损敌人*/if (leftCount > 0) {for (int i = 0; i != 3; i++) {if (enemy[i].blood == 0) {if (freezeTime[i] == 0) {freezeTime[i] = REBIRTHTIME;reset(enemy[i]);existCount++;leftCount--;}else freezeTime[i]--;}}}}}void TankGame::update_keyBoard_char(char& c){if (_kbhit()) {c = getch();if (c == -32) {c = getch();if (c != UP && c != DOWN && c != LEFT && c != RIGHT)c = -1;else if (c == RIGHT)c = 0;else if (c == UP)c = 1;else if (c == LEFT)c = 2;elsec = 3;}elsec = 32;}}void TankGame::enter_picture(char &command){string captions[6];captions[0] = "◥◣◢◤■■■■■◥◣◢◤";captions[1] = " ◥◣◢◤◢◤◥◣◢◤";captions[2] = " ◥◣◢◤◢◤◥◣◢◤";captions[3] = " ◢◤◢◤◢◤◥◣";captions[4] = " ◢◤◢◤◢◤◥◣";captions[5] = " ◢◤■■■■■◢◤◥◣";string s = " ";color(0x0e);for (int i = 0; i != 6; i++)grid(7, 6 + i, captions[i]);Frame frame(30,15);frame.draw_frame(4,19,0x09);string sentence[3];sentence[0] = "This small game is made by yzx in 2010.";sentence[1] = "Wlecome to play it.";sentence[2] = "All Rights Reserved.";color(0x0e);for (int i = 0; i != 3; i++) {for (int k = 0; k != sentence[i].size(); k++) {grid(14+k,21+2*i,sentence[i][k]);sleep(50);}sleep(1000);}grid(7, 28,"Enter : 开始ESC : 退出");while (true) {if (_kbhit()) {command = getch();if (command == ENTER || command == ESC)break;}}// clear screen picture in wallclear_picture();}void TankGame::turn_to_next_task(char& command){clear_picture();color(0x0e);grid(18, 20, "第");grid(20, 20, no);grid(22, 20, "关");while (true) {if (_kbhit()) {command = getch();if (command == ENTER || command == ESC)break;}}grid(18, 20," ");}void TankGame::success_gameover(){clear_picture();Frame frame(30,15);frame.draw_frame(4,10,0x09);string sentence[3];sentence[0] = "Congratulations for Successfully finishing all tasks";sentence[1] = "Thank you for using it deeply.";sentence[2] = "And welcome to use it next time.";color(0x0e);for (int i = 0; i != 3; i++) {for (int k = 0; k != sentence[i].size(); k++) {grid(12+k,14+2*i,sentence[i][k]);sleep(50);}sleep(1000);}while (true) {if (_kbhit()) {char command = getch();if (command == ENTER || command == ESC)break;}}}void TankGame::game_over(){clear_picture();Frame frame(30,15);frame.draw_frame(4,15,0x09);string sentence[4];sentence[0] = "Game over, but you can try it again.";sentence[1] = "Thank you for using it deeply.";sentence[2] = "And welcome to use it next time.";sentence[3] = "All rights reserved.(Violators will be prosecuted.) .";color(0x0e);for (int i = 0; i != 4; i++) {for (int k = 0; k != sentence[i].size(); k++) {grid(13+k,18+2*i,sentence[i][k]);sleep(50);}sleep(1000);}while (true) {if (_kbhit()) {char command = getch();if (command == ENTER || command == ESC)break;}}}void TankGame::clear_picture(){int cirX = wide / 2;int cirY = high / 2;int depth = cirY > cirX ? cirY + 2 : cirX + 2;int lx, rx, uy, by;int l, r, u, b;for (int i = 0; i != depth; i++) {lx = cirX - i;rx = cirX + i;uy = cirY - i;by = cirY + i;uy <= 0 ? u = 1 : u = uy;by >= high - 1 ? b = high - 2 : b = by;lx <= 0 ? l = 1 : l = lx;rx >= wide -1 ? r = wide - 2 : r = rx;if (rx < wide - 1) {for (int k = u; k <= b; k++)grid(rx, k, " ");}if (lx > 0) {for (int k = u; k <= b; k++)grid(lx, k, " ");}if (by < high - 1) {for (int k = l; k <= r; k++)grid(k, by, " ");}if (uy > 0) {for (int k = l; k <= r; k++)grid(k, uy, " ");}}}void TankGame::test(){for (int y = 0; y != 40; y++) {for (int x = 0; x != 40; x++) {if (gameSpace[y][x].have)// && gameSpace[y][x].kind == 3)grid(x, 42+y, (char)gameSpace[y][x].no);elsegrid(x, 42+y, " ");}}}。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
} else
{ setfillstyle(1,get
pixel(shoot[i].x-6,shoot[i].y+14)); bar(shoot[i].x-5,
shoot[i].y+14,shoot[i].x-1,shoot[i].y+17); }
break; case RIGHTWAY:
if((shoot[i].x-15)%30==0) if(map[(shoot[i].y-15)/
/*声明区*/ void allcircle(int i,int j); void start(); void play();
void map_all(int map[15][15]); void control_shoot(int m,int map[15][15],int i); void enemy_control(int map[15][15]);
{8 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,8 }, {8 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,8 }, {8 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,8 }, {8 ,5 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,5 ,5 ,5 ,8 }, {8 ,5 ,0 ,0 ,7 ,7 ,7 ,6 ,7 ,7 ,7 ,5 ,5 ,5 ,8 }, {8 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,5 ,5 ,5 ,8 }, {8 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,8 }, {8 ,0 ,0 ,0 ,0 ,0 ,0 ,6 ,0 ,0 ,0 ,6 ,0 ,0 ,8 }, {8 ,5 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 ,5 ,5 ,5 ,8 }, {8 ,5 ,0 ,0 ,5 ,5 ,5 ,5 ,5 ,5 ,0 ,5 ,5 ,5 ,8 }, {8 ,5 ,0 ,0 ,5 ,5 ,5 ,5 ,5 ,5 ,0 ,5 ,5 ,5 ,8 }, {8 ,0 ,0 ,0 ,0 ,5 ,5 ,5 ,5 ,5 ,0 ,0 ,0 ,0 ,8 }, {8 ,0 ,0 ,1 ,0 ,5 ,5 ,9 ,5 ,5 ,2 ,0 ,0 ,0 ,8 }, {8 ,8 ,8 ,8 ,8 ,8 ,8 ,8 ,8 ,8 ,8 ,8 ,8 ,8 ,8 }};
30+1][(shoot[i].x-15)/30]!=0) { shoot[i].
life=0;
control_ shoot(map[(shoot[i].y-15)/30+1][(shoot[i].x-15)/30],map,i);
} if(shoot[i].y>405)
shoot[i].life=0; if(shoot[i].life!=0)
getch(); cleardevice(); getch();
} void play() {
int key;int i;int num=0; int map[15][15]={ 数组*/
map_all(map); while(1) {
{8 ,8 ,8 ,8 ,8 ,8 ,8 ,8 ,8 ,8 ,8 ,8 ,8 ,8 ,8 },/*初始化地图
30][(shoot[i].x-15)/30-1]!=0) { shoot[i].
life=0; control_
shoot(map[(shoot[i].y-15)/30][(shoot[i].x-15)/30-1],map,i); }
if(shoot[i].x<47) shoot[i].life=0;
} else
{ setfillstyle(1,get
pixel(shoot[i].x+14,shoot[i].y-6)); bar(shoot[i].x+
14,shoot[i].y-5,shoot[i].x+17,shoot[i].y-1); }
break; case DOWNWAY:
if((shoot[i].y-15)%30==0) if(map[(shoot[i].y-15)/
void uptank(int i,int j,int color);/*画坦克函数*/ void downtank(int i,int j,int color); void lefttank(int i,int j,int color); void righttank(int i,int j,int color); void blank(int i,int j);
{ setfilshoot[i].y+35,shoot[i].x+17,shoot[i].y+32);setcolor(7); line(shoot[i].x+
14,shoot[i].y+31,shoot[i].x+17,shoot[i].y+31); shoot[i].y++;
void end();
main() {
start(); play(); end(); } void start() {
int i; int driver=VGA,mode=VGAHI;/*初始化图形模式*/ initgraph(&driver,&mode,"");
setbkcolor(7);/*设定背景*/ settextstyle(4,0,0); outtextxy(500,300,"made"); outtextxy(540,300,"by"); outtextxy(562,300,"lihaifei"); while(!kbhit()) { setcolor(i); settextstyle(0,0,10); outtextxy(150,100,"TANK"); i++; }
} else
{ setfillstyle(1,get
pixel(shoot[i].x+14,shoot[i].y+36)); bar(shoot[i].x+
14,shoot[i].y+35,shoot[i].x+17,shoot[i].y+31); }
break; case LEFTWAY:
if((shoot[i].x-15)%30==0) if(map[(shoot[i].y-15)/
} else
{ setfillstyle(1,get
pixel(shoot[i].x+36,shoot[i].y+14)); bar(shoot[i].x+
35,shoot[i].y+14,shoot[i].x+31,shoot[i].y+17); }
break; } delay(1500);num++; if(num==30) {
struct ENEMY /*定义敌人结构体*/ {
int life; int x,y; int i,j;
int way; int control; }enemy[5]={{1,0,0,1,1,DOWNWAY,0},{1,0,0,1,2,DOWNWAY,0},{1,0,0,1,3,DOWNWAY,0}, {1,0,0,1,4,DOWNWAY,0},{1,0,0,1,5,DOWNWAY,0}};
if(shoot[i].life!=0) { setfillstyle(1,1); bar(shoot[i].x+
14,shoot[i].y-5,shoot[i].x+17,shoot[i].y-2); setcolor(7); line(shoot[i].x+
14,shoot[i].y-1,shoot[i].x+17,shoot[i].y-1); shoot[i].y--;
#define b_UP 0x1177/*定义 B 坦克按键*/ #define b_DOWN 0x1f73 #define b_LEFT 0x1e61 #define b_RIGHT 0x2064 #define b_shoot 0x246a
#define ESC 0x011b
#define UPWAY 1/*定义方向*/ #define DOWNWAY 2 #define LEFTWAY 3 #define RIGHTWAY 4 int enemynum=3;
30][(shoot[i].x-15)/30+1]!=0) { shoot[i].
life=0; control_
shoot(map[(shoot[i].y-15)/30][(shoot[i].x-15)/30+1],map,i); }
if(shoot[i].x>405) shoot[i].life=0;
void map_water(int i,int j);/*画地图函数*/ void map_steel(int i,int j); void map_wall(int i,int j); void map_border(int i,int j); void map_base(int i,int j);
if(shoot[i].life!=0) { setfillstyle(1,1); bar(shoot[i].x-5,
shoot[i].y+14,shoot[i].x-2,shoot[i].y+17);setcolor(7); line(shoot[i].x-1,
shoot[i].y+14,shoot[i].x-1,shoot[i].y+17); shoot[i].x--;
30-1][(shoot[i].x-15)/30]!=0) { shoot[i].
相关文档
最新文档