飞机大战程序代码

合集下载

python实例:利用pygame实现小游戏“飞机大战”

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语言飞机大战游戏的源码,包括了基本的界面、移动控制、碰撞检测和计分等功能。

```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;```这个源码实现了一个控制飞机射击敌人并计分的简单游戏。

飞机大战java源代码

飞机大战java源代码

package ;import java.awt. Color;import java・awt.Font;import java. awt. Graphics;import java・awt.1mage;import java.awt.Rectangle;import java・ awt・ event・ KeyEvent;import java・ io. IOException;import javax・ inuigeio. ImagelO;public class Plane {Image feijiImage = null;int x = 300;int y = 700;int 1ifeCount=5;pub 1 ic Plane () {try {feijiImage 二Image10. read(Plane.class・getClsssLoader()・ getResourceAsStream("images/feiji. png ff));} catch (IOException e) {e. printStackTrace();}}public void draw(Graphics g) {// 画飞机图片g・drawlmage(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)*1 ifeCount, 10);g.setColor(Color・ blue);g. setFont (new Font (M幼圆",Font. BOLD, 30));g. drawString("Score:"+Play01. count, 20, 60);pub1ic void move(){if(isUP && !isDown && !isLeft && !isRight){// 上y=y-5;}else if (! islJP && 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 (! islIP && 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 &&右下x=x+5; y二y+5;boolean isUP = false;boolean isDown = false;boolean isLeft = false;boolean isRight = false;//据下pub1ic void keyPressed(KeyEvent e) { int keyCode = e. getKeyCodeO : !isLeft && isRight){//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 I 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. getKeyCodeO :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 I keyCode == KeyEvent. VK_W){ isUP=false;} else if (keyCode == KeyEvent. VK DOWN keyCode == KeyEvent. VK S){ isDown=false;}}public Rectangle getRectangle() {return new Rec tangle(x,y,feijilmage・ getWidth(null),feijiImage・ getHeight (null));}}package ;public class PlaneStatus {public static int roleNum = 1;publ ic static int playStatus = 0; // 0 游戏开始前1 第一关游戏结束}package ;import java. awt. Graphics;import java・awt・ Image;import java・swt.Rectangle;import java・ awt・ event・ KeyEvent;import java・ io. IOException;import javax・ inuigeio. ImsgelO;public class Power {Image PowerImage = null;int x = 20;int y = 0;public Power() {this, x二(int) (Math, random() *540) +20: try {Power Image 二ImagelO. read(Gift. class. getdassLoader ()・ getResourceAsStream(" images/power・ pnj?"));} catch (IOException e) {e.printStackTrace();}}public void draw(Graphics g) {// 画血瓶图片g. drawlmage(PowerImage, x, y. null):// 血瓶移动y++;}pub 1 ic Rectangle getRectangleO {returnnew Rectangle(x,y t Powei'Image・ getWidth(null),PowerImage・ getHeight(null)); }} package ;import java. awt. Graphics; import java・swt・ Image; import java・awt.Rectangle;import java・ awt・ event・ KeyEvent;import java・ io. IOException;import java .util. ArrayList;import java.util.List;import javax・ imageio. ImagelO;//第一关public class PlayOl {static int count=0;Image bglmage = nul1://战机Plane plane = new PlaneO ://战机子弹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 /\rrayList<Power>(): public PlayOl() { try {bglmage = Image10. read(Play01. class・getClassLoader()・ getResourceAsStream("images/bg 01. jpg"));} catch (IOException e) {e.printStackTrace();}}int bgYl = 0;int bgY2 = -600;int fireTime = 0;boolean flag=false;public void draw(Graphics g) {//画背景图片g. drawImage(bgImage, 0, bgY11 null):bgYl += 5;if (bgYl <= 600) {bgYl = 0;}g. drawImage(bgImage, 0. bgY2f 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・ removed);}}//添加子弹if (isFirel == true && flag==false) {if (fireTime % 8 == 0) {mzds.sdd(new MyZiDan(plane.x + 25, plane.y + 0)): } fireTime++;}if (isFirel== true && fl3g==true) {if (fireTime % 4 == 0) {mzds・3dd(new MyZiDan(plane. x +8. plane.y +0));mzds・3dd(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 < di jis. size(): i++) {Di ji dj = di jis. get (i):if (dj. x < -100) {dijis・ remove(i);}//抽奖:添加敌机if ((int) (Math, random() * 20) == 5) {di jis.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 < di jis. size() ; i++) {Diji dj = dijis. get (i):dj・ draw(g);}//画飞机plane・ draw(g);//判断战机相撞for (int i = 0; i < di jis. size(): i++) {//先得到每一个敌机Diji dj = dijis・get(i);Rectangle rl = dj. getRectangleO :Rectangle r2 = plane.getRectangleO; if (rl. intersects(r2)) {dijis・ remove(i);plane・ lifeCount = plane・ lifeCount 一1; if(plane. lifeCount>0) flag=false;if(plane. lifeCount<l){ PlaneStatus・pl3ySt3tus=-l; }}}//判断战机和血瓶相撞for (int i = 0; i < gifts. size(): i++) {//先得到每一个血瓶Gift gift = gifts・get(i);Rectangle rl = gift. getRectangle();Rectangle r2 = plane・getRectsngleO; if (rl. intersects(r2)) {gifts・ remove(i);if (plane.1ifeCount <5) {plane・ lifeCount = plane. lifeCount + 1: }}}////判断战机和Power相撞for (int i = 0; i < powers.size(); i++) {//先得到每一个powerPower power = powers・get(i);Rectangle rl = power. getRectangleO :Rectangle r2 = plane.getRectangleO; if (rl. intersects(r2)) {powers. remove(i):flag=true;}}//判断敌机在中弹for (int i = 0; i < mzds.size(); i++) {//得到每个战机子弹MyZiDan myzidan = mzds ・get(i);Rectangle rl = myzidan. getRectangleO : for (int j = 0; j < di jis. size() ; j++) { //每一个敌机Di ji di ji = di jis. get (j):Rectangle r2 = di ji. getRectangleO : if (rl. intersects(r2)) { mzds.remove(i); dijis ・ remove(j);}count++; }}}boolean boolean isFirel = false ;isFire2 = false ;public void keyPressed(KeyEvent e) { plane. keyPressed(e);if (e. getKeyCodeO == KeyEvent. VK J) { isFirel = true ;}/♦if (e. getKeyCodeO == KeyEvent. VK K) { isFire2 = true ;public void keyReleased(KeyEvent e) { plane ・ keyReleased(e);if (e. getKeyCodeO == KeyEvent. VK J) { isFirel = false ;fi reTime = 0;}/♦if (e. getKeyCodeO == KeyEvent. VK K) { isFire2 = false ;fireTime = 0; }*/if ( e. getKeyCodeO —KeyEvent. VK P) {for(int i=0; i<dijis.size();i++) di jis. remove(i);}package ;import java・swt.Color;import java・owt・Font;import java. awt. Graphics;import java.awt.1mage;import java・ awt・ event・ KeyEvent;import java・ io. IOException;import javax・ inuigeio. ImagelO;//游戏结束public class Over {Image obg=null;Image ng=nul1:public Over() {try {obgImage10. read(Before・ class・ getClassLoader()・ getResourceAsStream(n images/obg・jpg” ));ngI mage 10. read (Before ・ class ・ getClassLoader ()・ getResourceAsStreomC'inuiges/ng ・png"));} catch (IOException e) {e.printStackTrace();}}pub1ic void draw(Graphics g){g・drawlmage(obg, 0. 0. null);g. drawlmage(ng, 120,100. null);g.setColor(Color・ black);g. setFont (new Font (n幼圆Font. BOLD, 40));g. drawString(R游戏结束啦! ".200 ,600 );}public void keyPressed(KeyEvent e) {}public void keyReleased(KeyEvent e) {}}package ;import java.awt. Color;import java・swt.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():PlavOl playOl = new PlayOl():Over over = new Over ():public MainFrameO {// 设置标题this. setTitleC1' 让子弹飞一会、*);// 设置大小this.setSize(600, 800);// 定位居中this. setLocationRelativeTo(null);// 添加关闭操作this. setDefaultCloseOperation(JFrame.EXIT ON CLOSE):// 禁止重置大小zthis・ setResizable(false);// 添加键盘监听器KeyLi stener --> KeyAdapter this.addKeyListener(new KeyAdaptei-() {Overridepublic void keyPressed(KeyEvent e) { if(PlaneStatus. playStatus == 0) { before・keyPressed (e);}else if(PlaneStatus.playStatus =1) { playOl. keyPressed(e);}else if (PlaneStatus・ playStatus二=T) { over・ keyPressed(e);Overridepublic void keyReleased(KeyEvent e) { if (PlaneStatus. playStatus == 0){ before・ keyReleased(e);}else if(PlaneStatus.playStatus =1) { playOl. keyReleased(e);}else if (PlaneStatus・ playStatusHT) { 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) {bufferlmage = this・ cre3teIni8ge(600, 800):}Graphics g4Image = bufferimage・getGraphicsO: g4Image. setColor(Color.BLACK);g4Image. fillRect(0, 0. 600, 800);this・ draw(g41mage);g. drawImage(bufferImage, 0, 0, null);}public void draw(Graphics g){if(PlaneStatus. playStatus == 0){before・ draw(g);}else if(PlaneStatus.playStatus =1) {play0L draw(g);}else if (PlaneStatus・ pl3yStatus==T) {}over. draw(g);pub1ic static void main(String[] args) { new MoinFrame():}}package ;import java. awt. Graphics;import java.awt・ Inuige;import java.awt.Rectangle;import java・ io. IOException;import javax・ inuigeio. ImagelO;public class MyZiDan {Image zidanImage = null;int x ;int y ;public MyZiDan(int x,int y) {this・ x=x;this・ y=y;try {zidanImage 二Image10. read(MyZiDan.class・getClassLosder()・ getResourceAsStream("images/zidan・ png w));} catch (IOException e) {e. printStackTrace ();}}pub1ic void draw(Graphics g) {// 画我军子弹图片g. drawlmage(zidanlmage, x, y. null)://我的飞机子弹移动速度y-二20;}public Rectangle getRectangle() {returnnew Rectangle(x,y t zidanImage. getWidth(null),zidanlmage・ getHeight (null)); }package ;import java. awt. Graphics;import java・awt・ Image;import java・awt.Rectangle;import java・ awt・ event・ KeyEvent;import java・ io. IOException;import javax・ imageio. ImsgelO;public class Diji {Image dijiImage = null;int y = -20;int x = 10;//20 ~ 760int r;public Di ji () {this. x=(int) (Math, random()*540) +40:try {r = (int) (Math, random () *3)+1 :dijiImage = ImagelO. read(Diji・class. getClassLoader()・ getResource/XsStream(" images/di j i "+r+"・ png n)); } catch (IOException e) {e. “intStackTra ceO ;}}pub1ic void draw(Graphics g) {// 画敌机图片g・drawlmage(dijiImage, x, y, nul1):// 敌机移动if(r==l) {y+=4;}else if(r==2) {y+=4;}else if(r==3){y+=7:}}pub 1 ic Rectangle getRectangleO {return newRec tangle(x,y,d i j iImage. getWidth(nu11),dijiImage・ getHeight (nul1)); } }package ;import java. awt. Graphics;import java.awt・ Image;import java・owt.Rectangle;import java・ awt・ event・ KeyEvent;import java・ io. IOException;import javax・ inuigeio. ImagelO;public class Gift {Image Giftimage = null;int x = 20;int y = 0;pub 1 ic Gift () {this. x=(int) (Math, random()*540) +20:try {Gift Image = Image10. read(Gift・cl^ss・getClossLoader ()・ getResourceAsStream("images/blood・ png"));} catch (IOException e) {e.printStackTrace();}}public void draw(Graphics g) {// 画血瓶图片g. draw I mage (G i f 11 mage t x, y, null):// 血瓶移动y++;}public Rectangle getRectangleO {return new Rectangle(x,y,GiftImage・ getWidth(null).Giftimage・ getHeight(null));package ;import java. awt. Graphics;import java.awt.1mage;import java.awt.Rectangle;import java・ io. IOException;import javax・ inuigeio. ImagelO;public class DijiZiDan {Image zidanImage = null;int x ;int y ;int fangxiang =0;pub1ic DijiZiDan(int x,int y) {this・ x=x;this・ y二y;fangxiang = (int) (Math•匸andom()*5) ;//0、7 try {zidanImage = Image10. read(DijiZiDan.class・getClassLoaderO・ getResourceAsStreamCiniages/dijizidan. jpg"));} catch (IOException e) {e.printStackTrace();}}pub1ic void draw(Graphics g) {// 画敌机子弹图片g. drawImage(zidanlmage, x, y, null);//移动this・ move():}public void move(){if (fangxiang==0){// 下y=y+2;}else if(fangxiang==l) {// 左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 t zidanImage. getWidth(null),zidanlmage・ getHeight(null));}} package ;import java・awt.Color;import java・nwt.Font;import java. awt. Graphics;import java.awt・ Image;import java・ awt・ event・ KeyEvent;import java・ io. IOException;import javax・ imageio. ImagelO;//游戏开始之前public class Before {Image bg=null;Image wfeiji二null;Image kdiji1二null;Image kdiji2二null;Image kdiji3=null;public Before() {try {bg = Image10. read(Before・ class・ getClassLoader()・ getResourceAsStream(n images/bg・ jpg H));wt e1j iImage 10. read (Before ・ class ・ getClassLoader ()・ get Resource?\sS tream (n i mages/f e i j i1. png"));kdijil= Image10. read(Before ・ class ・ getClassLoader()・ getResourceAsStream(n images/kdi ji 01 .png"));kdiji2= Image10. read(Before ・ class ・ getClassLoader()・ getResource/\sStream(n images/kdi ji 02 .png"));kdiji3= Image 10. read (Before ・ class ・ getClassLoader ()・ getResource/XsSti'eam (n i mages/kd i j i03 .png"));} catch (IOException e) {e. pr i ntStackTrace ();}}int time^O ;pub1ic void draw(Graphics g) {if (PlaneStatus. roleNum^^l) {//画妹妹 g. drawlmage(bg, 0, 0, null);g. drawImage(wfeiji t 260, 600, null)g. drawImage(kdiji11g. drawImage(kdiji11g. drawlmage(kdiji1,g. drawlmage(kdiji1,g. drawlmage(kdiji2,g. drawlmage(kdiji2,g. drawlmage(kdiji2,g. drawlmage(kdiji3,g. drawlmage(kdiji3,g. drawlmage(kdiji3,}// 画回车符 time++;g. setColor(Color. YELLOW); 200 • 50, null); 400. 50, null); 150, 480, null); 400, 480, null); 100, 200, null); 300. 100, null); 480 • 2001 null); 300. 300, null); 70. 400, null); 510. 400, null);g. setFont (new Font(w幼圆Font. BOLD・ 30)): if (time<=10){g. drawString(w[Enter]»n, 50, 750);}else if(time<=20) {g. drawString(" [Enter] »n. 50, 750);}else if(time<=30) {g. drawString(" [Enter] »n■50, 750);if(time==30){time=0;}}}public void keyPressed(KeyEvent e) {int keyCode = e. getKeyCodeO ;if(keyCode == KeyEvent. VK ENTER){PlaneStatus・ playStatus=l:}if(keyCode ==KeyEvent. VK LEFT keyCode==KeyEvent. VK RIGHT ){ PlaneStatus. roleNum = 3-PlaneStatus. roleNum;//1^2 互换 }}pub1ic void keyReleased(KeyEvent e) {}。

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。

python实现飞机大战游戏

python实现飞机大战游戏

python实现飞机⼤战游戏飞机⼤战(Python)代码分为两个python⽂件,⼯具类和主类,需要安装pygame模块,能完美运⾏(⽹上好多不完整的,调试得⼼累。

实现出来,成就感还是满满的),如图所⽰:完整代码如下:1.⼯具类plane_sprites.pyimport 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):# 在屏幕的垂直⽅向上移动self.rect.y += self.speedclass Background(GameSprite):"""游戏背景精灵"""def __init__(self, is_alt=False):super().__init__("C:/Users/Administrator/Desktop/background.png")# 1. 调⽤⽗类⽅法实现精灵的创建(image/rect/speed) if is_alt:# 2. 判断是否是交替图像,如果是,需要设置初始位置self.rect.y = -self.rect.heightdef update(self):super().update()# 1. 调⽤⽗类的⽅法实现if self.rect.y >= SCREEN_RECT.height:# 2. 判断是否移出屏幕,如果移出屏幕,将图像设置到屏幕的上⽅self.rect.y = -self.rect.heightclass Enemy(GameSprite):"""敌机精灵"""def __init__(self):super().__init__("C:/Users/Administrator/Desktop/enemy1.png")# 1. 调⽤⽗类⽅法,创建敌机精灵,同时指定敌机图⽚ self.speed = random.randint(1, 3)# 2. 指定敌机的初始随机速度 1 ~ 3self.rect.bottom = 0# 3. 指定敌机的初始随机位置max_x = SCREEN_RECT.width - self.rect.widthself.rect.x = random.randint(0, max_x)def update(self):super().update()# 1. 调⽤⽗类⽅法,保持垂直⽅向的飞⾏# 2. 判断是否飞出屏幕,如果是,需要从精灵组删除敌机if self.rect.y >= SCREEN_RECT.height:self.kill()# print("飞出屏幕,需要从精灵组删除...")# kill⽅法可以将精灵从所有精灵组中移出,精灵就会被⾃动销毁def __del__(self):# print("敌机挂了 %s" % self.rect)passclass Hero(GameSprite):"""英雄精灵"""def __init__(self):super().__init__("C:/Users/Administrator/Desktop/me1.png", 0)self.rect.centerx = SCREEN_RECT.centerxself.rect.bottom = SCREEN_RECT.bottom - 120self.bullets = pygame.sprite.Group()def update(self):self.rect.x += self.speedif self.rect.x < 0:self.rect.x = 0elif self.rect.right > SCREEN_RECT.right:self.rect.right = SCREEN_RECT.rightdef fire(self):print("发射⼦弹...")for i in (0, 1, 2):bullet = Bullet()bullet.rect.bottom = self.rect.y - i * 20bullet.rect.centerx = self.rect.centerxself.bullets.add(bullet)class Bullet(GameSprite):"""⼦弹精灵"""def __init__(self):super().__init__("C:/Users/Administrator/Desktop/bullet1.png", -2)def update(self):super().update()if self.rect.bottom < 0:self.kill()def __del__(self):print("⼦弹被销毁...")2.主类plane_main.pyimport pygamefrom plane_sprites import *class PlaneGame(object):"""飞机⼤战主游戏"""def __init__(self):print("游戏初始化")self.screen = pygame.display.set_mode(SCREEN_RECT.size)self.clock = pygame.time.Clock()self.__create_sprites()pygame.time.set_timer(CREATE_ENEMY_EVENT, 1000)pygame.time.set_timer(HERO_FIRE_EVENT, 500)def __create_sprites(self):bg1 = Background()bg2 = Background(True)self.back_group = pygame.sprite.Group(bg1, bg2)self.enemy_group = pygame.sprite.Group()self.hero = Hero()self.hero_group = pygame.sprite.Group(self.hero)def start_game(self):print("游戏开始...")while True:self.clock.tick(FRAME_PER_SEC)self.__event_handler()self.__check_collide()self.__update_sprites()pygame.display.update()def __event_handler(self):for event in pygame.event.get():if event.type == pygame.QUIT:PlaneGame.__game_over()elif event.type == CREATE_ENEMY_EVENT:# print("敌机出场...")# 创建敌机精灵enemy = Enemy()self.enemy_group.add(enemy)elif event.type == HERO_FIRE_EVENT:self.hero.fire()# elif event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:# print("向右移动...")keys_pressed = pygame.key.get_pressed()if keys_pressed[pygame.K_RIGHT]:self.hero.speed = 2elif keys_pressed[pygame.K_LEFT]:self.hero.speed = -2else:self.hero.speed = 0def __check_collide(self):for event in pygame.event.get():if event.type == pygame.QUIT:PlaneGame.__game_over()elif event.type == CREATE_ENEMY_EVENT:enemy = Enemy()self.enemy_group.add(enemy)elif event.type == HERO_FIRE_EVENT:self.hero.fire()keys_pressed = pygame.key.get_pressed()if keys_pressed[pygame.K_RIGHT]:self.hero.speed = 2elif keys_pressed[pygame.K_LEFT]:self.hero.speed = -2else:self.hero.speed = 0def __check_collide(self):pygame.sprite.groupcollide(self.hero.bullets, self.enemy_group, True, True)enemies = pygame.sprite.spritecollide(self.hero, self.enemy_group, True)if len(enemies) > 0:self.hero.kill()PlaneGame.__game_over()def __update_sprites(self):self.back_group.update()self.back_group.draw(self.screen)self.enemy_group.update()self.enemy_group.draw(self.screen)self.hero_group.update()self.hero_group.draw(self.screen)self.hero.bullets.update()self.hero.bullets.draw(self.screen)@staticmethoddef __game_over():print("游戏结束")pygame.quit()exit()if __name__ == '__main__':game = PlaneGame()game.start_game()更多关于python游戏的精彩⽂章请点击查看以下专题:更多有趣的经典⼩游戏实现专题,分享给⼤家:以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

python飞机大战的核心语句

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版)简介使⽤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”弹出窗⼝,即可对其操作游玩。

Python小游戏代码:飞机大战(超详细)

Python小游戏代码:飞机大战(超详细)

Python⼩游戏代码:飞机⼤战(超详细)我⽤的是pycharm,⼤家可以⽤别的Python编辑器。

创建⼀个新的⽂件夹,把图⽚的⽂件夹导⼊,图⽚的链接我放下⾯了,⼤家⾃取。

提取码:Leo1在刚才的⽂件夹⾥新建Python⽂件,输⼊以下代码# coding:utf-8import pygame, sys, random, time, easyguifrom pygame.locals import *# 初始化pygame环境pygame.init()# 创建⼀个长宽分别为480/650窗⼝canvas = pygame.display.set_mode((480, 650))canvas.fill((255, 255, 255))# 设置窗⼝标题pygame.display.set_caption("飞机⼤战")bg = pygame.image.load("images/bg1.png")enemy1 = pygame.image.load("images/enemy1.png")enemy2 = pygame.image.load("images/enemy2.png")enemy3 = pygame.image.load("images/enemy3.png")b = pygame.image.load("images/bullet1.png")h = pygame.image.load("images/hero.png")#开始游戏图⽚startgame=pygame.image.load("images/startGame.png")#logo图⽚logo=pygame.image.load("images/LOGO.png")#暂停图⽚pause = pygame.image.load("images/game_pause_nor.png")# 添加时间间隔的⽅法def isActionTime(lastTime, interval):if lastTime == 0:return TruecurrentTime = time.time()return currentTime - lastTime >= interval# 定义Sky类class Sky():def __init__(self):self.width = 480self.height = 852self.img = bgself.x1 = 0self.y1 = 0self.x2 = 0self.y2 = -self.height# 创建paint⽅法def paint(self):canvas.blit(self.img, (self.x1, self.y1))canvas.blit(self.img, (self.x2, self.y2))# 创建step⽅法def step(self):self.y1 = self.y1 + 1self.y2 = self.y2 + 1if self.y1 > self.height:self.y1 = -self.heightif self.y2 > self.height:self.y2 = -self.height# 定义⽗类FlyingObjectclass FlyingObject(object):def __init__(self, x, y, width, height, life, img):self.x = xself.y = yself.width = widthself.height = heightself.life = lifeself.img = img# 敌飞机移动的时间间隔stTime = 0self.interval = 0.01# 添加删除属性self.canDelete = False# 定义paint⽅法def paint(self):canvas.blit(self.img, (self.x, self.y))# 定义step⽅法def step(self):# 判断是否到了移动的时间间隔if not isActionTime(stTime, self.interval):returnstTime = time.time()# 控制移动速度self.y = self.y + 2# 定义hit⽅法判断两个对象之间是否发⽣碰撞def hit(self, component):c = componentreturn c.x > self.x - c.width and c.x < self.x + self.width and \ c.y > self.y - c.height and c.y < self.y + self.height# 定义bang⽅法处理对象之间碰撞后的处理def bang(self, bangsign):# 敌机和英雄机碰撞之后的处理if bangsign:if hasattr(self, 'score'):GameVar.score += self.scoreif bangsign == 2:self.life -= 1# 设置删除属性为Trueself.canDelete = True# 敌机和⼦弹碰撞之后的处理else:self.life -= 1if self.life == 0:# 设置删除属性为Trueself.canDelete = Trueif hasattr(self, 'score'):GameVar.score += self.score# 定义outOfBounds⽅法判断对象是否越界def outOfBounds(self):return self.y > 650# 重构Enemy类class Enemy(FlyingObject):def __init__(self, x, y, width, height, type, life, score, img):FlyingObject.__init__(self, x, y, width, height, life, img)self.type = typeself.score = score# 重构Hero类class Hero(FlyingObject):def __init__(self, x, y, width, height, life, img):FlyingObject.__init__(self, x, y, width, height, life, img)self.x = 480 / 2 - self.width / 2self.y = 650 - self.height - 30self.shootLastTime = 0self.shootInterval = 0.3def shoot(self):if not isActionTime(self.shootLastTime, self.shootInterval):returnself.shootLastTime = time.time()GameVar.bullets.append(Bullet(self.x + self.width / 2 - 5, self.y - 10, 10, 10, 1, b))# 重构Bullet类class Bullet(FlyingObject):def __init__(self, x, y, width, height, life, img):FlyingObject.__init__(self, x, y, width, height, life, img)def step(self):self.y = self.y - 2# 重写outOfBounds⽅法判断⼦弹是否越界def outOfBounds(self):return self.y < -self.height# 创建componentEnter⽅法def componentEnter():# 随机⽣成坐标x = random.randint(0, 480 - 57)x1 = random.randint(0, 480 - 50)x2 = random.randint(0, 480 - 100)# 根据随机整数的值⽣成不同的敌飞机n = random.randint(0, 9)# 判断是否到了产⽣敌飞机的时间if not isActionTime(stTime, GameVar.interval):returnstTime = time.time()if n <= 7:GameVar.enemies.append(Enemy(x, 0, 57, 45, 1, 1, 1, enemy1))elif n == 8:GameVar.enemies.append(Enemy(x1, 0, 50, 68, 2, 3, 5, enemy2))elif n == 9:if len(GameVar.enemies) == 0 or GameVar.enemies[0].type != 3:GameVar.enemies.insert(0, Enemy(x2, 0, 100, 153, 3, 10, 20, enemy3))# 创建画组件⽅法def componentPaint():# 判断是否到了飞⾏物重绘的时间if not isActionTime(GameVar.paintLastTime, GameVar.paintInterval):returnGameVar.paintLastTime = time.time()# 调⽤sky对象的paint⽅法GameVar.sky.paint()for enemy in GameVar.enemies:enemy.paint()# 画出英雄机GameVar.hero.paint()# 画出⼦弹对象for bullet in GameVar.bullets:bullet.paint()# 写出分数和⽣命值renderText('SCORE:' + str(GameVar.score), (0, 0))renderText('LIFE:' + str(GameVar.heroes), (380, 0))# 创建组件移动的⽅法def componentStep():# 调⽤sky对象的step⽅法GameVar.sky.step()for enemy in GameVar.enemies:enemy.step()# 使⼦弹移动for bullet in GameVar.bullets:bullet.step()# 创建删除组件的⽅法def componentDelete():for enemy in GameVar.enemies:if enemy.canDelete or enemy.outOfBounds():GameVar.enemies.remove(enemy)for bullet in GameVar.bullets:if bullet.canDelete or bullet.outOfBounds():GameVar.bullets.remove(bullet)# 从列表中删除英雄机if GameVar.hero.canDelete == True:GameVar.heroes -= 1if GameVar.heroes == 0:#easygui.msgbox('游戏结束')GameVar.state = GameVar.STATES['GAME_OVER']else:GameVar.hero = Hero(0, 0, 60, 75, 1, h)# 定义GameVar类class GameVar():sky = Sky()enemies = []# 产⽣敌飞机的时间间隔lastTime = 0interval = 1.5# 重绘飞⾏物的时间间隔paintLastTime = 0paintInterval = 0.04# 创建英雄机对象hero = Hero(0, 0, 60, 75, 1, h)# 创建列表存储⼦弹对象bullets = []# 添加分数和⽣命值score = 0heroes = 3#创建字典存储游戏状态STATES = {'START':1,'RUNNING':2,'PAUSE':3,'GAME_OVER':4}state = STATES['START']print(GameVar.state)# 定义renderText⽅法def renderText(text, position):my_font = pygame.font.SysFont("微软雅⿊", 40)newText = my_font.render(text, True, (255, 255, 255))canvas.blit(newText, position)# 创建游戏退出事件处理⽅法def handleEvent():for event in pygame.event.get():if event.type == pygame.QUIT or event.type == KEYDOWN and event.key == K_ESCAPE: pygame.quit()sys.exit()#点击⿏标开始游戏if event.type == MOUSEBUTTONDOWN and event.button == 1:if GameVar.state == GameVar.STATES['START']:GameVar.state = GameVar.STATES['RUNNING']# 英雄机跟随⿏标移动if event.type == MOUSEMOTION:if GameVar.state == GameVar.STATES['RUNNING']:GameVar.hero.x = event.pos[0] - GameVar.hero.width / 2GameVar.hero.x = event.pos[0] - GameVar.hero.width / 2 GameVar.hero.y = event.pos[1] - GameVar.hero.height / 2# 调⽤⽅法判断⿏标移⼊画布if isMouseOver(event.pos[0], event.pos[1]):#print('⿏标移⼊事件')if GameVar.state == GameVar.STATES['PAUSE']:GameVar.state = GameVar.STATES['RUNNING']# 调⽤⽅法判断⿏标移出画布if isMouseOut(event.pos[0], event.pos[1]):#print('⿏标移出事件')if GameVar.state == GameVar.STATES['RUNNING']:GameVar.state = GameVar.STATES['PAUSE']# 创建⽅法判断⿏标移出画布def isMouseOut(x, y):if x >= 479 or x <= 0 or y >= 649 or y <= 0:return Trueelse:return False# 创建⽅法判断⿏标移⼊画布def isMouseOver(x, y):if x > 1 and x < 479 and y > 1 and y < 649:return Trueelse:return False# 创建checkHit⽅法def checkHit():# 判断英雄机是否与每⼀架敌飞机发⽣碰撞for enemy in GameVar.enemies:if GameVar.hero.hit(enemy):# 敌机和英雄机调⽤bang⽅法enemy.bang(1)GameVar.hero.bang(2)# 判断每⼀架敌飞机是否与每⼀颗⼦弹发⽣碰撞for bullet in GameVar.bullets:if enemy.hit(bullet):# 敌机和⼦弹调⽤bang⽅法enemy.bang(0)bullet.bang(0)#创建controlState⽅法控制游戏状态def controlState():#游戏开始状态if GameVar.state == GameVar.STATES['START']:GameVar.sky.paint()GameVar.sky.step()canvas.blit(logo,(-40,200))canvas.blit(startgame,(150,400))#游戏运⾏状态elif GameVar.state == GameVar.STATES['RUNNING']:componentEnter()componentPaint()componentStep()checkHit()GameVar.hero.shoot()componentDelete()#游戏暂停状态elif GameVar.state == GameVar.STATES['PAUSE']:componentPaint()componentPaint()GameVar.sky.step()canvas.blit(pause,(0,0))#游戏结束状态elif GameVar.state == GameVar.STATES['GAME_OVER']: componentPaint()GameVar.sky.step()renderText('gameOver',(180,320))while True:#调⽤控制游戏状态的⽅法controlState()# 刷新屏幕pygame.display.update()# 调⽤handleEvent⽅法handleEvent()# 延迟处理pygame.time.delay(15)运⾏程序就可以了!。

飞机大战 java 源代码

飞机大战 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) {}}。

飞机大战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语言飞机大战代码

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语言飞机大战的代码,代码的功能是控制一架飞机位置并且记分,玩家通过按键来控制飞机的位置,飞机撞到边界则游戏结束。

飞机大战(完整代码)

飞机大战(完整代码)

飞机大战(完整代码)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键)和射击(空格键)功能。

python飞机大战源码和素材

python飞机大战源码和素材

python飞机⼤战源码和素材python飞机⼤战素材及代码已上传百度云,链接: 提取码: pqxnplane_main1 import pygame2 from plane_sprites import *345 class PlaneGame(object):6 """飞机⼤战主游戏"""78 def __init__(self):9 print("游戏初始化")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()1718 # 4.设置定时器事件——创建敌机 1S19 pygame.time.set_timer(CREATE_ENEMY_EVENT, 1000)20 pygame.time.set_timer(HERO_FIRE_EVENT, 500)2122 # 定义精灵和精灵组23 def __create_sprites(self):24 # 创建背景精灵和精灵组25 bg1 = Background()26 bg2 = Background(True)27 # bg2起始位置在bg1的上⽅28 # bg2.rect.y = -bg2.rect.height2930 self.back_group = pygame.sprite.Group(bg1, bg2)3132 # 创建敌机的精灵组33 self.enemy_group = pygame.sprite.Group()3435 # 创建英雄的精灵和精灵组36 self.hero = Hero()37 self.hero_group = pygame.sprite.Group(self.hero)3839 # 游戏循环40 def start_game(self):41 print("游戏开始...")4243 while True:44 # 1.设置刷新帧率45 self.clock.tick(FRAME_PER_SEC)46 # 2.事件监听47 self.__even_handler()48 # 3.碰撞检测49 self.__check_collide()50 # 4.更新/绘制精灵组51 self.__update_sprites()52 # 5.更新屏幕显⽰53 pygame.display.update()5455 pass5657 # 定义事件监听函数58 def __even_handler(self):59 for event in pygame.event.get():6061 # 判断是否退出游戏62 if event.type == pygame.QUIT:63 PlaneGame.__game_over()64 elif event.type == CREATE_ENEMY_EVENT:65 # print("敌机出场...")66 # 创建敌机精灵67 enemy = Enemy()6869 # 将敌机精灵添加到敌机精灵组70 self.enemy_group.add(enemy)71 elif event.type == HERO_FIRE_EVENT:72 self.hero.fire()73 # 直接判断键盘按键不能持续的获取按键事件74 # elif event.type == pygame.KEYDOWN and event.type == pygame.K_RIGHT:75 # print("向右移动...")7677 # 使⽤键盘模块提供的⽅法获取键盘按键——键盘模块可以持续的获取键盘按键78 keys_pressed = pygame.key.get_pressed()79 # 判断元祖中对应的按键索引值80 if keys_pressed[pygame.K_RIGHT] or keys_pressed[pygame.K_d]:81 self.hero.rect.x += 282 elif keys_pressed[pygame.K_LEFT] or keys_pressed[pygame.K_a]:83 self.hero.rect.x -= 284 elif keys_pressed[pygame.K_UP] or keys_pressed[pygame.K_w]:85 self.hero.rect.y -= 286 elif keys_pressed[pygame.K_DOWN] or keys_pressed[pygame.K_s]:87 self.hero.rect.y += 288 else:89 self.hero.speed = 09091 # 定义碰撞检测92 def __check_collide(self):9394 # 1.⼦弹摧毁敌机—— groupcollide可以判断两个精灵组之间是否碰撞95 pygame.sprite.groupcollide(self.hero.bullets, self.enemy_group, True, True)9697 # 敌机撞毁英雄——spritecollide可以判断精灵和精灵组之间是否碰撞98 enemies = pygame.sprite.spritecollide(self.hero, self.enemy_group, True)99100 # 判断列表是否有内容101 if len(enemies) > 0:102103 # 让英雄牺牲104 self.hero.kill()105106 # 结束游戏107 PlaneGame.__game_over()108109 # 定义精灵组调⽤update()和draw()⽅法实现屏幕更新110 def __update_sprites(self):111112 self.back_group.update()113 self.back_group.draw(self.screen)114 self.enemy_group.update()115 self.enemy_group.draw(self.screen)116 self.hero_group.update()117 self.hero_group.draw(self.screen)118 self.hero.bullets.update()119 self.hero.bullets.draw(self.screen)120121 # 游戏结束122 @staticmethod123 def __game_over():124 print("游戏结束...")125126 pygame.quit()127 exit()128129130 if __name__ == '__main__':131132 # 创建游戏对象133 game = PlaneGame()134135 # 启动游戏136 game.start_game()plane_sprites1 import random2 import 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 + 1121314 class GameSprite(pygame.sprite.Sprite):15 """飞机⼤战游戏精灵"""1617 def __init__(self, image_name, speed=1):1819 # 调⽤⽗类的初始化⽅法20 super().__init__()2122 # 定义对象的属性23 self.image = pygame.image.load(image_name)24 self.rect = self.image.get_rect()25 self.speed = speed2627 def update(self):2829 # 在屏幕的垂直⽅向上移动30 self.rect.y += self.speed313233 class Background(GameSprite):34 """游戏背景精灵"""35 def __init__(self, is_alt=False):3637 # 1.调⽤⽗类⽅法实现精灵的创建38 super().__init__("./images/background.png")3940 if is_alt:41 self.rect.y = -self.rect.height4243 def update(self):4445 # 1.调⽤⽗类的⽅法实现46 super().update()4748 # 2.判断是否移出屏幕,如果移出,将图像移⾄屏幕上⽅49 if self.rect.y >= SCREEN_RECT.height:50 self.rect.y = -self.rect.height515253 class Enemy(GameSprite):54 """敌机精灵"""5556 def __init__(self):5758 # 1.调⽤⽗类⽅法,创建敌机精灵,同时指定敌机图⽚59 super().__init__("./images/enemy1.png")60 # 2.指定敌机的初始随机速度——1到361 self.speed = random.randint(1, 3)6263 # 3.指定敌机的初始随机位置64 self.rect.bottom = 0 # 设置敌机是从屏幕外飞进屏幕65 # 敌机要完整的在屏幕内 — 敌机的最⼤X值是屏幕的宽减去敌机的宽66 max_x = SCREEN_RECT.width-self.rect.width67 self.rect.x = random.randint(0, max_x)6869 def update(self):7071 # 1.调⽤⽗类⽅法保持垂直⽅向的飞⾏72 super().update()73 # 2.判断是否飞出屏幕,如果是需要从精灵组中删除敌机74 if self.rect.y >= SCREEN_RECT.height: # 敌机的y值⼤于屏幕的⾼即飞出屏幕75 # print("飞出屏幕,需从精灵组中删除...")76 # kill⽅法可以将精灵从所有精灵组中移出,精灵就好被⾃动销毁77 self.kill()7879 # 判断敌机是否被销毁80 def __del__(self):81 # print("敌机挂了 %s" % self.rect)82 pass838485 class Hero(GameSprite):86 """英雄精灵"""8788 def __init__(self):8990 # 1.调⽤⽗类⽅法设置image和速度91 super().__init__("./images/me1.png", 0)92 # 2.设置英雄的初始位置93 self.rect.centerx = SCREEN_RECT.centerx94 self.rect.bottom = SCREEN_RECT.bottom - 1209596 # 3.创建⼦弹的精灵组97 self.bullets = pygame.sprite.Group()9899 def update(self):100101 # # 英雄在⽔平⽅向移动102 # self.rect.x += self.speed103104 # 控制英雄不能离开屏幕105 if self.rect.x < 0:106 self.rect.x = 0107 elif self.rect.right > SCREEN_RECT.width:108 self.rect.right = SCREEN_RECT.width109 elif self.rect.y < 0:110 self.rect.y = 0111 elif self.rect.bottom > SCREEN_RECT.bottom:112 self.rect.bottom = SCREEN_RECT.bottom113114 def fire(self):115116 # 1.创建⼦弹精灵117 # bullet = Bullet()118 # bullet1 = Bullet()119 # bullet2 =Bullet()120121 # # 2.设置⼦弹精灵的位置122 # bullet.rect.bottom = self.rect.y - 20123 # bullet1.rect.bottom = self.rect.y124 # bullet2.rect.bottom = self.rect.y -40125 # bullet.rect.centerx = self.rect.centerx126 # bullet1.rect.centerx = self.rect.centerx127 # bullet2.rect.centerx = self.rect.centerx128129 for i in (0, 1, 2):130131 # 1.创建⼦弹精灵132 bullet = Bullet()133134 # 2.设置⼦弹的位置135 bullet.rect.bottom = self.rect.y - i*20136 bullet.rect.centerx = self.rect.centerx137138 # 3.将精灵添加到精灵组139 self.bullets.add(bullet)140 pass141142143 class Bullet(GameSprite):144 """⼦弹精灵"""145146 def __init__(self):147148 # 调⽤⽗类⽅法设置⼦弹图⽚和初始速度149 super().__init__("./images/bullet2.png", -2) 150151 def update(self):152153 # 调⽤⽅法让⼦弹沿垂直⽅向飞⾏154 super().update()155156 # 判断⼦弹是否飞出屏幕157 if self.rect.bottom < 0:158 self.kill()159160 # def __del__(self):161 # print("⼦弹被销毁")。

卡西欧计算器飞机大战游戏代码

卡西欧计算器飞机大战游戏代码

卡西欧计算器飞机大战游戏代码[object Object]以下是一个使用卡西欧计算器编写的飞机大战游戏代码:```'版本:1.0'适用于卡西欧计算器'游戏设置Dim screenWidth As Integer = 127Dim screenHeight As Integer = 63Dim playerWidth As Integer = 5Dim playerHeight As Integer = 5Dim bulletWidth As Integer = 1Dim bulletHeight As Integer = 3Dim enemyWidth As Integer = 4Dim enemyHeight As Integer = 4Dim enemySpeed As Integer = 1Dim maxBullets As Integer = 5Dim maxEnemies As Integer = 5'游戏状态Dim gameOver As Boolean = FalseDim score As Integer = 0'玩家Dim playerX As Integer = (screenWidth - playerWidth) / 2 Dim playerY As Integer = screenHeight - playerHeight - 1 '子弹Dim bulletsX(maxBullets - 1) As IntegerDim bulletsY(maxBullets - 1) As IntegerDim bulletsFired(maxBullets - 1) As Boolean'敌人Dim enemiesX(maxEnemies - 1) As IntegerDim enemiesY(maxEnemies - 1) As IntegerDim enemiesAlive(maxEnemies - 1) As Boolean'游戏循环While Not gameOver'清空屏幕ClrDraw'绘制玩家DrawBox playerX, playerY, playerX + playerWidth, playerY + playerHeight'绘制子弹For i = 0 To maxBullets - 1If bulletsFired(i) ThenDrawBox bulletsX(i), bulletsY(i), bulletsX(i) + bulletWidth, bulletsY(i) + bulletHeightEndIfNext i'绘制敌人For i = 0 To maxEnemies - 1If enemiesAlive(i) ThenDrawBox enemiesX(i), enemiesY(i), enemiesX(i) + enemyWidth, enemiesY(i) + enemyHeightEndIfNext i'显示得分Locate 1, 1Print "得分:" + Str$(score)'移动玩家If GetKeyState(K_LEFT) ThenplayerX = playerX - 1EndIfIf GetKeyState(K_RIGHT) ThenplayerX = playerX + 1EndIf'发射子弹If GetKeyState(K_UP) ThenFor i = 0 To maxBullets - 1If Not bulletsFired(i) ThenbulletsFired(i) = TruebulletsX(i) = playerX + playerWidth / 2 - bulletWidth / 2 bulletsY(i) = playerY - bulletHeightExit ForEndIfNext iEndIf'移动子弹For i = 0 To maxBullets - 1If bulletsFired(i) ThenbulletsY(i) = bulletsY(i) - 1'子弹与敌人碰撞检测For j = 0 To maxEnemies - 1If enemiesAlive(j) ThenIf bulletsX(i) >= enemiesX(j) And bulletsX(i) <= enemiesX(j) + enemyWidth And bulletsY(i) >= enemiesY(j) And bulletsY(i) <= enemiesY(j) + enemyHeight ThenbulletsFired(i) = FalseenemiesAlive(j) = Falsescore = score + 1Exit ForEndIfEndIfNext j'子弹与屏幕边界碰撞检测If bulletsY(i) < 0 ThenbulletsFired(i) = FalseEndIfEndIfNext i'生成新的敌人For i = 0 To maxEnemies - 1If Not enemiesAlive(i) ThenenemiesAlive(i) = TrueenemiesX(i) = Rnd * (screenWidth - enemyWidth)enemiesY(i) = 0Exit ForEndIfNext i'移动敌人For i = 0 To maxEnemies - 1 If enemiesAlive(i) Then enemiesY(i) = enemiesY(i) + enemySpeed'敌人与玩家碰撞检测If enemiesX(i) >= playerX And enemiesX(i) <= playerX + playerWidth And enemiesY(i) >= playerY And enemiesY(i) <= playerY + playerHeight ThengameOver = TrueExit WhileEndIf'敌人与屏幕底部碰撞检测If enemiesY(i) > screenHeight Then enemiesAlive(i) = FalseEndIfEndIfNext i'延时,控制游戏速度Sleep 50End While'游戏结束ClsLocate 1, 1Print "游戏结束"Locate 3, 1Print "得分:" + Str$(score)```这是一个简单的飞机大战游戏,玩家可以使用左右箭头键移动飞机,并使用上箭头键发射子弹。

飞机大战游戏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)。

L1.Y1 = C2.Top - 840 L1.Y2 = C2.Top L1.X1 = C2.Left + C2.Width / 2 L1.X2 = C2.Left + C2.Width / 2 f2 = True Timer1.Enabled = False End If End Sub Private Sub Timer2_Timer() Randomize f1 = Int(((form1.ScaleWidth - L6.Width) * Rnd)) If f1 Mod 2 = 0 Then C1.Left = C1.Left + 300 If C1.Left + C1.Width / 2 >= form1.ScaleWidth Then C1.Left = 0 End If Else C1.Left = C1.Left - 300 If C1.Left + C1.Width < 0 Then C1.Left = form1.ScaleWidth - C1.Width End If End If End Sub
Form2 Dim a As Integer Dim b As Integer Dim c As Integer Dim d As Integer Dim e As Integer Dim f1 As Integer Dim f2 As Boolean Dim f3 As Integer Private Sub C1_Click() Text1.SetFocus End Sub Private Sub C2_Click() Text1.SetFocus End Sub Private Sub Form_Activate() Text1.SetFocus End Sub Private Sub Form_Click() If Label6.Visible = False Then If f3 <> 0 Then L1.Visible = True Timer1.Enabled = True f3 = f3 - 1 Label5.Caption = f3 End If End If
Text1.Text = "" Text1.SetFocus ElseIf KeyAscii = Asc("e") Then End ElseIf KeyAscii = Asc("w") Then C2.Top = C2.Top - 250 L1.Y2 = C2.Top L1.Y1 = C2.Top - 840 If C2.Top < 0 Then C2.Top = 0 End If ElseIf KeyAscii = Asc("r") Then Call GAMESTART ElseIf KeyAscii = Asc("s") Then C2.Top = C2.Top + 250 L1.Y2 = C2.Top L1.Y1 = C2.Top - 840 If C2.Top + C2.Height > form1.Height Then C2.Top = form1.Height - C2.Height End If ElseIf KeyAscii = Asc("l") Then Form_Click ElseIf KeyAscii = Asc("y") Then f3 = f3 + 1 Label5.Caption = f3 ElseIf KeyAscii = Asc("o") Then e=e+1 Label3.Caption = e If C2.Top + C2.Height > form1.ScaleHeight Then C2.Top = form1.ScaleHeight - C2.Height End If End If
Private Sub Form_Load() d = 10 f2 = True f3 = 20 La1.Caption = d e=5 Label3.Caption = e Label5.Caption = f3 End Sub Private Sub Text1_KeyPress(KeyAscii As Integer) If KeyAscii = 97 Then C2.Left = C2.Left - 250 If C2.Left + C2.Width / 2 <= 0 Then C2.Left = form1.ScaleWidth - C2.Width End If If f2 = True Then L1.X1 = C2.Left + C2.Width / 2 L1.X2 = C2.Left + C2.Width / 2 End If Text1.Text = "" Text1.SetFocus ElseIf KeyAscii = 100 Then C2.Left = C2.Left + 250 If C2.Left + C2.Width / 2 >= form1.ScaleWidth Then C2.Left = 0 End If If f2 = True Then L1.X1 = C2.Left + C2.Width / 2 L1.X2 = C2.Left + C2.Width / 2 End If
游戏规则及说明
用W,A,S,D控制飞机移动,按R重新开 始,按E直接退出游戏,可点击L或者鼠标 左键进行射击,当敌方血量为0时游戏胜利, 当我方子弹用尽或者血量为O时游戏失败, 打中敌机即出现子弹补给。 按y键你的子弹数就加1; 按o键你的生命值就加1. 不过如果你技术好的话唔用秘技也能赢。
按键作用
Private Sub Timer3_Timer() L2.Y2 = L2.Y2 + 300 L2.Y1 = L2.Y1 + 300 If L2.Y2 >= C2.Top And L2.Y1 <= C2.Top + C2.Height And L2.X1 >= C2.Left And L2.X1 <= C2.Left + C2.Width Then e=e-1 Label3.Caption = e If e = 0 Then Call GAMEOVER End If L2.X1 = C1.Left + C1.Width / 2 L2.X2 = C1.Left + C1.Width / 2 L2.Y1 = C1.Top L2.Y2 = C1.Top + 700 End If If L2.Y2 >= form1.ScaleHeight Then L2.X1 = C1.Left + C1.Width / 2 L2.X2 = C1.Left + C1.Width / 2 L2.Y1 = C1.Top L2.Y2 = C1.Top + 700 End If End Sub Private Sub Timer4_Timer() L6.Visible = True L6.Top = L6.Top + 250 If L6.Top + L6.Height >= C2.Top And L6.Top <= C2.Top + C2.Height And L6.Left + L6.Width >= C2.Left And L6.Left <= C2.Left + C2.Width Then L6.Visible = False
Sub GAMESTART() Label6.Visible = False L1.Visible = True C2.Visible = True C1.Visible = True L2.Visible = True Label6.Visible = False L2.Y1 = C1.Top L2.Y2 = C1.Top + 840 Timer2.Enabled = True Timer3.Enabled = True Form_Load End Sub Sub WINNER() C1.Visible = False Timer3.Enabled = False L2.Visible = False Label6.Visible = True Label6.Caption = "你赢了! " End Sub
蔡成 霞员 鲁唐 恒洋 应 希 辰
飞 机 大 战
目录
设计思路
游戏规则及说明
界面设计
代码
设计思路
在繁重而沉闷的学习生活中,我们总要找一些有 趣的事情来丰富我们的精神世界。于是,我们小组 的同学想出了这款游戏——飞机大战。 这款名为飞机大战的游戏,老少皆宜,男女通用, 可操作性极高。在丰富了我们的精神生活之余,还 可以提高我们大脑的机能。
Private Sub Timer1_Timer() L1.Y1 = L1.Y1 - 500 L1.Y2 = L1.Y2 - 500 f2 = False If L1.Y1 <= 0 Then If f3 <= 0 And L6.Visible = False Then Call GAMEOVER Timer1.Enabled = False End If L1.Y1 = C2.Top - 840 L1.Y2 = C2.Top L1.X1 = C2.Left + C2.Width / 2 L1.X2 = C2.Left + C2.Width / 2 f2 = True Timer1.Enabled = False End If If L1.Y1 <= C1.Top + C1.Height And L1.Y2 >= C1.Top And L1.X1 >= C1.Left And L1.X1 <= C1.Left + C1.Width Then If f3 = 0 Then L1.Visible = False End If Timer4.Enabled = True L6.Top = C1.Top L6.Left = f1 d=d-1 La1.Caption = d If d = 0 Then Call WINNER End If
相关文档
最新文档