此代码参考传智播客推箱子视频并进行改进 增加esc关闭窗口,用adws或控制方向 的代码
import game.qust.cn.MainFrame;
//启动入口
public class App {
public static void main(String[] args) {
new MainFrame();
}
}
package game.qust.cn;
import java.awt.Frame;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
public class MainFrame extends Frame implements KeyListener{
public MainFrame() {
wolfInit();//做人物
sheepInit();//做箱子
targetInit();//做笼子
treeInit();//做障碍
backgroundInit();//背景初始化
//设置整个窗体
setMainFrameUI();
this.addKeyListener(this);//使窗口监听键盘(写窗口初始化后面)
}
JLabel[][] sheeps=new JLabel[12][16];//用来存储三只羊
//场景数据模拟 二维数组
//1代表障碍 0代表空地
int[][] datas= {
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,1,0,0,1,1,1,1,0,1,1,1,0,0,1},
{1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,1,0,0,0,0,0,1,0,0,0,1,0,0,1},
{1,0,1,0,0,1,1,1,1,0,1,1,1,0,0,1},
{1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1},
{1,0,1,0,0,1,0,0,0,0,0,0,1,0,0,1},
{1,0,1,0,0,1,1,1,1,0,1,1,1,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
};
int wx ;//代表人物横向位置
int wy ;//代表人物纵向位置
//代表当前有多少个箱子移动到了目标中
int num = 0;
//代表箱子的总数
int total = 3;
private void treeInit() {
//创建图片
Icon ic=new ImageIcon("tree.png");
// 遍历二维数组
for(int i=0;i