C语言飞机大战源码

合集下载

C语言实现飞机游戏(1)

C语言实现飞机游戏(1)

C语⾔实现飞机游戏(1)本⽂实例为⼤家分享了C语⾔实现飞机游戏的具体代码,供⼤家参考,具体内容如下本节我们将在上⼀节实现基础上完成简单的飞机游戏。

scanf 控制飞机移动我们可以使⽤ scanf 函数来检测输⼊,分别使⽤ a , s , d , w .来控制 x , y 坐标来实现飞机移动。

#include <stdio.h>#include <stdlib.h>int main(){int i,j;int x = 5;int y = 10;char input; //此处声明变量⽤于检测输⼊while(1){system("cls"); //清屏,Linux改为clear//输出上⽅空⾏for(i=0; i<x; i++)printf("\n");//输出左侧空格for(j=0; j<y; j++)printf(" ");printf("*"); //飞机使⽤ * 表⽰printf("\n");scanf("%c", &input); //检测输⼊if(input == 'a')y --;if(input == 'd')y ++;if(input == 's')x ++;if(input == 'w')x --;}return 0;}说明:scanf 函数中,%c 表⽰输⼊值类型为字符(char),&input表⽰把输⼊的值赋给 input 。

getch 控制飞机移动之前我们使⽤ scanf 函数来控制移动,它要求每次输⼊之后按下回车才能继续,交互效果不好。

为了优化效果,我们使⽤ getch 函数,不需要回车就能得到输⼊字符。

⾸先要包含 <conio.h>。

C语言飞机大战源码

C语言飞机大战源码

C语言飞机大战源码下面是一个简单的C语言飞机大战游戏源码。

```c#include <stdio.h>#include <stdlib.h>#include <conio.h>#include <windows.h>#define WIDTH 30#define HEIGHT 20#define KEY_UP 72#define KEY_DOWN 80#define KEY_LEFT 75#define KEY_RIGHT 77#define KEY_SPACE 32int score = 0;int gameover = 0;int bulletX = -1;int bulletY = -1;int bulletFired = 0;int enemyX = -1;int enemyY = -1;void gotoxy(int x, int y)COORD coord;coord.X = x;coord.Y = y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);void drawBordeint i;for (i = 0; i <= HEIGHT + 1; i++)gotoxy(0, i);printf("#");gotoxy(WIDTH + 1, i);printf("#");}for (i = 0; i <= WIDTH + 1; i++)gotoxy(i, 0);printf("#");gotoxy(i, HEIGHT + 1);printf("#");}void drawPlayer(int x, int y) gotoxy(x, y);printf("\033[0m");void drawBullet(int x, int y) gotoxy(x, y);printf("\033[0;31m,");printf("\033[0m");void drawEnemy(int x, int y) gotoxy(x, y);printf("\033[0;33mO");printf("\033[0m");void eraseBullet(int x, int y) gotoxy(x, y);printf(" ");void eraseEnemy(int x, int y) gotoxy(x, y);printf(" ");void updateScorgotoxy(WIDTH + 5, HEIGHT + 2);printf("Score: %d", score);int isEnemyKilled(int bulletX, int bulletY, int enemyX, int enemyY)if (bulletX == enemyX && bulletY == enemyY)return 1;}return 0;int isGameover(int x, int y)if (y == HEIGHT , (x == enemyX && y == enemyY))return 1;}return 0;void movePlayer(int key, int *x, int *y)eraseBullet(*x, *y);switch (key)case KEY_UP:if (*y > 1)(*y)--;}break;case KEY_DOWN: if (*y < HEIGHT) (*y)++;}break;case KEY_LEFT: if (*x > 1)(*x)--;}break;case KEY_RIGHT: if (*x < WIDTH) (*x)++;}break;case KEY_SPACE:if (!bulletFired)bulletX = *x;bulletY = *y - 1;bulletFired = 1;}break;}drawPlayer(*x, *y);if (bulletFired)drawBullet(bulletX, bulletY); }void moveBulleif (bulletY > 0)eraseBullet(bulletX, bulletY); bulletY--;drawBullet(bulletX, bulletY); } elseeraseBullet(bulletX, bulletY);bulletX = -1;bulletY = -1;bulletFired = 0;}void moveEnemif (enemyY < HEIGHT) eraseEnemy(enemyX, enemyY); enemyY++;drawEnemy(enemyX, enemyY); } elseeraseEnemy(enemyX, enemyY); enemyX = rand( % WIDTH + 1; enemyY = 1;drawEnemy(enemyX, enemyY); }int maiint playerX = WIDTH / 2;int playerY = HEIGHT;int key;system("cls");drawBorder(;updateScore(;drawPlayer(playerX, playerY);while (!gameover)if (_kbhit()key = _getch(;if (key == 'q' , key == 'Q')break;}movePlayer(key, &playerX, &playerY);}if (bulletFired)moveBullet(;}moveEnemy(;if (isEnemyKilled(bulletX, bulletY, enemyX, enemyY)) bulletX = -1;bulletY = -1;bulletFired = 0;score++;updateScore(;}if (isGameover(playerX, playerY))gameover = 1;break;}Sleep(100);}gotoxy(0, HEIGHT + 3);printf("Game Over. Your score is %d\n", score);return 0;```这是一个文本模式下的简单飞机大战游戏源码。

C语言控制台实现打飞机小游戏

C语言控制台实现打飞机小游戏

C语⾔控制台实现打飞机⼩游戏本⽂实例为⼤家分享了C语⾔实现打飞机⼩游戏的具体代码,供⼤家参考,具体内容如下初学C语⾔总觉得不能做些什么好玩的,这个⼩游戏只需 “⼀点点” (千真万确)C语⾔知识就能完成!总计不到200⾏的⾮空⽩代码(没有强⾏压缩⾏数)操作说明:1.W、S、A、D 控制上、下、左、右⽅向,空格攻击2.每击中⼀架敌机增加1分,界⾯下⽅显⽰实时分数3.撞到敌机后显⽰ game over! 2.5秒(时间可更改)⼦弹连发移动的同时发射⼦弹飞机撞上敌机结束游戏可通过更改相关变量的值来调节敌机飞⾏速度、敌机密度、敌机刷新速度等相⽐与上⼀个极度简陋版,功能基本完善所需C语⾔知识真的不多,感兴趣的C程序员朋友来复刻吧!以下是详细注释的源代码:#include <stdio.h>#include <stdlib.h>#include <conio.h>#include <windows.h>#define high 25 //画布⾼#define width 60 //画布宽#define border -1 //边界#define blank 0 //空⽩#define plane 1 //飞机#define bullet 2 //⼦弹#define enemy 3 //敌机#define destroy 4 //摧毁标记int canvas[high+2][width+2]; //游戏场景的⾼和宽int pos_h, pos_w; //飞机位置int enemynum; //敌机数量int interval; //同个计次来模拟时间间隔int itv_move; //敌机移动的时间间隔int itv_new; //敌机刷新的时间间隔int score; //分数int IsOver; //判断游戏是否结束void Startup(); //游戏数值初始化void Show(); //游戏界⾯输出void UpdateInput(); //与输⼊⽆关的游戏状态更新void UpdateNormal(); //因输⼊导致的游戏状态更新int main(){Startup(); //初始化while(IsOver){ //游戏循环UpdateInput();UpdateNormal();Show();}printf("\t\tgame over!\n");Sleep(2500); //暂停游戏结束界⾯(毫秒)system("pause");return 0;}void Startup(){ //游戏数值初始化IsOver=1;score=0; //初始化分数for(int i=0;i<high+2;i++){ //初始化画布for(int j=0;j<width+2;j++){if(i==0 || i==high+1 ||j==0 || j==width+1){canvas[i][j]=border;}else canvas[i][j]=blank;}}pos_h=high/2; //初始化飞机竖直坐标pos_w=width/2; //初始化飞机⽔平坐标canvas[pos_h][pos_w]=plane; //初始化飞机位置enemynum=3; //敌机数量srand(time(NULL));interval=4; //初始化时间间隔计数itv_move=5; //初始化敌机移动时间间隔itv_new =40; //初始化敌机刷新时间间隔}void Show(){ //游戏界⾯输出HideCursor(); //隐藏光标gotoxy(1,1); //回调光标、刷新画⾯for(int i=0;i<high+2;i++){for(int j=0;j<width+2;j++){if( canvas[i][j] == plane ){ //当前位置为飞机位置printf("*");}else if( canvas[i][j] == bullet ){ //当前位置为⼦弹位置printf("|");}else if( canvas[i][j] == enemy ){ //当前位置为敌机位置printf("@");}else if( canvas[i][j] == border ){ //当前位置为边界printf("#");}else if( canvas[i][j] == blank ){ //当前位置⽆物,且在边界内 printf(" ");}else if( canvas[i][j] == destroy ){ //当前位置⽆物,且在边界内 printf("x");}}printf("\n");}printf("\n得分:%d",score);}void UpdateInput(){ //与输⼊⽆关的游戏状态更新char key_W=GetKeyState('W'), //监测 W 键是否按下key_S=GetKeyState('S'), //监测 S 键是否按下key_A=GetKeyState('A'), //监测 A 键是否按下key_D=GetKeyState('D'), //监测 D 键是否按下key_attack=GetKeyState(' '); //监测空格键是否按下if(kbhit()){ //当有键按下时if(key_W<0){ //当按下 W 键,上移if(pos_h>1){canvas[pos_h][pos_w]=blank;if(canvas[pos_h-1][pos_w] == enemy){ //下个位置是敌机,撞毁canvas[pos_h-1][pos_w]= destroy;IsOver=0;}else canvas[--pos_h][pos_w]=plane;}}if(key_S<0){ //当按下 S 键,下移if(pos_h<high){canvas[pos_h][pos_w]=blank;if(canvas[pos_h+1][pos_w] == enemy){ //下个位置是敌机,撞毁 canvas[pos_h+1][pos_w]= destroy;IsOver=0;}else canvas[++pos_h][pos_w]=plane;}}if(key_A<0){ //当按下 A 键,左移if(pos_w>1){canvas[pos_h][pos_w]=blank;if(canvas[pos_h][pos_w-1] == enemy){ //下个位置是敌机,撞毁canvas[pos_h][pos_w-1]= destroy;IsOver=0;}else canvas[pos_h][--pos_w]=plane;}}if(key_D<0){ //当按下 D 键,右移if(pos_w<width){canvas[pos_h][pos_w]=blank;if(canvas[pos_h][pos_w+1] == enemy){ //下个位置是敌机,撞毁 canvas[pos_h][pos_w+1]= destroy;IsOver=0;}else canvas[pos_h][++pos_w]=plane;}}if(key_attack<0){ //当按下空格键,发射⼦弹if(pos_h!=1)canvas[pos_h-1][pos_w]=bullet;}}}void UpdateNormal(){ //因输⼊导致的游戏状态更新int temp[high+2][width+2]; //⽤来判断原位置的临时数组for(int i=1;i<=high;i++){for(int j=1;j<=width;j++){temp[i][j]=canvas[i][j];}}for(int i=1;i<=high;i++){ //遍历临时数组,修改画布for(int j=1;j<=width;j++){if(temp[i][j]==enemy && interval%itv_move==0){ //当前位置为敌机 canvas[i][j]=blank;if(temp[i+1][j]==bullet){ //下⾯为⼦弹,敌机被击中canvas[i+1][j]=blank;score++;printf("\a"); //击中⾳效}else if(i<high){canvas[i+1][j]=enemy;}if(i+1==pos_h&&j==pos_w){ //下⾯为飞机,玩家飞机被撞毁canvas[i+1][j]=destroy;IsOver=0;}}if(temp[i][j]==bullet){ //当前位置为⼦弹canvas[i][j]=blank;if(temp[i-1][j]==enemy){ //下个位置是敌机,敌机被击毁canvas[i-1][j]=blank;score++;printf("\a");}else if(i>1){canvas[i-1][j]=bullet;}}}}if(interval%itv_new==0) //刚好到时间间隔for(int i=0;i<enemynum;i++){ //新增敌机群canvas[rand()%2+1][rand()%width+1]=enemy;}if(interval<=100){ //时间间隔计次interval++;}else{ //时间间隔计次清零interval=0;}}void gotoxy(int x,int y){ //回调光标COORD pos;pos.X=x-1;pos.Y=y-1;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos);}void HideCursor(){ //隐藏光标函数CONSOLE_CURSOR_INFO cursor;cursor.bVisible = FALSE;cursor.dwSize = sizeof(cursor);HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);SetConsoleCursorInfo(handle, &cursor);}更多有趣的经典⼩游戏实现专题,分享给⼤家:以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

C语言飞机大战源码

C语言飞机大战源码

include<iostream>include<windows.h>include<conio.h>include<time.h>include<string>using namespace std;/=============== all the structures ===============/ typedef struct Frame{COORD position2;int flag;}Frame;/=============== all the functions ===============/ void SetPosCOORD a// set cursor{HANDLE out=GetStdHandleSTD_OUTPUT_HANDLE;SetConsoleCursorPositionout; a;}void SetPosint i; int j// set cursor{COORD pos={i; j};SetPospos;}void HideCursor{CONSOLE_CURSOR_INFO cursor_info = {1; 0};SetConsoleCursorInfoGetStdHandleSTD_OUTPUT_HANDLE; &cursor_info;}//把第y行;x1; x2 之间的坐标填充为 chvoid drawRowint y; int x1; int x2; char ch{SetPosx1;y;forint i = 0; i <= x2-x1; i++cout<<ch;}//在a; b 纵坐标相同的前提下;把坐标 a; b 之间填充为 ch void drawRowCOORD a; COORD b; char ch{ifa.Y == b.YdrawRowa.Y; a.X; b.X; ch;else{SetPos0; 25;cout<<"error code 01:无法填充行;因为两个坐标的纵坐标x不相等";system"pause";}}//把第x列;y1; y2 之间的坐标填充为 chvoid drawColint x; int y1; int y2; char ch{int y=y1;whiley=y2+1{SetPosx; y;cout<<ch;y++;}}//在a; b 横坐标相同的前提下;把坐标 a; b 之间填充为 chvoid drawColCOORD a; COORD b; char ch{ifa.X == b.XdrawCola.X; a.Y; b.Y; ch;else{SetPos0; 25;cout<<"error code 02:无法填充列;因为两个坐标的横坐标y不相等";system"pause";}}//左上角坐标、右下角坐标、用row填充行、用col填充列void drawFrameCOORD a; COORD b; char row; char col{drawRowa.Y; a.X+1; b.X-1; row;drawRowb.Y; a.X+1; b.X-1; row;drawCola.X; a.Y+1; b.Y-1; col;drawColb.X; a.Y+1; b.Y-1; col;}void drawFrameint x1; int y1; int x2; int y2; char row; char col {COORD a={x1; y1};COORD b={x2; y2};drawFramea; b; row; col;}void drawFrameFrame frame; char row; char col{COORD a = frame.position0;COORD b = frame.position1;drawFramea; b; row; col;}void drawPlaying{drawFrame0; 0; 48; 24; '='; '|';// draw map frame;drawFrame49; 0; 79; 4; '-'; '|';// draw output framedrawFrame49; 4; 79; 9; '-'; '|';// draw score framedrawFrame49; 9; 79; 20; '-'; '|';// draw operate framedrawFrame49; 20; 79; 24; '-'; '|';// draw other message frameSetPos52; 6;cout<<"得分:";SetPos52; 7;cout<<"称号:";SetPos52;10;cout<<"操作方式:";SetPos52;12;cout<<" a;s;d;w 控制战机移动..";SetPos52;14;cout<<" p 暂停游戏..";SetPos52;16;cout<<" e 退出游戏..";}//在a; b之间产生一个随机整数int randomint a; int b{int c=rand % a-b+ a;return c;}//在两个坐标包括的矩形框内随机产生一个坐标COORD randomCOORD a; COORD b{int x=randoma.X; b.X;int y=randoma.Y; b.Y;COORD c={x; y};return c;}bool judgeCoordInFrameFrame frame; COORD spot {ifspot.X>=frame.position0.Xifspot.X<=frame.position1.Xifspot.Y>=frame.position0.Yifspot.Y<=frame.position0.Yreturn true;return false;}void printCoordCOORD a{cout <<" "<<a.X<<" ; "<<a.Y<<" "; }void printFrameCoordFrame a{printCoorda.position0;cout <<" - ";printCoorda.position1;}int drawMenu{SetPos30; 1;cout<<"P l a n e W a r";drawRow3; 0; 79; '-';drawRow5; 0; 79; '-';SetPos28; 4;cout<<"w 和 s 选择; k 确定";SetPos15; 11;cout<<"1. 简单的敌人";SetPos15; 13;cout<<"2. 冷酷的敌人";drawRow20; 0; 79; '-';drawRow22; 0; 79; '-';SetPos47; 11;cout<<"简单的敌人:";SetPos51; 13;cout<<"简单敌人有着较慢的移动速度.."; SetPos24; 21;int j=11;SetPos12; j;cout<<">>";//drawFrame45; 9; 79; 17; '='; '|'; while1{ if _kbhit{char x=_getch;switch x{case 'w' :{if j == 13{SetPos12; j;cout<<" ";j = 11;SetPos12; j;cout<<">>";SetPos51; 13;cout<<" ";SetPos47; 11;cout<<"简单的敌人:";SetPos51; 13;cout<<"简单敌人有着较慢的移动速度..";}break;}case 's' :{if j == 11{SetPos12; j;cout<<" ";j = 13;SetPos12; j;cout<<">>";SetPos51; 13;cout<<" ";SetPos47; 11;cout<<"冷酷的敌人:";SetPos51; 13;cout<<"冷酷的敌人移动速度较快..";}break;}case 'k' :{if j == 8 return 1;else return 2;}}}}}/DWORD WINAPI MusicFunLPVOID lpParamte{//DWORD OBJ;sndPlaySoundTEXT"bgm.wav"; SND_FILENAME|SND_ASYNC;return 0;}//================== the Game Class ==================/ class Game{public:COORD position10;COORD bullet10;Frame enemy8;int score;int rank;int rankf;string title;int flag_rank;Game ;//初始化所有void initPlane;void initBullet;void initEnemy;//初始化其中一个//void initThisBullet COORD ;//void initThisEnemy Frame ;void planeMovechar;void bulletMove;void enemyMove;//填充所有void drawPlane;void drawPlaneToNull;void drawBullet;void drawBulletToNull;void drawEnemy;void drawEnemyToNull;//填充其中一个void drawThisBulletToNull COORD ; void drawThisEnemyToNull Frame ; void Pause;void Playing;void judgePlane;void judgeEnemy;void Shoot;void GameOver;void printScore;};Game::Game{initPlane;initBullet;initEnemy;score = 0;rank = 25;rankf = 0;flag_rank = 0;}void Game::initPlane{COORD centren={39; 22};position0.X=position5.X=position7.X=position9.X=centren.X;position1.X=centren.X-2;position2.X=position6.X=centren.X-1;position3.X=position8.X=centren.X+1;position4.X=centren.X+2;forint i=0; i<=4; i++positioni.Y=centren.Y;forint i=6; i<=8; i++positioni.Y=centren.Y+1;position5.Y=centren.Y-1;position9.Y=centren.Y-2;}void Game::drawPlane{forint i=0; i<9; i++{SetPospositioni;ifi=5cout<<"O";else ifi==5cout<<"|";}}void Game::drawPlaneToNull{forint i=0; i<9; i++{SetPospositioni;cout<<" ";}}void Game::initBullet{forint i=0; i<10; i++bulleti.Y = 30;}void Game::drawBullet{forint i=0; i<10; i++{if bulleti.Y = 30{SetPosbulleti;cout<<"^";}}}void Game::drawBulletToNull{forint i=0; i<10; i++if bulleti.Y = 30{COORD pos={bulleti.X; bulleti.Y+1};SetPospos;cout<<" ";}}void Game::initEnemy{COORD a={1; 1};COORD b={45; 15};forint i=0; i<8; i++{enemyi.position0 = randoma; b;enemyi.position1.X = enemyi.position0.X + 3;enemyi.position1.Y = enemyi.position0.Y + 2;}}void Game::drawEnemyforint i=0; i<8; i++drawFrameenemyi.position0; enemyi.position1; '-'; '|'; }void Game::drawEnemyToNull{forint i=0; i<8; i++{drawFrameenemyi.position0; enemyi.position1; ' '; ' ';}}void Game::Pause{SetPos61;2;cout<<" ";SetPos61;2;cout<<"暂停中...";char c=_getch;whilec='p'c=_getch;SetPos61;2;cout<<" ";void Game::planeMovechar x{ifx == 'a'ifposition1.X = 1forint i=0; i<=9; i++positioni.X -= 2;ifx == 's'ifposition7.Y = 23forint i=0; i<=9; i++positioni.Y += 1;ifx == 'd'ifposition4.X = 47forint i=0; i<=9; i++positioni.X += 2;ifx == 'w'ifposition5.Y = 3forint i=0; i<=9; i++positioni.Y -= 1; }void Game::bulletMove{forint i=0; i<10; i++{if bulleti.Y = 30{bulleti.Y -= 1;if bulleti.Y == 1{COORD pos={bulleti.X; bulleti.Y+1};drawThisBulletToNull pos ;bulleti.Y=30;}}}}void Game::enemyMove{forint i=0; i<8; i++{forint j=0; j<2; j++enemyi.positionj.Y++;if24 == enemyi.position1.Y{COORD a={1; 1};COORD b={45; 3};enemyi.position0 = randoma; b;enemyi.position1.X = enemyi.position0.X + 3;enemyi.position1.Y = enemyi.position0.Y + 2;}}}void Game::judgePlane{forint i = 0; i < 8; i++forint j=0; j<9; j++ifjudgeCoordInFrameenemyi; positionj{SetPos62; 1;cout<<"坠毁";drawFrameenemyi; '+'; '+';Sleep1000;GameOver;break;}}void Game::drawThisBulletToNull COORD c{SetPosc;cout<<" ";}void Game::drawThisEnemyToNull Frame f{drawFramef; ' '; ' ';}void Game::judgeEnemy{forint i = 0; i < 8; i++forint j = 0; j < 10; j++if judgeCoordInFrameenemyi; bulletj{score += 5;drawThisEnemyToNull enemyi ;COORD a={1; 1};COORD b={45; 3};enemyi.position0 = randoma; b;enemyi.position1.X = enemyi.position0.X + 3;enemyi.position1.Y = enemyi.position0.Y + 2;drawThisBulletToNull bulletj ;bulletj.Y = 30;}}void Game::Shoot{forint i=0; i<10; i++ifbulleti.Y == 30{bulleti.X = position5.X;bulleti.Y = position5.Y-1;break;}}void Game::printScore{ifscore == 120 && flag_rank == 0{rank -= 3;flag_rank = 1;}else if score == 360 && flag_rank == 1{rank -= 5;flag_rank = 2;}else if score == 480 && flag_rank == 2 {rank -= 5;flag_rank = 3;}int x=rank/5;SetPos60; 6;cout<<score;if rank=rankf{SetPos60; 7;if x == 5title="初级飞行员";else if x == 4title="中级飞行员";else if x == 3title="高级飞行员";else if x == 2title="王牌飞行员";cout<<title;}rankf = rank;}void Game::Playing{//HANDLE MFUN;//MFUN= CreateThreadNULL; 0; MusicFun; NULL; 0; NULL;drawEnemy;drawPlane;int flag_bullet = 0;int flag_enemy = 0;while1{Sleep8;if_kbhit{char x = _getch;if 'a' == x || 's' == x || 'd' == x || 'w' == x{drawPlaneToNull;planeMovex;drawPlane;judgePlane;}else if 'p' == xPause;else if 'k' == xShoot;else if 'e' == x{//CloseHandleMFUN;GameOver;break;}}/ 处理子弹 /if 0 == flag_bullet{bulletMove;drawBulletToNull;drawBullet;judgeEnemy;}flag_bullet++;if 5 == flag_bulletflag_bullet = 0;/ 处理敌人 /if 0 == flag_enemy{drawEnemyToNull;enemyMove;drawEnemy;judgePlane;}flag_enemy++;if flag_enemy >= rankflag_enemy = 0;/ 输出得分 /printScore;}}void Game::GameOver{system"cls";COORD p1={28;9};COORD p2={53;15};drawFramep1; p2; '='; '|';SetPos36;12;string str="Game Over";forint i=0; i<str.size; i++{Sleep80;cout<<stri;}Sleep1000;system"cls";drawFramep1; p2; '='; '|';SetPos31; 11;cout<<"击落敌机:"<<score/5<<" 架"; SetPos31; 12;cout<<"得分:"<<score;SetPos31; 13;cout<<"获得称号:"<<title;SetPos30; 16;Sleep1000;cout<<"继续是y| 否n";as:char x=_getch;if x == 'n'exit0;else if x == 'y'{system"cls";Game game;int a = drawMenu;ifa == 2game.rank = 20;system"cls";drawPlaying;game.Playing;}else goto as;}/================== the main function ==================/ int main{//游戏准备srandinttime0; //随机种子HideCursor; //隐藏光标Game game;int a = drawMenu;ifa == 2game.rank = 20;system"cls";drawPlaying;game.Playing;}。

funcode太空战机代码c语言

funcode太空战机代码c语言

funcode太空战机代码c语言下面是一个简单的太空战机的 C 语言代码示例:```c#include <stdio.h>#include <stdbool.h>#include <conio.h>#define WIDTH 80#define HEIGHT 24char space[WIDTH][HEIGHT];int spaceshipX;bool isGameOver;void initSpace() {for (int y = 0; y < HEIGHT; y++) {for (int x = 0; x < WIDTH; x++) {space[x][y] = ' ';}}}void drawSpace() {system("cls");for (int y = 0; y < HEIGHT; y++) {for (int x = 0; x < WIDTH; x++) {printf("%c", space[x][y]);}printf("\n");}}void drawSpaceship() {space[spaceshipX][HEIGHT - 1] = 'A'; }void moveSpaceship(int direction) {space[spaceshipX][HEIGHT - 1] = ' '; spaceshipX += direction;if (spaceshipX < 0) {spaceshipX = 0;} else if (spaceshipX >= WIDTH) {spaceshipX = WIDTH - 1;}drawSpaceship();}void fireBullet() {int x = spaceshipX;int y = HEIGHT - 2;while (y > 0) {space[x][y] = '|';drawSpace();space[x][y] = ' ';y--;}}void handleInput() {if (kbhit()) {int key = getch();switch (key) {case 'a':moveSpaceship(-1); break;case 'd':moveSpaceship(1); break;case ' ':fireBullet();break;case 'q':isGameOver = true; break;}}}void updateGame() {handleInput();// 游戏状态更新逻辑}void gameLoop() {while (!isGameOver) {updateGame();drawSpace();}}int main() {initSpace();spaceshipX = WIDTH / 2;isGameOver = false;gameLoop();return 0;}```这段代码实现了一个简单的太空战机游戏。

飞机大战c++语言源代码,C++编写简易的飞机大战

飞机大战c++语言源代码,C++编写简易的飞机大战

飞机⼤战c++语⾔源代码,C++编写简易的飞机⼤战初学C/C++的⼩伙伴可以⽤做这个⼩游戏来熟悉⼀下编程的乐趣。

#include#include"resource.h"#include#include#include#define TIMER_DIREN 101 //定义定时器#define TIMER_DIRENMOVE 102#define TIMER_ZIDAN 103#define TIMER_DIRENRELEASE 104typedef struct Node //敌⼈,⾃⼰,⼦弹结构体{int x;int y;struct Node *pnext;}DiRen,FeiJi,ZiDan;void ZaoDiRen(); //造敌⼈void ShowDiRen(DiRen *pHead,HWND hWnd); //显⽰敌⼈void ZaoZiDan(); //造⼦弹void ShowZiDan(ZiDan *pHead,HWND hWnd); //显⽰⼦弹void DiRenMove(DiRen *pHead); //敌⼈移动void ZiDanMove(DiRen *pHead); //⼦弹移动void shoot(HWND hWnd,FeiJi *ziji,DiRen **diren,ZiDan **zidan);//判断是否射中void ReleaseDiren(DiRen **pHead); //释放出去的敌⼈void ReleaseZidan(ZiDan **pHead); //释放出去的⼦弹void ZaoZiJi(HWND hWnd); //造⾃⼰LRESULT CALLBACK pp(HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam);//回调函数int __stdcall WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow){WNDCLASSEX wc;HWND hWnd;wc.cbClsExtra=0;wc.cbSize=sizeof(WNDCLASSEX);wc.cbWndExtra=0;wc.hIcon=NULL ;wc.hCursor=NULL ;wc.hIconSm=NULL;wc.lpfnWndProc=pp;wc.lpszClassName="hello";wc.lpszMenuName=NULL;wc.style=CS_HREDRAW|CS_VREDRAW | CS_OWNDC ;wc.hbrBackground=(HBRUSH)5;RegisterClassEx(&wc);hWnd=CreateWindow("hello","world", WS_OVERLAPPEDWINDOW,100,100,600,600,NULL,NULL,hInstance,NULL); ShowWindow(hWnd,nCmdShow);while(GetMessage(&msg,NULL,0,0)){TranslateMessage(&msg);DispatchMessage(&msg);}return 0;}DiRen *pDiRen=NULL; //敌⼈ZiDan *pZiDan=NULL; //⼦弹FeiJi *pZiJi=NULL; //⾃⼰static int score=0; //分数static char sco[20]; //装分数的字符窜LRESULT CALLBACK pp(HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam){int i=1, //位jscore;HDC hdc;HDC memdc;switch(msg){case WM_TIMER: //定时器hdc=GetDC(hWnd); //得到设备句柄hbm=LoadBitmap(GetModuleHandle(NULL),MAKEINTRESOURCE(IDB_BITMAP4));//载⼊背景位图GetObject(hbm, sizeof(bminfo), &bminfo);memdc=CreateCompatibleDC(hdc);SelectObject(memdc,hbm);BitBlt(hdc,0,0,600,600,memdc,0,0,SRCCOPY);/*itoa(score,sco,10);*/sprintf(sco,"%d",score); //将分数装⼊字符窜jscore=score;while((jscore=jscore/10)>0) //判断分数有⼏位i++;TextOut(hdc,0,0,"分数",4);TextOut(hdc,30,0,sco,i); //显⽰分数DeleteDC(memdc);ReleaseDC(hWnd,hdc); //释放句柄DeleteObject(hbm);ZaoZiJi(hWnd); //造⾃⼰if(TIMER_ZIDAN==wParam) //定时器101{ZiDanMove(pZiDan); //⼦弹移动ReleaseZidan(&pZiDan); //释放出屏幕的⼦弹}else if( TIMER_DIREN==wParam) //定时器102{ZaoDiRen(); //造敌⼈}else if(TIMER_DIRENRELEASE==wParam) //定时器103{ReleaseDiren(&pDiRen); //释放出屏幕的敌⼈DiRenMove(pDiRen); //敌⼈移动ShowZiDan(pZiDan,hWnd); //显⽰⼦弹shoot(hWnd,pZiJi,&pDiRen,&pZiDan); //是否射中break;case WM_CLOSE: //关闭PostQuitMessage(0);break;case WM_KEYDOWN: //判断按键switch(wParam){case VK_LEFT: //左移if(pZiJi->x>0)pZiJi->x-=20;break;case VK_RIGHT: //右移if(pZiJi->x<530)pZiJi->x+=20;break;case VK_UP: //上移if(pZiJi->y>0)pZiJi->y-=20;break;case VK_DOWN: //下移if(pZiJi->y<520)pZiJi->y+=20;break;case VK_SPACE: //空格发射⼦弹ZaoZiDan();break;}break;case WM_CREATE: //创建pZiJi->x=200; //⾃⼰的xpZiJi->y=500; //⾃⼰的ySetTimer(hWnd,TIMER_DIREN,1000,NULL); //设置定时器SetTimer(hWnd,TIMER_DIRENMOVE,200,NULL);SetTimer(hWnd,TIMER_ZIDAN,100,NULL);SetTimer(hWnd,TIMER_DIRENRELEASE,300,NULL);break;}return DefWindowProc(hWnd,msg,wParam,lParam);}void ZaoDiRen() //造⼦弹{DiRen *u;u=(struct Node*)malloc(sizeof(struct Node));u->x=rand()%550; //⼦弹的x随机出现u->y=-10; //出现的纵坐标固定u->pnext=NULL;if(NULL==pDiRen){pDiRen=u;}else{u->pnext=pDiRen; //将新产⽣的链表放在头pDiRen=u;}}void ShowDiRen(struct Node *pHead,HWND hWnd) //显⽰敌⼈{HDC hdc;HDC memdc;HBITMAP hbm;hbm=LoadBitmap(GetModuleHandle(NULL),MAKEINTRESOURCE(IDB_BITMAP1));//载⼊敌⼈位图GetObject(hbm, sizeof(bminfo), &bminfo);memdc=CreateCompatibleDC(hdc);SelectObject(memdc,hbm);while(pHead!=NULL) //敌⼈链表不为空,显⽰敌机{BitBlt(hdc,pHead->x,pHead->y,40,40,memdc,0,0,SRCCOPY);pHead=pHead->pnext;}DeleteDC(memdc);ReleaseDC(hWnd,hdc);DeleteObject(hbm);}void ZaoZiJi(HWND hWnd){HDC hdc;HDC memdc;HBITMAP hbm;BITMAP bminfo;hdc=GetDC(hWnd);hbm=LoadBitmap(GetModuleHandle(NULL),MAKEINTRESOURCE(IDB_BITMAP3));//载⼊⾃⼰的位图GetObject(hbm, sizeof(bminfo), &bminfo);memdc=CreateCompatibleDC(hdc);SelectObject(memdc,hbm);BitBlt(hdc,pZiJi->x,pZiJi->y,40,40,memdc,0,0,SRCCOPY); //显⽰⾃⼰DeleteDC(memdc);ReleaseDC(hWnd,hdc);DeleteObject(hbm);}void ZaoZiDan() //造⼦弹{ZiDan *u;u->y=pZiJi->y+10;u->pnext=NULL;if(pZiDan==NULL){pZiDan=u;}else{u->pnext=pZiDan; //将⼦弹放在链表头pZiDan=u;}}void ShowZiDan(ZiDan *pHead,HWND hWnd) //显⽰⼦弹{HDC hdc;HDC memdc;HBITMAP hbm;BITMAP bminfo;hdc=GetDC(hWnd);hbm=LoadBitmap(GetModuleHandle(NULL),MAKEINTRESOURCE(IDB_BITMAP2)); //插⼊⼦弹位图GetObject(hbm, sizeof(bminfo), &bminfo);memdc=CreateCompatibleDC(hdc);SelectObject(memdc,hbm);while(pHead!=NULL) //⼦弹链表不为空,显⽰⼦弹{/*Ellipse(hdc,pHead->x,pHead->y,pHead->x+5,pHead->y+5);*/BitBlt(hdc,pHead->x,pHead->y,10,10,memdc,0,0,SRCCOPY);pHead=pHead->pnext;}DeleteDC(memdc);ReleaseDC(hWnd,hdc);DeleteObject(hbm);{while(pHead!=NULL) //链表不为空,敌⼈移动{if(score<500){pHead->y+=10;pHead=pHead->pnext;}else{pHead->y+=20;pHead=pHead->pnext;}}}void ZiDanMove(DiRen *pHead) //⼦弹移动{while(pHead!=NULL) //链表不为空⼦弹移动{pHead->y-=20;pHead=pHead->pnext;}}void shoot(HWND hWnd,FeiJi *ziji,DiRen **diren,ZiDan **zidan) //判断是否中{DiRen *js1=*diren;ZiDan *js2=*zidan;int n = 1;while(js1!=NULL) //判断⾃⼰是否撞机{//撞击释放定时器游戏结束if((ziji->x-js1->x<30&&ziji->x-js1->x>-38)&&(ziji->y-js1->y<25&&ziji->y-js1->y>-38))KillTimer(hWnd,TIMER_ZIDAN);KillTimer(hWnd,TIMER_DIRENMOVE);KillTimer(hWnd,TIMER_DIRENRELEASE);MessageBox(hWnd,"You Lose","窗⼝",MB_OK);PostQuitMessage(0);break;}elsejs1=js1->pnext; //没有判断下⼀个敌机}js1=*diren; //敌机回到头while((js1=*diren)!=NULL) //判断敌⼈是否为空{zidan = &pZiDan;n = 0;while((js2=*zidan)!=NULL) //判断⼦弹是否为空{//敌机中弹if((js2->x - js1->x <= 40&&js2->x - js1->x>=-5)&&(js2->y - js1->y <= 40&&js2->y - js1->y>=-8)) {score+=100;n = 1;*zidan = js2->pnext;if(js1->pnext!=NULL) //链表下节不为空,指向下⼀个释放中弹的飞机⼦弹{*diren = js1->pnext;diren = &pDiRen;free(js1);free(js2);}else*diren = NULL;else{zidan = &js2->pnext; //没中看下⼀个}}if(n != 1) //判断是否是中弹出来的{diren = &js1->pnext;}}}void ReleaseDiren(DiRen **pHead) //释放飞出屏幕的敌⼈{DiRen *js=*pHead;while((js=*pHead)!=NULL){if(js->y>600) //飞出屏幕释放{*pHead=js->pnext;free(js);}else{pHead = &js->pnext; //看下⼀个}}}void ReleaseZidan(ZiDan **pHead) //释放⼦弹{ZiDan *js=*pHead;while((js=*pHead)!=NULL){*pHead=js->pnext;free(js);}elsepHead=&js->pnext; //没飞出看下⼀个}}同时分享⼀个⽹友的⽅法//mytestView.cpp:Cmytest;//;#include"stdafx.h;#include"mytest.h;#include"mytestDoc;#include"mytestView;#ifdef_DEBUG;#definenewDEBUG_NEW;#endif;//CmytestVie// mytestView.cpp : CmytestView 类的实现//#include "stdafx.h"#include "mytest.h"#include "mytestDoc.h"#include "mytestView.h"#ifdef _DEBUG#define new DEBUG_NEW#endif// CmytestViewIMPLEMENT_DYNCREATE(CmytestView, CView) BEGIN_MESSAGE_MAP(CmytestView, CView) ON_WM_CREATE()ON_WM_TIMER()ON_WM_KEYDOWN()END_MESSAGE_MAP()CmytestView::CmytestView(){// TODO: 在此处添加构造代码m_x_me=0;m_x_enemy=0;m_y_enemyone=0;m_y_enemytwo=0;m_y_bomb=0;m_x_bomb=0;m_x_ball=0;m_y_ball=0;m_x_explsion=0;}CmytestView::~CmytestView(){}BOOL CmytestView::PreCreateWindow(CREATESTRUCT& cs) {// TODO: 在此处通过修改// CREATESTRUCT cs 来修改窗⼝类或样式return CView::PreCreateWindow(cs);}// CmytestView 绘制void CmytestView::OnDraw(CDC* pDC){CmytestDoc* pDoc = GetDocument();ASSERT_VALID(pDoc);if (!pDoc)return;// TODO: 在此处为本机数据添加绘制代码/*CBitmap bitmap;bitmap.LoadBitmapW(IDB_ME);*//*pDC->BitBlt(100,50,50,60,&MemDC,0,0,SRCCOPY);*/ /*POINT pt;pt.x=200;pt.y=200;CImageList imageList;imageList.Create(50,60,ILC_COLOR24|ILC_MASK,1,0); imageList.Add(&bitmap,RGB(0,0,0));imageList.Draw(pDC,0,pt,ILD_TRANSPARENT);CDC MemDC;MemDC.CreateCompatibleDC(NULL);MemDC.SelectObject(&bitmap);*///RECT rc;//GetClientRect(&rc);//CBrush brush;//brush.CreateSolidBrush(RGB(3,108,254));//pDC->SelectObject(&brush);//CBrush *oldbrush=pDC->SelectObject(&brush);//pDC->Rectangle(&rc);//pDC->SelectObject(oldbrush);//CBitmap bitmap;//bitmap.LoadBitmapW(IDB_ME);//POINT pt;//pt.x=200;//pt.y=200;//CImageList imageList;//imageList.Create(60,50,ILC_COLOR24|ILC_MASK,1,0); //imageList.Add(&bitmap,RGB(0,0,0));//imageList.Draw(pDC,0,pt,ILD_TRANSPARENT);// CDC MemDC;//MemDC.CreateCompatibleDC(NULL);//MemDC.SelectObject(&bitmap);//刷新RECT rc;CBrush brush;brush.CreateSolidBrush(RGB(3,108,254));pDC->SelectObject(&brush);CBrush *oldbrush=pDC->SelectObject(&brush);pDC->Rectangle(&rc);pDC->SelectObject(oldbrush);//敌机CBitmap bitmap1;bitmap1.LoadBitmapW(IDB_enemy);POINT pt1;pt1.x=200;pt1.y=m_y_enemyone;POINT pt1_2;pt1_2.x=300;pt1_2.y=m_y_enemytwo;CImageList imageList1;imageList1.Create(35,35,ILC_COLOR24|ILC_MASK,1,0); imageList1.Add(&bitmap1,RGB(0,0,0));imageList1.Draw(pDC,0,pt1,ILD_TRANSPARENT); imageList1.Draw(pDC,1,pt1_2,ILD_TRANSPARENT);//战机CBitmap bitmap2;bitmap2.LoadBitmapW(IDB_ME);POINT pt2;pt2.x=m_x_me;pt2.y=100;CImageList imageList2;imageList2.Create(50,60,ILC_COLOR24|ILC_MASK,1,0); imageList2.Add(&bitmap2,RGB(0,0,0));imageList2.Draw(pDC,0,pt2,ILD_TRANSPARENT);//⼦弹CBitmap bitmap3;bitmap3.LoadBitmapW(IDB_ball);pt3.y=m_y_ball;CImageList imageList3;imageList3.Create(8,8,ILC_COLOR24|ILC_MASK,1,0); imageList3.Add(&bitmap3,RGB(0,0,0));imageList3.Draw(pDC,0,pt3,ILD_TRANSPARENT);//炸弹CBitmap bitmap4;bitmap4.LoadBitmapW(IDB_bomb);POINT pt4;pt4.x=m_x_bomb;pt4.y=250;CImageList imageList4;imageList4.Create(10,20,ILC_COLOR24|ILC_MASK,1,0); imageList4.Add(&bitmap4,RGB(0,0,0));imageList4.Draw(pDC,0,pt4,ILD_TRANSPARENT);//爆炸CBitmap bitmap5;bitmap5.LoadBitmapW(IDB_explsion);POINT pt5_1;pt5_1.x=310;pt5_1.y=310;POINT pt5_2;pt5_2.x=330;pt5_2.y=330;POINT pt5_3;pt5_3.x=350;pt5_3.y=450;POINT pt5_4;pt5_4.x=470;pt5_4.y=470;POINT pt5_5;pt5_5.x=510;pt5_6.x=530;pt5_6.y=530;POINT pt5_7;pt5_7.x=540;pt5_7.y=540;POINT pt5_8;pt5_8.x=450;pt5_8.y=250;CImageList imageList5;imageList5.Create(66,66,ILC_COLOR24|ILC_MASK,1,0); imageList5.Add(&bitmap5,RGB(0,0,0));imageList5.Draw(pDC,0,pt5_1,ILD_TRANSPARENT); imageList5.Draw(pDC,1,pt5_2,ILD_TRANSPARENT); imageList5.Draw(pDC,2,pt5_3,ILD_TRANSPARENT); imageList5.Draw(pDC,3,pt5_4,ILD_TRANSPARENT); imageList5.Draw(pDC,4,pt5_5,ILD_TRANSPARENT); imageList5.Draw(pDC,5,pt5_6,ILD_TRANSPARENT); imageList5.Draw(pDC,6,pt5_7,ILD_TRANSPARENT); imageList5.Draw(pDC,7,pt5_8,ILD_TRANSPARENT);/*CDC MemDC;MemDC.CreateCompatibleDC(NULL);MemDC.SelectObject(&bitmap2);*/}// CmytestView 诊断#ifdef _DEBUGvoid CmytestView::AssertValid() const{CView::AssertValid();}void CmytestView::Dump(CDumpContext& dc) const{CView::Dump(dc);CmytestDoc* CmytestView::GetDocument() const // ⾮调试版本是内联的 {ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CmytestDoc))); return (CmytestDoc*)m_pDocument; }#endif //_DEBUG// CmytestView 消息处理程序int CmytestView::OnCreate(LPCREATESTRUCT lpCreateStruct){if (CView::OnCreate(lpCreateStruct) == -1)return -1;// TODO: 在此添加您专⽤的创建代码SetTimer(1,30,NULL);return 0;}void CmytestView::OnTimer(UINT_PTR nIDEvent){// TODO: 在此添加消息处理程序代码和/或调⽤默认值CView::OnTimer(nIDEvent);CDC *pDC=GetDC();//刷新背景RECT rc;GetClientRect(&rc);CBrush brush;brush.CreateSolidBrush(RGB(3,108,254));pDC->SelectObject(&brush);CBrush *oldbrush=pDC->SelectObject(&brush);pDC->Rectangle(&rc);pDC->SelectObject(oldbrush);//战机CBitmap bitmap2;bitmap2.LoadBitmapW(IDB_ME);POINT pt2;pt2.x=m_x_me;pt2.y=100;imageList2.Create(50,60,ILC_COLOR24|ILC_MASK,1,0); imageList2.Add(&bitmap2,RGB(0,0,0));imageList2.Draw(pDC,0,pt2,ILD_TRANSPARENT);//⼦弹欢迎试玩⼀下游戏 ⽅向键:w,a,s,d 控制键:J,K。

VC++电脑游戏飞机大战的开发与设计(含源文件)

VC++电脑游戏飞机大战的开发与设计(含源文件)

毕业设计(论文)题目:飞机大战游戏的设计与开发学院:计算机科学学院摘要飞机游戏是一款风靡全球的电视机游戏和掌上游戏机产品,曾几何时,它创造了一个无法企及的游戏巅峰,也曾影响了一代产业链。

虽然它辉煌的业绩在历史的涡轮中渐渐远去,但这款游戏每每提及,总会令人爱不释手,魂牵梦绕。

这款游戏的名字叫做飞机大战,它是运行于Windows操作系统下的一款2D 游戏,以C/C++为开发语言,构建于Microsoft Foundation Class Library(MFC)框架体系中,其中调用了部分的Win32API函数接口,在Visual Studio2010环境下开发的一款多媒体游戏。

随着硬件性能的不断提高,游戏的日益普及,使开发者不再需要过多的关注不同的硬件设备。

本论文着眼于双缓冲绘图的运用,开发出仅用于理论研究的二维平面射击类游戏。

本文首先分析了电脑游戏的发展历史,然后分析了制作游戏的基本流程和游戏本身所要包含的几种元素以及游戏应具备的游戏层次。

根据2D游戏的特点和游戏的角色,以及给用户呈现的游戏界面的特效,对2D图形技术,Windows 图形界面编程技术GDI,DirectDraw的显卡接口和DirectSound声卡接口以及MVC 设计模式下的MFC框架等技术进行了比较仔细的研究。

通过自定义一个游戏类CGame,封装了游戏元素的基本属性和行为,这样便于在用到游戏的行为操作是,只要轻松的产生CGame对象便可直接调用其方法,也有利于升级为双人游戏,乃至网络版时,只需要在该类中添加相应的行为便可。

当我们向用户呈现游戏运行的界面时,通过Timer时钟控件,映射到相应的处理函数,使得游戏界面大约每2秒钟刷新一下界面,这样才能让一张位图背景图片具有动态效果。

当使用DirectSound声卡接口时,我方和敌方相互射击所发出的声音,都是在时钟映射函数调用时处理的。

【关键词:】C/C++; VS 2010/MFC; 飞机大战游戏IABSTRACTAirplane game is a popular global TV game and handheld game products,once upon a time,it creates a game out of reach peak,have influenced a generation of industrial chain. Although it brilliant performance in the history of turbine faded away,but the game is often mentioned always miss.The game's name is ,it is running on Windows operating systems,a 2 d game,with C/C + + as development language,building on the Microsoft Foundation Class Library MFC framework,which invokes the part Win32API function interface,in the Visual Studio 2010 environment using DirectX software development kit SDK to develop a multimedia game.With the constant improvement of the hardware performance,the rising popularity of the game,DirectX development kit update and perfect,make developers don't need too much attention to different hardware devices. The use of this thesis focus on DirectSound,DirectDraw,developed only due to the theoretical research of two-dimensional plane shooting game.This article first analyzes the development history of computer games,and then analyze the basic process of making game and the game itself need to include what kind of elements and the game should have level. According to the characteristics of the 2 d game and game role,and to the user interface rendering effects,the technology of 2 d graphics,the graphics interface and DirectSound DirectDraw sound card interface and MFC framework of MVC design mode to compare the careful research. Through a custom game CGame class,encapsulates the basic attribute of game elements and behavior,so easy to use in the game operation,as long as easy to produce the CGame object can be directly to call its methods,but also to when upgraded to a double game,online version,just need to add the proper behavior in the class. When we present game operation interface to the user,by the Timer clock control that is mapped to the corresponding processing function,makes the game about every 2 seconds refresh interface,in this way can we make a bitmap background picture with dynamic effect. When using DirectSound sound card interface,we and the noise made by enemy fire,are on the clock whenprocessing the mapping function call.KEY WORDS: C/C + +; VS 2010/MFC; plane war game目录第1章绪论 (1)1.1 系统研究的背景及意义 (1)1.2 国内外的发展现状 (1)1.4 本文的组织结构 (2)1.5 本章小结 (2)第2章游戏的相关知识和系统开发平台的阐述 (3)2.1游戏基本流程概述 (3)2.2游戏系统元素阐述 (4)2.3开发环境和相关技术的概述 (5)2.3.1 开发环境 (5)2.3.2 相关技术 (5)2.4本章小结 (10)第3章游戏分析 (11)3.1 用户功能需求分析 (11)3.2 系统性能要求 (12)3.3可行性分析 (12)3.4本章小结 (13)第4章游戏设计 (14)4.1游戏整体设计 (14)4.1.1 整体结构 (14)4.1.2 游戏对战规则 (14)4.2游戏界面设计 (15)4.2.1游戏起始界面设计 (15)4.2.2游戏运行界面设计 (17)4.2.3游戏结束界面设计 (18)4.3游戏功能设计 (19)4.3.1双缓冲绘图 (19)4.3.2功能实现 (19)4.4本章小结 (26)第5章系统测试 (27)5.1软件测试基础理论 (27)5.1.1 软件测试定义 (27)5.1.2 软件测试基本概念 (27)5.2软件测试目的 (27)5.3软件测试方法分类 (28)5.3.1 静态测试与动态测试 (28)5.3.2 黑盒白盒与白盒测试 (28)5.3.3 单元测试、集成测试、系统测试、验证测试和确认测试 (29)5.4论坛测试 (29)5.4.1 测试用例设计要求 (29)5.5测试用例 (30)5.6测试结果 (30)5.6本章小结 (31)第6章工作总结 (32)致谢 (33)参考文献 (34)附录1 (35)第1章绪论第1章绪论1.1 系统研究的背景及意义当今社会是一个信息社会,一个知识经济的年代。

飞机大战程序代码

飞机大战程序代码
按键作用点击开始按钮迚入游戏点击退出退出游戏点击帮助游戏规则界面设计界面设计代码form1privatesublabel3clickmsgbox用wasd控制飞机移动按r重新开始按e直接退出游戏可点击l或者鼠标左键迚行射击当敌方血量为0时游戏胜利当我方子弹用尽或者血量为o时游戏失败打中敌机即出现子弹补给
Sub GAMESTART() Label6.Visible = False L1.Visible = True C2.Visible = True C1.Visible = True L2.Visible = True Label6.Visible = False L2.Y1 = C1.Top L2.Y2 = C1.Top + 840 Timer2.Enabled = True Timer3.Enabled = True Form_Load End Sub Sub WINNER() C1.Visible = False Timer3.Enabled = False L2.Visible = False Label6.Visible = True Label6.Caption = "你赢了! " End Sub
Private Sub Form_Load() d = 10 f2 = True f3 = 20 La1.Caption = d e=5 Label3.Caption = e Label5.Caption = f3 End Sub Private Sub Text1_KeyPress(KeyAscii As Integer) If KeyAscii = 97 Then C2.Left = C2.Left - 250 If C2.Left + C2.Width / 2 <= 0 Then C2.Left = form1.ScaleWidth - C2.Width End If If f2 = True Then L1.X1 = C2.Left + C2.Width / 2 L1.X2 = C2.Left + C2.Width / 2 End If Text1.Text = "" Text1.SetFocus ElseIf KeyAscii = 100 Then C2.Left = C2.Left + 250 If C2.Left + C2.Width / 2 >= form1.ScaleWidth Then C2.Left = 0 End If If f2 = True Then L1.X1 = C2.Left + C2.Width / 2 L1.X2 = C2.Left + C2.Width / 2 End If

c语言飞机大战代码

c语言飞机大战代码

c语言飞机大战代码#include<stdio.h>#include<stdlib.h>#include<time.h>#include<windows.h>#define LEFT 75 //宏定义方向键#define RIGHT 77#define UP 72#define DOWN 80int main(){char a; //声明变量aint x=10,y=10; //声明变量x,y分别表示飞机的横纵坐标 int stp; //声明变量stpint direct; //声明变量directint i,j; //声明变量i,j循环int score; //声明变量scorechar key; //声明变量keyscore = 0; //初始分数设为0srand((unsigned)time(NULL)); //设置随机数system("cls"); //清屏while(1){key=_getch(); //读取按键if(key=='w') //若键盘输入的是w{direct=UP;key=' ';}if(key=='s') //若键盘输入的是s{direct=DOWN;key=' ';}if(key=='a') //若键盘输入的是a{direct=LEFT;key=' ';}if(key=='d') //若键盘输入的是d{direct=RIGHT;key=' ';}if(direct==UP) //若direction的值为UPy=y-1; //将y的值减1if(direct==DOWN) //若direction的值为DOWN y=y+1; //将y的值加1if(direct==LEFT) //若direction的值为LEFT x=x-1; //将x的值减1if(direct==RIGHT) //若direction的值为RIGHTx=x+1; //将x的值加1system("cls"); //清屏for(i=0;i<20;i++) //循环20次{for(j=0;j<40;j++) //循环40次{if(i==x && j==y) //如果i等于x并且j等于y printf("A"); //输出Aelseprintf("-"); //输出-}printf("\n"); //换行}Sleep(50); //休眠50毫秒if(x==0||x==20||y==0||y==20)break; //若x或y的值为0,20则结束程序stp=rand()%8; //随机一个stp的值if(stp==0){score++; //每随机出0时分数加1printf("分数:%d\n",score); //显示分数}}printf("你的最终得分是:%d\n",score); //显示最终得分return 0;}上面是C语言飞机大战的代码,代码的功能是控制一架飞机位置并且记分,玩家通过按键来控制飞机的位置,飞机撞到边界则游戏结束。

C语言代码实现飞机大战

C语言代码实现飞机大战

C语⾔代码实现飞机⼤战本⽂实例为⼤家分享了C语⾔实现简单飞机⼤战的具体代码,供⼤家参考,具体内容如下这个游戏的功能很单⼀,也就是“飞机⼤战”,哈哈哈哈。

总共只有300多⾏代码左右,你也可以想想它会有多简陋,把它复制下来编译⼀下可以直接执⾏,需要的同学可以⾃取~PS:我运⾏的环境是 dev c++,前提你要在C99的环境中执⾏以下是源代码#include<stdio.h>#include<stdio.h>#include<windows.h> //将⽤户从键盘获得的输⼊进⾏输出#include<conio.h> //获得⽤户键盘的输⼊//定义全局变量int high,width; //定义边界int position_x,position_y; //飞机位置int bullet_x,bullet_y; //⼦弹位置int enemy_x,enemy_y; //敌军飞机int score; //获得分数int flag; //飞机状态void gotoxy(int x,int y); //光标移动到(x,y)位置void welcometogame(); //初始化界⾯int color(int c); //更改⽂字颜⾊void explation(); //游戏右侧显⽰void scoreandtips(); //显⽰游戏提⽰void show(); //显⽰游戏界⾯void endgame(); //游戏结束/*** ⽂字颜⾊函数*/int color(int c){SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), c); //更改⽂字颜⾊return 0;}/*** 设置光标位置*/void gotoxy(int x,int y){COORD c;c.X=x;c.Y=y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),c);}void welcometogame() //开始界⾯{int n;color(15);gotoxy(43,10);printf("飞机⼤战");color(11);gotoxy(25, 22);printf("1.开始游戏");gotoxy(45, 22);printf("2.游戏说明");gotoxy(65, 22);printf("3.退出游戏");gotoxy(40,27);color(3);printf("请选择 1 2 3:");color(14);scanf("%d", &n); //输⼊选项switch (n){case 1:break;case 2:explation(); //游戏说明函数break;case 3:exit(0); //退出游戏break;default:color(12);gotoxy(40,28);printf("请输⼊1-3之间的数!");_getch(); //输⼊任意键system("cls"); //清屏welcometogame();}}void explation() //游戏提⽰{int i,j = 1;system("cls");color(10);gotoxy(44,1);printf("游戏说明");color(2);for (i = 3; i <= 28; i++) //输出上下边框==={for (j = 6; j <= 80; j++) //输出左右边框||{gotoxy(j, i);if (i == 3 || i == 28) printf("=");else if (j == 6 || j == 80) printf("||");}}color(3);gotoxy(20,5);printf("1. W,A,S,D 分别控制飞机的上下左右移动");color(10);gotoxy(20,8);printf("2. 按空格发射⼦弹,打中敌机即可得到⼀分");color(14);gotoxy(20,11);printf("3.碰到敌机⼦弹死亡");color(11);gotoxy(20,14);printf("4. ESC :退出游戏");color(4);gotoxy(20,17);printf("5. 玩的愉快");color(7);gotoxy(20,20);printf("/*****按任意键返回主页⾯*****/");_getch(); //按任意键返回主界⾯system("cls");welcometogame();}void scoreandtips()//游戏侧边提⽰{gotoxy(50,8);color(14);printf("游戏得分:%d ",score);gotoxy(50,10);printf("⽤W A S D 分别控制飞机的移动");gotoxy(50,12);printf("按下空格键即为发射炮弹");gotoxy(50,14);printf("@ 的样⼦就是敌⼈的飞机");}void HideCursor() // ⽤于隐藏光标{CONSOLE_CURSOR_INFO cursor_info = {1, 0}; // 第⼆个值为0表⽰隐藏光标}void startup() //数据初始化{high=20; //定义游戏界⾯的⾼度width=40; //游戏界⾯的宽度position_x=high-3; //定义飞机的初始位置position_y=width/2;bullet_x=0;bullet_y=position_y;enemy_x=0;enemy_y=position_y;score=0;flag=0; //飞机完好HideCursor();}void show() //显⽰界⾯{int i,j,k;for(i=0;i<high;i++){for(j=0;j<width;j++){if(flag)break;else if((i==position_x)&&(j==position_y)) //飞机坐标{printf("^");}else if((i==enemy_x)&&(j==enemy_y)) //敌机坐标printf("@");else if((i==bullet_x)&&(j==bullet_y)) //⼦弹坐标printf("|");else if ((j==width-1)||(i==high-1)||(j==0)||(i==0)) //打印边界 printf("-");elseprintf(" ");}printf("\n");}printf("\n");if((position_x==enemy_x)&&(position_y==enemy_y)){flag=1; //飞机撞毁游戏结束system("cls");printf("游戏结束\n");}else{printf("分数 %d",score);}/** _getch(); //按任意键返回主界⾯system("cls");welcometogame();*/}void endgame(){int k,f;system("cls");printf("输⼊1再玩⼀次,输⼊2返回主菜单,输⼊3退出游戏"); scanf("%d",&k);case 1:printf("重新玩游戏");system("cls");startup(); // 数据初始化show();break;case 2:printf("返回主菜单");system("cls");welcometogame();startup();break;case 3:printf("退出成功");exit(0);break;default:color(12);gotoxy(40,28);system("cls");printf("输⼊错误,输⼊任意键回到主菜单");_getch(); //输⼊任意键welcometogame();startup();system("cls"); //清屏}}void withoutInpute() //与⽤户输⼊⽆关{if(bullet_x>0) //⼦弹上升效果bullet_x--;if((bullet_x==enemy_x)&&(bullet_y==enemy_y)) //⼦弹命中敌机 {score++;bullet_x=-1;enemy_x=1;enemy_y=2+rand()%width-2;}static int speed;if(speed<30) //减慢敌机速度,不影响飞机和⼦弹速度speed++;if(speed==30){if(enemy_x<high)enemy_x++;else{enemy_x=0;enemy_y=2+rand()%width-2;}speed=0;}}void withInpute() //与⽤户输⼊有关{char input;if(kbhit()) //控制飞机⽅向{input=getch();if((input=='w')&&position_x>1)position_x--;if((input=='s')&&position_x<high-2)position_x++;if((input=='a')&&position_y>1)position_y--;if((input=='d')&&position_y<width-2)bullet_x=position_x-1;bullet_y=position_y;}}}int main(){system("mode con cols=100 lines=30"); //设置控制台的宽⾼welcometogame();startup(); // 数据初始化//explation();while(1) // 游戏循环执⾏{gotoxy(0,0);show(); // 显⽰画⾯scoreandtips();if(flag == 1){endgame();}withoutInpute(); // 与⽤户输⼊⽆关的更新withInpute(); // 与⽤户输⼊有关的更新}return 0;}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

c语言飞机大战源代码

c语言飞机大战源代码

#include<stdio.h>#include<conio.h>#include<stdlib.h>#include<time.h>#define N 35void print(int [][N]);//输出void movebul(int [][N]);//子弹移动void movepla(int [][N]);//敌机移动void setting();//设置void menu();//菜单int scr[22][N]={0},pl=9,width=24,speed=3,density=30,score=0,death=0;//界面,位置,宽度,速度,密度,分数,死亡main(){menu();int i=0,j=0,c;scr[21][pl]=1;scr[0][5]=3;while(1) //控制阶段(开始){if(kbhit())switch(getch()){case 'a':case 'A': if(pl>0) scr[21][pl]=0,scr[21][--pl]=1;break;case 'd':case 'D': if(pl<width-2)scr[21][pl]=0,scr[21][++pl]=1;break;case 'w':case 'W': s cr[20][pl]=2;break;case 27: setting();break;} //控制阶段(结束)if(++j%density==0){j=0;srand(time(NULL));c=rand()%width;scr[][c]=3;}if(++i%speed==0)movepla(scr);movebul(scr);print(scr);if(i==30000)i=0;}return 0;}void menu()//菜单{printf("A,D控制方向,W发射子弹\n设置Esc\n按任意键开始\nby:Lzh");if (getch()==27)setting();}void print(int a[][N])//输出{system("cls");int i,j;for (i=0;i<22;i++){a[i][width-1]=4;for (j=0;j<width;j++){if(a[i][j]==0)printf("");if(a[i][j]==1)printf("\5");if(a[i][j]==2)printf(".");if(a[i][j]==3)printf("\3");if(a[i][j]==4)printf("|");if(i==0&&j==width-1)printf("得分:%d",score);if(i==1&&j==width-1)printf("死亡:%d",death);if(i==2&&j==width-1)printf("设置:Esc");if(i==3&&j==width-1)printf("机智的我编的__LZH");}printf("\n");}}void movebul(int a[][N]) //子弹{int i,j;for (i=0;i<22;i++)for (j=0;j<width-1;j++){if (i==0&&a[i][j]==2)a[i][j]=0;if (a[i][j]==2){if(a[i-1][j]==3)score+=10,printf("\7");a[i][j]=0,a[i-1][j]=2;}}}void movepla(int a[][N]) //敌机{int i,j;for (i=21;i>=0;i--)for (j=0;j<width;j++){if(i==21&&a[i][j]==3)a[i][j]=0;if(a[i][j]==3)a[i][j]=0,a[i+1][j]=3;}if(a[20][pl]==3&&a[21][pl]==1)death++; }void setting() //设置{}.。

飞机大战(完整代码)

飞机大战(完整代码)

飞机大战(完整代码)package com.cetc.shoot;/** 敌机: 是飞行物,也是敌人 */public class Airplane extends FlyingObject implements Enemy {private int speed = 2; //走步的步数/** 构造方法 */public Airplane(){image = ShootGame.airplane; //图片width = image.getWidth(); //宽height = image.getHeight(); //高x = (int) (Math.random()*(ShootGame.WIDTH-this.width));// x=100;// y=100;}/** 重写getScore() */public int getScore(){return 5;}/** 重写step() */public void step(){y+=speed; //y加(向下)}/** 重写outOfBounds() */public boolean outOfBounds(){return this.y>=ShootGame.HEIGHT; //敌机的y>=屏幕的高,即为越界}}Award类的完整代码如下所示:package com.cetc.shoot;public interface Award {public int DOUBLE_FIRE = 0; //火力public int LIFE = 1; //命/** 获取奖励类型 0为火力 1为命 */public int getType();}Bee类的完整代码如下所示:package com.cetc.shoot;import java.util.Random;/** 小蜜蜂: 是飞行物,也是奖励 */public class Bee extends FlyingObject implements Award {private int xSpeed = 1; //x坐标走步步数private int ySpeed = 2; //y坐标走步步数private int awardType; //奖励类型/** 构造方法 */public Bee(){image = ShootGame.bee; //图片width = image.getWidth(); //宽height = image.getHeight(); //高y = -height; //y:负的蜜蜂的高Random rand = new Random(); //创建随机数对象x = rand.nextInt(ShootGame.WIDTH-this.width); //x:0到(屏幕宽-蜜蜂宽)之内的随机数 awardType = rand.nextInt(2); //奖励类型为0到1之间的随机数// x=100;// y=200;}/** 重写getType() */public int getType(){return awardType;}/** 重写step() */public void step(){x+=xSpeed; //x加(向左或向右)y+=ySpeed; //y加(向下)if(x>=ShootGame.WIDTH-this.width){ //x>=(屏幕宽-蜜蜂宽)时,x减(向左)xSpeed = -1;}if(x<=0){ //x<=0时,x加(向右)xSpeed = 1;}}/** 重写outOfBounds() */public boolean outOfBounds(){return this.y>=ShootGame.HEIGHT; //蜜蜂的y>=屏幕的高,即为越界 }}Bullet类的完整代码如下所示:package com.cetc.shoot;/** 子弹: 是飞行物 */public class Bullet extends FlyingObject {private int speed = 3; //走步步数/** 构造方法 x:子弹的x坐标 y:子弹的y坐标*/public Bullet(int x,int y){image = ShootGame.bullet; //图片this.x = x; //x坐标:与英雄机有关this.y = y; //y坐标:与英雄机有关}/** 重写step() */public void step(){y-=speed; //y减(向上)}/** 重写outOfBounds() */public boolean outOfBounds(){return this.y<=-this.height; //子弹的y<=负的子弹的高,即为越界 }}Enemy类的完整代码如下所示:package com.cetc.shoot;/*** 敌人 ,可以有分数**/public interface Enemy {/*** 敌人的分数*/public int getScore();}FlyingObject类的完整代码如下所示:package com.cetc.shoot;import java.awt.image.BufferedImage;public abstract class FlyingObject {protected int x; //x坐标protected int y; //y坐标protected int width; //宽protected int height; //高protected BufferedImage image; //图片public int getX() {return x;}public void setX(int x) {this.x = x;}public int getY() {return y;}public void setY(int y) {this.y = y;}public int getWidth() {return width;}public void setWidth(int width) {this.width = width;}public int getHeight() {return height;public void setHeight(int height) {this.height = height;}public BufferedImage getImage() {return image;}public void setImage(BufferedImage image) {this.image = image;}/** 飞行物走一步 */public abstract void step();/*** 检查当前飞行物体是否被子弹(x,y)击(shoot)中,* @param bullet 子弹对象* @return true表示击中*/public boolean shootBy(Bullet bullet) {int x = bullet.x;int y = bullet.y;return this.x<x && x<this.x+width&&this.y<y && y<this.y+height;}/** 检查飞行物是否出界 */public abstract boolean outOfBounds();}Hero类的完整代码如下所示:```csharppackage com.cetc.shoot;import java.awt.image.BufferedImage;/** 英雄机: 是飞行物 */public class Hero extends FlyingObject {private int life; //命private int doubleFire; //火力值private BufferedImage[] images = {}; //图片切换数组private int index = 0; //协助图片切换/** 构造方法 */public Hero(){image = ShootGame.hero0; //图片width = image.getWidth(); //宽height = image.getHeight(); //高x = 150; //x坐标:固定的值y = 400; //y坐标:固定的值life = 3; //命数为3doubleFire = 0; //火力值为0(单倍火力)images = new BufferedImage[]{ShootGame.hero0,ShootGame.hero1}; //两张图片切换}/** 重写step() */public void step() {if(images.length>0) {image = images[index++/10%images.length];}}/** 英雄机发射子弹 */public Bullet[] shoot(){int xStep = this.width/4; //1/4英雄机的宽int yStep = 20; //固定的值if(doubleFire>0){ //双倍Bullet[] bs = new Bullet[2]; //两发子弹bs[0] = new Bullet(this.x+1*xStep,this.y-yStep); //x:英雄机的x+1/4英雄机的宽 y:英雄机的y-20 bs[1] = new Bullet(this.x+3*xStep,this.y-yStep); //x:英雄机的x+3/4英雄机的宽 y:英雄机的y-20 doubleFire-=2; //发射一次双倍火力时,火力值减2return bs;}else{ //单倍Bullet[] bs = new Bullet[1]; //一发子弹bs[0] = new Bullet(this.x+2*xStep,this.y-yStep); //x:英雄机的x+2/4英雄机的宽 y:英雄机的y-20 return bs;}}/** 英雄机随着鼠标移动 x:鼠标的x坐标 y:鼠标的y坐标*/public void moveTo(int x,int y){this.x = x - this.width/2; //英雄机的x:鼠标的x-1/2英雄机的宽this.y = y - this.height/2; //英雄机的y:鼠标的y-1/2英雄机的高/** 英雄机增火力 */public void addDoubleFire(){doubleFire+=40; //火力值增40}/** 增命 */public void addLife(){life++; //命数增1}/** 获取命 */public int getLife(){return life; //返回命数}/** 减命 */public void subtractLife(){life--;}public void setDoubleFire(int doubleFire) {this.doubleFire = doubleFire;}/** 重写outOfBounds() */public boolean outOfBounds(){return false; //永不越界}/** 检测英雄机与敌人的碰撞 this:英雄机 other:敌人 */public boolean hit(FlyingObject other){int x1 = other.x-this.width/2; //x1:敌人的x-1/2英雄机的宽int x2 = other.x+other.width+this.width/2; //x2:敌人的x+敌人的宽+1/2英雄机的宽 int y1 = other.y-this.height/2; //y1:敌人的y-1/2英雄机的高int y2 = other.y+other.height+this.height/2; //y2:敌人的y+敌人的高+1/2英雄机的高 int x = this.x+this.width/2; //x:英雄机的x+1/2英雄机的宽int y = this.y+this.height/2; //y:英雄机的y+1/2英雄机的高return x>x1 && x<x2&&y>y1 && y<y2; //x在x1和x2之间,并且,y在y1和y2之间,即为撞上了}}ShootGame类的完整代码如下所示:package com.cetc.shoot;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.awt.image.BufferedImage;import java.util.Arrays;import java.util.Random;import java.util.Timer;import java.util.TimerTask;import javax.imageio.ImageIO;import javax.swing.JFrame;import javax.swing.JPanel;//主程序类public class ShootGame extends JPanel{public static final int WIDTH = 400; //窗口宽public static final int HEIGHT = 654; //窗口高public static BufferedImage background; //背景图public static BufferedImage start; //启动图public static BufferedImage pause; //暂停图public static BufferedImage gameover; //游戏结束图public static BufferedImage airplane; //敌机public static BufferedImage bee; //小蜜蜂public static BufferedImage bullet; //子弹public static BufferedImage hero0; //英雄机0public static BufferedImage hero1; //英雄机1private Hero hero = new Hero(); //英雄机对象private FlyingObject[] flyings = {}; //敌人(敌机+小蜜蜂)数组private Bullet[] bullets = {}; //子弹数组private Timer timer; //定时器private int intervel = 1000/100; //时间间隔(毫秒)private int score = 0; //玩家的得分private int state;public static final int START = 0; //启动状态public static final int RUNNING = 1; //运行状态public static final int PAUSE = 2; //暂停状态public static final int GAME_OVER = 3; //游戏结束状态public ShootGame(){// flyings = new FlyingObject[2];// flyings[0] = new Airplane();// flyings[1] = new Bee();// bullets = new Bullet[1];// bullets[0] = new Bullet(150,180);}static{ //加载图片try{background = ImageIO.read(ShootGame.class.getResource('background.png'));start = ImageIO.read(ShootGame.class.getResource('start.png'));pause = ImageIO.read(ShootGame.class.getResource('pause.png'));gameover = ImageIO.read(ShootGame.class.getResource('gameover.png'));airplane = ImageIO.read(ShootGame.class.getResource('airplane.png'));bee = ImageIO.read(ShootGame.class.getResource('bee.png'));bullet = ImageIO.read(ShootGame.class.getResource('bullet.png'));hero0 = ImageIO.read(ShootGame.class.getResource('hero0.png'));hero1 = ImageIO.read(ShootGame.class.getResource('hero1.png'));}catch(Exception e){e.printStackTrace();}}/** 重写paint() g:画笔*/public void paint(Graphics g){g.drawImage(background,0,0,null); //画背景图paintHero(g); //画英雄机paintFlyingObjects(g); //画敌人(敌机+小蜜蜂)paintBullets(g); //画子弹paintScore(g); //画分数paintState(g); //画状态}/** 画英雄机对象 */public void paintHero(Graphics g){g.drawImage(hero.image,hero.x,hero.y,null); //画对象}/** 画敌人(敌机+小蜜蜂)对象 */public void paintFlyingObjects(Graphics g){for(int i=0;i<flyings.length;i++){ //遍历敌人(敌机+小蜜蜂)数组FlyingObject f = flyings[i]; //获取每一个敌人g.drawImage(f.image,f.x,f.y,null); //画敌人对象}}/** 画子弹对象 */public void paintBullets(Graphics g){for(int i=0;i<bullets.length;i++){ //遍历子弹数组Bullet b = bullets[i]; //获取每一个子弹g.drawImage(b.image,b.x,b.y,null); //画子弹对象}}public static void main(String[] args) {JFrame frame = new JFrame('Fly'); //创建一个Jframe对象ShootGame game = new ShootGame(); //创建一个JPanel对象frame.add(game); //将面板添加到框架中frame.setSize(WIDTH, HEIGHT); //设置窗口大小frame.setAlwaysOnTop(true); //设置总是在最上面frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设置默认关闭操作(窗口关闭时退出程序) frame.setLocationRelativeTo(null); //设置居中显示frame.setVisible(true); //1.设置窗口可见 2.尽快调用paint()game.action(); //启动执行}/** 随机生成飞行物 */public FlyingObject nextOne(){Random rand = new Random(); //创建随机数对象int type = rand.nextInt(20); //生成0到19之间的随机数if(type==0){ //为0时返回蜜蜂对象return new Bee();}else{ //为1到19时返回敌机对象return new Airplane();}}int flyEnteredIndex = 0; //敌人入场计数/** 敌人(敌机+小蜜蜂)入场 */public void enterAction(){ //10毫秒走一次flyEnteredIndex++; //每10毫秒增1if(flyEnteredIndex%40==0){ //400(10*40)毫秒走一次FlyingObject obj = nextOne(); //获取敌人(敌机+小蜜蜂)对象flyings = Arrays.copyOf(flyings,flyings.length+1); //扩容(扩大一个容量) flyings[flyings.length-1] = obj; //将敌人对象赋值给数组的最后一个元素}}/** 飞行物走一步 */public void stepAction(){ //10毫秒走一次hero.step(); //英雄机走一步for(int i=0;i<flyings.length;i++){ //遍历所有敌人flyings[i].step(); //每个敌人走一步}for(int i=0;i<bullets.length;i++){ //遍历所有子弹bullets[i].step(); //每个子弹走一步}}/** 启动程序的执行 */public void action(){MouseAdapter l = new MouseAdapter(){ //创建侦听器对象/** 鼠标移动事件 */public void mouseMoved(MouseEvent e){if(state==RUNNING){ //运行状态时执行int x = e.getX(); //获取鼠标的x坐标int y = e.getY(); //获取鼠标的y坐标hero.moveTo(x, y); //英雄机随着鼠标动}}/** 鼠标点击事件 */public void mouseClicked(MouseEvent e){switch(state){ //不同状态时点击后有不同的反应case START: //启动状态时state = RUNNING; //当前状态变为运行状态break;case GAME_OVER: //游戏结束状态时score = 0; //清理现场hero = new Hero();flyings = new FlyingObject[0];bullets = new Bullet[0];state = START; //当前状态变为启动状态break;}}/** 鼠标移出事件 */public void mouseExited(MouseEvent e){if(state==RUNNING){ //运行状态时state=PAUSE; //当前状态改为暂停状态}}/** 鼠标移入事件 */public void mouseEntered(MouseEvent e){if(state==PAUSE){ //暂停状态时state=RUNNING; //当前状态改为运行状态}}};this.addMouseListener(l); //处理鼠标操作事件this.addMouseMotionListener(l); //处理鼠标滑动操作timer = new Timer(); //创建定时器对象timer.schedule(new TimerTask(){public void run(){ //10毫秒走一次--定时干的那个事if(state==RUNNING){ //运行状态时执行enterAction(); //敌人(敌机+小蜜蜂)入场stepAction(); //飞行物走一步shootAction(); //英雄机发射子弹--子弹入场bangAction(); //子弹与敌人的碰撞outOfBoundsAction(); //删除越界的飞行物checkGameOverAction(); //检测游戏是否结束}repaint(); //重画,调用paint()}},intervel,intervel);}int shootIndex = 0; //射击计数/** 英雄机发射子弹(子弹入场) */public void shootAction(){ //10毫秒走一次shootIndex++; //每10毫秒增1if(shootIndex%30==0){ //每300(10*30)毫秒走一次Bullet[] bs = hero.shoot(); //获取英雄机发射出来的子弹bullets = Arrays.copyOf(bullets, bullets.length+bs.length); //扩容(bs有几个元素就扩大几个容量)System.arraycopy(bs,0,bullets,bullets.length-bs.length,bs.length); //数组的追加(将bs追加到bullets数组中) }}/** 所有子弹与所有敌人撞 */public void bangAction(){ //10毫秒走一次for(int i=0;i<bullets.length;i++){ //遍历所有子弹Bullet b = bullets[i]; //获取每一个子弹bang(b); //一个子弹与所有敌人撞}}/** 一个子弹与所有敌人撞 */public void bang(Bullet b){int index = -1; //被撞敌人的下标for(int i=0;i<flyings.length;i++){ //遍历所有敌人FlyingObject f = flyings[i]; //获取每一个敌人if(f.shootBy(b)){ //撞上了index = i; //记录被撞敌人的下标break; //其余敌人不再比较}}if(index != -1){ //有撞上的FlyingObject one = flyings[index]; //获取被撞的敌人对象if(one instanceof Enemy){ //若被撞对象是敌人Enemy e = (Enemy)one; //将被撞对象强转为敌人score += e.getScore(); //累加分数}if(one instanceof Award){ //若被撞对象是奖励Award a = (Award)one; //将被撞对象强转为奖励int type = a.getType(); //获取奖励类型switch(type){ //根据type的不同取值获取相应的奖励case Award.DOUBLE_FIRE: //奖励类型为火力时hero.addDoubleFire(); //英雄机增火力break;case Award.LIFE: //奖励类型为命时hero.addLife(); //英雄机增命break;}}//交换被撞敌人对象与数组中的最后一个元素FlyingObject t = flyings[index];flyings[index] = flyings[flyings.length-1];flyings[flyings.length-1] = t;//缩容(去掉最后一个元素,即:被撞敌人对象)flyings = Arrays.copyOf(flyings, flyings.length-1);}}/** 画分数 */public void paintScore(Graphics g){int x = 10;int y = 25;Font font = new Font(Font.SANS_SERIF,Font.BOLD,14);g.setColor(new Color(0x3A3B3B)); //设置颜色(纯红)g.setFont(font); //设置样式(字体:SANS_SERIF,样式:加粗,字号:24)g.drawString('SCORE: '+score,x,y); //画分y+=20;g.drawString('LIFE: '+hero.getLife(),x,y); //画命}/** 删除越界的飞行物 */public void outOfBoundsAction(){int index = 0; //1.不越界敌人数组下标 2.不越界敌人个数FlyingObject[] flyingLives = new FlyingObject[flyings.length]; //不越界敌人数组for(int i=0;i<flyings.length;i++){ //遍历所有敌人FlyingObject f = flyings[i]; //获取每一个敌人if(!f.outOfBounds()){ //不越界flyingLives[index] = f; //将不越界敌人添加到不越界敌人数组中index++; //1.下标增一 2.不越界敌人个数增一}}flyings = Arrays.copyOf(flyingLives, index); //将不越界敌人复制到flyings数组中,index为flyings的新长度index = 0; //1.下标归零 2.不越界个数归零Bullet[] bulletLives = new Bullet[bullets.length]; //不越界子弹数组for(int i=0;i<bullets.length;i++){ //遍历所有子弹Bullet b = bullets[i]; //获取每一个子弹if(!b.outOfBounds()){ //不越界bulletLives[index] = b; //将不越界子弹添加到不越界子弹数组中index++; //1.下标增一 2.不越界子弹个数增一}}bullets = Arrays.copyOf(bulletLives, index); //将不越界敌人复制到bullets数组中,index为bullets的新长度}。

飞机大战c语言代码

飞机大战c语言代码

飞机大战这种游戏较为复杂,无法直接给出完整的C语言源代码。

但是,我可以提供一个简单的基本构架,以便你了解如何利用C语言开始编写一个飞机大战游戏。

若要构建完整游戏,你需要进一步完善该基本结构并添加更多功能。

以下是C语言实现一个简易飞机大战游戏的基本雏形:#include <stdio.h>#include <stdlib.h>#include <conio.h>#include <windows.h>// 常量,用于界定屏幕尺寸#define SCREEN_WIDTH 50#define SCREEN_HEIGHT 20// 玩家结构体typedef struct {int x, y;} Player;// 敌人结构体typedef struct {int x, y;} Enemy;// 子弹结构体typedef struct {int x, y;} Bullet;// 按ASCII码清屏void clearScreen() {system("cls");}// 跳转到指定坐标void gotoxy(int x, int y) {COORD coord;coord.X = x;coord.Y = y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);}// 游戏循环void gameLoop() {Player player;Enemy enemy[10];Bullet bullet;int i;// 初始化游戏player.x = SCREEN_WIDTH / 2;player.y = SCREEN_HEIGHT - 1;// 敌人的初始位置for (i = 0; i < 10; i++) {enemy[i].x = i * 5 + 1;enemy[i].y = 1;}// 游戏主循环while (1) {clearScreen();// 绘制玩家gotoxy(player.x, player.y);printf("^");// 绘制敌人for (i = 0; i < 10; i++) {gotoxy(enemy[i].x, enemy[i].y);printf("V");}// 绘制子弹 (若存在)if (bullet.y >= 0) {gotoxy(bullet.x, bullet.y);printf("|");// 更新子弹位置bullet.y -= 1;// 判断是否击中敌人for (i = 0; i < 10; i++) {if (bullet.x == enemy[i].x && bullet.y == enemy[i].y) { enemy[i].y = -1; // 隐藏已经被击中的敌人}}}// 检测操作if (_kbhit()) {char input = _getch();switch (input) {case 'a': // 往左移动player.x -= 1;break;case 'd': // 往右移动player.x += 1;break;case ' ': // 发射子弹bullet.x = player.x;bullet.y = player.y - 1;break;case 'q': // 退出游戏exit(0);break;}}// 刷新画布Sleep(100);}}int main() {gameLoop();return 0;}这个代码示例使用了C语言(在Windows操作系统下运行),为玩家提供了移动(A,D键)和射击(空格键)功能。

C语言打飞机.发两颗子弹

C语言打飞机.发两颗子弹

打飞机发两颗子弹的代码:#include <iostream>#include <stdio.h>#include <stdlib.h>#include <conio.h>#include <windows.h>#include <time.h> //step 3#define WIDTH 40 /* Step 1 : Width of Box */ #define HEIGHT 20 /* Step 1 : Height of Box */#define BLOCKS 4 /* Step 2 : Number of Block */#define beep() cout << ("\a") /* Step 5 : Define Beep function*/ using namespace std;/* Define Variables */char box[WIDTH+2][HEIGHT+1]; /* Step 1 : Array of Box */char block[BLOCKS][4][4]={ /* Step 2 : 7 types of block */{ { 1,0,0,0 }, { 1,0,0,0 }, { 1,0,0,0 }, { 1,0,0,0 } },{ { 0,1,0,0 }, { 0,1,0,0 }, { 0,1,0,0 }, { 0,1,0,0 } },{ { 0,0,1,0 }, { 0,0,1,0 }, { 0,0,1,0 }, { 0,0,1,0 } },{ { 0,0,0,1 }, { 0,0,0,1 }, { 0,0,0,1 }, { 0,0,0,1 } } };char current_block[4][4]; /* Step 2 : Current block */int blockx, blocky,a=3000; /* Step 2 : Position of block */char current_blocknum; /* Step 3 : No of present block */int dz[HEIGHT]; /* if -1, not selected */int nextblock,bz=0,sc=0,bz2=0,bz3=0; /* Step 3 : Next block number */ int bkx,bky,fdx,fdy,fdx1,fdy1;char c_block[2][2];/* Define Function */void gotoxy(int x, int y) // Step 1 : Move the cursor{COORD Pos = {x-1, y-1}; //COORD is Structure data typeSetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), Pos);}void init_box(void) /* Step 1 : Function of setup initial screen */{int x, y; // x -> width, y -> heightfor(y=0;y<HEIGHT;y++){box[0][y] = 1; /* Set wall of the Box # */box[WIDTH+1][y] = 1; /* Set wall of the Box # */for(x=1;x<=WIDTH;x++)box[x][y] = 0; /* Space in the Box .... */}for(x=0;x<=WIDTH+1;x++)box[x][HEIGHT] = 1; /* Bottom of the Box # */}void draw_box(void) /* Step 1 : Draw screen */{int x,y;gotoxy(1,1); // Move Cursorfor(y=0;y<=HEIGHT-4;y++){if(y!=fdy){for(x=0;x<WIDTH+2;x++){if(current_blocknum != -1 && x >= blockx && x < blockx + 4 && // Step 3y >= blocky && y < blocky + 4 ) // Step 3cout <<("%c", (current_block[x - blockx][y - blocky]) ? '@' : // Step 3(box[x][y]==1) ? '#' : '.' ); // Step 3 elsecout <<("%c", (box[x][y]==1) ? '#' : '.' );/* if box[x][y] is 1 ==> draw #, box[x][y] is 0 ==> draw . */ }}cout <<("\n\r");}}void draw2_box(void) /* Step 1 : Draw screen */{int x,y,x1;x1=0;gotoxy(1,HEIGHT-3); // Move Cursorfor(y=HEIGHT-3;y<=HEIGHT;y++){for(x=0;x<WIDTH+2;x++){if( x >= bkx && x < bkx + 3 && // Step 3y > bky && y < bky + 3)// Step 3cout <<("%c", (c_block[x - bkx][y - bky]) ? '@' : // Step 3(box[x][y]==1) ? '#' : '.' ); // Step 3elsecout <<("%c", (box[x][y]==1) ? '#' : '.' );}cout <<("\n\r");}}void draw3_box(void) /* Step 1 : Draw screen */{int x;if (bz2==0)fdx=bkx+1;if (fdy>0 && bz2==1){gotoxy(1,fdy); // Move Cursorfor(x=0;x<WIDTH+2;x++){if( x == fdx) // Step 3cout <<("%c", '$'); // Step 3elsecout <<("%c", (box[x][fdy]==1) ? '#' : '.' );}//cout << ("\n\r");}}void draw4_box(void) /* Step 1 : Draw screen */{int x;if (bz3==0)fdx1=bkx+1;if (fdy1>0 && bz3==1){gotoxy(1,fdy1); // Move Cursorfor(x=0;x<WIDTH+2;x++){if( x == fdx1) // Step 3cout <<("%c", '$'); // Step 3elsecout <<("%c", (box[x][fdy1]==1) ? '#' : '.' );}//cout << ("\n\r");}}int check_crash(void) /* Step 5: Check crash with box */ {int x,y;for( x = 0; x<4; x++ )for( y = 0; y < 4; y++ )if(current_block[x][y] && box[x+blockx][y+blocky])return 0;//crashreturn 1;//no crash}int check1_crash(void) /* Step 5: Check crash with box */{int x,y;for( x = 0; x<4; x++ )for( y = 0; y < 4; y++ )if(current_block[x][y] && (x+blockx==fdx) && (y+blocky==fdy)&& y==current_blocknum )return 0;//crashreturn 1;//no crash}int check2_crash(void) /* Step 5: Check crash with box */{int x,y;for( x = 0; x<4; x++ )for( y = 0; y < 4; y++ )if(current_block[x][y] && (x+blockx==fdx1) && (y+blocky==fdy1) && y==current_blocknum )return 0;//crashreturn 1;//no crash}void up_1(){int x;if(check1_crash()){if (fdy>0 && bz2==1)fdy--;else{bz2=0;fdy=HEIGHT-3;}}else{for(x=1;x<WIDTH+1;x++)box[x][fdy]=0;bz2=0;fdy=HEIGHT-3;current_blocknum = -1;sc=sc+100;if(bz==0)bz=1;elsebz=0;gotoxy(10,22);cout <<("total=");cout <<("%d",sc);}}void up_2(){int x;if(check2_crash()){if (fdy1>0 && bz3==1)fdy1--;else{bz3=0;fdy1=HEIGHT-3;}}else{for(x=1;x<WIDTH+1;x++)box[x][fdy1]=0;bz3=0;fdy1=HEIGHT-3;current_blocknum = -1;sc=sc+100;if(bz==0)bz=1;elsebz=0;gotoxy(10,22);cout <<("total=");cout <<("%d",sc);}}void rotate(void) /* Step 4 : Rotate block */{if(bz2==1 && bz3==1)return;if (bz2==0 && bz3==0)bz2=1;elseif (bz2==1 && bz3==0)bz3=1;}void init_cblk(){c_block[0][0]=0;c_block[1][0]=0;c_block[2][0]=0;c_block[0][1]=0;c_block[1][1]=1;c_block[2][1]=0;c_block[0][2]=1;c_block[1][2]=1;c_block[2][2]=1;}void down() // Step 3 : Drop block one line{int x,y; // Step 5 : x-> wif(bz==1)blockx++;/* move one */elseblockx--;if(!check_crash()) /* Step 5: Check crash with block placed in bottom and make bottom area */{if (bz==1)bz=0;elsebz=1;for(x=0;x<4;x++)for(y=0;y<4;y++)if(current_block[x][y])box[blockx+x][blocky+y] = 0;box[0][current_blocknum+1]=1;box[WIDTH+1][current_blocknum+1]=1;// Make bottom area(Fix block in the bottom)current_blocknum = -1; // Call Next block}}void left() /* Step 4 : move left */{bkx--;if (bkx<=0)bkx++;}void right() /* Step 4 : Move left */{bkx++;if (bkx>=WIDTH-1) bkx--;}/* Main Function */int main(){int key; // Step 4 : check keyint timer=0; // Step 3system("cls"); //Step 1init_box(); //Step 1 Setup initialize Secreeninit_cblk();current_blocknum = -1; // Step 3 : Present Blocksrand((unsigned int)time(NULL)); // Step 3nextblock = rand() % BLOCKS;bkx=(WIDTH+2)/2;bky=HEIGHT-3;fdy=HEIGHT-3;fdy1=HEIGHT-3;while(1) // Step 3{int x,y ;if(current_blocknum==-1) /* Step 3 : if block is not selsected */{//Step 2current_blocknum = nextblock; // Step 3nextblock = rand() % BLOCKS; // Step 3for(y=0;y<4;y++) //Step 2 Set the current blockfor(x=0;x<4;x++)current_block[x][y] = block[current_blocknum][x][y]; // Step 3if (bz==1)blockx = 1; //Step 2 set the starting position of block elseblockx=(WIDTH-2);blocky = 1; //Step 2}timer++; // Step 3if( timer >= a){ /* // Step 3 : if timer >= 100, down block one line */draw_box(); //Step 1 Draw screendraw2_box();draw3_box();draw4_box();timer = 0;down();if (bz2==1)up_1();if (bz3==1)up_2();continue;}if(kbhit()) /* Check key, if key is pressed, return true */{key = getch();switch(key){case 224:continue;case 72: // Up keyif(bz2==0 || bz3==0)rotate();break;case 75: /* Left Key */left();break;case 77: /* Right Key */right();break;case 80: /* increase speed Key */a-=50;if(a<=50) a=50;break;case 27: /* Esc.. End of Game */return 0;}}}}。

飞机大战c语言

飞机大战c语言

飞机大战c语言
飞机大战是一款老少皆宜的经典游戏,游戏中玩家以及敌机以及子弹均由c语言实现。

本文通过介绍飞机大战的游戏历史、游戏逻辑以及c语言的使用方法,来探索使用c语言实现飞机大战的细节。

首先,关于飞机大战游戏的历史,经典的游戏是由1972由Namco 公司开发的“铁路大亨”而脱颖而出。

经过数十年的发展,飞机大战游戏以一种极具耐玩性的游戏模式变得越来越流行。

在游戏中,玩家需要控制飞机来在2D的游戏场景中运用机动技巧来攻击敌机,当玩家的飞机击中敌机,敌机就会被摧毁并爆炸,而游戏的胜利也就自然而然的所得了。

其次,游戏的逻辑如何使用c语言来实现呢?一般而言,游戏的逻辑部分可以用c语言函数struct结构来定义,可以定义飞机的坐标,飞机的速度,敌机的坐标,敌机的速度,以及子弹的坐标和速度等数据。

接着,就可以使用if-else结构和switch结构来实现判断,以及循环结构来实现循环的逻辑。

最后,游戏的画面部分可以通过c语言的函数,来在窗口上实现绘制飞机、敌机以及子弹的图像。

c语言的常用函数有setfillchar() bar3d(),这两个函数可以实现图形化绘制棋子,以及其他游戏元素。

总之,经过介绍,我们知道,可以通过c语言的函数struct结构和if-else结构,以及setfillchar() bar3d()数,来实现飞机大战游戏的历史、游戏逻辑以及游戏画面。

了解了这些知识,将会帮助热爱游戏的编程爱好者们更好的编写游戏,满足自己的游戏需求,以
获得满足感。

VC++电脑游戏飞机大战的开发与设计(含源文件)

VC++电脑游戏飞机大战的开发与设计(含源文件)

毕业设计(论文)题目:飞机大战游戏的设计与开发学院:计算机科学学院摘要飞机游戏是一款风靡全球的电视机游戏和掌上游戏机产品,曾几何时,它创造了一个无法企及的游戏巅峰,也曾影响了一代产业链。

虽然它辉煌的业绩在历史的涡轮中渐渐远去,但这款游戏每每提及,总会令人爱不释手,魂牵梦绕。

这款游戏的名字叫做飞机大战,它是运行于Windows操作系统下的一款2D 游戏,以C/C++为开发语言,构建于Microsoft Foundation Class Library(MFC)框架体系中,其中调用了部分的Win32API函数接口,在Visual Studio2010环境下开发的一款多媒体游戏。

随着硬件性能的不断提高,游戏的日益普及,使开发者不再需要过多的关注不同的硬件设备。

本论文着眼于双缓冲绘图的运用,开发出仅用于理论研究的二维平面射击类游戏。

本文首先分析了电脑游戏的发展历史,然后分析了制作游戏的基本流程和游戏本身所要包含的几种元素以及游戏应具备的游戏层次。

根据2D游戏的特点和游戏的角色,以及给用户呈现的游戏界面的特效,对2D图形技术,Windows 图形界面编程技术GDI,DirectDraw的显卡接口和DirectSound声卡接口以及MVC 设计模式下的MFC框架等技术进行了比较仔细的研究。

通过自定义一个游戏类CGame,封装了游戏元素的基本属性和行为,这样便于在用到游戏的行为操作是,只要轻松的产生CGame对象便可直接调用其方法,也有利于升级为双人游戏,乃至网络版时,只需要在该类中添加相应的行为便可。

当我们向用户呈现游戏运行的界面时,通过Timer时钟控件,映射到相应的处理函数,使得游戏界面大约每2秒钟刷新一下界面,这样才能让一张位图背景图片具有动态效果。

当使用DirectSound声卡接口时,我方和敌方相互射击所发出的声音,都是在时钟映射函数调用时处理的。

【关键词:】C/C++; VS 2010/MFC; 飞机大战游戏IABSTRACTAirplane game is a popular global TV game and handheld game products,once upon a time, it creates a game out of reach peak, have influenceda generation of industrial chain. Although it brilliant performance in the history of turbine faded away, but the game is often mentioned always miss.The game's name is , it is running on Windows operating systems,a 2 d game, with C/C + + as development language, building on the Microsoft Foundation Class Library MFC framework, which invokes the part Win32API function interface, in the Visual Studio 2010 environment using DirectX software development kit SDK to develop a multimedia game.With the constant improvement of the hardware performance, the rising popularity of the game, DirectX development kit update and perfect, make developers don't need too much attention to different hardware devices. The use of this thesis focus on DirectSound, DirectDraw, developed only due to the theoretical research of two-dimensional plane shooting game.This article first analyzes the development history of computer games, and then analyze the basic process of making game and the game itself need to include what kind of elements and the game should have level. According to the characteristics of the 2 d game and game role, and to the user interface rendering effects, the technology of 2 d graphics,the graphics interface and DirectSound DirectDraw sound card interface and MFC framework of MVC design mode to compare the careful research. Through a custom game CGame class, encapsulates the basic attribute of game elements and behavior, so easy to use in the game operation, as long as easy to produce the CGame object can be directly to call its methods, but also to when upgraded to a double game, online version,just need to add the proper behavior in the class. When we present game operation interface to the user, by the Timer clock control that is mappedto the corresponding processing function, makes the game about every 2 seconds refresh interface, in this way can we make a bitmap background picture with dynamic effect. When using DirectSound sound card interface,we and the noise made by enemy fire, are on the clock whenprocessing the mapping function call.KEY WORDS: C/C + +; VS 2010/MFC; plane war game目录第1章绪论 (1)1.1 系统研究的背景及意义 (1)1.2 国内外的发展现状 (1)1.4 本文的组织结构 (2)1.5 本章小结 (2)第2章游戏的相关知识和系统开发平台的阐述 (3)2.1游戏基本流程概述 (3)2.2游戏系统元素阐述 (4)2.3开发环境和相关技术的概述 (5)2.3.1 开发环境 (5)2.3.2 相关技术 (5)2.4本章小结 (10)第3章游戏分析 (11)3.1 用户功能需求分析 (11)3.2 系统性能要求 (12)3.3可行性分析 (12)3.4本章小结 (13)第4章游戏设计 (14)4.1游戏整体设计 (14)4.1.1 整体结构 (14)4.1.2 游戏对战规则 (14)4.2游戏界面设计 (15)4.2.1游戏起始界面设计 (15)4.2.2游戏运行界面设计 (17)4.2.3游戏结束界面设计 (18)4.3游戏功能设计 (19)4.3.1双缓冲绘图 (19)4.3.2功能实现 (19)4.4本章小结 (26)第5章系统测试 (27)5.1软件测试基础理论 (27)5.1.1 软件测试定义 (27)5.1.2 软件测试基本概念 (27)5.2软件测试目的 (27)5.3软件测试方法分类 (28)5.3.1 静态测试与动态测试 (28)5.3.2 黑盒白盒与白盒测试 (28)5.3.3 单元测试、集成测试、系统测试、验证测试和确认测试 (29)5.4论坛测试 (29)5.4.1 测试用例设计要求 (29)5.5测试用例 (30)5.6测试结果 (30)5.6本章小结 (31)第6章工作总结 (32)致谢 (33)参考文献 (34)附录1 (35)。

飞机大战游戏C++编写的程序

飞机大战游戏C++编写的程序

// mytestView.cpp : CmytestView 类的实现//#include"stdafx.h"#include"mytest.h"#include"mytestDoc.h"#include"mytestView.h"#ifdef _DEBUG#define new DEBUG_NEW#endif// CmytestViewIMPLEMENT_DYNCREATE(CmytestView, CView)BEGIN_MESSAGE_MAP(CmytestView, CView)ON_WM_CREATE()ON_WM_TIMER()ON_WM_KEYDOWN()END_MESSAGE_MAP()// CmytestView 构造/析构CmytestView::CmytestView(){// TODO: 在此处添加构造代码m_x_me=0;m_x_enemy=0;m_y_enemyone=0;m_y_enemytwo=0;m_y_bomb=0;m_x_bomb=0;m_x_ball=0;m_y_ball=0;m_x_explsion=0;}CmytestView::~CmytestView(){}BOOL CmytestView::PreCreateWindow(CREATESTRUCT& cs) {// TODO: 在此处通过修改// CREATESTRUCT cs 来修改窗口类或样式return CView::PreCreateWindow(cs);}// CmytestView 绘制void CmytestView::OnDraw(CDC* pDC){CmytestDoc* pDoc = GetDocument();ASSERT_VALID(pDoc);if (!pDoc)return;// TODO: 在此处为本机数据添加绘制代码/*CBitmap bitmap;bitmap.LoadBitmapW(IDB_ME);*///画图/*pDC->BitBlt(100,50,50,60,&MemDC,0,0,SRCCOPY);*//*POINT pt;pt.x=200;pt.y=200;CImageList imageList;imageList.Create(50,60,ILC_COLOR24|ILC_MASK,1,0);imageList.Add(&bitmap,RGB(0,0,0));imageList.Draw(pDC,0,pt,ILD_TRANSPARENT);CDC MemDC;MemDC.CreateCompatibleDC(NULL);MemDC.SelectObject(&bitmap);*///RECT rc;//GetClientRect(&rc);//CBrush brush;//brush.CreateSolidBrush(RGB(3,108,254));//pDC->SelectObject(&brush);//CBrush *oldbrush=pDC->SelectObject(&brush);//pDC->Rectangle(&rc);//pDC->SelectObject(oldbrush);//CBitmap bitmap;//bitmap.LoadBitmapW(IDB_ME);//POINT pt;//pt.x=200;//pt.y=200;//CImageList imageList;//imageList.Create(60,50,ILC_COLOR24|ILC_MASK,1,0);//imageList.Add(&bitmap,RGB(0,0,0));//imageList.Draw(pDC,0,pt,ILD_TRANSPARENT);// CDC MemDC;//MemDC.CreateCompatibleDC(NULL);//MemDC.SelectObject(&bitmap);//刷新RECT rc;GetClientRect(&rc);CBrush brush;brush.CreateSolidBrush(RGB(3,108,254));pDC->SelectObject(&brush);CBrush *oldbrush=pDC->SelectObject(&brush);pDC->Rectangle(&rc);pDC->SelectObject(oldbrush);//敌机CBitmap bitmap1;bitmap1.LoadBitmapW(IDB_enemy);POINT pt1;pt1.x=200;pt1.y=m_y_enemyone;POINT pt1_2;pt1_2.x=300;pt1_2.y=m_y_enemytwo;CImageList imageList1;imageList1.Create(35,35,ILC_COLOR24|ILC_MASK,1,0);imageList1.Add(&bitmap1,RGB(0,0,0));imageList1.Draw(pDC,0,pt1,ILD_TRANSPARENT);imageList1.Draw(pDC,1,pt1_2,ILD_TRANSPARENT);//战机CBitmap bitmap2;bitmap2.LoadBitmapW(IDB_ME);POINT pt2;pt2.x=m_x_me;pt2.y=100;CImageList imageList2;imageList2.Create(50,60,ILC_COLOR24|ILC_MASK,1,0);imageList2.Add(&bitmap2,RGB(0,0,0));imageList2.Draw(pDC,0,pt2,ILD_TRANSPARENT);//子弹CBitmap bitmap3;bitmap3.LoadBitmapW(IDB_ball);POINT pt3;pt3.x=150;pt3.y=m_y_ball;CImageList imageList3;imageList3.Create(8,8,ILC_COLOR24|ILC_MASK,1,0);imageList3.Add(&bitmap3,RGB(0,0,0));imageList3.Draw(pDC,0,pt3,ILD_TRANSPARENT);//炸弹CBitmap bitmap4;bitmap4.LoadBitmapW(IDB_bomb);POINT pt4;pt4.x=m_x_bomb;pt4.y=250;CImageList imageList4;imageList4.Create(10,20,ILC_COLOR24|ILC_MASK,1,0);imageList4.Add(&bitmap4,RGB(0,0,0));imageList4.Draw(pDC,0,pt4,ILD_TRANSPARENT);//爆炸CBitmap bitmap5;bitmap5.LoadBitmapW(IDB_explsion);POINT pt5_1;pt5_1.x=310;pt5_1.y=310;POINT pt5_2;pt5_2.x=330;pt5_2.y=330;POINT pt5_3;pt5_3.x=350;pt5_3.y=450;POINT pt5_4;pt5_4.x=470;pt5_4.y=470;POINT pt5_5;pt5_5.x=510;pt5_5.y=510;POINT pt5_6;pt5_6.x=530;pt5_6.y=530;POINT pt5_7;pt5_7.x=540;pt5_7.y=540;POINT pt5_8;pt5_8.x=450;pt5_8.y=250;CImageList imageList5;imageList5.Create(66,66,ILC_COLOR24|ILC_MASK,1,0);imageList5.Add(&bitmap5,RGB(0,0,0));imageList5.Draw(pDC,0,pt5_1,ILD_TRANSPARENT);imageList5.Draw(pDC,1,pt5_2,ILD_TRANSPARENT);imageList5.Draw(pDC,2,pt5_3,ILD_TRANSPARENT);imageList5.Draw(pDC,3,pt5_4,ILD_TRANSPARENT);imageList5.Draw(pDC,4,pt5_5,ILD_TRANSPARENT);imageList5.Draw(pDC,5,pt5_6,ILD_TRANSPARENT);imageList5.Draw(pDC,6,pt5_7,ILD_TRANSPARENT);imageList5.Draw(pDC,7,pt5_8,ILD_TRANSPARENT);/*CDC MemDC;MemDC.CreateCompatibleDC(NULL);MemDC.SelectObject(&bitmap2);*/}// CmytestView 诊断#ifdef _DEBUGvoid CmytestView::AssertValid() const{CView::AssertValid();}void CmytestView::Dump(CDumpContext& dc) const{CView::Dump(dc);}CmytestDoc* CmytestView::GetDocument() const// 非调试版本是内联的{ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CmytestDoc)));return (CmytestDoc*)m_pDocument;}#endif//_DEBUG// CmytestView 消息处理程序int CmytestView::OnCreate(LPCREATESTRUCT lpCreateStruct){if (CView::OnCreate(lpCreateStruct) == -1)return -1;// TODO: 在此添加您专用的创建代码SetTimer(1,30,NULL);return 0;}void CmytestView::OnTimer(UINT_PTR nIDEvent){// TODO: 在此添加消息处理程序代码和/或调用默认值CView::OnTimer(nIDEvent);CDC *pDC=GetDC();//刷新背景RECT rc;GetClientRect(&rc);CBrush brush;brush.CreateSolidBrush(RGB(3,108,254));pDC->SelectObject(&brush);CBrush *oldbrush=pDC->SelectObject(&brush);pDC->Rectangle(&rc);pDC->SelectObject(oldbrush);//战机CBitmap bitmap2;bitmap2.LoadBitmapW(IDB_ME);POINT pt2;pt2.x=m_x_me;pt2.y=100;CImageList imageList2;imageList2.Create(50,60,ILC_COLOR24|ILC_MASK,1,0);imageList2.Add(&bitmap2,RGB(0,0,0));imageList2.Draw(pDC,0,pt2,ILD_TRANSPARENT);//子弹CBitmap bitmap3;bitmap3.LoadBitmapW(IDB_ball);POINT pt3;pt3.x=150;pt3.y=m_y_ball;CImageList imageList3;imageList3.Create(8,8,ILC_COLOR24|ILC_MASK,1,0);imageList3.Add(&bitmap3,RGB(0,0,0));imageList3.Draw(pDC,0,pt3,ILD_TRANSPARENT);//炸弹CBitmap bitmap4;bitmap4.LoadBitmapW(IDB_bomb);POINT pt4;pt4.x=m_x_bomb;pt4.y=m_y_bomb;CImageList imageList4;imageList4.Create(10,20,ILC_COLOR24|ILC_MASK,1,0);imageList4.Add(&bitmap4,RGB(0,0,0));imageList4.Draw(pDC,0,pt4,ILD_TRANSPARENT);//敌机CBitmap bitmap1;bitmap1.LoadBitmapW(IDB_enemy);POINT pt1;pt1.x=200;pt1.y=m_y_enemyone;POINT pt1_2;pt1_2.x=300;pt1_2.y=m_y_enemytwo;CImageList imageList1;imageList1.Create(35,35,ILC_COLOR24|ILC_MASK,1,0);imageList1.Add(&bitmap1,RGB(0,0,0));imageList1.Draw(pDC,0,pt1,ILD_TRANSPARENT);imageList1.Draw(pDC,1,pt1_2,ILD_TRANSPARENT);//爆炸CBitmap bitmap5;bitmap5.LoadBitmapW(IDB_explsion);POINT pt5_1;pt5_1.x=310;pt5_1.y=310;POINT pt5_2;pt5_2.x=330;pt5_2.y=330;POINT pt5_3;pt5_3.x=350;pt5_3.y=450;POINT pt5_4;pt5_4.x=470;pt5_4.y=470;POINT pt5_5;pt5_5.x=510;pt5_5.y=510;POINT pt5_6;pt5_6.x=530;pt5_6.y=530;POINT pt5_7;pt5_7.x=540;pt5_7.y=540;POINT pt5_8;pt5_8.x=450;pt5_8.y=250;CImageList imageList5;imageList5.Create(66,66,ILC_COLOR24|ILC_MASK,1,0);imageList5.Add(&bitmap5,RGB(0,0,0));imageList5.Draw(pDC,0,pt5_1,ILD_TRANSPARENT);imageList5.Draw(pDC,1,pt5_2,ILD_TRANSPARENT);imageList5.Draw(pDC,2,pt5_3,ILD_TRANSPARENT);imageList5.Draw(pDC,3,pt5_4,ILD_TRANSPARENT);imageList5.Draw(pDC,4,pt5_5,ILD_TRANSPARENT);imageList5.Draw(pDC,5,pt5_6,ILD_TRANSPARENT);imageList5.Draw(pDC,6,pt5_7,ILD_TRANSPARENT);imageList5.Draw(pDC,7,pt5_8,ILD_TRANSPARENT);//敌机自动飞m_y_enemyone --;m_y_enemytwo ++;//炸弹自己飞的条件if(m_y_bomb>0){m_y_bomb ++;}//子弹自己飞m_y_ball++;//爆炸效果for(i=0;i<=7;i++){}void CmytestView::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) {// TODO: 在此添加消息处理程序代码和/或调用默认值CView::OnKeyDown(nChar, nRepCnt, nFlags);if (nChar==VK_RIGHT){m_x_me ++;if(nChar!=VK_UP)m_x_bomb ++;}if (nChar==VK_LEFT){m_x_me --;if(nChar!=VK_UP)m_x_bomb --;}if(nChar==VK_UP)m_y_bomb ++;}。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

#include<iostream>#include<windows.h>#include<conio.h>#include<time.h>#include<string>using namespace std;/*=============== all the structures ===============*/typedef struct Frame{COORD position[2];int flag;}Frame;/*=============== all the functions ===============*/void SetPos(COORD a)// set cursor{HANDLE out=GetStdHandle(STD_OUTPUT_HANDLE);SetConsoleCursorPosition(out, a);}void SetPos(int i, int j)// set cursor{COORD pos={i, j};SetPos(pos);}void HideCursor(){CONSOLE_CURSOR_INFO cursor_info = {1, 0};SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info); }//把第y行,[x1, x2) 之间的坐标填充为chvoid drawRow(int y, int x1, int x2, char ch){SetPos(x1,y);for(int i = 0; i <= (x2-x1); i++)cout<<ch;}//在a, b 纵坐标相同的前提下,把坐标[a, b] 之间填充为chvoid drawRow(COORD a, COORD b, char ch){if(a.Y == b.Y)drawRow(a.Y, a.X, b.X, ch);else{SetPos(0, 25);cout<<"error code 01:无法填充行,因为两个坐标的纵坐标(x)不相等";system("pause");}}//把第x列,[y1, y2] 之间的坐标填充为chvoid drawCol(int x, int y1, int y2, char ch){int y=y1;while(y!=y2+1){SetPos(x, y);cout<<ch;y++;}}//在a, b 横坐标相同的前提下,把坐标[a, b] 之间填充为chvoid drawCol(COORD a, COORD b, char ch){if(a.X == b.X)drawCol(a.X, a.Y, b.Y, ch);else{SetPos(0, 25);cout<<"error code 02:无法填充列,因为两个坐标的横坐标(y)不相等";system("pause");}}//左上角坐标、右下角坐标、用row填充行、用col填充列void drawFrame(COORD a, COORD b, char row, char col){drawRow(a.Y, a.X+1, b.X-1, row);drawRow(b.Y, a.X+1, b.X-1, row);drawCol(a.X, a.Y+1, b.Y-1, col);drawCol(b.X, a.Y+1, b.Y-1, col);}void drawFrame(int x1, int y1, int x2, int y2, char row, char col){COORD a={x1, y1};COORD b={x2, y2};drawFrame(a, b, row, col);}void drawFrame(Frame frame, char row, char col){COORD a = frame.position[0];COORD b = frame.position[1];drawFrame(a, b, row, col);}void drawPlaying(){drawFrame(0, 0, 48, 24, '=', '|');// draw map frame;drawFrame(49, 0, 79, 4, '-', '|');// draw output framedrawFrame(49, 4, 79, 9, '-', '|');// draw score framedrawFrame(49, 9, 79, 20, '-', '|');// draw operate framedrawFrame(49, 20, 79, 24, '-', '|');// draw other message frame SetPos(52, 6);cout<<"得分:";SetPos(52, 7);cout<<"称号:";SetPos(52,10);cout<<"操作方式:";SetPos(52,12);cout<<" a,s,d,w 控制战机移动。

";SetPos(52,14);cout<<" p 暂停游戏。

";SetPos(52,16);cout<<" e 退出游戏。

";}//在[a, b)之间产生一个随机整数int random(int a, int b){int c=(rand() % (a-b))+ a;return c;}//在两个坐标包括的矩形框内随机产生一个坐标COORD random(COORD a, COORD b){int x=random(a.X, b.X);int y=random(a.Y, b.Y);COORD c={x, y};return c;}bool judgeCoordInFrame(Frame frame, COORD spot) {if(spot.X>=frame.position[0].X)if(spot.X<=frame.position[1].X)if(spot.Y>=frame.position[0].Y)if(spot.Y<=frame.position[0].Y)return true;return false;}void printCoord(COORD a){cout <<"( "<<a.X<<" , "<<a.Y<<" )";}void printFrameCoord(Frame a){printCoord(a.position[0]);cout <<" - ";printCoord(a.position[1]);}int drawMenu(){SetPos(30, 1);cout<<"P l a n e W a r";drawRow(3, 0, 79, '-');drawRow(5, 0, 79, '-');SetPos(28, 4);cout<<"w 和s 选择,k 确定";SetPos(15, 11);cout<<"1. 简单的敌人";SetPos(15, 13);cout<<"2. 冷酷的敌人";drawRow(20, 0, 79, '-');drawRow(22, 0, 79, '-');SetPos(47, 11);cout<<"简单的敌人:";SetPos(51, 13);cout<<"简单敌人有着较慢的移动速度。

";SetPos(24, 21);cout<<"制作:中北大学12060341 梦笔西谈";int j=11;SetPos(12, j);cout<<">>";//drawFrame(45, 9, 79, 17, '=', '|');while(1){ if( _kbhit() ){char x=_getch();switch (x){case 'w' :{if( j == 13){SetPos(12, j);cout<<" ";j = 11;SetPos(12, j);cout<<">>";SetPos(51, 13);cout<<" ";SetPos(47, 11);cout<<"简单的敌人:";SetPos(51, 13);cout<<"简单敌人有着较慢的移动速度。

";}break;}case 's' :{if( j == 11 ){SetPos(12, j);cout<<" ";j = 13;SetPos(12, j);cout<<">>";SetPos(51, 13);cout<<" ";SetPos(47, 11);cout<<"冷酷的敌人:";SetPos(51, 13);cout<<"冷酷的敌人移动速度较快。

";}break;}case 'k' :{if (j == 8) return 1;else return 2;}}}}}/*DWORD WINAPI MusicFun(LPVOID lpParamte){//DWORD OBJ;sndPlaySound(TEXT("bgm.wav"), SND_FILENAME|SND_ASYNC);return 0;}*//*================== the Game Class ==================*/class Game{public:COORD position[10];COORD bullet[10];Frame enemy[8];int score;int rank;int rankf;string title;int flag_rank;Game ();//初始化所有void initPlane();void initBullet();void initEnemy();//初始化其中一个//void initThisBullet( COORD );//void initThisEnemy( Frame );void planeMove(char);void bulletMove();void enemyMove();//填充所有void drawPlane();void drawPlaneToNull();void drawBullet();void drawBulletToNull();void drawEnemy();void drawEnemyToNull();//填充其中一个void drawThisBulletToNull( COORD );void drawThisEnemyToNull( Frame );void Pause();void Playing();void judgePlane();void judgeEnemy();void Shoot();void GameOver();void printScore();};Game::Game(){initPlane();initBullet();initEnemy();score = 0;rank = 25;rankf = 0;flag_rank = 0;}void Game::initPlane(){COORD centren={39, 22};position[0].X=position[5].X=position[7].X=position[9].X=centren.X;position[1].X=centren.X-2;position[2].X=position[6].X=centren.X-1;position[3].X=position[8].X=centren.X+1;position[4].X=centren.X+2;for(int i=0; i<=4; i++)position[i].Y=centren.Y;for(int i=6; i<=8; i++)position[i].Y=centren.Y+1;position[5].Y=centren.Y-1;position[9].Y=centren.Y-2;}void Game::drawPlane(){for(int i=0; i<9; i++){SetPos(position[i]);if(i!=5)cout<<"O";else if(i==5)cout<<"|";}}void Game::drawPlaneToNull(){for(int i=0; i<9; i++){SetPos(position[i]);cout<<" ";}}void Game::initBullet(){for(int i=0; i<10; i++)bullet[i].Y = 30;}void Game::drawBullet(){for(int i=0; i<10; i++){if( bullet[i].Y != 30){SetPos(bullet[i]);cout<<"^";}}}void Game::drawBulletToNull(){for(int i=0; i<10; i++)if( bullet[i].Y != 30 ){COORD pos={bullet[i].X, bullet[i].Y+1};SetPos(pos);cout<<" ";}}void Game::initEnemy(){COORD a={1, 1};COORD b={45, 15};for(int i=0; i<8; i++){enemy[i].position[0] = random(a, b);enemy[i].position[1].X = enemy[i].position[0].X + 3;enemy[i].position[1].Y = enemy[i].position[0].Y + 2;}}void Game::drawEnemy(){for(int i=0; i<8; i++)drawFrame(enemy[i].position[0], enemy[i].position[1], '-', '|'); }void Game::drawEnemyToNull(){for(int i=0; i<8; i++){drawFrame(enemy[i].position[0], enemy[i].position[1], ' ', ' ');}}void Game::Pause(){SetPos(61,2);cout<<" ";SetPos(61,2);cout<<"暂停中...";char c=_getch();while(c!='p')c=_getch();SetPos(61,2);cout<<" ";}void Game::planeMove(char x){if(x == 'a')if(position[1].X != 1)for(int i=0; i<=9; i++)position[i].X -= 2;if(x == 's')if(position[7].Y != 23)for(int i=0; i<=9; i++)position[i].Y += 1;if(x == 'd')if(position[4].X != 47)for(int i=0; i<=9; i++)position[i].X += 2;if(x == 'w')if(position[5].Y != 3)for(int i=0; i<=9; i++)。

相关文档
最新文档