⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 firstgame.java

📁 j2me的打飞机的小程序
💻 JAVA
字号:
package GameTest;

import java.io.IOException;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.midlet.MIDlet;

import java.util.Enumeration;
import java.util.Random;
import java.util.Vector;

public class FirstGame extends Canvas implements CommandListener, Runnable {
	/**
	 * 自己的坐标
	 */
	public int userX;

	public int userY;

	/**
	 * 屏幕的宽度
	 */
	final int WIDTH = this.getWidth();

	/**
	 * 屏幕的高度
	 */
	final int HEIGHT = this.getHeight();

	Vector vector = new Vector();

	/**
	 * 移动的速度
	 */
	int speed = 5;

	int imageWidth = 30;

	int imageHeight = 30;

	int currentUser = 0;

	int currentEnemy = 0;

	Random random = new Random();

	/**
	 * 敌人的坐标3*X数组,分别是X坐标,Y坐标,是否显示标志
	 */
	public int enemy[][];

	/**
	 * 子弹的坐标
	 */
	int ballX, ballY;

	// public int ball[];

	/**
	 * 分数
	 */
	static int score = 0;

	/**
	 * 杀死敌人的数目
	 */
	static int killEnemyNum = 0;

	/**
	 * 自己生命
	 */
	int life = 100;

	/**
	 * 逃跑的敌人数目
	 */
	static int loseNum = 0;

	int MaxLoseNum = 10;

	/**
	 * 是否开火
	 */
	boolean isFire = false;

	public static MIDlet midlet;

	/**
	 * 是否游戏结束
	 */
	public boolean isGameOver = false;

	public boolean isStop = false;

	/**
	 * 退出游戏按钮
	 */
	private Command cmdExit;

	/**
	 * 暂停游戏按钮
	 */
	private Command cmdPause;

	/**
	 * 继续游戏按钮
	 */
	private Command cmdResume;

	/**
	 * 帮助按钮
	 */
	private Command cmdHelp;

	/**
	 * 敌人PNG
	 */
	Image enemyImage[] = new Image[2];

	/**
	 * 玩家PNG
	 */
	Image userImage[] = new Image[2];

	/**
	 * 子弹PNG
	 */
	Image ballImage = null;

	/**
	 * 爆炸PNG
	 */
	Image blastImage = null;

	boolean isBlast = false;

	/**
	 * 本类的一个实例
	 */
	private static FirstGame instance;

	static String userName = "";

	int enemyNum = 3;

	int ballWidth, ballHeight;

	int enemyWidth, enemyHeight;

	int userWidth, userHeight;

	int delay = 100;

	/**
	 * 初始化各个坐标、Command按键、创建Image
	 * 
	 */
	private FirstGame() {
		// 初始化

		userX = WIDTH >>> 1;
		userY = HEIGHT - 40;

		ballX = userX + 10;
		ballY = userY;

		enemy = new int[3][];
		enemy[0] = new int[enemyNum];
		enemy[1] = new int[enemyNum];
		enemy[2] = new int[enemyNum];

		for (int i = 0; i < enemyNum; i++) {

			enemy[0][i] = random.nextInt(WIDTH - 30);
			enemy[1][i] = random.nextInt(10);
			enemy[2][i] = 1;
		}

		// 获取用户输入的玩家名字
		userName = LoginForm.userName.getString();
		if (userName == null || "".equals(userName)) {
			userName = "PLAY1";
		}
		cmdExit = new Command("EXIT", Command.EXIT, 0);
		cmdPause = new Command("PAUSE", Command.ITEM, 1);
		cmdResume = new Command("RESUME", Command.ITEM, 1);
		cmdHelp = new Command("HELP", Command.HELP, 0);
		this.addCommand(cmdExit);
		this.addCommand(cmdPause);
		this.addCommand(cmdHelp);
		this.setCommandListener(this);
		/**
		 * 创建PNG
		 */
		try {
			ballImage = Image.createImage("/res/ball.png");
			blastImage = Image.createImage("/res/blast.png");
			for (int i = 0; i < 2; i++) {
				userImage[i] = Image.createImage("/res/plane" + i + ".png");
			}

			for (int i = 0; i < 2; i++) {
				enemyImage[i] = Image.createImage("/res/enemy" + i + ".png");

			}

		} catch (IOException e) {
			e.printStackTrace();
		}

		this.ballHeight = ballImage.getHeight();
		this.ballWidth = ballImage.getWidth();
		this.enemyWidth = enemyImage[currentEnemy].getWidth();
		this.enemyHeight = enemyImage[currentEnemy].getHeight();
		this.userWidth = userImage[currentUser].getWidth();
		this.userHeight = userImage[currentUser].getHeight();
		this.setFullScreenMode(true);
	}

	public static FirstGame getInstance() {
		if (instance == null) {
			instance = new FirstGame();
		}
		return instance;
	}

	/**
	 * 清空屏幕
	 * 
	 * @param graphics
	 */
	public void clearScreen(Graphics graphics) {
		graphics.setColor(0xFFFFFFFF);
		graphics.fillRect(0, 0, this.getWidth(), this.getHeight());
	}

	/**
	 * 描画
	 */
	protected void paint(Graphics g) {
		this.clearScreen(g);
		g.setColor(0xFF000000);

		// 描画自己
		g.drawImage(userImage[currentUser], userX, userY, Graphics.TOP
				| Graphics.LEFT);
		// 描画敌人,敌人的数目始终设置为enemyNum个
		for (int i = 0; i < enemyNum; i++) {
			if (enemy[2][i] == 1) {
				g.drawImage(enemyImage[currentEnemy], enemy[0][i], enemy[1][i],
						Graphics.TOP | Graphics.LEFT);
				// 描画
				if (isFire) {
					g.drawImage(blastImage, enemy[0][i], enemy[1][i],
							Graphics.TOP | Graphics.LEFT);
					isFire = false;
				}
			}
		}

		// 描画子弹
		Enumeration e = vector.elements();
		while (e.hasMoreElements()) {
			int x[] = new int[3];
			x = (int[]) e.nextElement();
			if (x != null && x[2] == 1) {
				g.drawImage(ballImage, x[0], x[1], Graphics.BOTTOM
						| Graphics.LEFT);
			}
		}

		/**
		 * 显示用户游戏信息
		 */
		g.drawString(userName + " 得分 " + score, 5, this.getHeight() - 60,
				Graphics.TOP | Graphics.LEFT);
		g.drawString(userName + " HITS " + killEnemyNum, 5,
				this.getHeight() - 40, Graphics.TOP | Graphics.LEFT);
		g.drawString(userName + " LOSE " + loseNum, 5, this.getHeight() - 20,
				Graphics.TOP | Graphics.LEFT);
		g.drawString("生命 " + life, 5, 5, Graphics.TOP | Graphics.LEFT);
	}

	/**
	 * 监听用户键盘事件
	 */
	protected void keyPressed(int keyCode) {
		int key = keyCode;
		if (key < 0) {
			key = this.getGameAction(keyCode);
		}
		switch (key) {
		/**
		 * 上
		 */
		case Canvas.KEY_NUM2:
			movePlane(Properties.UP);
			break;
		/**
		 * 下
		 */
		case Canvas.KEY_NUM8:
			movePlane(Properties.DOWN);
			break;
		/**
		 * 左
		 */
		case Canvas.KEY_NUM4:
			movePlane(Properties.LEFT);
			break;
		/**
		 * 右
		 */
		case Canvas.KEY_NUM6:
			movePlane(Properties.RIGHT);
			break;
		/**
		 * 开火
		 */
		case Canvas.KEY_NUM5:
			addBall();
			break;
		case Canvas.UP:
			movePlane(Properties.UP);
			break;
		/**
		 * 下
		 */
		case Canvas.DOWN:
			movePlane(Properties.DOWN);
			break;
		/**
		 * 左
		 */
		case Canvas.LEFT:
			movePlane(Properties.LEFT);
			break;
		/**
		 * 右
		 */
		case Canvas.RIGHT:
			movePlane(Properties.RIGHT);
			break;
		case Canvas.FIRE:
			this.addBall();
			break;
		}
		repaint();
	}

	protected void keyRepeated(int keyCode) {
		if (this.hasRepeatEvents()) {
			this.keyPressed(keyCode);
		}
	}

	/**
	 * 游戏结束后显示玩家游戏信息
	 * 
	 */
	public void gameOver() {
		Navigator.current = Navigator.GAME_OVER_SCREEN;
		Navigator.show(null);

	}

	/**
	 * 监听Command按键
	 */
	public void commandAction(Command cmd, Displayable d) {
		Navigator.flow(cmd.getLabel());
		if (cmd == cmdPause) {
			this.removeCommand(cmdPause);
			this.addCommand(cmdResume);
			isStop = true;
			System.out.println("pause.....");
		}
		if (cmd == cmdResume) {
			this.removeCommand(cmdResume);
			this.addCommand(cmdPause);
			isStop = false;
			System.out.println("resume...");
		}
		if (cmd == cmdHelp) {
			Navigator.current = Navigator.GAME_HELP_SCREEN;
			Navigator.show(null);
		}
	}

	/**
	 * 移动玩家
	 * 
	 * @param moveFlag
	 *            moveFlag 的值分别是UP, DOWN, LEFT, RIGHT
	 */
	public void movePlane(int moveFlag) {
		switch (moveFlag) {
		case Properties.UP:
			userY -= speed;
			if (userY <= 0) {
				userY = 0;
			}
			break;
		case Properties.DOWN:
			userY += speed;
			if (userY >= HEIGHT - 30) {
				userY = HEIGHT - 30;
			}
			break;
		case Properties.LEFT:
			userX -= speed;
			if (userX <= 0) {
				userX = 0;
			}
			break;
		case Properties.RIGHT:
			userX += speed;
			if (userX + imageWidth >= WIDTH) {
				userX = WIDTH - imageWidth;
			}
			break;
		default:
			break;
		}
	}


	public void run() {
		while (true) {
			if (!(isGameOver || isStop)) {

				// Thread tempThread = Thread.currentThread();
				long lTimeStart = System.currentTimeMillis();

				currentUser = (currentUser + 1) % 2;
				currentEnemy = (currentEnemy + 1) % 2;
				doFire();

				repaint(0, 0, WIDTH, HEIGHT);
				serviceRepaints(); // 这是强制描绘 这2个描绘每次消耗的时间不一定相等

				long lTimeTaken = System.currentTimeMillis() - lTimeStart;
				// 获取时间间隔
				// 若小于1000/FPS,等待剩余时间
				if (lTimeTaken < (long) 60) {
					try {
						synchronized (this) {
							Thread.sleep((long) 60 - lTimeTaken);
						}
					} catch (InterruptedException e) {
						System.out.println("error=".concat(String
								.valueOf(String.valueOf(e))));
					}
				}
			} else {
				this.gameOver();
				break;
			}
		}
	}

	/**
	 * 处理敌人移动和子弹的移动,以及它们相碰的情况
	 * 
	 */
	public void doFire() {
		// System.out.println(vector.size());
		int ball[] = new int[3];
		for (int i = 0; i < enemyNum; i++) {
			// 如果当前PNG让显示
			if (enemy[2][i] == 1) {
				enemy[1][i] += speed;

				// 碰撞判断
				Enumeration e = vector.elements();
				while (e.hasMoreElements()) {
					ball = (int[]) e.nextElement();
					ball[1] -= speed;
					if (ball[1] < -30) {
						ball[2] = 0;
						vector.removeElement(ball);
					}

					// 如果敌人和子弹相碰,那么就让它们都不显示

					/**
					 * 一般规则的物体碰撞都可以处理成矩形碰撞,实现的原理就是检测两个矩形是否重叠。
					 * 我们假设矩形1的参数是:左上角的坐标是(x1,y1),宽度是w1,高度是h1;矩形2的参数是:
					 * 左上角的坐标是(x2,y2),宽度是w2,高度是h2。
					 * 在检测时,数学上可以处理成比较中心点的坐标在x和y方向上的距离和宽度的关系。
					 * 即两个矩形中心点在x方向的距离的绝对值小于等于矩形宽度和的二分之一,
					 * 同时y方向的距离的绝对值小于等于矩形高度和的二分之一。 下面是数学表达式: x方向:| (x1 + w1 / 2)
					 * –(x2 + w2/2) | < |(w1 + w2) / 2| y方向:| (y1 + h1 / 2) –
					 * (y2 + * h2/2) | < |(h1 + h2) / 2|
					 * 
					 */
					boolean x = Math.abs((ball[0] + this.ballWidth / 2)
							- (enemy[0][i] + this.enemyWidth / 2)) < (this.enemyWidth + this.ballWidth) / 2;
					boolean y = Math.abs((ball[1] + this.ballHeight / 2)
							- (enemy[1][i] + this.enemyHeight / 2)) < (this.enemyHeight + this.ballHeight) / 2;
					if (x && y) {
						isFire = true;
						enemy[2][i] = 0;
						ball[2] = 0;
						killEnemyNum++;
						score += 20;
						if (score % 500 == 0) {
							life += 100;
						}

						// 杀死敌人后,重新设置敌人坐标
						enemy[0][i] = random.nextInt(WIDTH - 30);
						enemy[1][i] = random.nextInt(5);
						enemy[2][i] = 1;

						vector.removeElement(ball);
					}
				}// end while
				// 如果敌人超出了边界,那么就让它不显示,然后在重新设置它的坐标
				if (enemy[1][i] >= HEIGHT) {
					enemy[2][i] = 0;
					loseNum++;

					// 重新设置坐标
					enemy[0][i] = random.nextInt(WIDTH - 10);
					enemy[1][i] = random.nextInt(5);
					enemy[2][i] = 1;
				}

				// 和玩家相撞
				boolean x = Math.abs((userX + this.userWidth / 2)
						- (enemy[0][i] + this.enemyWidth / 2)) < (this.enemyWidth + this.userWidth) / 2;
				boolean y = Math.abs((userY + this.userHeight / 2)
						- (enemy[1][i] + this.enemyHeight / 2)) < (this.enemyHeight + this.userHeight) / 2;
				if (x && y) {
					isFire = true;
					enemy[2][i] = 0;
					this.life -= 1;

					enemy[0][i] = random.nextInt(WIDTH - 10);
					enemy[1][i] = random.nextInt(5);
					enemy[2][i] = 1;
				}

			}// end if 结束判断当前PNG显示

			if (isGameOver) {
				gameOver();
			}
		}

		// 游戏结束
		if (loseNum == this.MaxLoseNum || this.life <= 0) {
			this.isGameOver = true;
		}
	}

	/**
	 * 添加子弹,当按下开火后,向Vector里面添加一个子弹
	 * 
	 */
	public void addBall() {
		int x[] = new int[3];

		x[0] = userX + 10;
		x[1] = userY;
		x[2] = 1;

		vector.addElement(x);
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -