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);}更多有趣的经典⼩游戏实现专题,分享给⼤家:以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

飞机大战源代码

飞机大战源代码
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void run() {
// TODO Auto-generated method stub
break;
}
}
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_D)
{
x=x+7;
}
if(e.getKeyCode()==KeyEvent.VK_A){
x=x-7;
}
if(e.getKeyCode()==KeyEvent.VK_W){
import javax.swing.*;
public class TakGame extends JFrame {
MyPanel mp=null;
public static void main(String[] args) {
// TODO Auto-generated method stub
TakGame tg=new TakGame();
g.drawImage(im, x,y, 60,50, this);
break;
case 1:
Image im1=Toolkit.getDefaultToolkit().
getImage(Panel.class.getResource("/tk.PNG"));

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。

C语言游戏设计——打飞机游戏

C语言游戏设计——打飞机游戏

1: C语言游戏设计1.1:课程设计目标C语言编写一款打飞机游戏,掌握函数的使用和编程的整体思路。

1.2:整体设计思路总体设想:运行游戏时显示游戏的界面,允许用户选择个性化设置,A、D、W分别控制飞机的左右移动和发射子弹,不同的敌机飞行和攻击,并不时伴有奖励。

游行运行时播放音效,同时记录飞机的生命和得分,达到一定的分数进入下一关。

需要构建的函数:位图调用模块、界面输出函数、主菜单函数、设置函数、速度选择函数、游戏控制函数、敌机移动函数、子弹移动函数、boss函数、计时函数。

: 需调用的头文件:include<stdio.h> //常规库头文件include<conio.h> //控制台输入输出流头文件 include<stdlib.h> //系统函数头文件include<time.h> //时间函数头文件include<windows.h> //windows函数库include<mmsystem.h> //导入声音头文件pragma comment(lib,"winmm.lib ")//导入声音头文件库1.4: 游戏过程模拟::显示效果如下图所示:初始设置界面:游戏界面2 算法实现需要了解的知识点:Main函数和menu函数编写比较顺利,在bmp函数中遇到如何显示窗口和调用图片的问题,看了一些例子和网上的资料,逐渐掌握了一下知识点:○1设备上下文:设备,显示器,打印机,数码相机,扫描仪这些类似的设备,上下文,就是上面设备的相关信息,比如屏幕分辨率等○2 HANDLE 通用句柄,实际上是一个指向指针的指针,在Windows操作系统中,内存操作器经常移动对象,来满足各种程序的内存需要,为了解决寻找对象问题,内存管理器开辟出一块专门的内存储存空间,把移动后的地址存储在该空间,这样就可以通过该地址间接寻找到对象。

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语言小飞机源代码在计算机科学领域中,编程语言是一种用于编写计算机程序的形式化语言。

C语言是一种通用编程语言,广泛用于系统编程和应用程序开发。

本文将详细介绍一个小飞机的C语言源代码,并逐步解释代码的每一部分。

首先,让我们从一个基本的C代码框架开始:#include <stdio.h>int main() {在此处编写代码return 0;}上面的代码是一个C语言程序的基本结构。

`#include <stdio.h>`语句引入了标准输入输出库,这使我们能够使用`printf()`函数和`scanf()`函数等来进行输入输出操作。

`int main()`是程序的入口点,它表示程序从这里开始执行。

要实现一个小飞机的源代码,我们可以使用ASCII字符来绘制它的形状。

以下是一个绘制小飞机的C代码:#include <stdio.h>int main() {printf(" __ooooooooo__\n");printf(" oOOOOOOOOOOOOOOOOOOOOo\n");printf(" oOOOOOOOOOOOOOOOOOOOOOOOOOOOo\n");printf(" oOO oOOOOOOOOOOOOOOOOOOOOOOOo\n");printf("oOOOOOo oOOO oOOO OOOOoOOOOOo\n");printf("OOOOOOO oOOO OOOOo OOOOOO\n");printf("OOOOOo oOOOOOo oOOOOOo oOOOOOOOOO\n");printf("oOOOo oOOOOOOOoOOOOOOOoOOOOOOO oOOo\n");printf("oOOO oOOOOOOOOOOOOOOOOOOOOOOOOO OOOo\n");printf(" OOOo OOOOO oOOOOOOOO oOOOOOO\n");printf(" OOOOoOOOOOOo oOOOOOOOOOo\n");printf(" oOOOOOOO oOOOOOOOOOOOOOOOOOOOO oOOo\n");printf(" oOOOOOo oOOOOo oOOOOOo\n");printf(" oOOOOO oOOO OOOOOO\n");printf(" oOOO OOOo\n");printf(" oO Oo\n");return 0;}在这个示例中,我们使用`printf()`函数来输出一个ASCII艺术图形,它形象地表示了一个小飞机的外形。

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;}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

(完整word版)飞机小游戏源代码

(完整word版)飞机小游戏源代码
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);
case '3':speed=4;
break;
default:printf("\n错误,请重新选择...\n");
sw=1;
}
}
while(sw);
for(i=0;i<22;i++)
for(j=0;Leabharlann <45;j++)
scr[i][j]=0;
scr[21][pl=9]=1;
printf("\n按任意键保存...");
{j=0;srand(time(NULL));
scr[0][rand()%width]=3;
}
if(++i%speed==0)//控制敌机移动速度,相对于子弹移动速度
movepla(scr);
movebul(scr);
print(scr);
if(i==30000)i=0;//以免i越界
}
}
void print(int a[][N]){system("cls");
default:printf("\n错误,请重新选择...\n");
sw=1;
}

飞机大战(完整代码)

飞机大战(完整代码)

飞机大战(完整代码)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语言飞机大战源码

#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 填充列 voiddrawFrame(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 frameSetPos(52, 6);cout<<" 得分: ";SetPos(52, 7);cout<<" 称号: ";SetPos(52,10);cout<<" 操作方式: ";SetPos(52,12);cout<<" a,s,d,w 控制战机移动。

飞机大战游戏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)。
}
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");
case 'w':
case 'W': scr[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)
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();//设置
void menu();//菜单
int scr[22][N]={0},pl=9,width=24,speed=3,density=30,score=0,death=0;//界面,位置,宽度,速度,
密度,分数,死亡
()
{
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;
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<time.h>
#define N 35
void print(int [][N]);//输出
void movebul(int [][N]);//子弹移动
void movepla(int [][N]);//敌机移动
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 setting() { }
//设置
} 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; } } }
相关文档
最新文档