Java实现简单的王者荣耀游戏

一、创建新项目

首先创建一个新的项目,并命名为wangzherongyao。

其次在飞翔的鸟项目下创建一个名为img的文件夹用来存放游戏相关图片。详细如下图:

二、游戏代码

1、创建怪物类

1.bear:
package beast;import wangzherogyao.GameFrame;public class Bear extends Beast {public Bear(int x, int y, GameFrame gameFrame) {super(x, y, gameFrame);setImg("img/bear.jpg");width = 85;height = 112;setDis(65);}}
2.beast:
package beast;import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.ArrayList;import wangzherogyao.*;public class Beast extends GameObject {public ArrayList<Beast> beastList = new ArrayList<>();int width;int height;// 复活的元素Beast beast = null;public Beast(GameFrame gameFrame) {super(gameFrame);beastList.add(new RedBuff(3045, 3170, gameFrame));beastList.add(new Bear(2800, 2855, gameFrame));beastList.add(new Bird(3570, 3380, gameFrame));beastList.add(new Xiyi(4585, 2365, gameFrame));beastList.add(new BlueBuff(4025, 2295, gameFrame));beastList.add(new Wolf(4235, 1945, gameFrame));}public Beast(int x, int y, GameFrame gameFrame) {super(x, y, gameFrame);setHp(1000);setCurrentHp(getHp());beast = this;}@Overridepublic void paintSelf(Graphics g) {if (getCurrentHp() <= 0) {System.out.println("beast die");setAlive(false);gameFrame.removeList.add(this);gameFrame.beast.beastList.remove(this);new ReviveCD().start();} else {// 添加生命值addHp(g, width / 2, 80, width, 20, Color.GREEN);g.drawImage(getImg(), getX() - width / 2, getY() - height / 2, null);g.setColor(Color.RED);g.fillOval(getX(), getY(), 10, 10);g.drawOval(getX() - getDis(), getY() - getDis(), 2 * getDis(), 2 * getDis());}}@Overridepublic Rectangle getRec() {return new Rectangle(getX() - width / 2, getY() - height / 2, width, height);}//野怪复活class ReviveCD extends Thread {public void run() {// 线程休眠try {Thread.sleep(5000);} catch (Exception e) {e.printStackTrace();}Beast reviveBeast;if (beast instanceof RedBuff) {reviveBeast = new RedBuff(3045, 3170, gameFrame);} else if (beast instanceof Bear) {reviveBeast = new Bear(2800, 2855, gameFrame);} else if (beast instanceof Bird) {reviveBeast = new Bird(3570, 3380, gameFrame);} else if (beast instanceof Xiyi) {reviveBeast = new Xiyi(4585, 2365, gameFrame);} else if (beast instanceof BlueBuff) {reviveBeast = new BlueBuff(4025, 2295, gameFrame);} else {reviveBeast = new Wolf(4235, 1945, gameFrame);}gameFrame.objList.add(reviveBeast);gameFrame.beast.beastList.add(reviveBeast);}}}
3.红隼:
package beast;
import wangzherogyao.GameFrame;
public class Bird extends Beast {public Bird(int x, int y, GameFrame gameFrame) {super(x, y, gameFrame);setImg("img/红隼.jpg");width = 122;height = 98;setDis(125);}}
4.蓝buff:
package beast;
import wangzherogyao.GameFrame;
public class BlueBuff extends Beast {public BlueBuff(int x, int y, GameFrame gameFrame) {super(x, y, gameFrame);setImg("img/blueBuff.jpg");width = 142;height = 176;setDis(70);}}
5.红buff:
package beast;
import wangzherogyao.GameFrame;
public class RedBuff extends Beast {public RedBuff(int x, int y, GameFrame gameFrame) {super(x, y, gameFrame);setImg("img/redBuff.jpg");width = 103;height = 150;setDis(70);}
}
6.wolf:
package beast;
import wangzherogyao.GameFrame;
public class Wolf extends Beast {public Wolf(int x, int y, GameFrame gameFrame) {super(x, y, gameFrame);setImg("img/wolf.jpg");width = 145;height = 140;setDis(65);}}
7.蜥蜴:
package beast;
import wangzherogyao.GameFrame;
public class Xiyi extends Beast {public Xiyi(int x, int y, GameFrame gameFrame) {super(x, y, gameFrame);setImg("img/蜥蜴.jpg");width = 111;height = 65;setDis(125);}
}

2、创建背景类

package wangzherogyao;import java.awt.*;
//背景类
public  class Background extends GameObject{public Background(GameFrame gameFrame) {super(gameFrame);}Image bg = Toolkit.getDefaultToolkit().getImage("img/Map.jpg");public void paintSelf(Graphics g){g.drawImage(bg,0,0,null);}@Overridepublic Rectangle getRec() {return null;}
}

3、创建英雄类

package wangzherogyao;import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;import javax.swing.JButton;//游戏英雄类
public abstract class Champion extends GameObject {// 移动public boolean up, down, left, right;// 移动图集static String[] imgs = new String[8];// 第几张图片int moveCount = 1;//技能图片Image abilityOne;Image abilityTwo;Image abilityThree;//技能冷却时间int coolDownTimeOne;int coolDownTimeTwo;int coolDownTimeThree;//三个技能是否处于冷却状态boolean coolDownOne = true;boolean coolDownTwo = true;boolean coolDownThree = true;static {for (int i = 1; i < 8; i++) {imgs[i] = "" + i + ".png";}}public Champion(GameFrame gameFrame) {super(gameFrame);//定义英雄的图片和坐标setImg("img/stand.png");setX(700);setY(3800);setSpd(75);setHp(24000);setDis(250);setAttackCoolDownTime(100);setCurrentHp(getHp());}public void keyPressed(KeyEvent e) {int key = e.getKeyCode();if (key == KeyEvent.VK_D) {right = true;}if (key == KeyEvent.VK_A) {left = true;}if (key == KeyEvent.VK_W) {up = true;}if (key == KeyEvent.VK_S) {down = true;}}public void keyReleased(KeyEvent e) {int key = e.getKeyCode();if (key == KeyEvent.VK_D) {right = false;}if (key == KeyEvent.VK_A) {left = false;}if (key == KeyEvent.VK_W) {up = false;}if (key == KeyEvent.VK_S) {down = false;}}public void move() {if (up) {setY(getY() - getSpd());}if (down) {setY(getY() + getSpd());}if (left) {setX(getX() - getSpd());}if (right) {setX(getX() + getSpd());}if (up || down || left || right) {setImg(imgs[moveCount]);moveCount++;if (moveCount == 8) {moveCount = 1;}} else {setImg("img/stand.png");}}//添加三个技能按钮public void addButton() {JButton button1 = new JButton();button1.setSize(100, 100);button1.setLocation(1056, 513);button1.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {abilityOne();}});JButton button2 = new JButton();button2.setSize(100, 100);button2.setLocation(1090, 370);button2.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {abilityTwo();}});JButton button3 = new JButton();button3.setSize(100, 100);button3.setLocation(1220, 300);button3.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {abilityThree();}});gameFrame.add(button1);gameFrame.add(button2);gameFrame.add(button3);}public abstract void abilityOne();public abstract void abilityTwo();public abstract void abilityThree();public abstract void abilityEffect(Graphics g);@Overridepublic void paintSelf(Graphics g) {// 生命值为0if (getCurrentHp() <= 0) {setAlive(false);gameFrame.removeList.add(this);} else {// 添加生命值addHp(g, 30, 80, 80, 20, Color.GREEN);//绘制技能图片g.drawImage(abilityOne, getX() + 360, getY() + 180, null);g.drawImage(abilityTwo, getX() + 400, getY() + 40, null);g.drawImage(abilityThree, getX() + 520, getY() - 30, null);// 绘制图片g.drawImage(this.getImg(), getX() - 33, getY() - 50, null);// 改变画笔颜色g.setColor(Color.GREEN);// 绘制中心圆点g.fillOval(getX(), getY(), 10, 10);// 绘制矩形边框g.drawRect(getX() - 23, getY() - 50, 60, 120);move();abilityEffect(g);}}@Overridepublic Rectangle getRec() {return new Rectangle(getX() - 30, getY() - 60, 60, 120);}}

玩家:

package wangzherogyao;import java.awt.Color;
import java.awt.Graphics;
import java.awt.Polygon;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Random;public class ChampionDaji extends Champion {// 技能是否处于释放状态boolean ifAbilityOne = false;boolean ifAbilityTwo = false;// 鼠标监视器MouseMonitor m;// 一技能多边形Polygon p;// 一技能三角函数double sin;double cos;// 一技能已经攻击过的目标ArrayList<GameObject> attacked;// 一技能移动次数int step = 0;// 技能二目标GameObject abilityTwoTarget;// 技能二子弹Bullet abilityTwoBullet;// 三技能的五个子弹,释放三技能后重新定义Bullet[] bulletList = { new Bullet(), new Bullet(), new Bullet(), new Bullet(), new Bullet() };public ChampionDaji(GameFrame gameFrame) {super(gameFrame);abilityOne = Toolkit.getDefaultToolkit().getImage("img/abilityOne.jpg");abilityTwo = Toolkit.getDefaultToolkit().getImage("img/abilityTwo.jpg");abilityThree = Toolkit.getDefaultToolkit().getImage("img/abilityThree.jpg");// 三个技能冷却时间coolDownTimeOne = 3000;coolDownTimeTwo = 5000;coolDownTimeThree = 8000;}public void exit() {this.gameFrame.removeMouseListener(m);}public void abilityOneMove() {p.translate((int) (50 * cos), -(int) (50 * sin));for (GameObject redObj : gameFrame.redList) {// 是红色方小兵 && 发生碰撞 && 没在attacked列表里if (redObj instanceof MinionRed && p.intersects(redObj.getRec()) && attacked.indexOf(redObj) == -1) {// 小兵扣血,添加到attacked里redObj.setCurrentHp(redObj.getCurrentHp() - 400);attacked.add(redObj);}}}@Overridepublic void abilityOne() {if (coolDownOne) {m = new MouseMonitor();p = new Polygon();gameFrame.addMouseListener(m);attacked = new ArrayList<GameObject>();}}public void abilityTwo() {if (coolDownTwo) {boolean find = false;for (GameObject redObj : gameFrame.objList) {// 是红色小兵 && 距离小于250 && 存活if (redObj instanceof MinionRed && recIntersectsCir(redObj.getRec(), getX(), getY(), 250)&& redObj.isAlive()) {// 添加子弹abilityTwoBullet = new Bullet(gameFrame, this, redObj, 250, 60, "C:\\Users\\24465\\Desktop\\王者荣耀图片(1)\\王者荣耀图片\\Daji\\abilityTwoBullet.png");gameFrame.objList.add(abilityTwoBullet);// 给目标赋值abilityTwoTarget = redObj;// 释放二技能ifAbilityTwo = true;find = true;break;}}if (find) {new AbilityTwoCD().start();find = false;}}}/*** 点击技能三释放技能 先将技能范围内目标储存到targetList里 提前定义五个子弹 技能释放时初始化五个子弹 子弹目标从targetList里随机选择* 如果期间目标死亡,制作一个目标替身,生命值设置为true 子弹与目标或替身碰撞后消失*/@Overridepublic void abilityThree() {if (coolDownThree) {// 创建列表来储存目标ArrayList<GameObject> targetList = new ArrayList<GameObject>();// 遍历redList,找到符合条件的目标,储存到列表里for (int i = 0; i < gameFrame.objList.size(); i++) {GameObject target = gameFrame.objList.get(i);// 是红色小兵 && 在技能范围里 && 存活if (target instanceof MinionRed && recIntersectsCir(target.getRec(), getX(), getY(), 250)&& target.isAlive()) {targetList.add(target);}}// 找到目标if (targetList.size() != 0) {// 创建五个子弹,随机攻击列表里的目标Random random = new Random();int count = 0; // 统计三技能发射子弹数量while (count < 5) {int r = random.nextInt(targetList.size());if (!targetList.get(r).isAlive()) {GameObject substitute = targetList.get(r);substitute.setAlive(true);bulletList[count] = new Bullet(gameFrame, this, substitute, 150, 60,"img/abilityTwoBullet.png");} else {bulletList[count] = new Bullet(gameFrame, this, targetList.get(r), 150, 60,"img/abilityTwoBullet.png");}count++;}new AbilityThreeBulletCD().start();// 三技能进入冷却new AbilityThreeCD().start();}}}@Overridepublic void abilityEffect(Graphics g) {if (ifAbilityOne) {g.setColor(Color.RED);g.fillPolygon(p);abilityOneMove();step++;if (step == 10) {step = 0;ifAbilityOne = false;}}if (ifAbilityTwo) {System.out.println(abilityTwoTarget.beControlled);if (abilityTwoBullet.getRec().intersects(abilityTwoTarget.getRec())) {new AbilityControllCD().start();ifAbilityTwo = false;}}}// 技能一冷却时间class AbilityOneCD extends Thread {public void run() {// 将技能一设置为冷却状态coolDownOne = false;// 线程休眠try {// one来表示一技能冷却时间int one = coolDownTimeOne;while (one > 0) {Thread.sleep(1000);System.out.println("一技能冷却时间: " + one / 1000);one -= 1000;}} catch (Exception e) {e.printStackTrace();}// 将技能一设置为攻击状态coolDownOne = true;// 线程终止this.interrupt();}}// 技能二冷却时间class AbilityTwoCD extends Thread {public void run() {// 将技能二设置为冷却状态coolDownTwo = false;// 线程休眠try {// one来表示二技能冷却时间int two = coolDownTimeTwo;while (two > 0) {Thread.sleep(1000);System.out.println("二技能冷却时间: " + two / 1000);two -= 1000;}} catch (Exception e) {e.printStackTrace();}// 将技能二设置为攻击状态coolDownTwo = true;// 线程终止this.interrupt();}}// 技能二控制时间class AbilityControllCD extends Thread {public void run() {abilityTwoTarget.beControlled = true;// 线程休眠try {Thread.sleep(20000);} catch (Exception e) {e.printStackTrace();}abilityTwoTarget.beControlled = false;this.interrupt();}}//技能三冷却状态class AbilityThreeCD extends Thread {public void run() {// 将攻击功能设置为冷却状态coolDownThree = false;// 休眠try {int three = coolDownTimeThree;while (coolDownTimeThree > 0) {Thread.sleep(1000);System.out.println("技能三冷却时间: " + coolDownTimeThree / 1000);coolDownTimeThree -= 1000;}coolDownTimeThree = three;} catch (Exception e) {e.printStackTrace();}// 将攻击功能解除冷却状态coolDownThree = true;// 线程终止this.interrupt();}}class AbilityThreeBulletCD extends Thread {public void run() {// 休眠try {System.out.println("Thread start");gameFrame.objList.add(bulletList[0]);Thread.sleep(100);gameFrame.objList.add(bulletList[1]);Thread.sleep(100);gameFrame.objList.add(bulletList[2]);Thread.sleep(100);gameFrame.objList.add(bulletList[3]);Thread.sleep(100);gameFrame.objList.add(bulletList[4]);} catch (Exception e) {e.printStackTrace();}// 线程终止this.interrupt();}}// 鼠标监视器private class MouseMonitor extends MouseAdapter {@Overridepublic void mousePressed(MouseEvent e) {// 当鼠标点击时int mouseX = e.getX(), mouseY = e.getY(), playerX = 700, playerY = 350;double dis = getDis(mouseX, mouseY, playerX, playerY);// 三角函数cos = (mouseX - playerX) / dis;sin = -(mouseY - playerY) / dis;// 坐标差int difX = (int) (60 * sin);int difY = (int) (60 * cos);p.addPoint(getX() - difX, getY() - difY);p.addPoint(getX() + difX, getY() + difY);p.addPoint(getX() + difX + (int) (20 * cos), getY() + difY - (int) (20 * sin));p.addPoint(getX() - difX + (int) (20 * cos), getY() - difY - (int) (20 * sin));exit();new AbilityOneCD().start();ifAbilityOne = true;}}
}

4、创建红方

package wangzherogyao;import java.util.ArrayList;public  class MinionRed extends Minion {public MinionRed(GameFrame gameFrame) {super(gameFrame);setImg("img/red.jpg");setX(5050);setY(1125);}@Overridepublic void move(ArrayList<GameObject> objList) {if (isIfFindTarget()) {// 离开检测范围if (!recIntersectsCir(getTarget().getRec(), getX(), getY(), 200)) {setIfFindTarget(false);} else {if (!isHasTarget()) {moveToTarget();}attack(objList);}} else {findTarget(objList);// 原路线移动if (getY() < 3125) {setSpd(28);setY(getY() + getSpd());} else if (getY() < 3750 && getY() >= 3125) {setSpd(20);setY(getY() + getSpd());setX(getX() - getSpd());} else if (getY() >= 3750) {setSpd(25);setX(getX() - getSpd());}}}}

5、创建蓝方

package wangzherogyao;import java.util.ArrayList;public  class MinionBlue extends Minion{public MinionBlue(GameFrame gameFrame) {super(gameFrame);setImg("img/blue.jpg");setX(1325);setY(3750);}@Overridepublic void move(ArrayList<GameObject> objList) {if(isIfFindTarget()) {//离开检测范围if(!recIntersectsCir(getTarget().getRec(), getX(), getY(), 200)) {setIfFindTarget(false);}else {if(!isHasTarget()) {moveToTarget();}attack(objList);}}else {findTarget(objList);//原路线移动if(getX() < 4425) {setSpd(5);setX(getX() + getSpd());}else if(getX() < 5100 && getX() >= 4425) {setSpd(20);setX(getX() + getSpd());setY(getY() - getSpd());}else if(getX() >= 4900) {setSpd(18);setY(getY() - getSpd());}}}
}

6、攻击效果,子弹类

package wangzherogyao;import java.awt.*;//子弹类
public  class Bullet extends GameObject {//发射子弹的游戏元素GameObject attacker;//目标GameObject target;//攻击力int ad;public Bullet(GameFrame gameFrame, GameObject attacker, GameObject target, int ad, int spd) {super(attacker.getX(), attacker.getY(), gameFrame);this.attacker = attacker;this.target = target;setAd(ad);setSpd(spd);}public Bullet(GameFrame gameFrame, GameObject attacker, GameObject target, int ad, int spd, String img) {super(attacker.getX(), attacker.getY(), gameFrame);this.attacker = attacker;this.target = target;setImg(img);setAd(ad);setSpd(spd);}public Bullet() {super();}public void move() {//子弹与目标碰撞,子弹消失,目标减血if (recIntersectsRec(getRec(), target.getRec())) {target.setCurrentHp(target.getCurrentHp() - getAd());gameFrame.removeList.add(this);}int dis = (int) getDis(getX(), getY(), target.getX(), target.getY());if (dis != 0) {int xSpeed =  (getSpd() * (target.getX() - getX()) / dis);int ySpeed =  (getSpd() * (target.getY() - getY()) / dis);setX(getX() + xSpeed);setY(getY() + ySpeed);}}@Overridepublic void paintSelf(Graphics g) {g.drawImage(getImg(), getX()-16, getY()-16, null);g.setColor(Color.BLACK);g.fillOval(getX()-5, getY()-5, 10, 10);g.drawRect(getX()-5, getY()-5, 10, 10);move();}@Overridepublic Rectangle getRec() {return new Rectangle(getX()-5, getY()-5, 10, 10);}public int getAd() {return ad;}public void setAd(int ad) {this.ad = ad;}
}

7、兵线类

package wangzherogyao;import java.awt.*;
import java.util.ArrayList;public abstract class Minion extends GameObject{// 是否生成下一个小兵private boolean nextMinion = true;// 是否生成下一波小兵private boolean nextLine = true;// 生成小兵数量private int minionCount = 0;// 是否检测到目标private boolean ifFindTarget = false;public Minion(GameFrame gameFrame) {super(gameFrame);setHp(800);setCurrentHp(getHp());setDis(100);setAttackCoolDownTime(2000);}/*** (1325, 3750) (4425, 3750) (5050, 3125) (5050, 1125)*/public abstract void move(ArrayList<GameObject> objList);public void findTarget(ArrayList<GameObject> objList) {for (GameObject obj : objList) {if (recIntersectsCir(obj.getRec(), getX(), getY(), 200)) {setTarget(obj);setIfFindTarget(true);}}if (objList == gameFrame.blueList) {if (recIntersectsCir(gameFrame.player.getRec(), getX(), getY(), 200)) {setTarget(gameFrame.player);setIfFindTarget(true);}}}public void moveToTarget() {int dis = (int) getDis(getX(), getY(), getTarget().getX(), getTarget().getY());if(dis!=0) {int xSpeed =  (getSpd() * (getTarget().getX() - getX()) / dis);int ySpeed = (getSpd() * (getTarget().getY() - getY()) / dis);setX(getX() + xSpeed);setY(getY() + ySpeed);}}public void createMinion(GameFrame gameFrame, ArrayList<GameObject> minionList) {if (nextLine) {if (nextMinion) {// 蓝色方小兵if (minionList == this.gameFrame.blueList) {MinionBlue mb = new MinionBlue(gameFrame);gameFrame.objList.add(mb);minionList.add(mb);}// 红色方小兵else {MinionRed mr = new MinionRed(gameFrame);gameFrame.objList.add(mr);minionList.add(mr);}minionCount++;new NextMinion().start();}if (minionCount == 3) {minionCount = 0;new NextLine().start();}}}// 每个小兵生成时间class NextMinion extends Thread {public void run() {nextMinion = false;// 休眠1.5stry {Thread.sleep(1500);} catch (Exception e) {e.printStackTrace();}nextMinion = true;// 线程终止this.interrupt();}}// 每波小兵生成时间class NextLine extends Thread {public void run() {nextLine = false;// 休眠15stry {Thread.sleep(15000);} catch (Exception e) {e.printStackTrace();}nextLine = true;// 线程终止this.interrupt();}}@Overridepublic void paintSelf(Graphics g) {// 生命值为0if (getCurrentHp() <= 0) {setAlive(false);gameFrame.removeList.add(this);if (this instanceof MinionBlue) {gameFrame.blueList.remove(this);} else {gameFrame.redList.remove(this);}} else {// 添加生命值if (this instanceof MinionBlue) {this.addHp(g, 17, 28, 45, 10, Color.GREEN);} else {this.addHp(g, 17, 28, 45, 10, Color.RED);}g.drawImage(getImg(), getX() - 16, getY() - 16, null);g.setColor(Color.RED);g.fillOval(getX(), getY(), 10, 10);g.drawRect(getX() - 16, getY() - 16, 45, 45);g.drawOval(getX() - 200, getY() - 200, 400, 400);// 小兵移动if (!beControlled) {if (this instanceof MinionBlue) {move(gameFrame.redList);} else {move(gameFrame.blueList);}}}}@Overridepublic Rectangle getRec() {return new Rectangle(getX() - 16, getY() - 16, 45, 45);}public boolean isIfFindTarget() {return ifFindTarget;}public void setIfFindTarget(boolean ifFindTarget) {this.ifFindTarget = ifFindTarget;}}

8、游戏窗口类

package wangzherogyao;import beast.Beast;import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.ArrayList;import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.FloatControl;
import javax.swing.JButton;
import javax.swing.JFrame;public class GameFrame extends JFrame {// 游戏开始 0, 游戏胜利1,游戏失败2int state = 0;// 窗口尺寸final int windowWidth = 1400;final  int windowHeight = 700;// 双缓冲图片private Image offScreenImage = null;// 攻击图片private Image attack = Toolkit.getDefaultToolkit().getImage("img/attack.jpg");//游戏胜利失败图片private Image gameWin = Toolkit.getDefaultToolkit().getImage("img/gameWin.png");private Image gameLose = Toolkit.getDefaultToolkit().getImage("img/gameLose.png");// 游戏背景Background background = new Background(this);// 游戏玩家Champion player = new ChampionDaji(this);// 双方小兵MinionBlue mb = new MinionBlue(this);MinionRed mr = new MinionRed(this);//野怪public Beast beast = new Beast(this);// 防御塔Turret turret = new Turret(this);// 游戏元素列表public ArrayList<GameObject> objList = new ArrayList<>();ArrayList<GameObject> redList = new ArrayList<>();// 红色方ArrayList<GameObject> blueList = new ArrayList<>();// 蓝色方public ArrayList<GameObject> removeList = new ArrayList<>();// 存放将要删除的元素public void launch() {// 设置尺寸setSize(windowWidth, windowHeight);// 窗口居中setLocationRelativeTo(null);// 关闭事件setDefaultCloseOperation(3);// 用户不能调整窗口大小setResizable(false);// 标题setTitle("王者荣耀");// 窗口可见setVisible(true);// 添加键盘监视器this.addKeyListener(new GameFrame.KeyMonitor());// 添加游戏元素objList.add(background);objList.add(player);objList.addAll(beast.beastList);objList.addAll(turret.turretList);playMusic();for (int i = 0; i < 4; i++) {blueList.add(turret.turretList.get(i));}for (int i = 4; i < 8; i++) {redList.add(turret.turretList.get(i));}/*** 攻击按钮*/JButton button = new JButton();button.setSize(130, 132);button.setLocation(1150, 430);button.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// 按钮事件player.attack(redList);}});this.add(button);player.addButton();while (true) {mb.createMinion(this, blueList);mr.createMinion(this, redList);repaint();try {Thread.sleep(25);} catch (Exception e) {e.printStackTrace();}}}public void paint(Graphics g) {if (offScreenImage == null) {offScreenImage = this.createImage(5984, 4452);}Graphics gImage = offScreenImage.getGraphics();if(state==0){turret.isLive();for (int i = 0; i < objList.size(); i++) {objList.get(i).paintSelf(gImage);}// 绘制攻击图片gImage.drawImage(attack, player.getX() + 500, player.getY() + 100, null);objList.removeAll(removeList);} else if (state ==1) {//游戏胜利gImage.drawImage(gameWin, player.getX()-700, player.getY()-300 , null);} else if (state == 2) {//游戏失败gImage.drawImage(gameLose, player.getX()-700, player.getY()-300, null);}g.drawImage(offScreenImage, -player.getX() + 700, -player.getY() + 350, null);// 添加按钮后不能调用键盘事件 因为程序的焦点变成了按钮 this.requestFocus() 把焦点重新改变到游戏界面上this.requestFocus();}// main方法public static void main(String[] args) {GameFrame gameFrame = new GameFrame();gameFrame.launch();}// 键盘事件private class KeyMonitor extends KeyAdapter {@Overridepublic void keyPressed(KeyEvent e) {int key = e.getKeyCode();player.keyPressed(e);}@Overridepublic void keyReleased(KeyEvent e) {int key = e.getKeyCode();player.keyReleased(e);}}static Clip clip;public static void playMusic() {try{//这里面放 绝对路径,音频必须是wav格式,用音频转换软件 把mp3 转成wav格式File musicPath = new File("C:\\Users\\23839\\IdeaProjects\\PlaneWar\\PlayMusic\\bgm.wav");if(musicPath.exists()){AudioInputStream audioInput = AudioSystem.getAudioInputStream(musicPath);clip = AudioSystem.getClip();clip.open(audioInput);FloatControl gainControl = (FloatControl)clip.getControl(FloatControl.Type.MASTER_GAIN);gainControl.setValue(-20.0f);//设置音量,范围为 -60.0f 到 6.0fclip.start();clip.loop(Clip.LOOP_CONTINUOUSLY);}else{}}catch(Exception ex){ex.printStackTrace();}}}

9、防御塔类

package wangzherogyao;import java.awt.*;
import java.util.ArrayList;
//防御塔类
public  class Turret extends GameObject{ArrayList<Turret> turretList = new ArrayList<>();public Turret turretBlueOne;public Turret turretBlueTwo;public Turret turretBlueThree;public Turret turretBlueBase;public Turret turretRedOne;public Turret turretRedTwo;public Turret turretRedThree;public Turret turretRedBase;public Turret(GameFrame gameFrame) {super(gameFrame);setImg("img/turret.png");// 初始化八个防御塔turretList.add(turretBlueOne = new TurretBlue(1860, 3790, gameFrame));turretList.add(turretBlueTwo = new TurretBlue(2650, 3820, gameFrame));turretList.add(turretBlueThree = new TurretBlue(3995, 3830, gameFrame));turretList.add(turretBlueBase = new TurretBlue(1130, 3650, gameFrame));turretList.add(turretRedOne = new TurretRed(5100, 3030, gameFrame));turretList.add(turretRedTwo = new TurretRed(5120, 2100, gameFrame));turretList.add(turretRedThree = new TurretRed(5060, 1570, gameFrame));turretList.add(turretRedBase = new TurretRed(4850, 1100, gameFrame));}public Turret(int x, int y, GameFrame gameFrame) {super(x, y, gameFrame);setImg("C:\\Users\\24465\\Desktop\\王者荣耀图片(1)\\王者荣耀图片\\turret.png");setHp(6000);setCurrentHp(getHp());setAttackCoolDownTime(1000);setDis(300);}public void isLive(){if(gameFrame.turret.turretBlueBase.getCurrentHp()==0){gameFrame.state=2;}if(gameFrame.turret.turretRedBase.getCurrentHp()==0){gameFrame.state=1;}}@Overridepublic void paintSelf(Graphics g) {// 生命值为0if (getCurrentHp() <= 0) {setAlive(false);gameFrame.removeList.add(this);if (this instanceof TurretBlue) {gameFrame.blueList.remove(this);} else {gameFrame.redList.remove(this);}} else {// 添加生命值if (this instanceof TurretBlue) {this.addHp(g, 50, 130, 100, 20, Color.GREEN);attack(gameFrame.redList);} else {this.addHp(g, 50, 130, 100, 20, Color.RED);attack(gameFrame.blueList);}g.drawImage(getImg(), getX() - 50, getY() - 100, null);g.fillOval(getX(), getY(), 10, 10);g.drawRect(getX() - 50, getY() - 100, 100, 180);g.drawOval(getX() - 300, getY() - 300, 600, 600);}}@Overridepublic Rectangle getRec() {return new Rectangle(getX() - 50, getY() - 100, 100, 180);}
}

10、蓝方防御塔类

package wangzherogyao;
//蓝方防御塔
public class TurretBlue extends Turret{public TurretBlue(GameFrame gameFrame){super(gameFrame);}public TurretBlue(int x,int y,GameFrame gameFrame){super(x,y,gameFrame);}
}

11、红方防御塔类

package wangzherogyao;
//红方防御塔
public class TurretRed extends Turret{//有参构造public TurretRed(GameFrame gameFrame){super(gameFrame);}public TurretRed(int x,int y,GameFrame gameFrame){super(x,y,gameFrame);}
}

三、运行效果

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/205862.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Linux 基本语句_13_消息队列

概念&#xff1a; 不同进程能通过消息队列来进行通信&#xff0c;不同进程也能获取或发送特定类型的消息&#xff0c;即选择性的收发消息。 一般一个程序采取子进程发消息&#xff0c;父进程收消息的模式 常用函数功能&#xff1a; fork(); // 创建子进程 struct msgbuf{ …

运维知识点-openResty

openResty 企业级实战——畅购商城SpringCloud-网站首页高可用解决方案-openRestynginxlua——实现广告缓存测试企业级实战——畅购商城SpringCloud-网站首页高可用解决方案-openRestynginxlua——OpenResty 企业级实战——畅购商城SpringCloud-网站首页高可用解决方案-openRes…

2023-简单点-树莓派-camera module 3介绍

Raspberry Pi Camera Module 3 介绍开头先说&#xff0c;注意事项libcamera感光芯片和驱动的兼容图额外&#xff1a;不同module的对应的参数图用bullseye系统测试摄像头预览窗口拍摄静态图片bayer raw图像获取超长曝光视频流raw视频流 ref 介绍 树莓派镜像在Bullseye版本之后&…

linux 讨论题合集(个人复习)

常规文件的权限是什么&#xff1f;如何分配或修改这些权限&#xff1f;文件夹&#xff08;目录&#xff09;的权限是什么&#xff1f;显示常规文件和文件夹的区别 讨论&#xff1a;①常规的文件权限有四种&#xff0c;r可读、w可写、x可执行、-没有权限&#xff1b;②可以使用c…

如何使用录屏软件在电脑录制PDF文件

我有一个PDF文件&#xff0c;想用录屏软件将它录制下来并添加上详细的注释&#xff0c;然后发给客户看&#xff0c;请问应该如何录制呢&#xff1f;有没有推荐的录屏软件呢&#xff1f; 不用担心&#xff0c;本文将会详细的为您讲解如何使用录屏软件在电脑端录制PDF文件&#…

软件测试jmeter基本使用

1安装与配置 1.jdk下载 下载地址&#xff1a;https://www.oracle.com/java/technologies/downloads/#jdk18-windows&#xff08;压缩包中会给&#xff09; 2.jmeter下载 Apache JMeter - Download Apache JMeter&#xff08;压缩包中有&#xff09; 3.操作教学 打开软件后新…

【MySQL数据库】SQL查询语句总结

目录 一、查询数据 1.1 基本查询语句 1.2 表单查询 1.3 WHERE子句 1.3.1 IN关键字查询 1.3.2 Between查询范围 1.3.3 Like匹配查询 1.3.4 AND多条件查询&#xff08;等同于&&&#xff09; 1.3.5 OR多条件查询&#xff08;等同于||&#xff09; 1.3.6 LIMIT子句 1.3.7 对…

【Node.js】笔记整理4 - 版本管理工具nvm

写在最前&#xff1a;跟着视频学习只是为了在新手期快速入门。想要学习全面、进阶的知识&#xff0c;需要格外注重实战和官方技术文档&#xff0c;文档建议作为手册使用 系列文章 【Node.js】笔记整理 1 - 基础知识【Node.js】笔记整理 2 - 常用模块【Node.js】笔记整理 3 - n…

【docker】docker安装与优化

目录 一、安装Docker 1、关闭防火墙 2、安装依赖包 3、设置阿里云镜像源 4、安装Docker-CE社区版并设置为开机自启动 5、查看Docker信息 二、设置镜像加速 1、申请加速地址 2、实现加速操作 三、网络优化 1、如何网络优化 2、具体操作 四、docker-server端配置文件…

前端:实现二级菜单(点击实现二级菜单展开)

效果 代码 <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"><meta http-equiv"X-UA-Compatible" content"IEedge"><meta name"viewport" content"widthdevice-width, i…

【Excel】WPS快速按行筛选过滤

用的筛选都是进行列数据过滤&#xff0c;那么遇到一个情况需要行数据过滤查看数据 行过滤 选中行&#xff0c;然后右键菜单&#xff0c;行筛选。 列过滤

7Docker搭建es和kibana

一、安装es 1.拉取镜像 sudo docker pull elasticsearch:7.12.0 elasticsearch:7.12.0:我安装的版本是7.12.0&#xff0c;可以根据实际的情况安装 创建docker容器挂在的目录&#xff1a; sudo mkdir -p /opt/elasticsearch/config sudo mkdir -p /opt/elasticsearch/data s…

使用Python爬取快手视频与评论(App与Web端分析)

文章目录 1. APP端抓包配置2. APP端抓包分析3. Web端抓包分析4. 爬虫代码实现 【作者主页】&#xff1a;吴秋霖 【作者介绍】&#xff1a;Python领域优质创作者、阿里云博客专家、华为云享专家。长期致力于Python与爬虫领域研究与开发工作&#xff01; 【作者推荐】&#xff1a…

13:kotlin类和对象 -- 属性(Properties)

定义属性 类属性可使用var和val定义 class Address {var name: String "Holmes, Sherlock"var street: String "Baker"var city: String "London"var state: String? nullvar zip: String "123456" }属性使用 fun copyAddres…

【虚拟机】Docker基础 【一】

1.1.部署MySQL 首先&#xff0c;我们利用Docker来安装一个MySQL软件&#xff0c;大家可以对比一下之前传统的安装方式&#xff0c;看看哪个效率更高一些。 如果是利用传统方式部署MySQL&#xff0c;大概的步骤有&#xff1a; 搜索并下载MySQL安装包上传至Linux环境编译和配置…

低调使用。推荐一个 GPT4 Turbo、Vision、GPTs、DELL·E3 等所有最新功能同步可用国内网站

在 11 月 6 日&#xff0c;万众期待的 OpenAI DevDay&#xff0c;ChatGPT 发布了一系列新的产品&#xff0c;其中推出了 GPT4 Turbo&#xff0c;并且将GPT4 Vision&#xff0c;DELLE3 等等能力全部集合到一起&#xff0c;不需要再分开使用&#xff0c;原来的局限的文本聊天也进…

php订单发起退款(余额和微信支付)

index.html <a class"btn btn-danger btn-change btn-tuikuan btn-disabled" href"javascript:;"><i class"fa fa-tuikuan"></i> 订单退款</a>-->order.js // 为表格绑定事件Table.api.bindevent(table);//退款按钮…

【经验分享】openGauss 客户端(Data Studio / DBeaver)连接方式

前言 本篇介绍了openGauss常用的客户端连接工具Data Studio和DBeaver 01 客户端工具 openGauss部署之后&#xff0c;在服务器上提供了在命令行下运行的数据库连接工具gsql。此工具除了具备操作数据库的基本功能&#xff0c;还提供了若干高级特性&#xff0c;便于用户使用。…

建设“参与城市”大学--SMU在2023年绿色金融全球论坛上分享观点

2023年11月21日&#xff0c;由新加坡管理大学&#xff08;SMU&#xff0c;简称新大&#xff09;和中国人民大学&#xff08;RUC&#xff0c;简称人大&#xff09;联合主办的“绿色金融与治理&#xff1a;从承诺到行动”全球论坛在北京召开。论坛汇集了来自新加坡、中国及世界各…

【C++高阶(六)】哈希的应用--位图布隆过滤器

&#x1f493;博主CSDN主页:杭电码农-NEO&#x1f493;   ⏩专栏分类:C从入门到精通⏪   &#x1f69a;代码仓库:NEO的学习日记&#x1f69a;   &#x1f339;关注我&#x1faf5;带你学习C   &#x1f51d;&#x1f51d; 哈希的应用 1. 前言2. 位图的概念以及定义3. 位…