怎么样用Python写飞机大战游戏图片素材

java写飞机大战一 - 博客频道 - CSDN.NET
分类:java
从前看马士兵老师的教程,学过一个坦克大战,不过当时一头雾水,一直想着模仿着写一个飞机大战,放假了终于动手写了,虽然AWT似乎已经不推荐用了,但是懒得研究swing啊,作为javase的练习还是可以的。
有点成型,尚未完成。
飞机从一开始就一直发射子弹(和微信那个差不多),敌方飞机从“天上”往下降落,但是不会发射子弹。
普通敌方飞机一炸就死。
BOSS敌方飞机则需要较长时间的攻击。
我方飞机一炸就死。
我方飞机可以吃技能,分别是
无敌技能三射技能变弱技能
这三个技能不能共存,使用状态模式控制。
首先,实现游戏窗口:继承Frame类
public class GameClient extends Frame
启动窗口的方法:
// 启动窗口
private void launchFrame() {
// 位置,大小,添加按键监听
this.setLocation(GameConstant.FrameData.WIN_X,
GameConstant.FrameData.WIN_Y);
this.setSize(GameConstant.FrameData.WIN_WIDTH,
GameConstant.FrameData.WIN_HEIGHT);
this.setResizable(false);
this.setTitle(GameConstant.GameStr.GAME_NAME);
this.setBackground(GameConstant.ColorHelper.GAMEBKCOLOR);
this.addWindowListener(new MyWindowAdapter());
this.addKeyListener(new KeyMonitor());
setVisible(true);
new Thread(paintThread).start();
new Thread(attack).start();
new Thread(fire).start();
new Thread(bossAttackThread).start();
四个线程是分别控制游戏的线程,暂时不理。
GameConstant这个类是用来放一些静态变量的,可以自己控制调试,游戏速度,角色大小等。
import java.awt.C
public class GameConstant {
// 游戏窗口的静态变量
public static class FrameData {
public static final int WIN_WIDTH = 400;
public static final int WIN_HEIGHT = 600;
public static final int WIN_X = 350;
public static final int WIN_Y = 50;
public static class ColorHelper {
public static final Color MAIN_PALNE_COLOR = Color.BLUE;
public static final Color PCNORMALCOLOR = Color.RED;
public static final Color BOSSCOLOR = Color.YELLOW;
public static final Color MISSLECOLOR = Color.BLACK;
public static final Color GAMEBKCOLOR = Color.WHITE;
// 游戏相关的静态变量
public static class GameStr {
public static final String GAME_NAME = &beatPlane&;
// 子弹静态变量
public static class BulletData {
public static final int RADIUS = 10;
public static final int SPEED = 3;
public static final int ATTACKVALUE = 1;
// 我方飞机静态变量
public static class MainPlaneData {
public static final int RADIUS = 20;
public static final int FIRST_X = 175;
public static final int FIRST_Y = 550;
public static final int SPEED = 5;
// 普通敌方飞机的静态变量
public static class NormalPcPlaneData {
public static final int RADIUS = 20;
public static final int INIT_SPEED = 1;
public static final int BLOOD = 1;
// 敌方飞机BOSS的静态变量
public static class BossPcPlaneData {
public static final int RADIUS = 40;
public static final int INIT_SPEED = 1;
public static final int BLOOD = 10;
这里的MyWindowAdapter很简单,为了控制右上角点击xx时候的动作,默认当然是退出游戏。
public class MyWindowAdapter extends WindowAdapter{
public void windowClosing(WindowEvent arg0) {
System.exit(0);
按键监听的KeyMonitor,因为是按键主要是操作我方的飞机,所以这里采用了回调的方法,对我方飞机进行操作,可以暂时不理会。
// 按键监听
private class KeyMonitor extends KeyAdapter {
public void keyPressed(KeyEvent keyEvent) {
mainPlane.onkeyPressed(keyEvent);
在launchFrame方法执行之后,启动了四个线程:
new Thread(paintThread).start();
new Thread(attack).start();
new Thread(fire).start();
new Thread(bossAttackThread).start();
先看paintThread:
// 不断刷新画面的线程
private class PaintThread implements Runnable {
public void run() {
while (true) {
// 每隔15ms,调用父类的repaint()方法
repaint();
Thread.sleep(15);
} catch (InterruptedException e) {
e.printStackTrace();
为什么调用父类的repaint方法呢?
就要看这个update方法了:
// 重写update方法,在父类repaint()方法调用的时候会调用这个方法
public void update(Graphics g) {
if (offScreanImage == null) {
offScreanImage = this.createImage(GameConstant.FrameData.WIN_WIDTH,
GameConstant.FrameData.WIN_HEIGHT);
Graphics gOffScrean = offScreanImage.getGraphics();
Color preColor = gOffScrean.getColor();
gOffScrean.setColor(GameConstant.ColorHelper.GAMEBKCOLOR);
gOffScrean.fillRect(0, 0, GameConstant.FrameData.WIN_WIDTH,
GameConstant.FrameData.WIN_HEIGHT);
gOffScrean.setColor(preColor);
paint(gOffScrean);
g.drawImage(offScreanImage, 0, 0, null);
If this component is not a lightweight component, the AWT calls the update method in response to a call to
repaint. You can assume that the background is not cleared.&
简单理解,这个update就是用来刷新界面的,我其实也不是特别理解。
先到这里吧。
排名:千里之外
(9)(5)(2)(1)(12)(5)(4)java写飞机大战三 - 博客频道 - CSDN.NET
分类:java
前文有提到,我放飞机可以吃到三种技能,也就是有三种不同的状态。
无敌技能三射技能变弱技能
而我方飞机又是游戏角色之一,所以也具备基本的游戏角色的
在这里,比如无敌技能不会死,但是没有无敌技能的话,一撞就死。
所以,在不同的状态下,碰撞检测之后的操作就是不一样的。
可以用if else之类的语句去判断,但是如果后续修改游戏,比如多出一种,无敌+三射技能,要加的判断会比较多。
所以这里用到一个设计模式中的状态模式,但是状态较少的时候,代码量反而会交简单的逻辑判断语句多。
还是用一个接口来表示我方飞机的状态。
具体代码:
public interface MainPlaneState {
// 吃到无敌技能
public void eatStrong();
// 吃到三弹齐发技能
public void eatTriple();
// 吃到变弱技能
public void eatWeek();
// 发射子弹
public void fire();
// 和敌方飞机撞击
public void hit(GameRole gameRole);
不同状态的具体实现:
正常状态:
import com.mybeatplane.helper.GameC
import com.mybeatplane.interfase.GameO
import com.mybeatplane.interfase.GameR
import com.mybeatplane.role.B
import com.mybeatplane.role.MainP
import com.mybeatplane.role.NormalPcP
public class NormalState implements MainPlaneState {
private MainPlane mainP
public MainPlane getMainPlane() {
return mainP
public void setMainPlane(MainPlane mainPlane) {
this.mainPlane = mainP
public NormalState(MainPlane mainPlane) {
this.mainPlane = mainP
// 正常状态下吃到无敌技能会变无敌
public void eatStrong() {
mainPlane.setState(mainPlane.getStrongState());
// 正常状态下吃到三射技能会变成三射状态
public void eatTriple() {
mainPlane.setState(mainPlane.getTripleShootState());
// 正常状态下吃到变弱技能 不起作用
public void eatWeek() {
// 正常状态下子弹是单发的
public void fire() {
int currentX = mainPlane.getCurrentX()
+ (GameConstant.MainPlaneData.RADIUS - GameConstant.BulletData.RADIUS)
int currentY = mainPlane.getCurrentY();
GameObserver observer = mainPlane.getObserver();
Bullet bullet = new Bullet(currentX, currentY, observer);
observer.onBulletAppear(bullet);
// 正常状态下,如果我方飞机撞上对方飞机,我方飞机死亡
public void hit(GameRole gameRole) {
if (mainPlane.getRect().intersects(gameRole.getRect())) {
mainPlane.godie();
无敌状态:
import com.mybeatplane.helper.GameC
import com.mybeatplane.interfase.GameO
import com.mybeatplane.interfase.GameR
import com.mybeatplane.role.B
import com.mybeatplane.role.MainP
import com.mybeatplane.role.NormalPcP
public class StrongState implements MainPlaneState {
private MainPlane mainP
public MainPlane getMainPlane() {
return mainP
public void setMainPlane(MainPlane mainPlane) {
this.mainPlane = mainP
public StrongState(MainPlane mainPlane) {
this.mainPlane = mainP
// 无敌状态下吃到无敌技能不起作用
public void eatStrong() {
// 无敌状态下吃到三射技能不起作用
public void eatTriple() {
// 无敌状态下吃到变弱技能,会变成正常状态
public void eatWeek() {
mainPlane.setState(mainPlane.getNormalState());
// 无敌状态下发射子弹是单发的
public void fire() {
int currentX = mainPlane.getCurrentX()
+ (GameConstant.MainPlaneData.RADIUS - GameConstant.BulletData.RADIUS)
int currentY = mainPlane.getCurrentY();
GameObserver observer = mainPlane.getObserver();
Bullet bullet = new Bullet(currentX, currentY, observer);
observer.onBulletAppear(bullet);
// 无敌状态下撞击敌方飞机不受到伤害,敌方飞机死亡
public void hit(GameRole gameRole) {
gameRole.godie();
三射状态:
import java.util.ArrayL
import java.util.L
import com.mybeatplane.helper.GameC
import com.mybeatplane.interfase.GameO
import com.mybeatplane.interfase.GameR
import com.mybeatplane.role.B
import com.mybeatplane.role.MainP
import com.mybeatplane.role.NormalPcP
public class TripleShootState implements MainPlaneState {
private MainPlane mainP
public TripleShootState(MainPlane mainPlane) {
this.mainPlane = mainP
public MainPlane getMainPlane() {
return mainP
public void setMainPlane(MainPlane mainPlane) {
this.mainPlane = mainP
// 三射状态吃到无敌技能不起作用
public void eatStrong() {
// 三射状态吃到三射技能不起作用
public void eatTriple() {
// 三射状态吃到变弱技能 变成正常状态
public void eatWeek() {
mainPlane.setState(mainPlane.getNormalState());
// 三射状态下子弹一次产生三个子弹发射
public void fire() {
List&Bullet& newBullets = new ArrayList&Bullet&();
int currentXOne = mainPlane.getCurrentX()
+ (GameConstant.MainPlaneData.RADIUS - GameConstant.BulletData.RADIUS)
int currentXTwo = mainPlane.getCurrentX()
- GameConstant.BulletData.RADIUS;
int currentXThree = mainPlane.getCurrentX()
+ GameConstant.MainPlaneData.RADIUS;
int currentY = mainPlane.getCurrentY();
GameObserver observer = mainPlane.getObserver();
Bullet bulletOne = new Bullet(currentXOne, currentY, observer);
Bullet bulletTwo = new Bullet(currentXTwo, currentY, observer);
Bullet bulletThree = new Bullet(currentXThree, currentY, observer);
newBullets.add(bulletOne);
newBullets.add(bulletTwo);
newBullets.add(bulletThree);
observer.onBulletsAppear(newBullets);
// 三射状态下我方飞机撞击到敌方飞机,我方飞机死亡
public void hit(GameRole gameRole) {
if (mainPlane.getRect().intersects(gameRole.getRect())) {
mainPlane.godie();
先到这里。
排名:千里之外
(9)(5)(2)(1)(12)(5)(4)1447人阅读
Android 学习笔记(20)
暑假实训的一个程序,也是我第一次接触java和android开发,模仿微信的飞机大战,效果图如下:
一:素材整理
素材来自网络,下载地址在此:
二:遇到的问题
使用Android Suifaceview,之前开发时候遇到很多问题,比如闪屏、按home后再进入黑屏等问题,解决方法在其他转载文章中,
三:java继承、派生和多态的使用
由于有很多种敌机,所以可以抽象出一个基类,我定义了一个Things的基类。
(1)Things的基类
package com.swust.
import android.content.res.R
import android.graphics.B
import android.graphics.C
import android.graphics.RectF;
public abstract class Things {
//物体的right
//物体的buttom
public Bitmap
public int
private int S
public int getLifeValue() {
return lifeV
public void setLifeValue(int lifeValue) {
this.lifeValue = lifeV
public void lifeReduce(){
lifeValue--;
public float getR() {
public void setR(float r) {
public float getB() {
public void setB(float b) {
public float getX() {
public void setX(float x) {
public float getY() {
public void setY(float y) {
public float getWidth() {
public void setWidth(float width) {
this.width =
public float getHight() {
public void setHight(float hight) {
this.hight =
public void SetSpeed(float speed){
this.speed =
public RectF getrectf(){
return new RectF(x, y, x+width, y+hight);
public int getSorces() {
public void setSorces(int sorces) {
public abstract void Draw(Canvas canvas);//绘图
public abstract void Move();//物体移动
public abstract int check();//物体状态检查
public abstract void playsound(MainActivity act);//播放物体被销毁时的音效
然后分别派生出
自身飞机---Plane
package com.swust.
import java.util.ArrayL
import com.swust.gamedeom.R;
import android.content.res.R
import android.graphics.B
import android.graphics.BitmapF
import android.graphics.C
import android.graphics.RectF;
public class Plane extends Things{
private Bitmap Image1;
private Bitmap Image2;
private Bitmap Image3;
private Bitmap Image4;
public Plane(Resources r,float Swidth,float Sheight){
Image = BitmapFactory.decodeResource(res, R.drawable.hero1);
width = Image.getWidth();
hight = Image.getHeight();
setX((Swidth-width)/2);
setY(Sheight-hight);
setR(x+width);
setB(y+hight);
SetSpeed(10);
setLifeValue(1);
* 记载图片资源
public void Init(){
Image1 = BitmapFactory.decodeResource(res, R.drawable.hero_blowup_n1);
Image2 = BitmapFactory.decodeResource(res, R.drawable.hero_blowup_n2);
Image3 = BitmapFactory.decodeResource(res, R.drawable.hero_blowup_n3);
Image4 = BitmapFactory.decodeResource(res, R.drawable.hero_blowup_n4);
* 绘制飞机
public void Draw(Canvas canvas) {
// TODO Auto-generated method stub
if(getLifeValue()==1){
canvas.drawBitmap(Image, x, y,null);
if(num==1){
canvas.drawBitmap(Image1, x, y,null);
else if(num==2){
canvas.drawBitmap(Image2, x, y,null);
else if(num==3){
canvas.drawBitmap(Image3, x, y,null);
else if(num==4){
canvas.drawBitmap(Image4, x, y,null);
public void Move() {
// TODO Auto-generated method stub
* 检查飞机状态
public int check(){
if(num&=4){
* 碰撞检测
* @param EmPlanelist
敌方飞机集合
* @param act 声音控制
public void hitenemy( ArrayList&Things& EmPlanelist,MainActivity act){
RectF rect1 = new RectF(x+15,y+15,x+width-15,y+hight-15);
RectF rect2;
for (int i = 0; i & EmPlanelist.size(); i++) {
Things emPlane = EmPlanelist.get(i);
rect2 = emPlane.getrectf();
if(rect1.intersect(rect2)&& emPlane.getLifeValue()!=0&&this.getLifeValue()!=0){
this.lifeReduce();
emPlane.lifeReduce();
act.stopSound();
act.playSound(7, 0);
* @param ufo 道具
* @param act 声音
* @return 如果拾取到道具,返回true,否则false
public boolean GetUfo(Ufo ufo,MainActivity act){
RectF rect1 = this.getrectf();
RectF rect2 = ufo.getrectf();
if(rect1.intersect(rect2)){
ufo.lifeReduce();
act.playSound(8, 0);
public void playsound(MainActivity act) {
// TODO Auto-generated method stub
act.playSound(7, 0);
背景绘制---BackGround
package com.swust.
import android.content.res.R
import android.graphics.B
import android.graphics.BitmapF
import android.graphics.C
import android.graphics.M
import android.graphics.P
import android.graphics.T
class BackGround extends Things{
private Bitmap ImageS//开始游戏图片
private Bitmap bitmap1;//游戏背景运行图
private Bitmap bitmap2;
private Bitmap ImageO//游戏结束小图
private Bitmap ImageA//重新开始游戏图
private Bitmap ImageC//继续游戏图
private Bitmap ImageP//暂停游戏图
private B//游戏结束背景图
private Bitmap LoadImage1;//游戏加载图
private Bitmap LoadImage2;
private Bitmap LoadImage3;
private Bitmap LoadImage4;
private Bitmap titleI
private Bitmap ImageMusicC//音乐开关图
private Bitmap ImageMusicO
private float top = 0;
private int S//游戏状态
private int S//游戏分数
private int num = 0;
private MainA
private int highS//最高分
private Paint sorceP
public void setAct(MainActivity act) {
this.act =
public void setSources(int Score) {
this.Score = S
public int getStatue() {
public void setStatue(int statue,boolean isplay) {
this.isplay =
public BackGround(Resources r,float SWidth,float SHeight,Paint paint){
ImageAgain = BitmapFactory.decodeResource(res,R.drawable.game_again);
ImageStart = BitmapFactory.decodeResource(res,R.drawable.game_start);
ImageContinue = BitmapFactory.decodeResource(res,R.drawable.game_continue);
ImageOver = BitmapFactory.decodeResource(res,R.drawable.game_over);
ImagePassue = BitmapFactory.decodeResource(res,R.drawable.game_pause_nor);
bitmap1 = CreatBitmap(SWidth, SHeight,R.drawable.background);
bitmap2 = CreatBitmap(SWidth, SHeight,R.drawable.background);
bitmapover = CreatBitmap(SWidth, SHeight,R.drawable.gameover);
LoadImage1 = BitmapFactory.decodeResource(res,R.drawable.game_loading1);
LoadImage2 = BitmapFactory.decodeResource(res,R.drawable.game_loading2);
LoadImage3 = BitmapFactory.decodeResource(res,R.drawable.game_loading3);
LoadImage4 = BitmapFactory.decodeResource(res,R.drawable.game_loading4);
titleImage = BitmapFactory.decodeResource(res,R.drawable.shoot_copyright);
ImageMusicClose = BitmapFactory.decodeResource(res,R.drawable.bkmusic_close);
ImageMusicOpen = BitmapFactory.decodeResource(res,R.drawable.bkmusic_play);
this.hight = SH
this.width = SW
this.paint =
SetSpeed(3);
sorcePaint = new Paint();
Typeface font = Typeface.create(Typeface.SANS_SERIF,Typeface.BOLD);
sorcePaint.setTypeface(font);
sorcePaint.setColor(0xff949694);
sorcePaint.setTextSize(75);
* 根据屏幕尺寸动态调整背景图片大小
* @param SWidth
* @param SHeight 屏幕高度
* @param ID
调整后的图片
public Bitmap CreatBitmap(float SWidth,float SHeight,int ID){
Bitmap bitMap = BitmapFactory.decodeResource(res,ID);
int widtht = bitMap.getWidth();
int height = bitMap.getHeight();
int newWidth = (int)SW
int newHeight =(int)SH
float scaleWidth = ((float) newWidth) /
float scaleHeight = ((float) newHeight) /
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
bitMap = Bitmap.createBitmap(bitMap, 0, 0, widtht, height, matrix, true);
return bitM
* 根据游戏状态绘制相应图片
public void Draw(Canvas canvas) {
// TODO Auto-generated method stub
if(Statue == 1){
canvas.drawBitmap(bitmap1, 0, top - hight, null);
canvas.drawBitmap(bitmap2, 0, top, null);
canvas.drawBitmap(ImagePassue, 0, 0, null);
canvas.drawText(&&+Score,ImagePassue.getWidth()+10, 45, paint);
else if(Statue == 2){
canvas.drawBitmap(bitmap1, 0, 0, null);
if(isplay){
canvas.drawBitmap(ImageMusicOpen, width-ImageMusicOpen.getWidth(), 0, null);
canvas.drawBitmap(ImageMusicClose, width-ImageMusicClose.getWidth(), 0, null);
canvas.drawBitmap(ImageContinue, (width-ImageContinue.getWidth())/2,hight/2-150, null);
canvas.drawBitmap(ImageAgain, (width-ImageAgain.getWidth())/2,hight/2, null);
canvas.drawBitmap(ImageOver, (width-ImageOver.getWidth())/2,hight/2+150, null);
else if(Statue == 3){
String string = SDcardData.ReadDate();
highScore = Integer.valueOf(string).intValue();
if(highScore&Score){
highScore = S
SDcardData.WriteData(String.valueOf(highScore));
canvas.drawBitmap(bitmapover, 0, 0, null);
canvas.drawText(&&+highScore, width/4+20, 80, paint);
canvas.drawText(&&+Score, width/2-80, hight/2, sorcePaint);
canvas.drawBitmap(ImageAgain, (width-ImageAgain.getWidth())/2,hight-200, null);
else if(Statue ==0){
canvas.drawBitmap(bitmap1, 0, 0, null);
canvas.drawBitmap(titleImage, (width-titleImage.getWidth())-100, hight/4-50, null);
if(act.Loadflag == true){
canvas.drawBitmap(ImageStart, (width-ImageStart.getWidth())/2,hight-200, null);
if(num&10){
canvas.drawBitmap(LoadImage1, (width-LoadImage1.getWidth())/2, hight/2+50, null);
else if(num&=10 && num&20){
canvas.drawBitmap(LoadImage2, (width-LoadImage2.getWidth())/2, hight/2+50, null);
else if(num&=20&& num&30){
canvas.drawBitmap(LoadImage3, (width-LoadImage3.getWidth())/2, hight/2+50, null);
else if(num==30){
canvas.drawBitmap(LoadImage4, (width-LoadImage4.getWidth())/2, hight/2+50, null);
* 背景图片移动
public void Move() {
// TODO Auto-generated method stub
if (top &= (hight + speed))
public int check() {
// TODO Auto-generated method stub
public void playsound(MainActivity act) {
// TODO Auto-generated method stub
敌机---EmptyPlane
package com.swust.
import android.content.res.R
import android.graphics.B
import android.graphics.BitmapF
import android.graphics.C
public class EmptyPlane extends Things{
private float H
private Bitmap Image1;
private Bitmap Image2;
private Bitmap Image3;
private Bitmap Image4;
public EmptyPlane(Resources r,Float SWidth,float SHeight){
this.res =
Image = BitmapFactory.decodeResource(r, R.drawable.enemy1);
width = Image.getWidth();
hight = Image.getHeight();
setX((float)(Math.random()*(SWidth-width)));
SetSpeed(7);//15
this.Height = SH
setLifeValue(1);
setSorces(10);
public void Init(){
Image1 = BitmapFactory.decodeResource(res, R.drawable.enemy1_down1);
Image2 = BitmapFactory.decodeResource(res, R.drawable.enemy1_down2);
Image3 = BitmapFactory.decodeResource(res, R.drawable.enemy1_down3);
Image4 = BitmapFactory.decodeResource(res, R.drawable.enemy1_down4);
public void Draw(Canvas canvas) {
// TODO Auto-generated method stub
if(getLifeValue()==1){
canvas.drawBitmap(Image, x, y,null);
switch (num/3) {
canvas.drawBitmap(Image1, x, y,null);
canvas.drawBitmap(Image2, x, y,null);
canvas.drawBitmap(Image3, x, y,null);
canvas.drawBitmap(Image4, x, y,null);
public void Move() {
// TODO Auto-generated method stub
public int check(){
if(num&=12){
if(y&Height){
public void playsound(MainActivity act) {
// TODO Auto-generated method stub
act.playSound(3, 0);
敌机大飞机--&EmBigPlane
package com.swust.
import android.content.res.R
import android.graphics.B
import android.graphics.BitmapF
import android.graphics.C
public class EmBigPlane extends Things{
private float H
private Bitmap Image1;
private Bitmap Image2;
private Bitmap Image3;
private Bitmap Image4;
private Bitmap ImageH
public EmBigPlane(Resources r,Float SWidth,float SHeight){
this.res =
Image = BitmapFactory.decodeResource(r, R.drawable.enemy2);
ImageHit = BitmapFactory.decodeResource(r, R.drawable.enemy2_hit);
width = Image.getWidth();
hight = Image.getHeight();
setX((float)(Math.random()*(SWidth-width)));
SetSpeed(5);//13
this.Height = SH
setLifeValue(10);
setSorces(50);
public void Init(){
Image1 = BitmapFactory.decodeResource(res, R.drawable.enemy2_down1);
Image2 = BitmapFactory.decodeResource(res, R.drawable.enemy2_down2);
Image3 = BitmapFactory.decodeResource(res, R.drawable.enemy2_down3);
Image4 = BitmapFactory.decodeResource(res, R.drawable.enemy2_down4);
public void Draw(Canvas canvas) {
// TODO Auto-generated method stub
if(getLifeValue()&=10 && getLifeValue()&=5){
canvas.drawBitmap(Image, x, y,null);
else if(getLifeValue()&5&& getLifeValue()&=1){
canvas.drawBitmap(ImageHit, x, y,null);
switch (num/3) {
canvas.drawBitmap(Image1, x, y,null);
canvas.drawBitmap(Image2, x, y,null);
canvas.drawBitmap(Image3, x, y,null);
canvas.drawBitmap(Image4, x, y,null);
public void Move() {
// TODO Auto-generated method stub
public int check(){
if(num&=12){
if(y&Height){
public void playsound(MainActivity act) {
// TODO Auto-generated method stub
act.playSound(4, 0);
敌机Boss--EmBoss
import android.content.res.R
import android.graphics.B
import android.graphics.BitmapF
import android.graphics.C
import com.swust.gamedeom.R;
public class EmBoss extends Things{
private float H
private float W
private Bitmap Image1;
private Bitmap Image2;
private Bitmap Image3;
private Bitmap Image4;
private Bitmap Image5;
private Bitmap Image6;
private Bitmap ImageH
public EmBoss(Resources r,float SWidth,float SHeight){
this.res =
Image = BitmapFactory.decodeResource(r, R.drawable.enemy3_n1);
ImageHit = BitmapFactory.decodeResource(r, R.drawable.enemy3_hit);
width = Image.getWidth();
hight = Image.getHeight();
setX((float)(Math.random()*(SWidth-width)));
setY(-hight);
SetSpeed(2);
this.Height = SH
this.Width = SW
setLifeValue(60);
setSorces(300);
public void Init(){
Image1 = BitmapFactory.decodeResource(res, R.drawable.enemy3_down1);
Image2 = BitmapFactory.decodeResource(res, R.drawable.enemy3_down2);
Image3 = BitmapFactory.decodeResource(res, R.drawable.enemy3_down3);
Image4 = BitmapFactory.decodeResource(res, R.drawable.enemy3_down4);
Image5 = BitmapFactory.decodeResource(res, R.drawable.enemy3_down5);
Image6 = BitmapFactory.decodeResource(res, R.drawable.enemy3_down6);
public void Draw(Canvas canvas) {
// TODO Auto-generated method stub
if(getLifeValue()&=60 && getLifeValue()&=30){
canvas.drawBitmap(Image, x, y,null);
else if(getLifeValue()&30&& getLifeValue()&=1){
canvas.drawBitmap(ImageHit, x, y,null);
switch (num/3) {
canvas.drawBitmap(Image1, x, y,null);
canvas.drawBitmap(Image2, x, y,null);
canvas.drawBitmap(Image3, x, y,null);
canvas.drawBitmap(Image4, x, y,null);
canvas.drawBitmap(Image5, x, y,null);
canvas.drawBitmap(Image6, x, y,null);
public void Move() {
// TODO Auto-generated method stub
if(y&=(Height/2-hight)){
public int check(){
if(num&=18){
public void playsound(MainActivity act) {
// TODO Auto-generated method stub
act.playSound(5, 0);
道具---Ufo
package com.swust.
import android.content.res.R
import android.graphics.B
import android.graphics.BitmapF
import android.graphics.C
public class Ufo extends Things{
private Bitmap Image2;
private float H
private int
UfoFlag = 0;
public int getUfoFlag() {
return UfoF
public void setUfoFlag(int ufoFlag) {
UfoFlag = ufoF
public Ufo(Resources r,int flag,float SWidth,float SHeight){
Image = BitmapFactory.decodeResource(res, R.drawable.ufo1);
Image2 = BitmapFactory.decodeResource(res, R.drawable.ufo2);
width = Image.getWidth();
hight = Image.getHeight();
Height = SH
SetSpeed(4);//10
setUfoFlag(flag);
setLifeValue(1);
if(UfoFlag ==1){
setX(SWidth-width-50);
else if(UfoFlag == 2){
public int check(){
if(getLifeValue()==0){
if(y&Height){
public void Draw(Canvas canvas) {
// TODO Auto-generated method stub
if(UfoFlag ==1){
canvas.drawBitmap(Image, x, y,null);
else if(UfoFlag ==2){
canvas.drawBitmap(Image2, x, y,null);
public void Move() {
// TODO Auto-generated method stub
public void playsound(MainActivity act) {
// TODO Auto-generated method stub
act.playSound(8, 0);
子弹---Bullet
package com.swust.
import java.util.ArrayL
import android.content.res.R
import android.graphics.B
import android.graphics.BitmapF
import android.graphics.C
import android.graphics.RectF;
public class Bullet extends Things{
private Bitmap Image2;
private Bitmap Image3;
private int SuperB
public void setSuperBullet(int superBullet) {
SuperBullet = superB
public Bullet(Resources r){
Image = BitmapFactory.decodeResource(res, R.drawable.bullet1);
Image2 = BitmapFactory.decodeResource(res, R.drawable.bullet2);
Image3 = BitmapFactory.decodeResource(res, R.drawable.bomb);
width = Image.getWidth();
hight = Image.getHeight();
SetSpeed(60);
setLifeValue(1);
SuperBullet = 0;
public void Draw(Canvas canvas) {
// TODO Auto-generated method stub
if(SuperBullet == 0){
canvas.drawBitmap(Image, x, y,null);
else if(SuperBullet == 1){
canvas.drawBitmap(Image2, x, y,null);
else if(SuperBullet ==2){
canvas.drawBitmap(Image3, x, y,null);
public void Move() {
// TODO Auto-generated method stub
public int check() {
if(getLifeValue()==0){
if(this.y&0){
* 子弹和敌机的碰撞检测
* @param EmPlanelist
* @param act
public void hitenemy( ArrayList&Things&EmPlanelist,MainActivity act){
RectF rect1 = this.getrectf();
RectF rect2;
for (int i = 0; i & EmPlanelist.size(); i++) {
Things emPlane = EmPlanelist.get(i);
rect2 = emPlane.getrectf();
if(rect1.intersect(rect2)&& emPlane.getLifeValue()!=0){
this.lifeReduce();
emPlane.lifeReduce();
public void playsound(MainActivity act) {
// TODO Auto-generated method stub
四:简单工厂模式的使用
package com.swust.
import android.content.res.R
public class EmPlaneFactory {
private EmPlaneFactory(){
public static Things getEmPlane(int x,Resources r,Float SWidth,float SHeight){
Things emPlane =
switch (x) {
emPlane = new EmptyPlane(r,SWidth,SHeight);
emPlane = new EmBigPlane(r,SWidth,SHeight);
emPlane = new EmBoss(r,SWidth,SHeight);
return emP
五:主程序和音频加载
package com.swust.
import java.io.IOE
import java.util.HashM
import android.media.AudioM
import android.media.MediaP
import android.media.SoundP
import android.os.B
import android.annotation.SuppressL
import android.app.A
import android.content.C
import android.graphics.P
import android.graphics.T
import android.util.DisplayM
import android.view.M
import android.view.W
import android.view.WindowM
@SuppressLint(&UseSparseArrays&)
public class MainActivity extends Activity implements Runnable {
private MySuifaceV
private MediaPlayer mMediaP
private SoundP
private HashMap&Integer, Integer& spM
public boolean L
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
// 隐藏状态栏
DisplayMetrics metric = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metric);
Paint paint = new Paint();
Typeface font = Typeface.create(Typeface.SANS_SERIF,Typeface.BOLD);
paint.setTypeface(font);
paint.setColor(0xff949694);
paint.setTextSize(55);
float width = (float)metric.widthP
float height = (float) metric.heightP
Loadflag =
view = new MySuifaceView(this,width,height,this,paint);
setContentView(view);
new Thread(this).start();
public boolean onCreateOptionsMenu(Menu menu) {
// I this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
public void InitSound() {
mMediaPlayer = MediaPlayer.create(this, R.raw.game_music);
sp = new SoundPool(10, AudioManager.STREAM_MUSIC, 5);
spMap = new HashMap&Integer, Integer&();
spMap.put(2, sp.load(this, R.raw.bullet, 1));
spMap.put(3, sp.load(this, R.raw.enemy1_down,1));
spMap.put(4, sp.load(this, R.raw.enemy2_down,1));
spMap.put(5, sp.load(this, R.raw.enemy3_down,1));
spMap.put(6, sp.load(this, R.raw.use_bomb,1));
spMap.put(7, sp.load(this, R.raw.game_over,1));
spMap.put(8, sp.load(this, R.raw.get_bomb,1));
Loadflag =
public void playSound(int sound, int number) {
if(sound==1){
if (!mMediaPlayer.isPlaying()) {
mMediaPlayer.start();
AudioManager am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
float audioMaxVolumn = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volumnCurrent = am.getStreamVolume(AudioManager.STREAM_MUSIC);
float volumnRatio = volumnCurrent / audioMaxV
sp.play(spMap.get(sound), volumnRatio, volumnRatio, 1, number,
public void stopSound(){
if (mMediaPlayer.isPlaying()){
mMediaPlayer.pause();
protected void onResume() {
// TODO Auto-generated method stub
setContentView( view );
super.onResume();
public void run() {
// TODO Auto-generated method stub
InitSound();
mMediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}这里通过一个线程来单独加载音频,使用音频池。
六:Suifaceview 类(核心)
package com.swust.
import java.util.ArrayL
import android.annotation.SuppressL
import android.annotation.TargetA
import android.content.C
import android.graphics.C
import android.graphics.P
import android.graphics.P
import android.graphics.R
import android.view.MotionE
import android.view.SurfaceH
import android.view.SurfaceHolder.C
import android.view.SurfaceV
public class MySuifaceView extends SurfaceView implements Callback, Runnable {
private ArrayList&Bullet& bulletlist = new ArrayList&Bullet&();
private ArrayList&Things& EmPlanelist = new ArrayList&Things&();
private ArrayList&Bomb& bomblist = new ArrayList&Bomb&();
private Ufo ufo_
private Ufo ufo_
private SurfaceHolder mSurfaceHolder =
private boolean mbloop =
private BackG
private MainA
private Point point = new Point();
private boolean canDrag =
private int offsetX = 0, offsetY = 0;
private int Count = 0;
private int bossCount = 0;
private float SW
private float SH
private int S
private Canvas canvas=
private int E
private int EmB
private int EmB
private Rect rectM
private Rect rectP
private Rect rectA
private Rect rectC
private Rect rectO
private boolean bullet_
private boolean bullet_
private boolean bombS
private int bulletT
private boolean isP
@TargetApi(19)
@SuppressLint(&NewApi&)
public MySuifaceView(Context context, float width, float height,MainActivity act,Paint paint) {
super(context);
// TODO Auto-generated constructor stub
// 添加回调函数
mSurfaceHolder = this.getHolder();
mSurfaceHolder.addCallback(this);
this.setFocusable(true);
this.setKeepScreenOn(true);
this.activity =
Init(width,height);
bk = new BackGround(getResources(),width, height,paint);
statue =0;
rectbtn = new Rect((int)(width-300)/2,(int)(height-200),(int)(width/2+150),(int)(height-150));
rectPassue = new Rect(0,0,150,150);
rectContinue = new Rect((int)(width-300)/2,(int)(height/2-150),(int)(width/2+150),(int)(height/2-90));
rectAgain =
new Rect((int)(width-300)/2,(int)(height/2),(int)(width/2+150),(int)(height/2+60));
rectOver = new Rect((int)(width-300)/2,(int)(height/2+150),(int)(width/2+150),(int)(height/2+210));
rectbomb = new Rect(20,(int)(height-100),160,(int)(height));
rectMusic = new Rect((int)width-50,0,(int)width,50);
public void Init(float width, float height){
plane = new com.swust.gamedeom.Plane(getResources(), width, height);
rect = new Rect((int) plane.getX(), (int) plane.getY(),
(int) plane.getR(), (int) plane.getB());
bulletcreat = 7;
Emcreat = 15;
EmBicreat = 150;
EmBosscreat = 3379;
Score = 0;
Count = 0;
bullet_double =
bullet_super =
bulletTime = 0;
bombScreen =
bossCount = 0;
bulletlist.clear();
EmPlanelist.clear();
bomblist.clear();
ufo_double =
ufo_super =
public void DrawBitmap(){
bk.setAct(activity);
bk.setSources(Score);
bk.setStatue(statue,isPlay);
bk.Draw(canvas);
if(statue == 1){
plane.Draw(canvas);
if(plane.check()!=0){
statue = 3;
activity.stopSound();
plane.hitenemy(EmPlanelist,activity);
if(ufo_double!=null){
ufo_double.Draw(canvas);
bullet_double = plane.GetUfo(ufo_double,activity);
if(ufo_double.check()!=0){
ufo_double=
if(ufo_super!=null){
ufo_super.Draw(canvas);
bullet_super = plane.GetUfo(ufo_super,activity);
if(ufo_super.check()!=0){
ufo_super=
for (int i = 0; i & bulletlist.size(); i++) {
Bullet bullet = bulletlist.get(i);
bullet.Draw(canvas);
bullet.hitenemy(EmPlanelist,activity);
if (bullet.check()!=0) {
bulletlist.remove(bullet);
for (int i = 0; i & EmPlanelist.size(); i++) {
Things emPlane = EmPlanelist.get(i);
if(emPlane.check()==1){
Score+=emPlane.getSorces();
emPlane.playsound(activity);
EmPlanelist.remove(emPlane);
else if(emPlane.check()==2){
EmPlanelist.remove(emPlane);
emPlane.Draw(canvas);
for (int m = 0; m & bomblist.size(); m++) {
Bomb bomb = bomblist.get(m);
if(bombScreen){
bomb.lifeReduce();
ScreenBomb();
bombScreen =
if(bomb.check()!=0){
bomblist.remove(bomb);
bomb.setBombnum(bomblist.size());
bomb.Draw(canvas);
void Draw() {
canvas = mSurfaceHolder.lockCanvas();
if(canvas!=null){
DrawBitmap();
} catch (Exception e) {
// TODO: handle exception
if(canvas!=null)
mSurfaceHolder.unlockCanvasAndPost(canvas);
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
public void surfaceCreated(SurfaceHolder arg0) {
// TODO Auto-generated method stub
new Thread(this).start();
public void surfaceDestroyed(SurfaceHolder arg0) {
// TODO Auto-generated method stub
activity.stopSound();
statue =2;
public void run() {
// TODO Auto-generated method stub
int SLEEP_TIME=15;
while (mbloop) {
long start=System.currentTimeMillis();
if(statue == 1){
//Adjust();
AddEmBigPlane();
Addbuilt();
AddEmplane();
AddEmBoss();
Addbomb();
if(bullet_double){
checktime();
long end=System.currentTimeMillis();
if((end-start)&SLEEP_TIME){
Thread.sleep(SLEEP_TIME-(end-start));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
public void ScreenBomb(){
for (int i = 0; i & EmPlanelist.size(); i++) {
Things emPlane = EmPlanelist.get(i);
emPlane.setLifeValue(0);
public void Addbomb(){
if(bullet_super){
Bomb bomb = new Bomb(getResources(), SWidth, SHeight);
bomblist.add(bomb);
bullet_super =
public void Adjust(){
if((Score+10)%1000 == 0){
Emcreat-=1;
EmBicreat-=5;
public void checktime(){
bulletTime++;
if(bulletTime % 299==0){
bullet_double =
bulletTime = 0;
public void AddUfo(){
if(Count%579==0){
int num = (int) (Math.random()*9+1);
if(num%3==0){
ufo_super = new Ufo(getResources(), 2, SWidth, SHeight);
ufo_double = new Ufo(getResources(), 1, SWidth, SHeight);
public void Addbuilt() {
if (Count % bulletcreat== 0 ) {
if(!bullet_double){
Bullet bullet = BulletFactory.getBullet(getResources(),
plane.getX()+plane.getWidth()/2-5, plane.getY()-10);
bulletlist.add(bullet);
activity.playSound(2, 0);
Bullet bullet1 = BulletFactory.getBullet(getResources(),
plane.getX()+plane.getWidth()/2-30, plane.getY()-10);
bullet1.setSuperBullet(1);
Bullet bullet2 = BulletFactory.getBullet(getResources(),
plane.getX()+plane.getWidth()/2+30, plane.getY()-10);
bullet2.setSuperBullet(1);
bulletlist.add(bullet1);
bulletlist.add(bullet2);
activity.playSound(2, 0);
public void AddEmplane(){
if(Count%Emcreat==0 ){
Things emPlane = EmPlaneFactory.getEmPlane(1,getResources(), SWidth, SHeight);
EmPlanelist.add(emPlane);
public void AddEmBigPlane(){
if(Count%EmBicreat==0){
Things emPlane = EmPlaneFactory.getEmPlane(2,getResources(), SWidth, SHeight);
EmPlanelist.add(emPlane);
public void AddEmBoss(){
if(Count%EmBosscreat==0){
Things emPlane = EmPlaneFactory.getEmPlane(3,getResources(), SWidth, SHeight);
EmPlanelist.add(emPlane);
Count = 0;
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
point.x = (int) event.getX();
point.y = (int) event.getY();
if(statue == 3|| statue == 0){
if(rectbtn.contains(point.x, point.y)){
Init(SWidth, SHeight);
if(isPlay){
activity.playSound(1, -1);
if(statue == 1){
if(rectPassue.contains(point.x,point.y)){
statue = 2;
if(rectbomb.contains(point.x,point.y)&& bomblist.size()&0){
bombScreen =
if(statue == 2){
if(rectContinue.contains(point.x,point.y)){
else if(rectAgain.contains(point.x,point.y)){
Init(SWidth, SHeight);
else if(rectOver.contains(point.x,point.y)){
activity.finish();
else if(rectMusic.contains(point.x, point.y)){
if(isPlay){
activity.stopSound();
activity.playSound(1, -1);
if (rect.contains(point.x, point.y)) {
offsetX = point.x - rect.
offsetY = point.y - rect.
case MotionEvent.ACTION_MOVE:
if(canDrag){
rect.left = (int) event.getX() - offsetX;
rect.top = (int) event.getY() - offsetY;
rect.right = rect.left + (int) plane.getWidth();
rect.bottom = rect.top + (int) plane.getHight();
if (rect.left & 0) {
rect.left = 0;
rect.right = rect.left + (int) plane.getWidth();
if (rect.right & getMeasuredWidth()) {
rect.right = getMeasuredWidth();
rect.left = rect.right - (int) plane.getWidth();
if (rect.top & 0) {
rect.top = 0;
rect.bottom = rect.top + (int) plane.getHight();
if (rect.bottom & getMeasuredHeight()) {
rect.bottom = getMeasuredHeight();
rect.top = rect.bottom - (int) plane.getHight();
plane.setX((float) rect.left);
plane.setY((float) rect.top);
case MotionEvent.ACTION_UP:
核心就是DrawBitmap()函数,线程每隔15ms刷屏一次,每次都会调用DrawBitmap()函数去绘制各个物体,这样就会显示出游戏的效果了。
总体来说,用了2周的时间,从什么都不会到能做出一个小游戏,学到了很多东西,Surfaceview的认识更深刻了,也参见了好多大神的文章,在此表示感谢!
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:57037次
积分:2649
积分:2649
排名:第11809名
原创:215篇
转载:34篇
(214)(15)(6)(4)(14)(1)

我要回帖

更多关于 飞机大战单机游戏 的文章

 

随机推荐