Java坦克大战,基于Swing编写很哇塞的小游戏,可以做课程设计毕业设计
有图有真相
操作方法:ASDW控制移动,鼠标控制炮筒旋转,鼠标左键开枪,空格发射炮弹,
开发思路是标准的游戏开发思路,单线程帧率控制,调度器,绘图API,补间动画,技能冷却条,监听器,全都安排。
https://www.bilibili.com/video/BV1H54y1b7e9/
视频教程在这里,好好学习,天天向上,
收藏,点赞,好评,快来给我也安排一波
部分代码:
创建JFrame窗口,由于标题栏和边框也占用空间,所以实际内容和我们设置的尺寸会有出入,因此我们计算差值,重新设置尺寸,确保游戏画板的尺寸和我们预设的相同。
public class GameWindow extends JFrame {
public GameWindow(){
this.setSize(860,640);
this.setLocationRelativeTo(null);
//this.setResizable(false);
this.setTitle("坦克大战 V1.0");
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(panel);
int w = this.getContentPane().getSize().width;
int h = this.getContentPane().getSize().height;
System.out.println(w);
System.out.println(h);
int cw = 860-w;
int ch = 640-h;
this.setSize(860+cw,640+ch);
}
}
鼠标监听:
MouseAdapter adapter = new MouseAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
//System.out.println(e.getX()+","+e.getY());
double x = e.getX()-8;
double y = e.getY()-32;
tank.turretDir = Utils.ppDir(tank.x,tank.y,x,y)+90;
}
@Override
public void mousePressed(MouseEvent e) {
Shot shot = new Shot(tank.x, tank.y, tank.turretDir, 200);
Director.nodes.add(shot);
}
};
win.addMouseListener(adapter); //处理点击事件
win.addMouseMotionListener(adapter); //处理移动事件
win.addMouseWheelListener(adapter); //处理滚轮事件
控制游戏帧率:
long lastUpdate = System.currentTimeMillis(); //当前系统时间
int fps = 60; //理论帧数
while (true) {
long interval = 1000/fps; //理论间隔
long curr = System.currentTimeMillis();
long _time = curr-lastUpdate;
if (_time < interval) {
Thread.sleep(1);
}else{
lastUpdate = curr;
float dt = _time*0.001f; //两帧之间的间隔(秒)
Scheduler.getInstance().tick(dt); //推动调度器执行
win.update(dt);
}
}
坦克类:
package cn.itsub.tank.types;
import cn.itsub.tank.ImageCache;
import cn.itsub.tank.timer.Scheduler;
import java.awt.*;
public class Tank extends Node{
public double turretDir; //炮筒方向
public double hp=60;
public double hpmax=100;
public double hphf=10;//每秒回复生命
public Tank() {
//注册调度器,每帧都调用update方法,达到恢复生命值的目的
Scheduler.getInstance().scheduleUpdate(this,0,false);
}
public void update(float dt) {
hp += (hphf * dt);
if (hp > hpmax) {
hp = hpmax;
}
}
@Override
public void draw(Graphics2D g2) {
Graphics2D g = (Graphics2D) g2.create(); //复制画笔
g.translate(x, y);
g.drawImage(ImageCache.get("tank_red"),-18,-19,null);
g.drawRect(-23,-34,46,8);
g.setColor(Color.RED);
int whp = (int)(45.0*(hp/hpmax));
g.fillRect(-22,-33,whp,7);
g.rotate(Math.toRadians(this.turretDir));
g.drawImage(ImageCache.get("turret_red"),-32,-32,null);
}
}
这么好的东西我都安排了,
收藏,点赞,好评,也给我安排一波呗~~~