大鱼吃小鱼小游戏(Java版含源代码,JavaSwing+多线程+接口)

大鱼吃小鱼小游戏(Java版含源代码,JavaSwing+多线程+接口),第1张

         这是一款经典小游戏,大鱼吃小鱼,玩家 *** 控小鱼从小吃到大,直面Boss的挑战,全方面的代码解析,适合新手第一款的项目实战


其他项目:

1.飞机大战Java版(Java+JavaSwing+多线程结构)

2.Java之马里奥游戏


项目的完整结构图:


游戏效果图:



源代码如下:

游戏窗口类完整代码:

package game;

import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class FishFrame extends Frame {
	public static final int GAME_WIDTH = 1200;//游戏窗口的宽
	public static final int GAME_HEIGHT = 800;//游戏窗口的高
	private Image offScreenImage = null;//在paint方法进行画图前保存图画,以便一次画出,消除双缓冲现象
	public static Random r = new Random();//创建一个随机数生成器
	private boolean isStart = false;//判断游戏是否开始的变量
	MyFish myFish = new MyFish(GAME_WIDTH/2, GAME_HEIGHT/2, this);//创建一条我的小鱼
	List<EnemyFish> fishList_Left = new ArrayList<EnemyFish>();//装小鱼的集合
	List<EnemyFish> fishList_Right = new ArrayList<EnemyFish>();//装小鱼的集合

	/**
	 * 画出图片
	 */
	public void paint(Graphics g) {
		/*
		 * 通过isStart变量判断游戏是否开始,没有开始的话画出欢迎界面
		 */
		if(!isStart){
			draw_welcome(g);
			return;
		}
		
		//画出我方小鱼,如果我方小鱼吃掉了敌军小鱼会有GOOD字样显示
		myFish.draw(g);
		if(myFish.eatFishs(fishList_Left) || myFish.eatFishs(fishList_Right)){
			for(int i = 0; i < 5; i++){
				g.drawString("GOOD!", myFish.x, myFish.y);
			}
		}
		//设置我方小鱼可以被吃掉
		myFish.beEaten(fishList_Left);
		myFish.beEaten(fishList_Right);
		
		//画出敌方小鱼
		for(int i = 0; i < fishList_Left.size(); i++) {
			EnemyFish e = fishList_Left.get(i);
			e.draw(g);
		}
		
		for(int i = 0; i < fishList_Right.size(); i++) {
			EnemyFish e = fishList_Right.get(i);
			e.draw(g);
		}
		
		//画出当前小鱼数量和当前玩家积分字样
		g.setFont(new Font("宋体", Font.BOLD, 25));
		g.drawString("fish account : " + (fishList_Left.size()+fishList_Right.size()), 10, 50);
		g.drawString("you scores : " + myFish.scores, 10, 70);
		if(myFish.scores > 380) {
			g.drawString("你以为你真的能变成一条肥鱼吃遍天下吗? Too Young! Too Simple!", 200, 350);
		}
		
		//当我方小鱼阵亡时写出GAME OVER字样
		if(!myFish.live){
			g.setColor(Color.RED);
			g.setFont(new Font("宋体", Font.BOLD, 70));
			g.drawString("GAME OVER!!!", 300, 400);
		}
	}
	
	/**
	 * 画出欢迎界面
	 * @param g
	 */
	private void draw_welcome(Graphics g) {
		g.setColor(Color.RED);
		g.setFont(new Font("宋体", Font.BOLD, 75));
		g.drawString("Welcome to the FishGame!!!", 100, 150);
		g.setFont(new Font("宋体", Font.BOLD, 40));
		g.setColor(Color.YELLOW);
		g.drawString("How to play:", 200, 350);
		g.drawString("press W,A,S,D to move,", 200, 400);
		g.drawString("you can eat the samller ones,", 200, 450);
		g.drawString("but be careful to the big ones.", 200, 500);
		g.drawString("The boss is waiting for you, Let's go!", 200, 600);
		g.drawString("Press Enter to start...", 200, 650);
	}
	
	/**
	 * 游戏初始化
	 */
	private void launchFrame() {
		this.setLocation(50, 50);//设置游戏窗口的位置
		this.setSize(GAME_WIDTH, GAME_HEIGHT);//设置游戏窗口的宽高
		this.setVisible(true);//设置游戏窗口可见
		this.setResizable(false);//设置游戏窗口大小不可改变
		this.setTitle("FishGame");//设置游戏窗口标题
		
		this.addWindowListener(new WindowAdapter() {//添加窗口监听
			public void windowClosing(WindowEvent e) {//匿名内部类监听窗口关闭事件
				System.exit(0);//窗口关闭游戏退出
			}
		});
		this.addKeyListener(new KeyMonitorForStart());//添加键盘监听,看游戏是否开始
		this.addKeyListener(new KeyMonitor());//添加键盘监听
	
		new Thread(new RepaintThread()).start();//创建重画线程对象进行重画
	
		new Thread(new AddFishFromLeft(this)).start();//添加向右移动的小鱼
		new Thread(new AddFishFromRight(this)).start();//添加向左移动的小鱼
		
		//通过当前积分改变我方小鱼的移动速度
		changeMyFishSpeedByScores();
	}

	/**
	 * 根据积分改变稍微提高小鱼的速度
	 */
	private void changeMyFishSpeedByScores() {
		//先获取当前MyFish的积分
		int score = this.myFish.scores;//根据积分设置MyFish的速度
		if(score >= 0 && score <50) {
			addSpeed();
		}else if(score >= 50 && score < 100) {
			addSpeed();
		}else if(score >= 100 && score < 200){
			addSpeed();
		}else{
			addSpeed();
			addSpeed();
		}
	}
	/**
	 * 提高速度
	 */
	private void addSpeed() {
		myFish.xSpeed++;
		myFish.ySpeed++;
	}

	/**
	 * 设置游戏背景
	 */
	private void drawBackground(Graphics g) {
		Toolkit tk = Toolkit.getDefaultToolkit();//拿到当前系统默认的Toolkit
		Image background = tk.getImage(this.getClass()
				.getClassLoader().getResource("images/background/sea.jpg"));
		g.drawImage(background, 0, 0, null);
	}

	/**
	 * 消除双缓冲现象
	 */
	public void update(Graphics g) {
		if(null == offScreenImage) {//判断offScreenImage是否为空,为空则创建一张准备图片
			offScreenImage = this.createImage(GAME_WIDTH, GAME_HEIGHT);
		}
		Graphics og = offScreenImage.getGraphics();
		drawBackground(og);
		paint(og);//执行paint方法,把要画的图片画到缓冲的offScreenImage上
		g.drawImage(offScreenImage, 0, 0, null);//在屏幕上画出offScreenImage
	}

	/**
	 * 重画的线程类

	 *
	 */
	class RepaintThread implements Runnable{
		public void run() {
			while(true) {
				repaint();//启动线程后进行重画
				try {
					Thread.sleep(30);//每隔50毫秒重画一次
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/*
	 * 键盘监听内部类,用于改变鱼的位移,让鱼动起来
	 
	 
	 */
	class KeyMonitor extends KeyAdapter{
		public void keyPressed(KeyEvent e) {
			myFish.keyPressed(e);
		}

		public void keyReleased(KeyEvent e) {
			myFish.keyRelease(e);
		}
	}
	
	/*
	 * 键盘监听,监听是否按下了回车键,按下回车键设置isStart为true,游戏开始
	
	 */
	class KeyMonitorForStart extends KeyAdapter{
		
		public void keyPressed(KeyEvent e) {
			int key = e.getExtendedKeyCode();
			if(key == KeyEvent.VK_ENTER){
				isStart = true;
			}
		}
	}
	

	public static void main(String[] args) {
		FishFrame fishFrame = new FishFrame();//创建本类对象
		fishFrame.launchFrame();//加载游戏
	}
}


敌人鱼类:

package game;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.util.Random;

/**
 * 敌方小鱼类

 *
 */
public class EnemyFish extends GameObject {
	
	public MyFish OurEnemy;//敌军小鱼的敌人就是玩家的小鱼,用于判断是否能吃掉玩家的小鱼
	private Image image;//小鱼自己的图片
	
	/**
	 * 加载敌军小鱼的图片
	 */
	private static Random r = new Random();
	public static Image[] images = null;
	public static Toolkit tk = Toolkit.getDefaultToolkit();
	static {
		images = new Image[] {
			tk.createImage(EnemyFish.class.getClassLoader().getResource("images/enemyFish/fish1_l.gif")),
			tk.createImage(EnemyFish.class.getClassLoader().getResource("images/enemyFish/fish2_l.gif")),
			tk.createImage(EnemyFish.class.getClassLoader().getResource("images/enemyFish/fish3_l.gif")),
			tk.createImage(EnemyFish.class.getClassLoader().getResource("images/enemyFish/fish1_r.gif")),
			tk.createImage(EnemyFish.class.getClassLoader().getResource("images/enemyFish/fish2_r.gif")),
			tk.createImage(EnemyFish.class.getClassLoader().getResource("images/enemyFish/fish3_r.gif")),
			tk.createImage(EnemyFish.class.getClassLoader().getResource("images/enemyFish/boss.gif"))
		};
	}

	public EnemyFish(int x, int y, int width, int height,
			FishFrame ff, Direction dir, int speed, MyFish OurEnemy, Image image) {
		super();
		this.x = x;
		this.y = y;
		this.width = width;
		this.height = height;
		this.ff = ff;
		this.dir = dir;
		this.xSpeed = speed;
		this.OurEnemy = OurEnemy;
		this.image = image;
	}
	
	/**
	 * 画出小鱼的方法
	 * @param g
	 */
	public void draw(Graphics g) {
		if(!live) {
			if(dir.equals(Direction.R)){
				ff.fishList_Left.remove(this);//如果小鱼死亡就从容器中移除
			}else{
				ff.fishList_Right.remove(this);//如果小鱼死亡就从容器中移除
			}
			return;//小鱼死亡则不再画出
		}
		
		g.drawImage(image, x, y, width, height, null);//画出自己的图片
		
		move();//小鱼位置变化
	}
	
	/**
	 * 小鱼移动的方法
	 */
	private void move() {
		if(dir.equals(Direction.L)) {
			x -= xSpeed;//如果小鱼的方向是朝左的,x坐标递减向左移动
		}else {
			x += xSpeed;//否则向右移动
		}
		
		//小鱼如果走出边界则判断为死亡
		if(dir.equals(Direction.R)){
			if(x > ff.GAME_WIDTH) this.live = false;//向右的小鱼,如果x坐标大于窗口宽度则死亡
		}else{
			if(x < 0) this.live = false;//向左的小鱼,如果x坐标小于窗口宽度则死亡
		}
	}
}


人物类:

package game;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.util.List;

public class MyFish extends GameObject{
	
	boolean bU = false, bR = false, bD = false, bL = false;//四个方向的键是否被按下的布尔量
	public int scores = 0;//玩家的游戏积分
	
	/**
	 * 加载我方小鱼的图片
	 */
	private static Toolkit tk = Toolkit.getDefaultToolkit();//拿到系统的工具包
	private static Image myFish_left = null;//朝左的图片
	private static Image myFish_right = null;//朝右的图片
	
	//在静态代码区中完成对图片的加载
	static{
		myFish_left = tk.createImage(MyFish.class.getClassLoader().getResource("images/myFish/myfish_left.gif"));
		myFish_right = tk.createImage(MyFish.class.getClassLoader().getResource("images/myFish/myfish_right.gif"));
	}


	public MyFish(int x, int y, FishFrame ff) {
		super();
		this.x = x;
		this.y = y;
		this.xSpeed = 5;
		this.ySpeed = 5;
		this.dir = Direction.STOP;
		this.width = 40;
		this.height = 40;
		this.ff = ff;
	}

	public void draw(Graphics g) {
		if(!live) return;
		if(dir == Direction.U || dir == Direction.RU || dir == Direction.R || dir == Direction.RD){
			g.drawImage(myFish_right, x, y, width, height, null);
		}else{
			g.drawImage(myFish_left, x, y, width, height, null);
		}
		move();//每画一次就改变鱼的坐标
	}

	/**
	 * 按下键盘鱼的方向改变
	 * @param e
	 */
	public void keyPressed(KeyEvent e) {
		int key = e.getKeyCode();
		switch(key) {
		case KeyEvent.VK_W :
			bU = true;
			break;
		case KeyEvent.VK_D :
			bR = true;
			break;
		case KeyEvent.VK_S :
			bD = true;
			break;
		case KeyEvent.VK_A :
			bL = true;
			break;
		}
		getDirection();//获得鱼当前的方向
	}
	
	/**
	 * 释放键盘鱼的四个方向布尔值设置为false
	 * @param e
	 */
	public void keyRelease(KeyEvent e) {
		int key = e.getKeyCode();
		switch(key) {
		case KeyEvent.VK_W :
			bU = false;
			break;
		case KeyEvent.VK_D :
			bR = false;
			break;
		case KeyEvent.VK_S :
			bD = false;
			break;
		case KeyEvent.VK_A :
			bL = false;
			break;
		}
		getDirection();//获得鱼当前的方向
	}

	/**
	 * 根据四个方向的布尔量判断小鱼的方向
	 */
	private void getDirection() {
		if(bU && !bR && !bD && !bL) dir = Direction.U;
		else if(bU && bR && !bD && !bL) dir = Direction.RU;
		else if(!bU && bR && !bD && !bL) dir = Direction.R;
		else if(!bU && bR && bD && !bL) dir = Direction.RD;
		else if(!bU && !bR && bD && !bL) dir = Direction.D;
		else if(!bU && !bR && bD && bL) dir = Direction.LD;
		else if(!bU && !bR && !bD && bL) dir = Direction.L;
		else if(bU && !bR && !bD && bL) dir = Direction.LU;
		else if(!bU && !bR && !bD && !bL) dir = Direction.STOP;
	}
	
	/**
	 * 移动,即改变坐标
	 */
	private void move() {
		switch(dir) {
		case U :
			y -= ySpeed;
			break;
		case RU :
			y -= ySpeed;
			x += xSpeed;
			break;
		case R :
			x += xSpeed;
			break;
		case RD :
			y += ySpeed;
			x += xSpeed;
			break;
		case D :
			y += ySpeed;
			break;
		case LD :
			y += ySpeed;
			x -= xSpeed;
			break;
		case L :
			x -= xSpeed;
			break;
		case LU :
			y -= ySpeed;
			x -= xSpeed;
			break;
		}
		
		//防止鱼出界
		if(x < 2) x = 2;
		if(y < 31) y = 31;
		if(x > FishFrame.GAME_WIDTH - width) x = FishFrame.GAME_WIDTH - width;
		if(y > FishFrame.GAME_HEIGHT - height) y = FishFrame.GAME_HEIGHT - height;
	}

	/**
	 * 通过两条小鱼的碰撞检测判断是否吃掉小鱼
	 * @param ef
	 * @return
	 */
	public boolean eatFish(EnemyFish ef) {
		if(this.live && ef.live && this.getRectangle().intersects(ef.getRectangle()) 
				&& this.width > ef.width) {
			ef.live = false;
			int radius = r.nextInt(3) + 5;
			this.width += radius;
			this.height += radius;
			this.scores += r.nextInt(15);
			return true;
		}
		return false;
	}
	
	/**
	 * 吃掉多条小鱼
	 * @param list
	 * @return
	 */
	public boolean eatFishs(List<EnemyFish> list) {
		for(EnemyFish e : list) {
			if(this.eatFish(e)) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 玩家的小鱼可以被吃掉
	 * @param list
	 * @return
	 */
	public boolean beEaten(List<EnemyFish> list) {
		for(EnemyFish e : list) {
			if(live && e.live && this.getRectangle().intersects(e.getRectangle()) 
					&& this.width <= e.width){
				this.live = false;
				return true;
			}
		}
		return false;
	}
}





部分线程类:

package game;

import java.util.Random;
/**
 * 从游戏窗口的左边添加小鱼的线程类,注释请看AddFishFromright类

 *
 */
public class AddFishFromLeft implements Runnable {
	private FishFrame ff;
	private Random r = new Random();
	
	public AddFishFromLeft(FishFrame ff) {
		this.ff = ff;
	}

	public void run() {
		while(ff.myFish.scores < 420){
			//int position = r.nextInt(ff.GAME_HEIGHT);
			int width = getWidthByMyFish();
			int position = getPositionByWidth(width);
			int speed = getSpeedByMyFish();
			EnemyFish ef1 = new EnemyFish(0 - 300, position, width, width,
					ff, Direction.R, speed, ff.myFish, EnemyFish.images[r.nextInt(3) + 3]);
			ff.fishList_Left.add(ef1);
			try {
				Thread.sleep(1500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		addBoss();
	}

	private int getPositionByWidth(int width) {
		return (r.nextInt(ff.GAME_HEIGHT - width - 31) + 31);
	}

	private void addBoss() {
		int radius = FishFrame.GAME_HEIGHT - 100;
		int speed = 5;
		EnemyFish ef = new EnemyFish(0 - FishFrame.GAME_WIDTH, 50, radius, radius,
				ff, Direction.R, speed, ff.myFish, EnemyFish.images[EnemyFish.images.length-1]);
		ff.fishList_Left.add(ef);

	}

	private int getWidthByMyFish() {
		//先获取当前MyFish的积分
		int score = ff.myFish.scores;//根据积分设置小鱼的大小
		if(score >= 0 && score <50) {
			return r.nextInt(90) + 10;
		}else if(score >= 50 && score < 100) {
			return r.nextInt(127) + 13;
		}else if(score >= 100 && score < 200){
			return r.nextInt(160) + 15;
		}else{
			return r.nextInt(230) + 25;
		}
	}

	private int getSpeedByMyFish() {
		//先获取当前MyFish的积分
		int score = ff.myFish.scores;//根据积分设置小鱼的速度
		if(score >= 0 && score <50) {
			return r.nextInt(5) + 1;
		}else if(score >= 50 && score < 100) {
			return r.nextInt(9) + 1;
		}else if(score >= 100 && score < 200){
			return r.nextInt(13) + 1;
		}else{
			return r.nextInt(18) + 1;
		}
	}
}


作者:KJ.JK
本文仅用于交流学习,未经作者允许,禁止转载,更勿做其他用途,违者必究。
文章对你有所帮助的话,欢迎给个赞或者 star,你的支持是对作者最大的鼓励,不足之处可以在评论区多多指正,交流学习

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/735793.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-27
下一篇 2022-04-27

发表评论

登录后才能评论

评论列表(0条)

保存