第一步是创建项目 项目名自拟
第二部创建个包名 来规范class
创建类 GameFrame 运行类
package com.sxt;import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;import javax.swing.JButton;
import javax.swing.JFrame;public class GameFrame extends JFrame {// 窗口尺寸private int windowWidth = 1400;private int windowHeight = 700;// 双缓冲图片private Image offScreenImage = null;// 攻击图片private Image attack = Toolkit.getDefaultToolkit().getImage("img/attack.jpg");// 游戏背景Background background = new Background(this);// 游戏玩家Champion player = new ChampionHouyi(this);// 双方小兵MinionBlue mb = new MinionBlue(this);MinionRed mr = new MinionRed(this);// 防御塔Turret turret = new Turret(this);// 攻击按钮JButton attackButton;// 游戏元素列表ArrayList<GameObject> objList = new ArrayList<GameObject>();ArrayList<GameObject> redList = new ArrayList<GameObject>();// 红色方ArrayList<GameObject> blueList = new ArrayList<GameObject>();// 蓝色方ArrayList<GameObject> removeList = new ArrayList<GameObject>();// 存放将要删除的元素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(turret.turretList);blueList.add(turret.turretList.get(0));redList.add(turret.turretList.get(4));/*** 攻击按钮*/attackButton = new JButton();attackButton.setSize(130, 132);attackButton.setLocation(1150, 430);attackButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// 按钮事件player.attack(redList);}});this.add(attackButton);player.addButton();while (true) {mb.createMinion(this, blueList);mr.createMinion(this, redList);turret.addTurret(this);repaint();try {Thread.sleep(25);} catch (Exception e) {e.printStackTrace();}}}public void paint(Graphics g) {// System.out.println(player.getX()+" "+player.getY());if (offScreenImage == null) {offScreenImage = this.createImage(5984, 4452);}Graphics gImage = offScreenImage.getGraphics();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);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);}}
}