java推箱子游戏源代码(含推箱子的判断)

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

第一个Java文件:

package xiaoA;

import java.awt.Color;

import java.awt.HeadlessException;

import java.awt.event.KeyEvent;

import java.awt.event.KeyListener;

import javax.swing.ImageIcon;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

public class GameFrame extends JFrame {

JPanel zhuobu = new JPanel();

//工人

JLabel worker = null;

//箱子

JLabel box = null;

//目的地

JLabel goal = null;

JLabel[] walls = null;

public static final int SPEED = 12;

//设置图片大小

int imgSize = 48;

public void setImgSize(int imgSize){

this.imgSize = imgSize;

}

public GameFrame(String title) throws HeadlessException { super(title);

//构造方法中调用本类的其它方法

this.initContentPane();

this.addKeyListener(new KeyListener() {

//键盘按下事件

public void keyPressed(KeyEvent e) {

//[2.5] 使工人可以移动

int xSpeed = 0, ySpeed = 0;

switch (e.getKeyCode()) {

case KeyEvent.VK_LEFT :

xSpeed = -SPEED;

worker.setIcon(new ImageIcon("image/workerUp.gif"));

break;

case KeyEvent.VK_RIGHT :

xSpeed = SPEED;

worker.setIcon(new ImageIcon("image/workerUp.gif"));

break;

case KeyEvent.VK_UP :

ySpeed = -SPEED;

worker.setIcon(new ImageIcon("image/workerUp.gif"));

break;

case KeyEvent.VK_DOWN :

ySpeed = SPEED;

worker.setIcon(new ImageIcon("image/workerUp.gif"));

break;

default:

return;

}

worker.setBounds(worker.getX() + xSpeed, worker.getY() + ySpeed, worker.getWidth(), worker.getHeight());

//[2.7] 判断工人是否撞到墙壁

for (int i = 0; i < walls.length; i++) {

if(worker.getBounds().intersects(walls[i].getBounds())) {

worker.setBounds(worker.getX() - xSpeed, worker.getY() - ySpeed, worker.getWidth(), worker.getHeight());

}

}

//[3.2] 使工人可以推动箱子

if (worker.getBounds().intersects(box.getBounds())) {

box.setBounds(box.getX() + xSpeed, box.getY() + ySpeed, box.getWidth(), box.getHeight());

//[3.3] 判断箱子是否撞到墙壁

for (int i = 0; i < walls.length; i++) {

if (box.getBounds().intersects(walls[i].getBounds())) {

worker.setBounds(worker.getX() - xSpeed, worker.getY() - ySpeed, worker.getWidth(), worker.getHeight());

box.setBounds(box.getX() - xSpeed, box.getY() - ySpeed, box.getWidth(), box.getHeight());

}

}

//[3.4] 判断是否胜利

if (box.getX()==goal.getX() && box.getY()==goal.getY()) { JOptionPane.showMessageDialog(null, "您赢啦!");

}

相关文档
最新文档