控制台飞机大战代码
python实例:利用pygame实现小游戏“飞机大战”
python实例:利⽤pygame实现⼩游戏“飞机⼤战”0、程序代码代码1:1import random2import pygame34# 屏幕⼤⼩的常量5 SCREEN_RECT = pygame.Rect(0, 0, 480, 700)6# 刷新的帧率7 FRAME_PER_SEC = 608# 创建敌机的定时器常量9 CREATE_ENEMY_EVENT = EREVENT10# 英雄发射⼦弹事件11 HERO_FIRE_EVENT = EREVENT+112#⼦弹速度13 BULLET_SPEED = -2.5141516class GameSprite(pygame.sprite.Sprite):17""""飞机⼤战游戏精灵"""1819def__init__(self, image_name, speed = 1):20# 调⽤⽗亲的初始化⽅法21 super().__init__()22# 定义对象的属性23 self.image = pygame.image.load(image_name)24 self.rect = self.image.get_rect()25 self.speed = speed2627def update(self):28#在屏幕的垂直⽅向上移动29 self.rect.y += self.speed303132class Background(GameSprite):33""""游戏背景精灵"""3435def__init__(self, is_alt = False):36# 1.调⽤⽗类构造⽅法37 super().__init__("./images/background.png")38# 2.判断是否与前图像循环重合,若否,则需重新设置初始位置39if is_alt:40 self.rect.y = -self.rect.height414243def update(self):44# 1.调⽤⽗类的⽅法,,,注意super后⾯要加括号!!!45 super().update()46# 2.判断是否移出屏幕47if self.rect.y >= SCREEN_RECT.height:48 self.rect.y = -self.rect.height495051class Enemy(GameSprite):52""""敌机精灵"""5354def__init__(self):55# 1.调⽤⽗类⽅法,创建敌机精灵56 super().__init__("./images/enemy1.png")57# 2. 指定敌机的初始随机速度 1-2-358 self.speed = random.randint(1,3)59# 3.指定敌机的初始随机位置60 self.rect.bottom = 06162 max_x = SCREEN_RECT.width - self.rect.width63 self.rect.x = random.randint(0, max_x)646566def update(self):6768# 1.调⽤⽗类⽅法,保持垂直⽅向的飞⾏69 super().update()70# 2.判断是否⾮出屏幕,如果是,需要从精灵组删除敌机71if self.rect.y >= SCREEN_RECT.height:72#print("飞出屏幕,需要从精灵组删除...")73# kill⽅法可以将精灵从精灵组中移除74 self.kill()7576def__del__(self):77#print("敌机挂了%s" %self.rect)78pass798081class Hero(GameSprite):82"""英雄精灵"""8384def__init__(self):85# 1.调⽤⽗类⽅法,设置image和speed86 super().__init__("./images/me1.png", speed = 0)87 self.speed1 = 088# 2.设置英雄的初始位置89 self.rect.centerx = SCREEN_RECT.centerx90 self.rect.bottom = SCREEN_RECT.bottom - 10091# 3.创建⼦弹精灵组92 self.bullets = pygame.sprite.Group()9394def update(self):95#(错误的判断句,会导致⼀旦出界就很难再恢复回来)if 0 <= self.rect.x <= SCREEN_RECT.width - self.rect.width: 96 self.rect.x += self.speed97if self.rect.x < 0:98 self.rect.x = 099elif self.rect.right > SCREEN_RECT.width:100 self.rect.right = SCREEN_RECT.width101102 self.rect.y += self.speed1103if self.rect.y < 0:104 self.rect.y = 0105elif self.rect.bottom > SCREEN_RECT.height:106 self.rect.bottom = SCREEN_RECT.height107108109def fire(self):110#print("发射⼦弹")111# 1.创建⼦弹精灵112 bullet = Bullet()113# 2.设置精灵位置114 bullet.rect.bottom = self.rect.y115 bullet.rect.centerx = self.rect.centerx116# 3.将精灵添加到精灵组117 self.bullets.add(bullet)118119120class Bullet(GameSprite):121""""⼦弹精灵"""122123def__init__(self):124# 调⽤⽗类⽅法125 super().__init__("./images/bullet1.png", BULLET_SPEED)126127def update(self):128 super().update()129if self.rect.bottom < 0:130 self.kill()131132def__del__(self):133#print("⼦弹被销毁")134passView Code代码2:1from plane_sprites import *2# 游戏主程序34class PlaneGame(object):5""""飞机⼤战主游戏"""67def__init__(self):8print("游戏初始化")910# 1.创建游戏的窗⼝11 self.screen = pygame.display.set_mode(SCREEN_RECT.size)12# 2.创建游戏的时钟13 self.clock = pygame.time.Clock()14# 3.调⽤私有⽅法,精灵和精灵组的创建15 self.__create_sprites()16# 4.设置定时器事件——创建敌机 1s17 pygame.time.set_timer(CREATE_ENEMY_EVENT,1000)18 pygame.time.set_timer(HERO_FIRE_EVENT, 300)1920def__create_sprites(self):21# 创建背景精灵和精灵组22 bg1 = Background()23 bg2 = Background(True)24 self.back_group = pygame.sprite.Group(bg1, bg2)25# 创建敌机精灵26 self.enemy_group = pygame.sprite.Group()27# 创建英雄精灵28 self.hero = Hero()29 self.hero_group = pygame.sprite.Group(self.hero)303132def start_game(self):33print("游戏开始...")3435while True:36# 1.设置刷新帧率37 self.clock.tick(FRAME_PER_SEC)38# 2.事件监听39 self.__event_handler()40# 3.碰撞检测41 self.__check_collide()42# 4.更新/绘制精灵组43 self.__update_sprites()44# 5.更新显⽰45 pygame.display.update()464748def__event_handler(self):49for event in pygame.event.get():50#判断是否退出游戏51if event.type == pygame.QUIT:52 PlaneGame.__game_over()53elif event.type == CREATE_ENEMY_EVENT:54#print("敌机出现。
C语言飞机大战源码
C语言飞机大战源码以下是一个简单的C语言飞机大战游戏的源码,包括了基本的界面、移动控制、碰撞检测和计分等功能。
```c#include <stdio.h>#include <conio.h>#include <windows.h>#define SCREEN_WIDTH 80#define SCREEN_HEIGHT 25int shipX, shipY;int bulletX, bulletY;int enemyX, enemyY;int score;void SetCursorPosition(int x, int y)COORD position = {x, y};SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), position);void HideCursoCONSOLE_CURSOR_INFO cursor_info = {1, 0};SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);void DrawShiSetCursorPosition(shipX, shipY);printf("▲");void DrawBulleSetCursorPosition(bulletX, bulletY);printf(",");void DrawEnemSetCursorPosition(enemyX, enemyY);printf("■");void EraseBulleSetCursorPosition(bulletX, bulletY);printf(" ");void EraseEnemSetCursorPosition(enemyX, enemyY);printf(" ");void GameOvesystem("cls");printf("Game Over!\n");printf("Your score is: %d\n", score); exit(0);void UpdateScorSetCursorPosition(SCREEN_WIDTH - 10, 0); printf("Score: %d", score);void MoveShiif (_kbhit()switch (_getch()case 'a':if (shipX > 0) shipX--;break;case 'd':if (shipX < SCREEN_WIDTH - 1) shipX++; break;case ' ':bulletX = shipX;bulletY = shipY - 1;break;case 'q':GameOver(;break;}}void MoveBulleif (bulletY > 0)EraseBullet(;bulletY--;DrawBullet(;}elseEraseBullet(;bulletX = -1;bulletY = -1;}void MoveEnemif (enemyY < SCREEN_HEIGHT - 1) EraseEnemy(;enemyY++;DrawEnemy(;}elseEraseEnemy(;enemyX = rand( % SCREEN_WIDTH;enemyY = 0;score++;UpdateScore(;}void CheckCollisioif (bulletX == enemyX && bulletY == enemyY) EraseBullet(;bulletX = -1;bulletY = -1;enemyX = rand( % SCREEN_WIDTH;enemyY = 0;score++;UpdateScore(;}else if ((bulletX == enemyX - 1 , bulletX == enemyX ,bulletX == enemyX + 1) && bulletY == enemyY)EraseBullet(;bulletX = -1;bulletY = -1;enemyX = rand( % SCREEN_WIDTH;enemyY = 0;score++;UpdateScore(;}else if (bulletY == enemyY && (bulletX == enemyX - 1 ,bulletX == enemyX , bulletX == enemyX + 1))EraseBullet(;bulletX = -1;bulletY = -1;enemyX = rand( % SCREEN_WIDTH;enemyY = 0;score++;UpdateScore(;}else if (bulletX == enemyX && bulletY == enemyY + 1) EraseBullet(;bulletX = -1;bulletY = -1;enemyX = rand( % SCREEN_WIDTH;enemyY = 0;score++;UpdateScore(;}else if (bulletX == shipX && bulletY == shipY) GameOver(;}int maiHideCursor(;shipX = SCREEN_WIDTH / 2;shipY = SCREEN_HEIGHT - 1;bulletX = -1;bulletY = -1;enemyX = rand( % SCREEN_WIDTH; enemyY = 0;score = 0;while (1)DrawShip(;if (bulletX != -1 && bulletY != -1) MoveBullet(;}elseEraseBullet(;}MoveShip(;MoveEnemy(;CheckCollision(;Sleep(50);}return 0;```这个源码实现了一个控制飞机射击敌人并计分的简单游戏。
python--python语言实现飞机大战,附完整代码,可直接运行~
python--python语⾔实现飞机⼤战,附完整代码,可直接运⾏~前不久因为疫情的原因在家⼏个⽉,闲着⽆聊便开始学习python编程⼊门了python这门语⾔,在学习到⾯向对象的时候,最后的案例是开发⼀个飞机⼤战的项⽬游戏因此试着开发了⼀下还不错,故献上源代码和所需要的图⽚素材,想要试试开发的朋友可以直接下载到IDE上运⾏即可。
配置要求1. 安装 python的游戏包 pygame 包2. python版本为3.0以上(安装介绍:)⽂件要求1. 先新建⼀个⽂件夹命名:py_飞机⼤战2. 命名2个⽂件:plane_main.py(主控程序⽂件) 和plane_sprites.py(辅助⼯具⽂件)代码如下:(plane_main.py⽂件)1import pygame2from plane_sprites import *345class PlaneGame(object):6"""飞机⼤战主游戏"""78def__init__(self):9print("游戏初始化..")1011# 1.创建游戏窗⼝12 self.screen = pygame.display.set_mode(SCREEN_RECT.size)13# 2.创建游戏的时钟14 self.clock = pygame.time.Clock()15# 3.调⽤私有⽅法,精灵和精灵组的创建16 self.__create_sprites()17# 4.设置定时器--创建敌机出现 1s18 pygame.time.set_timer(CREATE_ENEMY_EVENT, 1000)1920def__create_sprites(self):21"""创建精灵和精灵组"""22# 1.创建背景精灵和精灵组23 bg1 = Background()24 bg2 = Background(True)25 bg2.rect.y = -bg2.rect.height26 self.back_group = pygame.sprite.Group(bg1, bg2)27# 2.创建敌机精灵组28 self.enemy_group = pygame.sprite.Group()29# 3.创建英雄精灵组30 self.hero = Hero()31 self.hero_group = pygame.sprite.Group(self.hero)3233def start_game(self):34print("游戏开始...")35while True:36# 1.设置刷新帧率37 self.clock.tick(FRAME_PER_SEC)38# 2.事件监听39 self.__event_handle()40# 3.碰撞检测41 self.__check_collide()42# 4.更新精灵组43 self.__update_sprites()44# 5.更新屏幕显⽰45 pygame.display.update()4647def__event_handle(self):48"""事件监听"""4950for event in pygame.event.get():51# 监听游戏是否退出52if event.type == pygame.QUIT:53 PlaneGame.__game_over()54# 监听敌机的出现55elif event.type == CREATE_ENEMY_EVENT:56print("敌机出场...")57# 创建敌机精灵58 enemy = Enemy()59 self.enemy_group.add(Enemy())60# 让英雄发射⼦弹61elif event.type == Hero_FIRE_EVENT:62 self.hero.fire()63# 获取⽤户按键64 keys_pressed = pygame.key.get_pressed()65if keys_pressed[pygame.K_RIGHT]:66 self.hero.speed = 267elif keys_pressed[pygame.K_LEFT]:68 self.hero.speed = -269else:70 self.hero.speed = 07172def__check_collide(self):73"""碰撞检测"""74# 1.设置⼦弹摧毁敌机75 pygame.sprite.groupcollide(self.hero.bullets,76 self.enemy_group, True, True) 77# 2.敌机摧毁英雄78 enemies = pygame.sprite.spritecollide(self.hero,79 self.enemy_group, True) 80# 2.1判断列表是否有内容81if len(enemies) > 0:82# 让英雄牺牲83 self.hero.kill()84# 结束游戏85 PlaneGame.__game_over()8687def__update_sprites(self):88"""更新精灵组"""89# 1.背景更新渲染显⽰90 self.back_group.update()91 self.back_group.draw(self.screen)92# 2.敌机渲染更新显⽰93 self.enemy_group.update()94 self.enemy_group.draw(self.screen)95# 3.英雄渲染更新显⽰96 self.hero_group.update()97 self.hero_group.draw(self.screen)98# 4.⼦弹渲染更新显⽰99 self.hero.bullets.update()100 self.hero.bullets.draw(self.screen)101102 @staticmethod103def__game_over():104"""游戏结束"""105print("游戏结束")106 pygame.quit()107 exit()108109if__name__ == '__main__':110# 创建游戏对象111 game = PlaneGame()112# 开始游戏113 game.start_game()(plane_sprites.py⽂件)import randomimport pygame# 游戏屏幕的尺⼨SCREEN_RECT = pygame.Rect(0, 0, 480, 700)# 游戏的刷新帧率FRAME_PER_SEC = 60# 敌机的定时器常量CREATE_ENEMY_EVENT = EREVENT# 英雄发射⼦弹事件Hero_FIRE_EVENT = EREVENT + 1class GameSprite(pygame.sprite.Sprite):"""游戏精灵基类"""def__init__(self, image_name, speed=1):# 调⽤⽗类的初始⽅法super().__init__()self.image = pygame.image.load(image_name)self.rect = self.image.get_rect()# 记录速度self.speed = speeddef update(self, *args):# 默认在垂直⽅向移动self.rect.y += self.speedclass Background(GameSprite):"""游戏背景精灵"""def__init__(self, is_alt=False):# 1.调⽤⽗类⽅法实现精灵的创建(image/rect/speed)image_name = "./images/background.png"super().__init__(image_name)# 2.判断是否交替图⽚,如果是,将图⽚设置到屏幕顶部if is_alt:self.rect.y = -self.rect.heightdef update(self, *args):# 1.调⽤⽗类⽅法实现super().update()# 2.判断是否移出屏幕,如移出,将图像设置到屏幕上⽅if self.rect.y >= SCREEN_RECT.height:self.rect.y = -self.rect.heightclass Enemy(GameSprite):"""敌机精灵"""def__init__(self):# 1.调⽤⽗类⽅法创建敌机精灵,并指定敌机图像super().__init__("./images/enemy1.png")# 2.设置敌机的随机速度(初始) 1~3self.speed = random.randint(1, 3)# 3.设置敌机的随机位置(初始)⽔平⽅向self.rect.bottom = 0max_x = SCREEN_RECT.width - self.rect.widthself.rect.x = random.randint(0, max_x)def update(self, *args):# 1.调⽤⽗类让敌机在垂直⽅向移动super().update()# 2.判断是否飞出屏幕,如果是,需将敌机删除if self.rect.y >= SCREEN_RECT.height:print("敌机飞出屏幕...")# 3.将精灵从所有组中删除self.kill()def__del__(self):print("敌机挂了 %s" % self.rect)class Hero(GameSprite):"""英雄精灵"""def__init__(self):super().__init__("./images/me1.png", 0)# 设置初始位置self.rect.centerx = SCREEN_RECT.centerxself.rect.bottom = SCREEN_RECT.bottom - 120 # 每隔 0.5s 发射⼀次⼦弹pygame.time.set_timer(Hero_FIRE_EVENT, 500) # 1.创建⼦弹的精灵组self.bullets = pygame.sprite.Group()def update(self, *args):# 英雄飞机在⽔平⽅向运动self.rect.x += self.speed# 判断屏幕边界if self.rect.left < 0:self.rect.left = 0if self.rect.right > SCREEN_RECT.right:self.rect.right = SCREEN_RECT.rightdef fire(self):print("发射⼦弹...")# 实现⼀次发射三枚⼦弹for i in (1, 2, 3):# 1.创建⼦弹精灵bullet = Bullet()# 2.设置⼦弹精灵位置bullet.rect.bottom = self.rect.y - i * 20bullet.rect.centerx = self.rect.centerx# 3.将⼦弹精灵添加到精灵组self.bullets.add(bullet)class Bullet(GameSprite):"""⼦弹精灵"""def__init__(self):super().__init__("./images/bullet1.png", -2) def update(self, *args):super().update()# 判断是否飞出屏幕,飞出删除if self.rect.bottom < 0:self.kill()涉及的素材图1.背景2.敌机3.主飞机4.⼦弹运⾏图可以试着运⾏玩⼀下效果,感受⼀下⽤python完成⼀次⾯向对象的⼩案例把~。
python飞机大战代码
python飞机大战代码以下是一个简单的 python 飞机大战游戏的代码示例:```python。
import pygame。
import random。
# 初始化 Pygame。
pygame.init()。
#设置游戏窗口大小和标题。
WINDOW_WIDTH=640。
WINDOW_HEIGHT=480。
screen = pygame.display.set_mode((WINDOW_WIDTH,WINDOW_HEIGHT))。
pygame.display.set_caption("飞机大战")。
#加载背景图片。
background_img =pygame.image.load("background.jpg").convert()。
#加载玩家飞机图片和音效。
player_img = pygame.image.load("player.png").convert_alpha()。
player_explosion_sound = pygame.mixer.Sound("explosion.wav")。
#加载敌机图片和音效。
enemy_img = pygame.image.load("enemy.png").convert_alpha()。
enemy_explosion_sound = pygame.mixer.Sound("explosion.wav")。
#加载子弹图片和音效。
bullet_img = pygame.image.load("bullet.png").convert_alpha()。
bullet_sound = pygame.mixer.Sound("bullet.wav")。
#定义玩家飞机和敌机的初始位置和速度。
player_x = 300。
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);}更多有趣的经典⼩游戏实现专题,分享给⼤家:以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
python飞机大战的核心语句
python飞机大战的核心语句Python飞机大战是一款非常经典的游戏,其核心语句包括以下几个方面:1. 导入必要的模块在Python飞机大战游戏中,需要导入Pygame模块来完成游戏的绘制、音效等功能。
通常使用以下语句进行导入:```pythonimport pygame```2. 初始化Pygame在导入Pygame模块后,需要初始化Pygame来设置窗口、音效等参数。
通常使用以下语句进行初始化:```pythonpygame.init()```3. 创建游戏窗口在Pygame中,使用display模块来创建游戏窗口。
通常使用以下语句创建大小为800x600的窗口:```pythonscreen = pygame.display.set_mode((800, 600))```4. 加载游戏资源在游戏中需要使用到音效、图片等资源,可以使用以下语句来加载:```pythonbg_img = pygame.image.load('bg.png')```5. 监听事件在游戏中需要监听玩家的键盘输入等事件,可以使用以下语句来监听:```pythonfor event in pygame.event.get():if event.type == pygame.KEYDOWN:if event.key == pygame.K_SPACE:# 玩家按下了空格键```6. 绘制游戏界面在游戏中需要绘制背景、敌机、玩家飞机等游戏元素,可以使用以下语句来绘制:```pythonscreen.blit(bg_img, (0, 0))```7. 更新游戏界面在每次绘制完游戏界面后,需要使用以下语句来更新:```pythonpygame.display.update()```上述是Python飞机大战的核心语句,其中还有很多游戏逻辑实现的代码,但以上这些语句是游戏实现的基础。
python实现飞机大战游戏(pygame版)
python实现飞机⼤战游戏(pygame版)简介使⽤python实现pygame版的飞机⼤战游戏;环境:Windows系统+python3.8.0游戏规则:1.点击“PLAY”或者按键“P”开始游戏;2.敌机根据设置频率从顶部随机位置⽣成,⽣成后向下移动;3.飞船在底部中间⽣成,玩家使⽤上下左右键控制飞船移动,敲击空格键发射⼦弹;4.⼦弹打到敌机,该敌机产⽣爆炸效果并累计分数到右上⾓;5.消灭10只飞机后,等级升⾼,敌机⽣成频率变快,下落速度也变快;6.当三条命都消失了,游戏结束。
游戏运⾏效果如下:实现过程1.新建⽂件“file.py”,⽤来存储信息到⽂件和读取⽂件的信息,本例⽤来存储和读取最⾼分;import pickle# filename = 'file/stats.pkl'# 存储信息到⽂件def save_file(obj, filename):statsObj = load_file(filename)if statsObj == 0:# 不存在⽂件时,直接保存字典with open(filename, 'wb') as f:pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)else:# 存在⽂件时,只修改⽂件中的最⾼分for key, val in statsObj.items():# 获取⽂件最⾼分的值(当⽂件字段不⽌⼀个时候使⽤)if key == 'highScore':statsObj[key] = obj['highScore']obj = statsObjwith open(filename, 'wb') as f:pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)# 读取信息def load_file(filename):try:with open(filename, 'rb') as f:return pickle.load(f)except FileNotFoundError:# 不存在⽂件则输⼊错误信息msg = "Sorry, the file " + filename + " does not exist."print(msg)return 0# obj = {'highScore': 20, 'points': 5}# obj = {'highScore': 50}# save_file(obj, filename)# filedata = load_file(filename)# print(filedata)2.k新建⽂件settings.py,⽤来定义⼀些必须的基本属性和初始值;import file as fclass Settings():def __init__(self):self.screen_width = 480self.screen_height = 660self.bg_color = (230, 230, 230)# ⼦弹设置(宽、⾼、颜⾊、最⼤数量)self.bullet_width = 5self.bullet_height = 15self.bullet_color = 255, 255, 255# 敌机移动频率self.enemy_frequency = 0# 加快游戏节奏的速度self.speedup_scale = 1.1# 分数的提⾼速度self.score_scale = 1.5self.initialize_settings()# 初始化统计信息self.reset_stats()# 统计信息⽂件路径self.filename = 'file/stats.pkl'# 游戏刚启动时处于⾮活动状态self.game_active = False# 读取⽂件的最⾼分,在任何情况下都不应重置最⾼得分statsObj = f.load_file(self.filename)if statsObj == 0:# 不存在⽂件则显⽰最⾼分0highScore = 0else:for key, val in statsObj.items():# 获取⽂件最⾼分的值(当⽂件字段不⽌⼀个时候使⽤)if key == 'highScore':highScore = valself.high_score = highScoredef initialize_settings(self):"""初始化随游戏进⾏⽽变化的设置"""self.player_move_speed = 2.5self.bullet_speed = 3self.enemy_move_speed = 1# 记分self.one_points = 50def increase_speed(self):"""提⾼速度设置"""# self.player_move_speed *= self.speedup_scaleself.bullet_speed *= self.speedup_scaleself.enemy_move_speed *= self.speedup_scaleself.one_points = int(self.one_points * self.score_scale)def reset_stats(self):"""初始化在游戏运⾏期间可能变化的统计信息"""# 可射失的数量self.player_limit = 3# 射击分数self.score = 0# 等级self.level = 1# 打中多少矩形升⼀级self.level_number = 10# ⽣成敌机频率间隔self.enemy_frequency_space = 503.新建⽂件enemy.py,⽤来定义敌机类(位置topleft随机⽣成)和声明⽅法move;import pygameimport randomfrom pygame.sprite import Spriteclass Enemy(Sprite):def __init__(self, enemy_down_imgs, settings):super(Enemy, self).__init__()self.image = pygame.image.load('images/enemy1.png')self.rect = self.image.get_rect()self.rect.topleft = [random.randint(0, settings.screen_width - self.rect.width), 0]self.down_imgs = enemy_down_imgsself.speed = settings.enemy_move_speedself.down_index = 0# 敌机移动,边界判断及删除在游戏主循环⾥处理def move(self):self.rect.top += self.speed4.新建⽂件player.py,⽤来定义玩家类(可上下左右移动)和相应的⽅法;import pygamefrom pygame.sprite import Spriteclass Player(Sprite):def __init__(self, settings, screen):super(Player, self).__init__()self.settings = settingsself.screen = screenself.screen_rect = self.screen.get_rect()# 引⼊飞船图⽚并定位self.image = pygame.image.load('images/player.png')self.rect = self.image.get_rect()self.rect.centerx = self.screen_rect.centerxself.rect.bottom = self.screen_rect.bottom# 移动标志self.move_left = Falseself.move_right = Falseself.move_down = Falseself.move_up = Falsedef rotate(self, angle):# 图⽚旋转self.image = pygame.transform.rotate(self.image, angle)def scale(self, multiple):# 图⽚缩放self.image = pygame.transform.smoothscale(self.image, (multiple, multiple))def update(self):if self.move_left and self.rect.left > self.screen_rect.left:self.rect.centerx -= self.settings.player_move_speedif self.move_right and self.rect.right < self.screen_rect.right:self.rect.centerx += self.settings.player_move_speedif self.move_down and self.rect.bottom < self.screen_rect.bottom:self.rect.centery += self.settings.player_move_speedif self.move_up and self.rect.top > 0:self.rect.centery -= self.settings.player_move_speeddef draw_player(self):"""绘制飞船到屏幕"""self.screen.blit(self.image, self.rect)5.新建⽂件“bullet.py”,⽤来定义⼦弹类(位置在飞船的顶部,并往上移动)和相应的⽅法;import pygamefrom pygame.sprite import Spriteclass Bullet(Sprite):""" ⼀个对飞船发射的⼦弹进⾏管理的类 """def __init__(self, settings, screen, player):""" 在飞船所处的位置创建⼀个⼦弹对象 """super(Bullet, self).__init__()self.screen = screen# 在 (0,0) 处创建⼀个表⽰⼦弹的矩形,再设置正确的位置self.rect = pygame.Rect(0, 0, settings.bullet_width, settings.bullet_height)self.rect.centerx = player.rect.centerx# 飞船顶部self.rect.bottom = player.rect.top# 存储⽤⼩数表⽰的⼦弹位置self.y = float(self.rect.y)self.color = settings.bullet_colorself.speed = settings.bullet_speeddef update(self):"""向上移动⼦弹"""# 更新表⽰⼦弹位置的⼩数值(⼦弹往右)self.y -= self.speed# 更新表⽰⼦弹的rect的位置self.rect.y = self.ydef draw_bullet(self):"""在屏幕上绘制⼦弹"""pygame.draw.rect(self.screen, self.color, self.rect)6.新建⽂件“button.py”,⽤来定义按钮类和相应⽅法,本例使⽤于绘制“PLAY”按钮;import pygame.fontclass Button():def __init__(self, screen, msg):"""初始化按钮的属性"""self.screen = screenself.screen_rect = screen.get_rect()# 设置按钮的尺⼨和其他属性self.width, self.height = 100, 30self.button_color = (216, 30, 6)self.text_color = (255, 255, 255)self.font = pygame.font.SysFont(None, 36)# 创建按钮的rect对象,并使其居中self.rect = pygame.Rect(0, 0, self.width, self.height)self.rect.center = self.screen_rect.center# 按钮的标签只需创建⼀次self.prep_msg(msg)def prep_msg(self, msg):"""将msg渲染为图像,并使其在按钮上居中"""self.msg_image = self.font.render(msg, True, self.text_color, self.button_color)self.msg_image_rect = self.msg_image.get_rect()self.msg_image_rect.center = self.rect.centerdef draw_button(self):# 绘制⼀个⽤颜⾊填充的按钮,再绘制⽂本self.screen.fill(self.button_color, self.rect)self.screen.blit(self.msg_image, self.msg_image_rect)7.新建⽂件“scoreboard.py”,⽤来定义记分板,本例使⽤于绘制左上⾓飞船(⽣命数)、顶部中间的“最⾼分”、右上⾓的“积分”和“等级”;import pygame.fontfrom pygame.sprite import Groupfrom player import Playerclass Scoreboard():"""显⽰得分信息的类"""def __init__(self, settings, screen):"""初始化显⽰得分涉及的属性"""self.screen = screenself.screen_rect = screen.get_rect()self.settings = settings# 显⽰得分信息时使⽤的字体设置self.text_color = (255, 255, 255)self.font = pygame.font.SysFont(None, 30)# 飞船缩放值self.scaleValue = 20# 准备初始得分图像\最⾼得分\等级self.prep_score()self.prep_high_score()self.prep_level()self.prep_players()def prep_score(self):"""将得分转换为渲染的图像"""rounded_score = int(round(self.settings.score, -1))score_str = '{:,}'.format(rounded_score)self.score_image = self.font.render(score_str, True, self.text_color)# 将得分放在屏幕右上⾓self.score_rect = self.score_image.get_rect()self.score_rect.right = self.screen_rect.right -20self.score_rect.top = 10def prep_high_score(self):""" 将最⾼得分转换为渲染的图像 """high_score = int(round(self.settings.high_score, -1))high_score_str = "{:,}".format(high_score)self.high_score_image = self.font.render(high_score_str, True, self.text_color)# 将最⾼得分放在屏幕顶部中央self.high_score_rect = self.high_score_image.get_rect()self.high_score_rect.centerx = self.screen_rect.centerxself.high_score_rect.top = self.score_rect.topdef prep_level(self):"""将等级转换为渲染的图像"""self.level_image = self.font.render(str(self.settings.level), True, self.text_color)# 将等级放在得分下⽅self.level_rect = self.level_image.get_rect()self.level_rect.right = self.score_rect.rightself.level_rect.top = self.score_rect.bottom + 10def prep_players(self):""" 显⽰还余下多少艘飞船 """self.players = Group()for player_number in range(self.settings.player_limit):player = Player(self.settings, self.screen)# 缩放球⼤⼩并赋值位置player.scale(self.scaleValue)player.rect.x = 10 + player.rect.width * player_number * 0.5player.rect.y = self.score_rect.topself.players.add(player)def show_score(self):"""在屏幕上显⽰得分"""self.screen.blit(self.score_image, self.score_rect)self.screen.blit(self.high_score_image, self.high_score_rect)self.screen.blit(self.level_image, self.level_rect)# 绘制飞船self.players.draw(self.screen)8.新建⽂件“game_functions.py”,存放跟游戏有关的所有业务逻辑函数(代码有详细的注释信息);import sysimport pygamefrom bullet import Bulletfrom enemy import Enemyimport file as f# 事件def check_events(settings, screen, player, play_button, scoreboard, bullets, fireSound):""" 响应按键和⿏标事件 """for event in pygame.event.get():if event.type == pygame.QUIT:save_file(settings)sys.exit()elif event.type == pygame.KEYDOWN:check_keydown_events(event, settings, screen, player, scoreboard, bullets, fireSound)elif event.type == pygame.KEYUP:check_keyup_events(event, player)elif event.type == pygame.MOUSEBUTTONDOWN:mouse_x, mouse_y = pygame.mouse.get_pos()check_play_button(settings, play_button, scoreboard, mouse_x, mouse_y)def check_keydown_events(event, settings, screen, player, scoreboard, bullets, fireSound):""" 响应按键 """if event.key == pygame.K_DOWN:player.move_down = Trueelif event.key == pygame.K_UP:player.move_up = Trueelif event.key == pygame.K_LEFT:player.move_left = Trueelif event.key == pygame.K_RIGHT:player.move_right = Trueelif event.key == pygame.K_SPACE:fireSound.play()# 点击空格键创建⼀颗⼦弹fire_bullet(settings, screen, player, bullets)elif event.key == pygame.K_p:start_game(settings, scoreboard)elif event.key == pygame.K_q:save_file(settings)sys.exit()def check_keyup_events(event, player):""" 响应松开 """if event.key == pygame.K_DOWN:player.move_down = Falseelif event.key == pygame.K_UP:player.move_up = Falseelif event.key == pygame.K_LEFT:player.move_left = Falseelif event.key == pygame.K_RIGHT:player.move_right = Falsedef check_play_button(settings, play_button, scoreboard, mouse_x, mouse_y):"""在玩家单击Play按钮时开始新游戏"""button_clicked = play_button.rect.collidepoint(mouse_x, mouse_y)if button_clicked and not settings.game_active:start_game(settings, scoreboard)def start_game(settings, scoreboard):"""开始游戏"""# 重置游戏设置settings.initialize_settings()# 隐藏光标pygame.mouse.set_visible(False)# 重置游戏统计信息settings.reset_stats()settings.game_active = True# 重置记分牌图像scoreboard.prep_score()scoreboard.prep_high_score()scoreboard.prep_level()scoreboard.prep_players()def save_file(settings):# 保持⽂件obj = {'highScore': settings.high_score}f.save_file(obj, settings.filename)# 敌机def update_enemies(settings, screen, scoreboard, enemies, enemies_down, enemy_down_imgs, player, bullets, explosiveSound): # ⽣成敌机,需要控制⽣成频率if settings.enemy_frequency % settings.enemy_frequency_space == 0:enemy1 = Enemy(enemy_down_imgs, settings)enemies.add(enemy1)settings.enemy_frequency += 1if settings.enemy_frequency >= 100:settings.enemy_frequency = 0for enemy in enemies:# 移动敌机enemy.move()# 敌机与玩家飞机碰撞效果处理两个精灵之间的圆检测if pygame.sprite.collide_circle(enemy, player):enemies_down.add(enemy)enemies.remove(enemy)settings.player_limit -= 1scoreboard.prep_players()break# 移动出屏幕后删除飞机if enemy.rect.top < 0:enemies.remove(enemy)# 敌机被⼦弹击中效果处理# 将被击中的敌机对象添加到击毁敌机 Group 中,⽤来渲染击毁动画# ⽅法groupcollide()是检测两个精灵组中精灵们的矩形冲突enemies1_down = pygame.sprite.groupcollide(enemies, bullets, True, True)if enemies1_down:explosiveSound.play()# 计算分数并渲染for enemys in enemies1_down.values():settings.score += settings.one_points * len(enemys)scoreboard.prep_score()# 渲染最⾼分check_high_score(settings, scoreboard)# 等达到等级数量升级并渲染新等级settings.level_number -= 1if settings.level_number == 0:settings.increase_speed()settings.level += 1scoreboard.prep_level()# 还原为4(同settings⼀致)settings.level_number = 10# 加快⽣成敌机if settings.enemy_frequency_space > 10:settings.enemy_frequency_space -= 10# 遍历key值返回的碰撞敌机for enemy_down in enemies1_down:# 点击销毁的敌机到列表enemies_down.add(enemy_down)# 敌机被⼦弹击中效果显⽰for enemy_down in enemies_down:if enemy_down.down_index == 0:passif enemy_down.down_index > 7:enemies_down.remove(enemy_down)continue#显⽰碰撞图⽚screen.blit(enemy_down.down_imgs[enemy_down.down_index // 2], enemy_down.rect) enemy_down.down_index += 1# 显⽰精灵enemies.draw(screen)# ⼦弹def fire_bullet(settings, screen, player, bullets):"""创建⼦弹"""new_bullet = Bullet(settings, screen, player)bullets.add(new_bullet)def update_bullets(screen, bullets):"""更新⼦弹的位置,并删除已消失的⼦弹"""# 更新⼦弹的位置bullets.update()# 删除已消失的⼦弹并同时更新飞船的⽣命for bullet in bullets.copy():if bullet.rect.top < screen.get_rect().top:bullets.remove(bullet)# 分数def check_high_score(settings, scoreboard):"""检查是否诞⽣了新的最⾼得分"""if settings.score > settings.high_score:settings.high_score = settings.scorescoreboard.prep_high_score()# 屏幕def update_screen(settings, screen, player, play_button, scoreboard, enemies, bullets): """ 更新屏幕上的图像,并切换到新屏幕 """# 绘制飞船到屏幕player.draw_player()# 绘制⼦弹到屏幕for bullet in bullets.sprites():bullet.draw_bullet()# 渲染记分牌信息scoreboard.show_score()#if settings.player_limit == 0:settings.game_active = Falsesettings.reset_stats()# 清空矩形列表和⼦弹列表enemies.empty()bullets.empty()screen_rect = screen.get_rect()player.rect.centerx = screen_rect.centerxplayer.rect.bottom = screen_rect.bottom# 如果游戏处于⾮活动状态,就绘制 Play 按钮if not settings.game_active:play_button.draw_button()# 让最近绘制的屏幕可见pygame.display.flip()9.新建⽂件shootingenemy.py,主函数⽤来初始化程序,并同步更新程序的信息;import pygamefrom pygame.sprite import Groupfrom settings import Settingsfrom button import Buttonfrom player import Playerimport game_functions as gffrom scoreboard import Scoreboarddef run_game():pygame.init()# 初始化全部⾳频,并加载爆炸声⾳乐pygame.mixer.init()# 等待1spygame.time.delay(1000)pygame.mixer.music.load('file/bgsound.mp3')# -1代表⽆限循环(背景⾳乐)pygame.mixer.music.play(-1)# 爆炸声explosiveSound = pygame.mixer.Sound('file/explosiveSound.wav')# 枪声fireSound = pygame.mixer.Sound('file/fireSound.wav')# 游戏循环帧率设置clock = pygame.time.Clock()settings = Settings()screen = pygame.display.set_mode((settings.screen_width, settings.screen_height))# 全屏显⽰# screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)pygame.display.set_caption('飞机⼤战')# 左上⾓图标ic_launcher = pygame.image.load('images/ic_launcher.png').convert_alpha()pygame.display.set_icon(ic_launcher)# 背景图background = pygame.image.load('images/background.png').convert_alpha()# 敌机图⽚enemy_img1= pygame.image.load('images/enemy1.png')enemy_img2= pygame.image.load('images/enemy2.png')enemy_img3= pygame.image.load('images/enemy3.png')enemy_img4= pygame.image.load('images/enemy4.png')# 敌机不同状态的图⽚列表,多张图⽚展⽰为动画效果enemy_down_imgs = []enemy_down_imgs.append(enemy_img1)enemy_down_imgs.append(enemy_img2)enemy_down_imgs.append(enemy_img3)enemy_down_imgs.append(enemy_img4)# 储存敌机enemies = Group()# 存储被击毁的飞机,⽤来渲染击毁动画enemies_down = Group()# 创建Play按钮play_button = Button(screen, 'Play')# 创建飞船player = Player(settings, screen)# 创建⼦弹的编组bullets = Group()# 创建记分牌scoreboard = Scoreboard(settings, screen)while True:# 绘制背景screen.blit(background, (0, 0))# 控制游戏最⼤频率clock.tick(60)# 检查玩家输⼊(不加会导致⼀直加载)gf.check_events(settings, screen, player, play_button, scoreboard, bullets, fireSound)if settings.game_active:# 更新飞船位置player.update()# 更新敌机gf.update_enemies(settings, screen, scoreboard, enemies, enemies_down, enemy_down_imgs, player, bullets, explosiveSound)# 更新⼦弹位置gf.update_bullets(screen, bullets)# 更新屏幕信息gf.update_screen(settings, screen, player, play_button, scoreboard, enemies, bullets)run_game(),10.在⽂件shootingenemy.py⽬录路径下,执⾏命令“python shootingenemy.py”弹出窗⼝,即可对其操作游玩。
飞机大战 java 源代码
package com;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Image;import java.awt.Rectangle;import java.awt.event.KeyEvent;import java.io.IOException;import javax.imageio.ImageIO;public class Plane {Image feijiImage = null;int x = 300;int y = 700;int lifeCount=5;public Plane() {try {feijiImage = ImageIO.read(Plane.class.getClassLoader().getResourceAsStream("images/feiji.png"));} catch (IOException e) {e.printStackTrace();}}public void draw(Graphics g) {//画飞机图片g.drawImage(feijiImage, x, y, null);//飞机移动this.move();// 血条if(lifeCount>0){g.setColor(Color.WHITE);g.fillRect(20, 80, 100, 10);g.setColor(Color.red);g.fillRect(20, 80, (100/5)*lifeCount, 10);g.setColor(Color.blue);g.setFont(new Font("幼圆", Font.BOLD, 30));g.drawString("Score:"+Play01.count, 20, 60);}}public void move(){if(isUP && !isDown && !isLeft && !isRight){//上y=y-5;}else if(!isUP && isDown && !isLeft && !isRight){ //下y=y+5;}else if(!isUP && !isDown && isLeft && !isRight){ //左x=x-5;}else if(!isUP && !isDown && !isLeft && isRight){ //右x=x+5;}else if(isUP && !isDown && isLeft && !isRight){ //左上x=x-5;y=y-5;}else if(!isUP && isDown && isLeft && !isRight){ //左下x=x-5;y=y+5;}else if(isUP && !isDown && !isLeft && isRight){ //右上x=x+5;y=y-5;}else if(!isUP && isDown && !isLeft && isRight){ //右下x=x+5;y=y+5;}}boolean isUP = false;boolean isDown = false;boolean isLeft = false;boolean isRight = false;// 摁下public void keyPressed(KeyEvent e) {int keyCode = e.getKeyCode();if (keyCode == KeyEvent.VK_RIGHT || keyCode == KeyEvent.VK_D) {isRight=true;} else if (keyCode == KeyEvent.VK_LEFT || keyCode == KeyEvent.VK_A) {isLeft=true;} else if (keyCode == KeyEvent.VK_UP || keyCode == KeyEvent.VK_W) {isUP=true;} else if (keyCode == KeyEvent.VK_DOWN || keyCode == KeyEvent.VK_S) { isDown=true;}}// 放开public void keyReleased(KeyEvent e) {int keyCode = e.getKeyCode();if (keyCode == KeyEvent.VK_RIGHT || keyCode == KeyEvent.VK_D) {isRight=false;} else if (keyCode == KeyEvent.VK_LEFT || keyCode == KeyEvent.VK_A) {isLeft=false;} else if (keyCode == KeyEvent.VK_UP || keyCode == KeyEvent.VK_W) {isUP=false;} else if (keyCode == KeyEvent.VK_DOWN || keyCode == KeyEvent.VK_S) { isDown=false;}}public Rectangle getRectangle(){return new Rectangle(x,y,feijiImage.getWidth(null),feijiImage.getHeight(null));}}package com;public class PlaneStatus {public static int roleNum = 1;public static int playStatus = 0;// 0 游戏开始前 1 第一关-1 游戏结束}package com;import java.awt.Graphics;import java.awt.Image;import java.awt.event.KeyEvent;import java.io.IOException;import javax.imageio.ImageIO;public class Power {Image PowerImage = null;int x = 20;int y = 0;public Power() {this.x=(int)(Math.random()*540)+20;try {PowerImage = ImageIO.read(Gift.class.getClassLoader().getResourceAsStream("images/power.png"));} catch (IOException e) {e.printStackTrace();}}public void draw(Graphics g) {//画血瓶图片g.drawImage(PowerImage, x, y, null);//血瓶移动y++;}public Rectangle getRectangle(){return new Rectangle(x,y,PowerImage.getWidth(null),PowerImage.getHeight(null));}}package com;import java.awt.Graphics;import java.awt.Image;import java.awt.Rectangle;import java.awt.event.KeyEvent;import java.util.ArrayList;import java.util.List;import javax.imageio.ImageIO;// 第一关public class Play01 {static int count=0;Image bgImage = null;// 战机Plane plane = new Plane();// 战机子弹List<MyZiDan> mzds = new ArrayList<MyZiDan>();// 敌机List<Diji> dijis = new ArrayList<Diji>();// 敌机子弹//List<DijiZiDan> dijizidans = new ArrayList<DijiZiDan>();// 血瓶List<Gift> gifts = new ArrayList<Gift>();List<Power> powers = new ArrayList<Power>();public Play01() {try {bgImage = ImageIO.read(Play01.class.getClassLoader().getResourceAsStream("images/bg_01.jpg"));} catch (IOException e) {e.printStackTrace();}}int bgY1 = 0;int bgY2 = -600;int fireTime = 0;boolean flag=false;public void draw(Graphics g) {// 画背景图片g.drawImage(bgImage, 0, bgY1, null);bgY1 += 5;if (bgY1 <= 600) {bgY1 = 0;}g.drawImage(bgImage, 0, bgY2, null);bgY2 += 5;if (bgY2 >= 0) {bgY2 = -600;}// 清理战机子弹for (int i = 0; i < mzds.size(); i++) {MyZiDan myZidan = mzds.get(i);if (myZidan.x > 800) {mzds.remove(i);}}// 添加子弹if (isFire1 == true && flag==false) {if (fireTime % 8 == 0) {mzds.add(new MyZiDan(plane.x + 25, plane.y + 0));}fireTime++;}if (isFire1== true && flag==true) {if (fireTime % 4 == 0) {mzds.add(new MyZiDan(plane.x +8, plane.y +0));mzds.add(new MyZiDan(plane.x +52, plane.y +0));}fireTime++;}// 画战机子弹for (int i = 0; i < mzds.size(); i++) {MyZiDan myZidan = mzds.get(i);myZidan.draw(g);}// 清理敌机for (int i = 0; i < dijis.size(); i++) {Diji dj = dijis.get(i);if (dj.x < -100) {dijis.remove(i);}}// 抽奖:添加敌机if ((int) (Math.random() * 20) == 5) {dijis.add(new Diji());}// 抽奖:添加血瓶if ((int) (Math.random() * 1000) == 5) {gifts.add(new Gift());}for (int i = 0; i < gifts.size(); i++) {Gift gift = gifts.get(i);gift.draw(g);}//// 抽奖:添加powerif ((int) (Math.random() * 1000) == 5) {powers.add(new Power());}for (int i = 0; i < powers.size(); i++) {Power power = powers.get(i);power.draw(g);}// 画敌机for (int i = 0; i < dijis.size(); i++) {Diji dj = dijis.get(i);dj.draw(g);}// 画飞机plane.draw(g);// 判断战机相撞for (int i = 0; i < dijis.size(); i++) {// 先得到每一个敌机Diji dj = dijis.get(i);Rectangle r1 = dj.getRectangle();Rectangle r2 = plane.getRectangle();if (r1.intersects(r2)) {dijis.remove(i);plane.lifeCount = plane.lifeCount - 1;if(plane.lifeCount>0)flag=false;if(plane.lifeCount<1){ PlaneStatus.playStatus=-1; }}// 判断战机和血瓶相撞for (int i = 0; i < gifts.size(); i++) {// 先得到每一个血瓶Gift gift = gifts.get(i);Rectangle r1 = gift.getRectangle();Rectangle r2 = plane.getRectangle();if (r1.intersects(r2)) {gifts.remove(i);if (plane.lifeCount <5) {plane.lifeCount = plane.lifeCount + 1;}}}//// 判断战机和Power相撞for (int i = 0; i < powers.size(); i++) {// 先得到每一个powerPower power = powers.get(i);Rectangle r1 = power.getRectangle();Rectangle r2 = plane.getRectangle();if (r1.intersects(r2)) {powers.remove(i);flag=true;}}// 判断敌机在中弹for (int i = 0; i < mzds.size(); i++) {// 得到每个战机子弹MyZiDan myzidan = mzds.get(i);Rectangle r1 = myzidan.getRectangle();for (int j = 0; j < dijis.size(); j++) {// 每一个敌机Diji diji = dijis.get(j);Rectangle r2 = diji.getRectangle();if (r1.intersects(r2)) {mzds.remove(i);dijis.remove(j);count++;}}}boolean isFire1 = false;boolean isFire2 = false;public void keyPressed(KeyEvent e) {plane.keyPressed(e);if (e.getKeyCode() == KeyEvent.VK_J) {isFire1 = true;}/*if (e.getKeyCode() == KeyEvent.VK_K) {isFire2 = true;}*/}public void keyReleased(KeyEvent e) {plane.keyReleased(e);if (e.getKeyCode() == KeyEvent.VK_J) {isFire1 = false;fireTime = 0;}/*if (e.getKeyCode() == KeyEvent.VK_K) {isFire2 = false;fireTime = 0;}*/if( e.getKeyCode()==KeyEvent.VK_P){for(int i=0;i<dijis.size();i++)dijis.remove(i);}}}package com;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Image;import java.awt.event.KeyEvent;import java.io.IOException;import javax.imageio.ImageIO;// 游戏结束public class Over {Image obg=null;Image ng=null;public Over() {try {obg = ImageIO.read(Before.class.getClassLoader().getResourceAsStream("images/obg.jpg"));ng = ImageIO.read(Before.class.getClassLoader().getResourceAsStream("images/ng.png"));} catch (IOException e) {e.printStackTrace();}}public void draw(Graphics g){g.drawImage(obg, 0, 0, null);g.drawImage(ng, 120,100, null);g.setColor(Color.black);g.setFont(new Font("幼圆", Font.BOLD, 40));g.drawString("游戏结束啦!",200 ,600 );}public void keyPressed(KeyEvent e) {}public void keyReleased(KeyEvent e) {}}package com;import java.awt.Color;import java.awt.Graphics;import java.awt.Image;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;import javax.swing.JFrame;public class MainFrame extends JFrame {Before before =new Before();Play01 play01 = new Play01();Over over = new Over();public MainFrame() {//设置标题this.setTitle(" 让子弹飞一会~"); //设置大小this.setSize(600, 800);//定位居中this.setLocationRelativeTo(null);//添加关闭操作this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //禁止重置大小zthis.setResizable(false);//添加键盘监听器//KeyListener --> KeyAdapterthis.addKeyListener(new KeyAdapter(){@Overridepublic void keyPressed(KeyEvent e) {if(PlaneStatus.playStatus == 0){before.keyPressed(e);}else if(PlaneStatus.playStatus ==1){play01.keyPressed(e);}else if(PlaneStatus.playStatus==-1){over.keyPressed(e);}}@Overridepublic void keyReleased(KeyEvent e) {if(PlaneStatus.playStatus == 0){before.keyReleased(e);}else if(PlaneStatus.playStatus ==1){play01.keyReleased(e);}else if(PlaneStatus.playStatus==-1){over.keyReleased(e);}}});//启动一个线程:每隔20 毫秒执行一次new Thread(){public void run(){while(true){MainFrame.this.repaint();try {Thread.sleep(20);} catch (InterruptedException e) {e.printStackTrace();}}}}.start();//显示this.setVisible(true);}Image bufferImage =null;//这个方法也是20毫秒执行一次public void paint(Graphics g){if(bufferImage==null){bufferImage = this.createImage(600, 800);}Graphics g4Image = bufferImage.getGraphics();g4Image.setColor(Color.BLACK);g4Image.fillRect(0, 0, 600, 800);this.draw(g4Image);g.drawImage(bufferImage, 0, 0, null);}public void draw(Graphics g){if(PlaneStatus.playStatus == 0){before.draw(g);}else if(PlaneStatus.playStatus ==1){play01.draw(g);}else if(PlaneStatus.playStatus==-1){over.draw(g);}}public static void main(String[] args) {new MainFrame();}}package com;import java.awt.Graphics;import java.awt.Image;import java.awt.Rectangle;import java.io.IOException;import javax.imageio.ImageIO;public class MyZiDan {Image zidanImage = null;int x ;int y ;public MyZiDan(int x,int y) {this.x=x;this.y=y;try {zidanImage = ImageIO.read(MyZiDan.class.getClassLoader().getResourceAsStream("images/zidan.png"));} catch (IOException e) {e.printStackTrace();}}public void draw(Graphics g) {//画我军子弹图片g.drawImage(zidanImage, x, y, null);//我的飞机子弹移动速度y-=20;}public Rectangle getRectangle(){return new Rectangle(x,y,zidanImage.getWidth(null),zidanImage.getHeight(null));}}package com;import java.awt.Graphics;import java.awt.Image;import java.awt.Rectangle;import java.awt.event.KeyEvent;import java.io.IOException;import javax.imageio.ImageIO;public class Diji {Image dijiImage = null;int y = -20;int x = 10;//20 ~ 760int r;public Diji() {this.x=(int)(Math.random()*540)+40;try {r = (int)(Math.random()*3)+1;dijiImage = ImageIO.read(Diji.class.getClassLoader().getResourceAsStream("images/diji_"+r+".png"));} catch (IOException e) {e.printStackTrace();}}public void draw(Graphics g) {//画敌机图片g.drawImage(dijiImage, x, y, null);//敌机移动if(r==1){y+=4;}else if(r==2){y+=4;}else if(r==3){y+=7;}}public Rectangle getRectangle(){return new Rectangle(x,y,dijiImage.getWidth(null),dijiImage.getHeight(null));}}package com;import java.awt.Graphics;import java.awt.Image;import java.awt.Rectangle;import java.awt.event.KeyEvent;import java.io.IOException;import javax.imageio.ImageIO;public class Gift {Image GiftImage = null;int x = 20;int y = 0;public Gift() {this.x=(int)(Math.random()*540)+20;try {GiftImage = ImageIO.read(Gift.class.getClassLoader().getResourceAsStream("images/blood.png"));} catch (IOException e) {e.printStackTrace();}}public void draw(Graphics g) {//画血瓶图片g.drawImage(GiftImage, x, y, null);//血瓶移动y++;}public Rectangle getRectangle(){return new Rectangle(x,y,GiftImage.getWidth(null),GiftImage.getHeight(null));}}package com;import java.awt.Graphics;import java.awt.Image;import java.awt.Rectangle;import java.io.IOException;import javax.imageio.ImageIO;public class DijiZiDan {Image zidanImage = null;int x ;int y ;int fangxiang =0;public DijiZiDan(int x,int y) {this.x=x;this.y=y;fangxiang = (int)(Math.random()*5);//0 ~ 7try {zidanImage = ImageIO.read(DijiZiDan.class.getClassLoader().getResourceAsStream("images/dijizidan.jpg"));} catch (IOException e) {e.printStackTrace();}}public void draw(Graphics g) {//画敌机子弹图片g.drawImage(zidanImage, x, y, null);//移动this.move();}public void move(){if(fangxiang==0){//下y=y+2;}else if(fangxiang==1){//左x=x-2;}else if(fangxiang==2){//右x=x+2;}else if(fangxiang==3){//左下x=x-2;y=y+2;}else if(fangxiang==4){//右下x=x+2;y=y+2;}}public Rectangle getRectangle(){return new Rectangle(x,y,zidanImage.getWidth(null),zidanImage.getHeight(null));}}package com;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Image;import java.awt.event.KeyEvent;import java.io.IOException;import javax.imageio.ImageIO;// 游戏开始之前public class Before {Image bg=null;Image wfeiji=null;Image kdiji1=null;Image kdiji2=null;Image kdiji3=null;public Before() {try {bg = ImageIO.read(Before.class.getClassLoader().getResourceAsStream("images/bg.jpg"));wfeiji = ImageIO.read(Before.class.getClassLoader().getResourceAsStream("images/feiji_1.png"));kdiji1 = ImageIO.read(Before.class.getClassLoader().getResourceAsStream("images/kdiji_01.png"));kdiji2 = ImageIO.read(Before.class.getClassLoader().getResourceAsStream("images/kdiji_02.png"));kdiji3 = ImageIO.read(Before.class.getClassLoader().getResourceAsStream("images/kdiji_03.png"));} catch (IOException e) {e.printStackTrace();}}int time=0;public void draw(Graphics g){if(PlaneStatus.roleNum==1){// 画妹妹g.drawImage(bg, 0, 0, null);g.drawImage(wfeiji, 260, 600, null);g.drawImage(kdiji1, 200, 50, null);g.drawImage(kdiji1, 400, 50, null);g.drawImage(kdiji1, 150, 480, null);g.drawImage(kdiji1, 400, 480, null);g.drawImage(kdiji2, 100, 200, null);g.drawImage(kdiji2, 300, 100, null);g.drawImage(kdiji2, 480, 200, null);g.drawImage(kdiji3, 300, 300, null);g.drawImage(kdiji3, 70, 400, null);g.drawImage(kdiji3, 510, 400, null);}//画回车符time++;g.setColor(Color.YELLOW);g.setFont(new Font("幼圆", Font.BOLD, 30));if(time<=10){g.drawString("[Enter]>>", 50, 750);}else if(time<=20){g.drawString("[Enter] >>", 50, 750);}else if(time<=30){g.drawString("[Enter] >>", 50, 750);if(time==30){time=0;}}}public void keyPressed(KeyEvent e) {int keyCode = e.getKeyCode();if(keyCode == KeyEvent.VK_ENTER){PlaneStatus.playStatus=1;}if(keyCode ==KeyEvent.VK_LEFT ||keyCode==KeyEvent.VK_RIGHT ){ PlaneStatus.roleNum = 3-PlaneStatus.roleNum;//1~2 互换}}public void keyReleased(KeyEvent e) {}}。
飞机大战源代码
}
@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"));
飞机大战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语言飞机大战代码#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语⾔实现简单飞机⼤战的具体代码,供⼤家参考,具体内容如下这个游戏的功能很单⼀,也就是“飞机⼤战”,哈哈哈哈。
总共只有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语言飞机大战源代码
#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() //设置{}.。
飞机大战 java 源代码,DOC
packagecom;importimportimportfeijiImage=.getResourceAsStream("images/feiji.png"));}catch(IOExceptione){e.printStackTrace();}}publicvoiddraw(Graphicsg){// 画飞机图片g.drawImage(feijiImage,x,y,null);// 飞机移动publicvoidmove(){if(isUP&&!isDown&&!isLeft&&!isRight){// 上y=y-5;}elseif(!isUP&&isDown&&!isLeft&&!isRight){// 下y=y+5;}elseif(!isUP&&!isDown&&isLeft&&!isRight){ // 左x=x-5;// 右上x=x+5;y=y-5;}elseif(!isUP&&isDown&&!isLeft&&isRight){ // 右下x=x+5;y=y+5;}}booleanisUP=false;nt.VK_A){isLeft=true;}elseif(keyCode==KeyEvent.VK_UP||keyCode==KeyEvent .VK_W){isUP=true;}elseif(keyCode==KeyEvent.VK_DOWN||keyCode==KeyE vent.VK_S){isDown=true;isLeft=false;}elseif(keyCode==KeyEvent.VK_UP||keyCode==KeyEvent .VK_W){isUP=false;}elseif(keyCode==KeyEvent.VK_DOWN||keyCode==KeyE vent.VK_S){isDown=false;}}packagecom;importimportimportimportimportimportpublicclassPower{ImagePowerImage=null;publicvoiddraw(Graphicsg){// 画血瓶图片g.drawImage(PowerImage,x,y,null); // 血瓶移动y++;}publicRectanglegetRectangle(){returnnewRectangle(x,y,PowerImage.getWidth(null),Pow erImage.getHeight(null));publicclassPlay01{staticintcount=0;ImagebgImage=null;//战机Planeplane=newPlane();//战机子弹List<MyZiDan>mzds=newArrayList<MyZiDan>(); //敌机List<Diji>dijis=newArrayList<Diji>();//敌机子弹intbgY1=0;intbgY2=-600;intfireTime=0;booleanflag=false;publicvoiddraw(Graphicsg){//画背景图片g.drawImage(bgImage,0,bgY1,null);bgY1+=5;if(bgY1<=600){bgY1=0;}//添加子弹if(isFire1==true&&flag==false){if(fireTime%8==0){mzds.add(newMyZiDan(plane.x+25,plane.y+0));}fireTime++;}if(isFire1==true&&flag==true){ if(fireTime%4==0){Dijidj=dijis.get(i);if(dj.x<-100){dijis.remove(i);}}//抽奖:添加敌机if((int)(Math.random()*20)==5){ dijis.add(newDiji());}//抽奖:添加血瓶for(inti=0;i<powers.size();i++){Powerpower=powers.get(i);power.draw(g);}//画敌机for(inti=0;i<dijis.size();i++){Dijidj=dijis.get(i);dj.draw(g);}//画飞机if(plane.lifeCount<1){PlaneStatus.playStatus=-1;} }}//判断战机和血瓶相撞for(inti=0;i<gifts.size();i++){//先得到每一个血瓶Giftgift=gifts.get(i);Rectangler1=gift.getRectangle();Rectangler2=plane.getRectangle();if(r1.intersects(r2)){if(r1.intersects(r2)){powers.remove(i);flag=true;}}//判断敌机在中弹for(inti=0;i<mzds.size();i++){//得到每个战机子弹MyZiDanmyzidan=mzds.get(i);Rectangler1=myzidan.getRectangle();booleanisFire1=false;booleanisFire2=false; publicvoidkeyPressed(KeyEvente){plane.keyPressed(e);if(e.getKeyCode()==KeyEvent.VK_J){isFire1=true;}/*if(e.getKeyCode()==KeyEvent.VK_K){ isFire2=true;}*/for(inti=0;i<dijis.size();i++)dijis.remove(i);}}}packagecom;importimportimportimporte.printStackTrace();}}publicvoiddraw(Graphicsg){g.drawImage(obg,0,0,null);g.drawImage(ng,120,100,null);g.setColor(Color.black);g.setFont(newFont("幼圆",Font.BOLD,40));g.drawString("游戏结束啦!",200,600);}publicclassMainFrameextendsJFrame{Beforebefore=newBefore();Play01play01=newPlay01();Overover=newOver();publicMainFrame(){// 设置标题this.setTitle("让子弹飞一会~");// 设置大小this.setSize(600,800);// 定位居中before.keyPressed(e);}elseif(PlaneStatus.playStatus==1){play01.keyPressed(e);}elseif(PlaneStatus.playStatus==-1){over.keyPressed(e);}}@Override publicvoidkeyReleased(KeyEvente){ if(PlaneStatus.playStatus==0){try{Thread.sleep(20);}catch(InterruptedExceptione){e.printStackTrace();}}}}.start();// 显示g.drawImage(bufferImage,0,0,null);}publicvoiddraw(Graphicsg){if(PlaneStatus.playStatus==0){before.draw(g);}elseif(PlaneStatus.playStatus==1){ play01.draw(g);}elseif(PlaneStatus.playStatus==-1){ over.draw(g);}ImagezidanImage=null;intx;inty;publicMyZiDan(intx,inty){this.x=x;this.y=y;try{zidanImage=.getResourceAsStream("images/zidan.png"));}catch(IOExceptione){mage.getHeight(null));}}packagecom;importimportimportimportimportimport}catch(IOExceptione){e.printStackTrace();}}publicvoiddraw(Graphicsg){// 画敌机图片g.drawImage(dijiImage,x,y,null); // 敌机移动if(r==1){y+=4;packagecom;importimportimportimportimportimportpublicclassGift{ImageGiftImage=null;intx=20;g.drawImage(GiftImage,x,y,null); // 血瓶移动y++;}publicRectanglegetRectangle(){returnnewRectangle(x,y,GiftImage.getWidth(null),GiftIma ge.getHeight(null));}}this.x=x;this.y=y;fangxiang=(int)(Math.random()*5);//0~7try{zidanImage=.getResourceAsStream("images/dijizidan.jpg"));}catch(IOExceptione){e.printStackTrace();}// 左x=x-2;}elseif(fangxiang==2){// 右x=x+2;}elseif(fangxiang==3){ // 左下x=x-2;y=y+2;}elseif(fangxiang==4){importimportimportimportimportimportimport//游戏开始之前publicclassBefore{Imagebg=null;e.printStackTrace();}}inttime=0;publicvoiddraw(Graphicsg){if(PlaneStatus.roleNum==1){//画妹妹g.drawImage(bg,0,0,null);g.drawImage(wfeiji,260,600,null);g.drawImage(kdiji1,200,50,null);g.setColor(Color.YELLOW);g.setFont(newFont("幼圆",Font.BOLD,30)); if(time<=10){g.drawString("[Enter]>>",50,750);}elseif(time<=20){g.drawString("[Enter]>>",50,750);}elseif(time<=30){g.drawString("[Enter]>>",50,750);if(time==30){time=0;互换}}publicvoidkeyReleased(KeyEvente){}}。
飞机大战(完整代码)
飞机大战(完整代码)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语言飞机大战源码
#include<iostream>#include<>#include<>#include<>#include<string>using namespace std;/*=============== all the structures ===============*/ typedef struct Frame{COORD position[2];int flag;}Frame;/*=============== all the functions ===============*/ void SetPos(COORD a)if<=[1].X)if>=[0].Y)if<=[0].Y)return true;return false;}void printCoord(COORD a){cout <<"( "<<<<" , "<<<<" )"; }void printFrameCoord(Frame a){printCoord[0]);cout <<" - ";printCoord[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<<"简单敌人有着较慢的移动速度。
飞机大战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语言飞机大战源码
#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 控制战机移动。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
offset temp3(-1,0);
oset = temp3;
}
if ((c == 'd' || c=='D' ) && planeBody[4].x <= M-4)
{
offset temp4(1,0);
oset = temp4;
}
SetPlanePos(oset);
}
}
//根据随机数,飞机移动(随机数为0-3四种情况,即四个方向)
#include <IOSTREAM>
#include <algorithm>
#include <TIME.H>
#include <CONIO.H>
#include <WINDOWS.H>
#include "bullet.h"
#include "plane.h"
#include "pos.h"
using namespace std;
void move()
{
if (bulletDirc == 'w' || bulletDirc == 'W')
{
bulletPos.y -=2;
}
if (bulletDirc == 's' || bulletDirc == 'S')
{
bulletPos.y +=2;
}
if (bulletDirc == 'a' || bulletDirc == 'A')
planeBody[0]=pos0;
planeBody[1]=pos1;
planeBody[2]=pos2;
planeBody[3]=pos3;
planeBody[4]=pos4;
planeBody[5]=pos5;
planeBody[6]=pos6;
planeBody[7]=pos7;
planeBody[8]=pos8;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////pos.h
#ifndef _POS_
#define _POS_
//节点,表示飞机或子弹
class pos
{
public:
pos(int a = 0,int b = 0):x(a),y(b){}
pos(const pos &b) {x=b.x,y=b.y;}
public:
bool operator==(pos a) const
{
return x==a.x && y==a.y;
{
bulletPos.x -=2;
}
if (bulletDirc == 'd' || bulletDirc == 'D')
{
bulletPos.x +=2;
}
}
//子弹到达边界
bool OnBorder() const
{
if( bulletPos.x >= M-3 || bulletPos.x <= 2 || bulletPos.y >= M-3 || bulletPos.y <= 2 )
////////plane.h
#include "pos.h"
#include <algorithm>
#include <IOSTREAM>
using namespace std;
//??
#define M 23
extern void gotoXY(pos s);
#ifndef _PLANE_
#define _PLANE_
#include "plane.h"
#include "pos.h"
#include <IOSTREAM>
using namespace std;
#ifndef _BULLET_
#define _BULLET_
//前置声明
class plane ;
//子弹
class bullet
{
public:
//子弹移动
//完全没什么优化的程序,中间数据一大堆....
//背景宽度
#define M 23
//初始化背景
void initWall()
{
int wall[M][M]={{0}};
cout << " ";
}
}
}
//设置飞机位置
void SetPlanePos(offset a)
{
for(int b=0;b<9;b++)
{
planeBody[b].x +=a.x;
planeBody[b].y +=a.y;
}
}
public:
//根据中心位置生成飞机
plane(pos p)
{
pos pos0(p.x-1,p.y-1),pos1(p.x,p.y-1),pos2(p.x+1,p.y-1),pos3(p.x-1,p.y),pos4(p.x,p.y),pos5(p.x+1,p.y),pos6(p.x-1,p.y+1),pos7(p.x,p.y+1),pos8(p.x+1,p.y+1);
cout << " ";
gotoXY(p32+planeBody[8] );
cout << " ";
}
}
if (planeDirc == 'd' || planeDirc == 'D')
{
gotoXY(planeBody[2]);
cout << " ";
gotoXYΒιβλιοθήκη planeBody[3]);cout << " ";
if (planeBody[4].y > 2)
{
pos p20(0,-1),p22(0,-1);
gotoXY(p20 + planeBody[0]);
cout << " ";
gotoXY( p22+planeBody[2]);
cout << " ";
}
}
if (planeDirc == 'a' || planeDirc == 'A')
//飞机
class plane
{
public:
//偏移量
typedef pos offset;
//根据输入,飞机移动
void move(char c)
{
if (planeDirc != c)
planeDirc =c;
else
{
offset oset;
if ((c == 'w' || c=='W' ) && planeBody[4].y >= 3)
~bullet(){}
public:
//子弹位置
pos bulletPos;
//子弹生成以后的方向(直至子弹消失前方向都是一定的)
char bulletDirc;
};
#endif
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////PFMain.cpp
planeDirc = 'w';
}
~plane()
{
}
public:
//机身
pos planeBody[9];
//飞机朝向(W,S,A,D)
char planeDirc;
};
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////bullet.h
{
temp.x +=2;
}
if (bulletDirc == 'd' || bulletDirc == 'D')
{
temp.x -=2;
}
gotoXY(temp);
cout << " ";
}
}
public:
//根据飞机生成子弹
bullet(plane &p):bulletPos(p.planeBody[4]),bulletDirc(p.planeDirc) {}
cout << " ";
gotoXY(planeBody[7]);
cout << " ";