Java面向对象推箱子源代码(可扩展)
- 格式:docx
- 大小:48.71 KB
- 文档页数:9
Java实现经典游戏推箱⼦的⽰例代码⽬录前⾔主要设计功能截图代码实现核⼼类声⾳播放类总结前⾔《推箱⼦》推箱⼦是⼀个古⽼的游戏,⽬的是在训练你的逻辑思考能⼒。
在⼀个狭⼩的仓库中,要求把⽊箱放到指定的位置,稍不⼩⼼就会出现箱⼦⽆法移动或者通道被堵住的情况,所以需要巧妙的利⽤有限的空间和通道,合理安排移动的次序和位置,才能顺利的完成任务。
游戏是⽤java语⾔实现,采⽤了swing技术进⾏了界⾯化处理,设计思路⽤了⾯向对象思想。
主要需求控制搬运⼯上下左右移动,来将箱⼦推到指定地点主要设计1、游戏⾯板⽣成显⽰2、地图⽣成算法3、⼈物移动算法4、播放背景⾳乐5、箱⼦移动算法6、全部箱⼦移动到指定位置,才算游戏过关功能截图游戏开始移动效果游戏过关代码实现核⼼类public class GameFrame extends JFrame implementsActionListener, MouseListener, KeyListener {// 实现动作事件监听器、⿏标事件监听器、键盘事件监听器// 当前的关卡数,默认为第⼀关,从1开始计数private int grade = 1;// row,column记载⼈的位置,分别表⽰⼆维数组中的⾏号和列号,即map[row][column]确定⼈的位置private int row = 7, column = 7;// leftX,leftY记载左上⾓图⽚的位置,避免图⽚从(0,0)坐标开始,因为是图⽚填充,从(0,0)开始不⾏private int leftX = 50, leftY = 50;// 记载地图的总共有多少⾏、多少列private int mapRow = 0, mapColumn = 0;// 记载屏幕窗⼝的宽度和⾼度private int width = 0, height = 0;private boolean acceptKey = true;// 程序所需要⽤到的图⽚private Image pics[] = null;// 图⽚数据private byte[][] map = null;// 地图数据private ArrayList list = new ArrayList();private SoundPlayerUtil soundPlayer;// 播放声⾳⼯具类/* 常量,即游戏中的资源 */private final static int WALL = 1;// 墙private final static int BOX = 2;// 箱⼦private final static int BOX_ON_END = 3;// 放到⽬的地的箱⼦private final static int END = 4;// ⽬的地private final static int MAN_DOWN = 5;// 向下的⼈private final static int MAN_LEFT = 6;// 向左的⼈private final static int MAN_RIGHT = 7;// 向右的⼈private final static int MAN_UP = 8;// 向上的⼈private final static int GRASS = 9;// 通道private final static int MAN_DOWN_ON_END = 10;// 站在⽬的地向下的⼈private final static int MAN_LEFT_ON_END = 11;// 站在⽬的地向左的⼈private final static int MAN_RIGHT_ON_END = 12;// 站在⽬的地向右的⼈private final static int MAN_UP_ON_END = 13;// 站在⽬的地向上的⼈private final static int MOVE_PIXEL = 30;// 表⽰每次移动30像素/*** 在构造⽅法GameFrame0中,调⽤initMap()法来初始化本关grade游戏地图,清空悔棋信* 息列表list,同时播放MIDI背景⾳乐。
总共四个包,因为不能上传图片所以在第2个包中,导入图片(图片可以去网上下载一些)或者高手帮我解决一下。
不用导入图片也能玩!(求大神)下面是整个游戏的代码:1:package com.sj.xzq;class BackUpInfo {private int[][] map;private int manX;private int manY;public BackUpInfo(int[][] map, int manX, int manY) {this.map = map;this.manX = manX;this.manY = manY;}public int[][] getMap() {return map;}public int getManX() {return manX;}public int getManY() {return manY;}}2:package com.sj.xzq;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Image;import java.awt.Toolkit;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;import java.util.Stack;import javax.swing.JOptionPane;import javax.swing.JPanel;public class Game extends JPanel {private LoadMap lm;private int level;private int manX, manY;private int lastImg = 2;private int[][] map; // 地图所对应的二维数组private int[][] backMap; // 地图所对应的二维数组,这个数组用于保存上一步的地图信息private static final int LEN = 30; // 图片的长private static final int WIDTH = 30; // 图片的宽private static final int SPEED = 30; // 移动速度,每次移动一格private static Toolkit tk = Toolkit.getDefaultToolkit();private static Image[] imgs = null;private Stack<BackUpInfo> myStack = new Stack<BackUpInfo>();private BackUpInfo bp;static {imgs = new Image[] {tk.getImage(GameFrame.class.getClassLoade r().getResource("imgs/0.gif")),tk.getImage(GameFrame.class.getClassLoade r().getResource("imgs/1.gif")),tk.getImage(GameFrame.class.getClassLoade r().getResource("imgs/2.GIF")),tk.getImage(GameFrame.class.getClassLoade r().getResource("imgs/3.GIF")),tk.getImage(GameFrame.class.getClassLoade r().getResource("imgs/4.gif")),tk.getImage(GameFrame.class.getClassLoade r().getResource("imgs/5.GIF")),tk.getImage(GameFrame.class.getClassLoade r().getResource("imgs/6.GIF")),tk.getImage(GameFrame.class.getClassLoade r().getResource("imgs/7.GIF")),tk.getImage(GameFrame.class.getClassLoade r().getResource("imgs/8.GIF")),tk.getImage(GameFrame.class.getClassLoade r().getResource("imgs/9.GIF")) };}public Game(int level) {this.setBounds(0, 0, 600, 600);this.setVisible(true);lm = new LoadMap(level);map = lm.getMap();this.manX = lm.getManX();this.manY = lm.getManY();this.level = level;}public void paint(Graphics g) {for (int i = 0; i < 20; i++) {for (int j = 0; j < 20; j++) {g.drawImage(imgs[map[i][j]], i * LEN, j * WIDTH, this);}}g.setColor(Color.BLUE);g.setFont(new Font("仿宋", Font.BOLD, 18));g.drawString("关卡:" + level, 50, 50);}// 响应键盘事件,松开键盘才响应// 上下左右四个键,实现人物的移动。
#include <dos.h>#include <stdio.h>#include <ctype.h>#include <conio.h>#include <bios.h>#include <alloc.h>typedef struct winer{int x,y;struct winer *p;}winer;char status [20][20];char far *printScreen=(char far* )0xB8000000;void putoutChar(int y,int x,char ch,char fc,char bc);void printWall(int x, int y);void printBox(int x, int y);void printBoxDes(int x, int y);void printDestination(int x, int y);void printDestination1(int x,int y,winer **win,winer **pw); void printMan(int x, int y);void init();winer *initStep1();winer *initStep2();winer *initStep3();winer *initStep4();void moveBoxSpacetoSpace(int x ,int y, char a);void moveBoxDestoSpace(int x ,int y, char a) ;void moveBoxSpacetoDes(int x, int y, char a);void moveBoxDestoDes(int x, int y, char a);int judge(int x, int y);void move(int x, int y, char a);void reset(int i);void putoutChar(int y,int x,char ch,char fc,char bc){printScreen[(x*160)+(y<<1)+0]=ch;printScreen[(x*160)+(y<<1)+1]=(bc*16)+fc;}void printWall(int x,int y){putoutChar(y-1,x-1,219,GREEN,BLACK);status[x][y]='w';}void printBox(int x,int y){putoutChar(y-1,x-1,10,WHITE,BLACK);status[x][y]='b';}void printDestination1(int x,int y,winer **win,winer **pw) {winer *qw;putoutChar(y-1,x-1,003,YELLOW,BLACK);status[x][y]='m';if(*win==NULL){*win=*pw=qw=(winer* )malloc(sizeof(winer));(*pw)->x=x;(*pw)->y=y;(*pw)->p=NULL;}else{qw=(winer* )malloc(sizeof(winer));qw->x=x;qw->y=y;(*pw)->p=qw;(*pw)=qw;qw->p=NULL;}}void printDestination(int x,int y){putoutChar(y-1,x-1,003,YELLOW,BLACK);status[x][y]='m';}void printMan(int x,int y){gotoxy(y,x);_AL=02;_CX=01;_AH=0xa;geninterrupt(0x10);}void printBoxDes(int x,int y){putoutChar(y-1,x-1,10,YELLOW,BLACK);status[x][y]='i';}void init(){int i,j;for(i=0;i<20;i++)for(j=0;j<20;j++)status[i][j]=0;_AL=3;_AH=0;geninterrupt(0x10);gotoxy(40,4);printf("Welcome to the box world!");gotoxy(40,6);printf("You can use up, down, left,");gotoxy(40,8);printf("right key to control it, or");gotoxy(40,10);printf("you can press Esc to quit it."); gotoxy(40,12);printf("Press space to reset the game."); gotoxy(40,14);printf("Wish you have a good time !");gotoxy(40,16);printf("April , 2007");}winer *initStep1(){int x;int y;winer *win=NULL;winer *pw;for(x=1,y=5;y<=9;y++)printWall(x+4,y+10);for(y=5,x=2;x<=5;x++)printWall(x+4,y+10);for(y=9,x=2;x<=5;x++)printWall(x+4,y+10);for(y=1,x=3;x<=8;x++)printWall(x+4,y+10);for(x=3,y=3;x<=5;x++)printWall(x+4,y+10);for(x=5,y=8;x<=9;x++)printWall(x+4,y+10);for(x=7,y=4;x<=9;x++)printWall(x+4,y+10);for(x=9,y=5;y<=7;y++)printWall(x+4,y+10);for(x=8,y=2;y<=3;y++)printWall(x+4,y+10);printWall(5+4,4+10);printWall(5+4,7+10);printWall(3+4,2+10);printBox(3+4,6+10);printBox(3+4,7+10);printBox(4+4,7+10);printDestination1(4+4,2+10,&win,&pw); printDestination1(5+4,2+10,&win,&pw); printDestination1(6+4,2+10,&win,&pw); printMan(2+4,8+10);return win;}winer *initStep2(){int x;int y;winer *win=NULL;winer *pw;for(x=1,y=4;y<=7;y++)printWall(x+4,y+10);for(x=2,y=2;y<=4;y++)printWall(x+4,y+10);for(x=2,y=7;x<=4;x++)printWall(x+4,y+10);for(x=4,y=1;x<=8;x++)printWall(x+4,y+10);for(x=8,y=2;y<=8;y++)printWall(x+4,y+10);for(x=4,y=8;x<=8;x++)for(x=4,y=6;x<=5;x++)printWall(x+4,y+10);for(x=3,y=2;x<=4;x++)printWall(x+4,y+10);for(x=4,y=4;x<=5;x++)printWall(x+4,y+10);printWall(6+4,3+10);printBox(3+4,5+10);printBox(6+4,6+10);printBox(7+4,3+10);printDestination1(5+4,7+10,&win,&pw); printDestination1(6+4,7+10,&win,&pw); printDestination1(7+4,7+10,&win,&pw); printMan(2+4,6+10);return win;}winer *initStep3(){int x;int y;winer *win=NULL;winer *pw;for(x=1,y=2;y<=8;y++)printWall(x+4,y+10);for(x=2,y=2;x<=4;x++)printWall(x+4,y+10);for(x=4,y=1;y<=3;y++)printWall(x+4,y+10);for(x=5,y=1;x<=8;x++)printWall(x+4,y+10);for(x=8,y=2;y<=5;y++)printWall(x+4,y+10);for(x=5,y=5;x<=7;x++)printWall(x+4,y+10);for(x=7,y=6;y<=9;y++)printWall(x+4,y+10);for(x=3,y=9;x<=6;x++)printWall(x+4,y+10);for(x=3,y=6;y<=8;y++)printWall(x+4,y+10);printWall(2+4,8+10);printWall(5+4,7+10);printBox(6+4,3+10);printBox(5+4,6+10);printDestination1(2+4,5+10,&win,&pw); printDestination1(2+4,6+10,&win,&pw); printDestination1(2+4,7+10,&win,&pw); printMan(2+4,4+10);return win;}winer *initStep4(){int x;int y;winer *win=NULL;winer *pw;for(x=1,y=1;y<=6;y++)printWall(x+4,y+10);for(x=2,y=7;y<=8;y++)printWall(x+4,y+10);for(x=2,y=1;x<=7;x++)printWall(x+4,y+10);for(x=7,y=2;y<=4;y++)printWall(x+4,y+10);for(x=6,y=4;y<=9;y++)printWall(x+4,y+10);for(x=3,y=9;x<=5;x++)printWall(x+4,y+10);for(x=3,y=3;y<=4;y++)printWall(x+4,y+10);printWall(3+4,8+10);printBox(3+4,5+10);printBox(4+4,4+10);printBox(4+4,6+10);printBox(5+4,5+10);printBox(5+4,3+10);printDestination1(3+4,7+10,&win,&pw); printDestination1(4+4,7+10,&win,&pw); printDestination1(5+4,7+10,&win,&pw); printDestination1(4+4,8+10,&win,&pw); printDestination1(5+4,8+10,&win,&pw); printMan(2+4,2+10);return win;}void moveBoxSpacetoSpace(int x,int y,char a) {switch(a){case 'u':status[x-1][y]=0;printf(" ");printBox(x-2,y);printMan(x-1,y);status[x-2][y]='b';break;case 'd':status[x+1][y]=0;printf(" ");printBox(x+2,y);printMan(x+1,y);status[x+2][y]='b';break;case 'l':status[x][y-1]=0;printf(" ");printBox(x,y-2);printMan(x,y-1);status[x][y-2]='b';break;case 'r':status[x][y+1]=0;printf(" ");printBox(x,y+2);printMan(x,y+1);status[x][y+2]='b';break;default:break;}}void moveBoxDestoSpace(int x,int y,char a) {switch(a){case 'u':status[x-1][y]='m';printf(" ");printBox(x-2,y);printMan(x-1,y);status[x-2][y]='b';break;case 'd':status[x+1][y]='m';printf(" ");printBox(x+2,y);printMan(x+1,y);status[x+2][y]='b';break;case 'l':status[x][y-1]='m';printf(" ");printBox(x,y-2);printMan(x,y-1);status[x][y-2]='b';break;case 'r':status[x][y+1]='m';printf(" ");printBox(x,y+2);printMan(x,y+1);status[x][y+2]='b';break;default:break;}}void moveBoxSpacetoDes(int x,int y,char a) {switch(a){case 'u':status[x-1][y]=0;printf(" ");printBoxDes(x-2,y);status[x-2][y]='i';break;case 'd':status[x+1][y]=0;printf(" ");printBoxDes(x+2,y);printMan(x+1,y);status[x+2][y]='i';break;case 'l':status[x][y-1]=0;printf(" ");printBoxDes(x,y-2);printMan(x,y-1);status[x][y-2]='i';break;case 'r':status[x][y+1]=0;printf(" ");printBoxDes(x,y+2);printMan(x,y+1);status[x][y+2]='i';break;default:break;}}void moveBoxDestoDes(int x,int y,char a) {switch(a){case 'u':status[x-1][y]='m';printf(" ");printBoxDes(x-2,y);printMan(x-1,y);status[x-2][y]='i';break;case 'd':status[x+1][y]='m';printf(" ");printMan(x+1,y);status[x+2][y]='i'; break;case 'l':status[x][y-1]='m'; printf(" ");printBoxDes(x,y-2); printMan(x,y-1);status[x][y-2]='i'; break;case 'r':status[x][y+1]='m'; printf(" ");printBoxDes(x,y+2); printMan(x,y+1);status[x][y+2]='i'; break;default:break;}}int judge(int x,int y) {int i;switch(status[x][y]) {case 0:i=1;break;case 'w':i=0;break;case 'b':i=2;break;case 'i':i=4;break;case 'm':i=3;break;default:break;}return i;}void move(int x,int y,char a){switch(a){case 'u':if(!judge(x-1,y)){gotoxy(y,x);break;}else if(judge(x-1,y)==1||judge(x-1,y)==3) {if(judge(x,y)==3){printDestination(x,y);printMan(x-1,y);break;}else{printf(" ");printMan(x-1,y);break;}}else if(judge(x-1,y)==2){if(judge(x-2,y)==1){moveBoxSpacetoSpace(x,y,'u');if(judge(x,y)==3)printDestination(x,y);gotoxy(y,x-1);}else if(judge(x-2,y)==3){moveBoxSpacetoDes(x,y,'u');if(judge(x,y)==3)printDestination(x,y);gotoxy(y,x-1);}elsegotoxy(y,x);break;}else if(judge(x-1,y)==4){if(judge(x-2,y)==1){moveBoxDestoSpace(x,y,'u');if(judge(x,y)==3)printDestination(x,y);gotoxy(y,x-1);}else if(judge(x-2,y)==3){moveBoxDestoDes(x,y,'u');if(judge(x,y)==3)printDestination(x,y);gotoxy(y,x-1);}elsegotoxy(y,x);break;}case 'd':if(!judge(x+1,y)){gotoxy(y,x);break;}else if(judge(x+1,y)==1||judge(x+1,y)==3) {if(judge(x,y)==3){printDestination(x,y);printMan(x+1,y);break;}else{printf(" ");printMan(x+1,y);break;}}else if(judge(x+1,y)==2){if(judge(x+2,y)==1){moveBoxSpacetoSpace(x,y,'d'); if(judge(x,y)==3)printDestination(x,y);gotoxy(y,x+1);}else if(judge(x+2,y)==3){moveBoxSpacetoDes(x,y,'d'); if(judge(x,y)==3)printDestination(x,y);gotoxy(y,x+1);}elsegotoxy(y,x);break;}else if(judge(x+1,y)==4){if(judge(x+2,y)==1){moveBoxDestoSpace(x,y,'d'); if(judge(x,y)==3)printDestination(x,y);gotoxy(y,x+1);}else if(judge(x+2,y)==3){moveBoxDestoDes(x,y,'d');if(judge(x,y)==3)printDestination(x,y);gotoxy(y,x+1);}elsegotoxy(y,x);break;}case 'l':if(!judge(x,y-1)){gotoxy(y,x);break;}else if(judge(x,y-1)==1||judge(x,y-1)==3) {if(judge(x,y)==3){printDestination(x,y);printMan(x,y-1);break;}else{printf(" ");printMan(x,y-1);break;}}else if(judge(x,y-1)==2){if(judge(x,y-2)==1){moveBoxSpacetoSpace(x,y,'l');if(judge(x,y)==3)printDestination(x,y);gotoxy(y-1,x);}else if(judge(x,y-2)==3){moveBoxSpacetoDes(x,y,'l');if(judge(x,y)==3)printDestination(x,y);gotoxy(y-1,x);}elsegotoxy(y,x);break;}else if(judge(x,y-1)==4){{moveBoxDestoSpace(x,y,'l');if(judge(x,y)==3)printDestination(x,y);gotoxy(y-1,x);}else if(judge(x,y-2)==3){moveBoxDestoDes(x,y,'l');if(judge(x,y)==3)printDestination(x,y);gotoxy(y-1,x);}elsegotoxy(y,x);break;}case 'r':if(!judge(x,y+1)){gotoxy(y,x);break;}else if(judge(x,y+1)==1||judge(x,y+1)==3) {if(judge(x,y)==3){printDestination(x,y);printMan(x,y+1);break;}else{printf(" ");printMan(x,y+1);break;}}else if(judge(x,y+1)==2){if(judge(x,y+2)==1){moveBoxSpacetoSpace(x,y,'r');printDestination(x,y); gotoxy(y+1,x);}else if(judge(x,y+2)==3){moveBoxSpacetoDes(x,y,'r'); if(judge(x,y)==3)printDestination(x,y); gotoxy(y+1,x);}elsegotoxy(y,x);break;}else if(judge(x,y+1)==4){if(judge(x,y+2)==1){moveBoxDestoSpace(x,y,'r'); if(judge(x,y)==3)printDestination(x,y); gotoxy(y+1,x);}else if(judge(x,y+2)==3){moveBoxDestoDes(x,y,'r'); if(judge(x,y)==3)printDestination(x,y); gotoxy(y+1,x);}elsegotoxy(y,x);break;}default:break;}}void reset(int i){switch(i){case 0:init();initStep1();break;case 1:init();initStep2();break;case 2:init();initStep3();break;case 3:init();initStep4();break;default:break;}}void main(){int key;int x;int y;int s;int i=0;winer *win;winer *pw;_AL=3;_AH=0;geninterrupt(0x10); init();win=initStep1();do{_AH=3;geninterrupt(0x10); x=_DH+1;y=_DL+1;while(bioskey(1)==0);key=bioskey(0);switch(key){case 0x4800:move(x,y,'u');break;case 0x5000:move(x,y,'d');break;case 0x4b00:move(x,y,'l');break;case 0x4d00:move(x,y,'r');break;case 0x3920:reset(i);break;default:break;}s=0;pw=win;while(pw){if(status[pw->x][pw->y]=='m')s++;pw=pw->p;}if(s==0){free(win);gotoxy(25,2);printf("congratulate! You have done this step!"); getch();i++;switch(i){case 1:init();win=initStep2();break;case 2:init();win=initStep3();break;case 3:init();win=initStep4();break;case 4:gotoxy(15,21);printf("Congratulation! \n");gotoxy(15,23);printf("You have done all the steps, Welcome to play again!"); key=0x011b;getch();break;default:break;}}}while(key!=0x011b);_AL=3;_AH=0;geninterrupt(0x10);}。
import javax.swing.*;import java.awt.event.*;import java.awt.*;import java.io.*;import javax.sound.midi.*;import java.util.Stack;public class Tuixiangzi{public static void main(String[] args){new mainFrame();}}class mainFrame extends JFrame implements ActionListener,ItemListener{JLabel lb;JLabel lb2;JButton btnrenew,btnlast,btnnext,btnchoose,btnfirst,btnover,btnmuc,btnback;mainpanel panel;Sound sound;JComboBox jc=new JComboBox();MenuItem renew=new MenuItem(" 重新开始");MenuItem back=new MenuItem(" 悔一步");MenuItem last=new MenuItem(" 上一关");MenuItem next=new MenuItem(" 下一关");MenuItem choose=new MenuItem(" 选关");MenuItem exit=new MenuItem(" 退出");MenuItem qin=new MenuItem(" 琴萧合奏");MenuItem po=new MenuItem(" 泡泡堂");MenuItem guang=new MenuItem(" 灌篮高手");MenuItem nor=new MenuItem(" 默认");MenuItem eye=new MenuItem(" eyes on me");MenuItem about=new MenuItem(" 关于推箱子...");mainFrame(){super("推箱子v2.0");setSize(720,720);setVisible(true);setResizable(false);setLocation(300,20);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);Container cont=getContentPane();cont.setLayout(null);cont.setBackground(Color.black);Menu choice=new Menu(" 选项");choice.add(renew);choice.add(last);choice.add(next);choice.add(choose);choice.add(back);choice.addSeparator();choice.add(exit);renew.addActionListener(this);last.addActionListener(this);next.addActionListener(this);choose.addActionListener(this);exit.addActionListener(this);back.addActionListener(this);Menu setmuc=new Menu(" 设置音乐");setmuc.add(nor);setmuc.add(qin);setmuc.add(po);setmuc.add(guang);setmuc.add(eye);nor.addActionListener(this);qin.addActionListener(this);po.addActionListener(this);guang.addActionListener(this);eye.addActionListener(this);Menu help=new Menu(" 帮助");help.add(about);about.addActionListener(this);MenuBar bar=new MenuBar();bar.add(choice);bar.add(setmuc);bar.add(help);setMenuBar(bar);nor.setEnabled(false);lb=new JLabel("JA V A推箱子v2.0版!!!提供友情下载。
#include <dos.h>#include <stdio.h>#include <ctype.h>#include <conio.h>#include <bios.h>#include <alloc.h>typedef struct winer{int x,y;struct winer *p;}winer;char status [20][20];char far *printScreen=(char far* )0xB8000000;void putoutChar(int y,int x,char ch,char fc,char bc);void printWall(int x, int y);void printBox(int x, int y);void printBoxDes(int x, int y);void printDestination(int x, int y);void printDestination1(int x,int y,winer **win,winer **pw); void printMan(int x, int y);void init();winer *initStep1();winer *initStep2();winer *initStep3();winer *initStep4();void moveBoxSpacetoSpace(int x ,int y, char a);void moveBoxDestoSpace(int x ,int y, char a) ;void moveBoxSpacetoDes(int x, int y, char a);void moveBoxDestoDes(int x, int y, char a);int judge(int x, int y);void move(int x, int y, char a);void reset(int i);void putoutChar(int y,int x,char ch,char fc,char bc){printScreen[(x*160)+(y<<1)+0]=ch;printScreen[(x*160)+(y<<1)+1]=(bc*16)+fc;}void printWall(int x,int y){putoutChar(y-1,x-1,219,GREEN,BLACK);status[x][y]='w';}void printBox(int x,int y){putoutChar(y-1,x-1,10,WHITE,BLACK);status[x][y]='b';}void printDestination1(int x,int y,winer **win,winer **pw) {putoutChar(y-1,x-1,003,YELLOW,BLACK); status[x][y]='m';if(*win==NULL){*win=*pw=qw=(winer* )malloc(sizeof(winer)); (*pw)->x=x;(*pw)->y=y;(*pw)->p=NULL;}else{qw=(winer* )malloc(sizeof(winer));qw->x=x;qw->y=y;(*pw)->p=qw;(*pw)=qw;qw->p=NULL;}}void printDestination(int x,int y){putoutChar(y-1,x-1,003,YELLOW,BLACK); status[x][y]='m';}void printMan(int x,int y){gotoxy(y,x);_AL=02;_CX=01;_AH=0xa;geninterrupt(0x10);}void printBoxDes(int x,int y){putoutChar(y-1,x-1,10,YELLOW,BLACK);status[x][y]='i';}void init(){int i,j;for(i=0;i<20;i++)for(j=0;j<20;j++)status[i][j]=0;_AL=3;_AH=0;geninterrupt(0x10);gotoxy(40,4);printf("Welcome to the box world!");gotoxy(40,6);printf("You can use up, down, left,");gotoxy(40,8);printf("right key to control it, or");gotoxy(40,10);gotoxy(40,12);printf("Press space to reset the game."); gotoxy(40,14);printf("Wish you have a good time !");gotoxy(40,16);printf("December , 2015");}winer *initStep1(){int x;int y;winer *win=NULL;winer *pw;for(x=1,y=5;y<=9;y++)printWall(x+4,y+10);for(y=5,x=2;x<=5;x++)printWall(x+4,y+10);for(y=9,x=2;x<=5;x++)printWall(x+4,y+10);for(y=1,x=3;x<=8;x++)printWall(x+4,y+10);for(x=3,y=3;x<=5;x++)printWall(x+4,y+10);for(x=5,y=8;x<=9;x++)printWall(x+4,y+10);for(x=7,y=4;x<=9;x++)printWall(x+4,y+10);for(x=9,y=5;y<=7;y++)printWall(x+4,y+10);for(x=8,y=2;y<=3;y++)printWall(x+4,y+10);printWall(5+4,4+10);printWall(5+4,7+10);printWall(3+4,2+10);printBox(3+4,6+10);printBox(3+4,7+10);printBox(4+4,7+10);printDestination1(4+4,2+10,&win,&pw); printDestination1(5+4,2+10,&win,&pw); printDestination1(6+4,2+10,&win,&pw); printMan(2+4,8+10);return win;}winer *initStep2(){int x;int y;winer *win=NULL;winer *pw;for(x=1,y=4;y<=7;y++)printWall(x+4,y+10);for(x=2,y=2;y<=4;y++)printWall(x+4,y+10);for(x=2,y=7;x<=4;x++)for(x=4,y=1;x<=8;x++)printWall(x+4,y+10);for(x=8,y=2;y<=8;y++)printWall(x+4,y+10);for(x=4,y=8;x<=8;x++)printWall(x+4,y+10);for(x=4,y=6;x<=5;x++)printWall(x+4,y+10);for(x=3,y=2;x<=4;x++)printWall(x+4,y+10);for(x=4,y=4;x<=5;x++)printWall(x+4,y+10);printWall(6+4,3+10);printBox(3+4,5+10);printBox(6+4,6+10);printBox(7+4,3+10);printDestination1(5+4,7+10,&win,&pw); printDestination1(6+4,7+10,&win,&pw); printDestination1(7+4,7+10,&win,&pw); printMan(2+4,6+10);return win;}winer *initStep3(){int x;int y;winer *win=NULL;winer *pw;for(x=1,y=2;y<=8;y++)printWall(x+4,y+10);for(x=2,y=2;x<=4;x++)printWall(x+4,y+10);for(x=4,y=1;y<=3;y++)printWall(x+4,y+10);for(x=5,y=1;x<=8;x++)printWall(x+4,y+10);for(x=8,y=2;y<=5;y++)printWall(x+4,y+10);for(x=5,y=5;x<=7;x++)printWall(x+4,y+10);for(x=7,y=6;y<=9;y++)printWall(x+4,y+10);for(x=3,y=9;x<=6;x++)printWall(x+4,y+10);for(x=3,y=6;y<=8;y++)printWall(x+4,y+10);printWall(2+4,8+10);printWall(5+4,7+10);printBox(6+4,3+10);printBox(4+4,4+10);printBox(5+4,6+10);printDestination1(2+4,5+10,&win,&pw); printDestination1(2+4,6+10,&win,&pw); printDestination1(2+4,7+10,&win,&pw); printMan(2+4,4+10);return win;winer *initStep4(){int x;int y;winer *win=NULL;winer *pw;for(x=1,y=1;y<=6;y++)printWall(x+4,y+10);for(x=2,y=7;y<=8;y++)printWall(x+4,y+10);for(x=2,y=1;x<=7;x++)printWall(x+4,y+10);for(x=7,y=2;y<=4;y++)printWall(x+4,y+10);for(x=6,y=4;y<=9;y++)printWall(x+4,y+10);for(x=3,y=9;x<=5;x++)printWall(x+4,y+10);for(x=3,y=3;y<=4;y++)printWall(x+4,y+10);printWall(3+4,8+10);printBox(3+4,5+10);printBox(4+4,4+10);printBox(4+4,6+10);printBox(5+4,5+10);printBox(5+4,3+10);printDestination1(3+4,7+10,&win,&pw);printDestination1(4+4,7+10,&win,&pw);printDestination1(5+4,7+10,&win,&pw);printDestination1(4+4,8+10,&win,&pw);printDestination1(5+4,8+10,&win,&pw);printMan(2+4,2+10);return win;}void moveBoxSpacetoSpace(int x,int y,char a) {switch(a){case 'u':status[x-1][y]=0;printf("");printBox(x-2,y);printMan(x-1,y);status[x-2][y]='b';break;case 'd':status[x+1][y]=0;printf("");printBox(x+2,y);printMan(x+1,y);status[x+2][y]='b';break;status[x][y-1]=0;printf("");printBox(x,y-2);printMan(x,y-1);status[x][y-2]='b';break;case 'r':status[x][y+1]=0;printf("");printBox(x,y+2);printMan(x,y+1);status[x][y+2]='b';break;default:break;}}void moveBoxDestoSpace(int x,int y,char a) {switch(a){case 'u':status[x-1][y]='m';printf("");printBox(x-2,y);printMan(x-1,y);status[x-2][y]='b';break;case 'd':status[x+1][y]='m';printf("");printBox(x+2,y);printMan(x+1,y);status[x+2][y]='b';break;case 'l':status[x][y-1]='m';printf("");printBox(x,y-2);printMan(x,y-1);status[x][y-2]='b';break;case 'r':status[x][y+1]='m';printf("");printBox(x,y+2);printMan(x,y+1);status[x][y+2]='b';break;default:break;}}void moveBoxSpacetoDes(int x,int y,char a) {switch(a){case 'u':status[x-1][y]=0;printf("");printBoxDes(x-2,y);printMan(x-1,y);status[x-2][y]='i';break;case 'd':status[x+1][y]=0;printf("");printBoxDes(x+2,y);printMan(x+1,y);status[x+2][y]='i';break;case 'l':status[x][y-1]=0;printf("");printBoxDes(x,y-2);printMan(x,y-1);status[x][y-2]='i';break;case 'r':status[x][y+1]=0;printf("");printBoxDes(x,y+2);printMan(x,y+1);status[x][y+2]='i';break;default:break;}}void moveBoxDestoDes(int x,int y,char a) {switch(a){case 'u':status[x-1][y]='m';printf("");printBoxDes(x-2,y);printMan(x-1,y);status[x-2][y]='i';break;case 'd':status[x+1][y]='m';printf("");printBoxDes(x+2,y);printMan(x+1,y);break;case 'l':status[x][y-1]='m';printf("");printBoxDes(x,y-2);printMan(x,y-1);status[x][y-2]='i';break;case 'r':status[x][y+1]='m';printf("");printBoxDes(x,y+2);printMan(x,y+1);status[x][y+2]='i';break;default:break;}}int judge(int x,int y){int i;switch(status[x][y]){case 0:i=1;break;case 'w':i=0;break;case 'b':i=2;break;case 'i':i=4;break;case 'm':i=3;break;default:break;}return i;}void move(int x,int y,char a) {switch(a){case 'u':if(!judge(x-1,y)){gotoxy(y,x);}else if(judge(x-1,y)==1||judge(x-1,y)==3) {if(judge(x,y)==3){printDestination(x,y);printMan(x-1,y);break;}else{printf("");printMan(x-1,y);break;}}else if(judge(x-1,y)==2){if(judge(x-2,y)==1){moveBoxSpacetoSpace(x,y,'u');if(judge(x,y)==3)printDestination(x,y);gotoxy(y,x-1);}else if(judge(x-2,y)==3){moveBoxSpacetoDes(x,y,'u');if(judge(x,y)==3)printDestination(x,y);gotoxy(y,x-1);}elsegotoxy(y,x);break;}else if(judge(x-1,y)==4){if(judge(x-2,y)==1){moveBoxDestoSpace(x,y,'u');if(judge(x,y)==3)printDestination(x,y);gotoxy(y,x-1);}else if(judge(x-2,y)==3){moveBoxDestoDes(x,y,'u');if(judge(x,y)==3)printDestination(x,y);gotoxy(y,x-1);}elsegotoxy(y,x);break;}if(!judge(x+1,y)){gotoxy(y,x);break;}else if(judge(x+1,y)==1||judge(x+1,y)==3) {if(judge(x,y)==3){printDestination(x,y);printMan(x+1,y);break;}else{printf("");printMan(x+1,y);break;}}else if(judge(x+1,y)==2){if(judge(x+2,y)==1){moveBoxSpacetoSpace(x,y,'d');if(judge(x,y)==3)printDestination(x,y);gotoxy(y,x+1);}else if(judge(x+2,y)==3){moveBoxSpacetoDes(x,y,'d');if(judge(x,y)==3)printDestination(x,y);gotoxy(y,x+1);}elsegotoxy(y,x);break;}else if(judge(x+1,y)==4){if(judge(x+2,y)==1){moveBoxDestoSpace(x,y,'d');if(judge(x,y)==3)printDestination(x,y);gotoxy(y,x+1);}else if(judge(x+2,y)==3){moveBoxDestoDes(x,y,'d');if(judge(x,y)==3)printDestination(x,y);gotoxy(y,x+1);}gotoxy(y,x);break;}case 'l':if(!judge(x,y-1)){gotoxy(y,x);break;}else if(judge(x,y-1)==1||judge(x,y-1)==3) {if(judge(x,y)==3){printDestination(x,y);printMan(x,y-1);break;}else{printf("");printMan(x,y-1);break;}}else if(judge(x,y-1)==2){if(judge(x,y-2)==1){moveBoxSpacetoSpace(x,y,'l');if(judge(x,y)==3)printDestination(x,y);gotoxy(y-1,x);}else if(judge(x,y-2)==3){moveBoxSpacetoDes(x,y,'l');if(judge(x,y)==3)printDestination(x,y);gotoxy(y-1,x);}elsegotoxy(y,x);break;}else if(judge(x,y-1)==4){if(judge(x,y-2)==1){moveBoxDestoSpace(x,y,'l');if(judge(x,y)==3)printDestination(x,y);gotoxy(y-1,x);}else if(judge(x,y-2)==3){moveBoxDestoDes(x,y,'l');printDestination(x,y);gotoxy(y-1,x);}elsegotoxy(y,x);break;}case 'r':if(!judge(x,y+1)){gotoxy(y,x);break;}else if(judge(x,y+1)==1||judge(x,y+1)==3) {if(judge(x,y)==3){printDestination(x,y);printMan(x,y+1);break;}else{printf("");printMan(x,y+1);break;}}else if(judge(x,y+1)==2){if(judge(x,y+2)==1){moveBoxSpacetoSpace(x,y,'r');if(judge(x,y)==3)printDestination(x,y);gotoxy(y+1,x);}else if(judge(x,y+2)==3){moveBoxSpacetoDes(x,y,'r');if(judge(x,y)==3)printDestination(x,y);gotoxy(y+1,x);}elsegotoxy(y,x);break;}else if(judge(x,y+1)==4){if(judge(x,y+2)==1){moveBoxDestoSpace(x,y,'r');if(judge(x,y)==3)printDestination(x,y);gotoxy(y+1,x);else if(judge(x,y+2)==3){moveBoxDestoDes(x,y,'r'); if(judge(x,y)==3)printDestination(x,y);gotoxy(y+1,x);}elsegotoxy(y,x);break;}default:break;}}void reset(int i){switch(i){case 0:init();initStep1();break;case 1:init();initStep2();break;case 2:init();initStep3();break;case 3:init();initStep4();break;default:break;}}void main(){int key;int x;int y;int s;int i=0;winer *win;winer *pw;_AL=3;_AH=0;geninterrupt(0x10);win=initStep1();do{_AH=3;geninterrupt(0x10);x=_DH+1;y=_DL+1;while(bioskey(1)==0);key=bioskey(0);switch(key){case 0x4800:move(x,y,'u');break;case 0x5000:move(x,y,'d');break;case 0x4b00:move(x,y,'l');break;case 0x4d00:move(x,y,'r');break;case 0x3920:reset(i);break;default:break;}s=0;pw=win;while(pw){if(status[pw->x][pw->y]=='m')s++;pw=pw->p;}if(s==0){free(win);gotoxy(25,2);printf("congratulate! You have done this step!"); getch();i++;switch(i){case 1:init();win=initStep2();break;case 2:init();win=initStep3();break;case 3:init();win=initStep4();case 4:gotoxy(15,21);printf("Congratulation! \n");gotoxy(15,23);printf("You have done all the steps, Welcome to play again!"); key=0x011b;getch();break;default:break;}}}while(key!=0x011b);_AL=3;_AH=0;geninterrupt(0x10);}。
import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.io.*;import javax.imageio.*;//Class GamePanel//The main class of the gameclass GamePanel extends JPanel implements KeyListener{private static final long serialVersionUID = 1L;private char[][] map; //Map stateprivate char[][] box;private int sX,sY; //Map sizeprivate Point player,p; //Point of playerprivate int Num=0; //Number of boxsprivate Point[] boxs; //Points of boxs;//private Point[] trg; //Points of target//private Point[] path;//private int steps;private Point[] dir;private int size;private Image imgfloor;private Image imgwall;private Image imgplayer;private Image imgbox1;private Image imgbox2;private Image imgtrg;//methodpublic GamePanel(char b[][],int w,int h,int size)throws Exception {sX = b.length;sY = b[0].length;Num = 0;map = new char[sX][sY];box = new char[sX][sY];player= new Point();p = new Point();boxs= new Point[sX*sY];dir = new Point[4];dir[0]= new Point(0,-1); //leftdir[1]= new Point(-1,0); //updir[2]= new Point(0, 1); //rightdir[3]= new Point(1, 0); //downFile parent = new File("E:/My Document/我的大学/JA V A/工作区/Program/src/images/");imgfloor = ImageIO.read(new File(parent,"Box_floor.gif"));imgwall = ImageIO.read(new File(parent,"Box_wall.gif"));imgplayer= ImageIO.read(new File(parent,"Box_player.gif"));imgtrg = ImageIO.read(new File(parent,"Box_trg.gif"));imgbox1 = ImageIO.read(new File(parent,"Box_box1.gif"));imgbox2 = ImageIO.read(new File(parent,"Box_box2.gif"));this.size=size;//set Mapfor(int i=0;i<sX;i++){for(int j=0;j<sY;j++){switch(b[i][j]){case 'P': //Playermap[i][j]='.';p.setLocation(i, j);break;case 'X': //Targetmap[i][j]='X';break;case 'B': //Boxmap[i][j]='.';boxs[Num++]=new Point(i, j);break;case '#': //Wallmap[i][j]='#';break;case '.': //floormap[i][j]='.';break;default :map[i][j]='.';}}}//end set Mapreset(); //reset Game}public void reset(){player.setLocation(p);for(int i=0;i<sX;i++)for(int j=0;j<sY;j++)box[i][j]=' ';for(int i=0;i<Num;i++)box[boxs[i].x][boxs[i].y]='B';//steps=0;repaint();}public void undo(){}public boolean judge(){for(int i=0;i<sX;i++)for(int j=0;j<sY;j++)if(box[i][j]=='B'&&map[i][j]!='X')return false;return true;}public void paint(Graphics g){//draw mapfor(int i=0;i<sX;i++){for(int j=0;j<sY;j++){switch(map[i][j]){case '.':g.drawImage(imgfloor, j*size, i*size, null);break;case '#':g.drawImage(imgwall, j*size, i*size, null);break;case 'X':g.drawImage(imgfloor, j*size, i*size, null);}if(box[i][j]=='B'&&map[i][j]=='X') g.drawImage(imgbox2, j*size, i*size, null);else if(box[i][j]=='B') g.drawImage(imgbox1, j*size, i*size, null);else if(map[i][j]=='X') g.drawImage(imgtrg, j*size, i*size, null);}}//draw playerg.drawImage(imgplayer, player.y*size, player.x*size, null);g.drawRect(0, 0, sY*size, sX*size);//get Focusthis.requestFocusInWindow(); /* ********* */}/* methods of KeyListener */public void keyPressed(KeyEvent e){int x=player.x;int y=player.y;int k,x0,y0;k=e.getKeyCode()-37;if(k<0||k>=4) return;x+=dir[k].x;y+=dir[k].y;if(x<0||x>=sX||y<0||y>=sY) return;if(map[x][y]=='#') return;if(box[x][y]!='B'&&(map[x][y]=='.'||map[x][y]=='X')){player.x=x;player.y=y;}if(box[x][y]=='B'){x0=x+dir[k].x;y0=y+dir[k].y;if(x0<0||y0<0||x0>=sX||y0>=sY) return;if(map[x0][y0]!='#'&&box[x0][y0]!='B'){box[x][y]=' ';box[x0][y0]='B';player.x=x;player.y=y;}}repaint();if(judge()){JOptionPane.showMessageDialog(null,"You win!");reset();}}public void keyReleased(KeyEvent e){}public void keyTyped(KeyEvent e){}}//Class PushBox//Creat JFrame to Play the gamepublic class PushBox extends JFrame{private static final long serialVersionUID = 1L;private JPanel top;private GamePanel center;private JPanel bottom;private JButton breset; //Button of resetprivate JButton bundo; //Button of undoprivate int width,height,size;private int sX,sY;//method of constitutionpublic PushBox(char[][] b)throws Exception{super("PushBox Game");//set Windowsize=35;sX=b.length;sY=b[0].length;width=size*sY+10;height=size*sX+100;top = new JPanel();center = new GamePanel(b,width,height-100,size); //Panel of Game bottom = new JPanel();breset = new JButton("Reset");bundo = new JButton("←Undo");//add Listenercenter.addKeyListener(center);breset.addActionListener(new ResetListener());bundo.addActionListener(new UndoListener());top.add(breset);//top.add(bundo);add(top,"North");add(center,"Center");add(bottom,"South");setSize(width,height);setVisible(true);}//classes of Listenerclass ResetListener implements ActionListener{public void actionPerformed(ActionEvent e){center.reset();}}class UndoListener implements ActionListener{public void actionPerformed(ActionEvent e){center.undo();}}//method mainpublic static void main(String[] args)throws Exception{char[][] b=new char[5][6];b[0]="##X##P".toCharArray();b[1]="##.##.".toCharArray();b[2]=".B.#..".toCharArray();b[3]="X..B..".toCharArray();b[4]="##....".toCharArray();PushBox p=new PushBox(b);p.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}。
第一个Java 文件:package ziaoA; import import import import j ava•awt•Color;java•awt•ReadiessException; j ava•awt•event•KeyEvent; j ava•awt•event•KeyListener ;import import importimport import j avaz•swing•Imageicon; j avax•swing•JFrame; j avax•swing•JLabel; j avax•swing•JOptionPane; j avax•swing•JPanel; public JPanel〃匸人 JLabel class GameFrame extends JFrame { zhuobu = new JPanel(); worker = null;//箱r JLabelbox = null; //目的地 JLabel goal = null; JLabel[] walls = null; public static final int SPEED = 12; //设s 图片人小 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) { //E2.5]使匸人可以移动 int 次Speed = 0, ySpeed = 0; switch (e•getKeyCode()){case KeyEvent• VK LEFT :xSpeed = -SPEED;worker . seticon (new Imageicon {'* image / workerUp • gif'*)); break;case KeyEvent• VK」工GHT :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 (x-zorker • getX () + KSpeed, 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 (x-zorker • getX () - :龙Speed, worker • getY () - ySpeed, worker•getWidth(), worker•getHeight());//E3.2]使I:人可以推动箱rif (worker•getBounds()•intersects(box•getBounds())){box•setBounds(box•getX() + xSpeed, box•getY () + ySpeed, box•getWidth(), box•getHeight());//[3.3]判断箱r是否撞到墙壁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, ”您贏啦!;public void keyReleased(KeyEvent e) {public void keyTyped(KeyEvent e) { }});*设置内容面板public void initContentPane() {zhuobu •setBackground(Color•red); zhuobu •setLayout (null);//调用父类的厲性和方法super •setcontentPane(zhuobu);public void addComponent (int tag. String imgPath, int x, int y) { Imageicon img = new Imageicon{imgPath); //创建JLabel^把工mage 工oon 通过构造方法传参传入〃把食物放到盘J"里JLabel componet = new JLabel(img);//设置盘f 在桌布上的位置和人小componet.setBounds(z, y, imgSize, imgSize);//把盘r 放到桌布上zhuobu •add(componet);switch (tag) {case 1:box = componet; break;case 2:*把某个图片以组件的力式加入窗体图片路径* @parain* Oparam* @param imgPath * Oparam 、* @param : * fireturn y width height y 宽度 拓度添加完的组件int index = 0;分别设置各个图片位置r(int i = 0; i < 14; i++) {//左边墙walls [index].setBounds(0, izhuobu •add (walls [index]); index++; //右边墙walls [index].setBounds(20 *for * imgSize , imgSize , imgSize );imgSize , i * imgSize , imgSize ,imgSize);zhuobu .add (walls [index]); index+-s-; for (int i = 0; i < 19; i++) {//上边墙walls [index].setBounds((i +1) * imgSize , 0, imgSize ,imgSize);zhuobu .add (walls [index]);index-5-+; //下边墙walls [index]•setBounds((i + 1) imgSize);zhuobu •add (walls [index]);inde:<++; * imgSize, 13 * imgSize, imgSize,goal = componet; break;case 3:worker = componet; break;for (int i = 0; i < walls .length; i++) {//创建没每■个闱墙,他们使用的是同 个图片walls [i] = new JLabel(walllmg);for (int i = 0; i < walls .length; i++) {//创建没每■个鬧墙,他们使用的是同■个图片walls [i] = new JLabel(walllmg);//添加中间障碍耦介解耦for (int i = 0; i < loactions.length; i++) {public void addWall(String Imageicon walllmg = new walls = new JLabel[66 +imgPath, int [][] loactions) {Imageicon(imgPath); loactions•length];walls[index]•setBounds(loactions[i][0]* imgSize, loactions[i][1]* imgSize, imgSize, imgSize);zhuobu.add(walls[index]);inde:<++;第二个Java文件:pubUc class Run {pubUc static void niain(String[] args) {GameFrame gameFramc = new GameFrame("推箱子游戏…”); 〃设置大小gameFrame.seiBoundsdOO. 50. 21 *48 + 5, 14*48 + 25); 〃窗体大小不可变ganieFrame.selRcsizable(false); ganieFrame5ClInigSize(48);ganieFrame.addComponenU3. '*workerUp.png"\ 4{M). 100):ganieFrame.addComponentf U "box,png*\ 160,60): ganieFrame.addComponenU2,"goal.png". 80.520); int[][] wallLocalions ={{4.5}.{5.5b(6.5|,{7.5},{8-5}.{9.51,(10,5}.{6-8}.{7-8}.{&8}・{9.8}.{10,8b{11.5}ganieFrame.addWall("wall.png"\ wallLocations);ganieFrame.setVisibleCtrue);。
Java面向对象实现推箱子的源代码目录一、首先: (1)二、以下为工程中各个类的源代码: (1)1、Box (1)2、GameMainTest (3)3、Man (4)4、Map (6)5、MovingException (7)6、Out (8)一、首先:在eclipse中新建一个工程,包名和类名(工程结构)如下:二、以下为工程中各个类的源代码:源代码按对应的类名复制粘贴进去即可。
1、Boxpackage tuixiangzi;import java.util.Random;public class Box {private static Random ran = new Random();private static int x = ran.nextInt(10); //箱子所在的位置(随机) private static int y = ran.nextInt(10); //箱子所在的位置(随机) private int [][]map = Map.getArray();private int h = map.length - 1;private int l = map[h].length - 1;/*** 箱子左移*/public void boxLMove()throws MovingException{if(y-1 < 0) {throw new MovingException("You Can't Moving Left!");}if(Man.getX() == x && Man.getY() == y) {y=(y-1);}/*** 箱子右移*/public void boxRMove()throws MovingException{if(y+1 > l) {throw new MovingException("You Can't Moving Right!");}if(Man.getX() == x && Man.getY() == y) {y=(y+1);}}/*** 箱子上移*/public void boxUMove()throws MovingException{if(x-1 < 0) {throw new MovingException("You Can't Moving Up!");}if(Man.getX() == x && Man.getY() == y) {x=(x-1);}}/*** 箱子下移*/public void boxDMove()throws MovingException{if(x+1 > h) {throw new MovingException("You Can't Moving Down!");}if(Man.getX() == x && Man.getY() == y) {x=(x+1);}}/*** 判断箱子是否能移动(死亡)或者是否通关* @return*/public String judgOver() {String msg = null;if(x == Out.getX() && y == Out.getY()) {msg = "You Win!";return msg;if(x == 0 && y == 0 || x == h && y == l || x == 0 && y == l || x == h && y == 0) { msg = "Game Over!";return msg;}else {msg = " ";return msg;}}public static int getX() {return x;}public static void setX(int x) {Box.x = x;}public static int getY() {return y;}public static void setY(int y) {Box.y = y;}}2、GameMainTestpackage tuixiangzi;import java.util.Scanner;public class GameMainTest {private static Scanner sc;public static void main(String[] args){Map map = new Map();Man man = new Man();Box box = new Box();sc = new Scanner(System.in);map.printMap();//游戏开始,打印地图System.out.println("推箱子游戏开始!");do {System.out.println("w:↑ s:↓ a:← d:→ 回车确认移动");String key = sc.next();switch (key){case"a": //左移try {man.leftMove(key);box.boxLMove();} catch (MovingException e) {System.out.println("走不下去啦!");}map.cleanManAfter(Man.getX(), Man.getY()+1);break;case"d": //右移try {man.rightMove(key);box.boxRMove();} catch (MovingException e) {System.out.println("走不下去啦!");}map.cleanManAfter(Man.getX(), Man.getY()-1);break;case"s": //下移try {man.downMove(key);box.boxDMove();} catch (MovingException e) {System.out.println("走不下去啦!");}map.cleanManAfter(Man.getX()-1, Man.getY());break;case"w": //上移try {man.upMove(key);box.boxUMove();} catch (MovingException e) {System.out.println("走不下去啦!");}map.cleanManAfter(Man.getX()+1, Man.getY());break;}System.out.println("\n\n\n\n");System.out.println(box.judgOver());map.printMap();}while(true);}}3、Manpackage tuixiangzi;public class Man {private static int x = 0; //人所在的行位置private static int y = 0; //人所在的列位置private int [][]map = Map.getArray();private int h = map.length-1;private int l = map[h].length-1;/*** 向左移动* @param key 移动按键* @throws MovingException 无法移动异常*/public void leftMove(String key)throws MovingException{if(y-1 < 0) {throw new MovingException("You Can't Moving Left!");}if(key.equals("a")) {y=(y-1);}}/*** 向右移动* @param key 移动按键* @throws MovingException 无法移动异常*/public void rightMove(String key)throws MovingException{ if(y+1 > l) {throw new MovingException("You Can't Moving Right!");}if(key.equals("d")) {y=(y+1);}}/*** 向上移动* @param key 移动按键* @throws MovingException 无法移动异常*/public void upMove(String key)throws MovingException{if(x-1 < 0) {throw new MovingException("You Can't Moving Up!");}if(key.equals("w")) {x=(x-1);}}/*** 向下移动* @param key 移动按键* @throws MovingException 无法移动异常*/public void downMove(String key)throws MovingException{ if(x+1 > h) {throw new MovingException("You Can't Moving Down!");}if(key.equals("s")) {x=(x+1);}}public static int getX() {return x;}public static void setX(int x) {Man.x = x;}public static int getY() {return y;}public static void setY(int y) {Man.y = y;}}4、Mappackage tuixiangzi;public class Map {private static int array[][] = new int[10][10];/*** 打印地图布局*/public void printMap() {array[Man.getX()][Man.getY()] = 1; //初始化人array[Box.getX()][Box.getY()] = 3; //初始化箱子array[Out.getX()][Out.getY()] = 2; //初始化出口for(int i = 0; i < array.length; i++) {for(int j = 0; j < array[i].length;j++) {if(array[i][j] == array[Man.getX()][Man.getY()]) {System.out.print("♀ ");} else if(array[i][j] == 0) {System.out.print("□ ");} else if(array[i][j] == array[Box.getX()][Box.getY()]) {System.out.print("■ ");} else if(array[i][j] == array[Out.getX()][Out.getY()]) {System.out.print("→ ");}}System.out.println();}}/*** 清除人和箱子移动后上一步的位置* @param x* @param y* @return*/public int cleanManAfter(int x,int y) {return array[x][y]=0;}public static int[][] getArray() {return array;}public static void setArray(int[][] array) {Map.array = array;}}5、MovingExceptionpackage tuixiangzi;public class MovingException extends Exception{private static final long serialVersionUID = 1L;public MovingException() {super();}public MovingException(String message) {super(message);}public MovingException(String message, Throwable cause) {super(message, cause);}public MovingException(Throwable cause) {super(cause);}}6、Outpackage tuixiangzi;public class Out {//后期可扩展为出口出现的位置随机private static int x = 9; //初始化出口的位置private static int y = 9; //初始化出口的位置public static int getX() {return x;}public static void setX(int x) {Out.x = x;}public static int getY() {return y;}public static void setY(int y) {Out.y = y;}}。
import java.util.Random;import java.util.Scanner;public class 推箱子 {public static void main(String[] args) {//推箱子int map[][]=new int[10][10]; //固定箱子,人,目的地的位置// int rx=0;// int ry=0;// map[rx][ry]=1;// int xx=5;// int xy=1;// map[xx][xy]=2;// int mx=6;// int my=4;// map[mx][my]=3;//随机生成人,箱子,目的地的位置Random r=new Random();int rx=r.nextInt(10);int ry=r.nextInt(10);map[rx][ry]=1;int xx=r.nextInt(10);int xy=r.nextInt(10);map[xx][xy]=2;int mx=r.nextInt(10);int my=r.nextInt(10);map[mx][my]=3;while(true){for(int i=0;i<map.length;i++){for(int j=0;j<map[i].length;j++){if(map[i][j]==1){System.out.print(" 人 ");}if(map[i][j]==2){//△代表箱子System.out.print(" △ ");}if(map[i][j]==3){//★代表箱子System.out.print(" ★ ");}if(map[i][j]==0){//◇代表箱子System.out.print(" ◇ ");}}System.out.println();}if(xx==mx&&xy==my){break;}if(xx==0&&mx!=0||xy==0&&my!=0||xx==9&&mx!=9||xy==9&&my!=9){// 判断箱子到边上而目的地不在边上的情况System.out.println("永远也到不了了~~~~(>_<)~~~~ ");}Scanner s = new Scanner(System.in);System.out.println("请输入要操作的动作:");System.out.println("w↑,s↓,a←,d→");String t=s.next();if(t.equals("d")){if(ry==9){System.out.println("此路不通!!~~~~(>_<)~~~~ ");}else if(t.equals("d")){ry++;if(map[rx][ry]==0){map[rx][ry]=1;map[rx][ry-1]=0;}else if(map[rx][ry]==2){xy++;map[xx][xy]=2;map[rx][ry]=1;map[rx][ry-1]=0;}}}if(t.equals("a")){if(ry==0){System.out.println("此路不通!!~~~~(>_<)~~~~ ");}else {ry--;if(map[rx][ry]==0){map[rx][ry]=1;map[rx][ry+1]=0;}else if(map[rx][ry]==2){xy--;map[xx][xy]=2;map[rx][ry+1]=0;map[rx][ry]=1;}}}if(t.equals("s")){if(rx==9){System.out.println("此路不通!!~~~~(>_<)~~~~ ");}else {rx++;if(map[rx][ry]==0){map[rx][ry]=1;map[rx-1][ry]=0;}else if(map[rx][ry]==2){xx++;map[xx][xy]=2;map[rx-1][ry]=0;map[rx][ry]=1;}}}if(t.equals("w")){if(rx==0){System.out.println("此路不通!!~~~~(>_<)~~~~ ");}else{rx--;if(map[rx][ry]==0){map[rx][ry]=1;map[rx+1][ry]=0;}else if(map[rx][ry]==2){xx--;map[xx][xy]=2;map[rx+1][ry]=0;map[rx][ry]=1;}}}}System.out.println("游戏结束!");}}。
import java.util.*;import java.io.*;public class Main{int r;//地图行数int c;//地图列数int begx, begy;//箱子开始坐标int endx, endy;//目标坐标int begsx, begsy;//人开始坐标char map[][];//地图int[] dx ={-1, 1, 0, 0};//人和箱子都有四个方向可移动int[] dy ={0, 0, 1, -1};char[] P ={'N', 'S', 'E', 'W'};//表示箱子向某个方向移动char[] M ={'n', 's', 'e', 'w'};//表示人向某个方向移动Node f=new Node(0,0,0,0,"");Node g=new Node(0,0,0,0,"");node1 F=new node1(0,0,"");node1 G=new node1(0,0,"");int mark[][];//标志数组,表示地图上某一位置mark[i][j]是否访问过。
public Main(char[][] map,int r,int c,int begx,int begy,int endx,int endy,int begsx,int begsy){this.map=map;this.r=r;this.c=c;this.begx=begx;this.begy=begy;this.endx=endx;this.endy=endy;this.begsx=begsx;this.begsy=begsy;mark=new int[r][c];}public boolean ok(int x,int y) {if (x >= 0 && x < r && y >= 0 && y < c) return true;return false;}public boolean SToB(int bx,int by,int ex, int ey) {//人到箱子BFSint[][] Mark1= new int[r][c]; //标志数组,表示地图上某一位置Mark1[i][j]是否访问过。
使⽤java实现简单推箱⼦游戏题⽬:编写⼀个简单的推箱⼦游戏,H表⽰墙壁;&表⽰玩家;O表⽰箱⼦,*表⽰⽬的地。
玩家输⼊W、A、S、D控制⾓⾊移动游戏结束画⾯:实现代码如下:import java.util.Scanner;public class Sokoban {public static void main(String[] args) {char map[][] = new char[8][10];// 地图Scanner sc = new Scanner(System.in);// 控制台输⼊扫描器int x = 1, y = 1;// 玩家⾓⾊坐标boolean finish = false;// 游戏是否结束for (int i = 0; i < map.length; i++) {// 地图外边墙壁if (i == 0 || i == 7) {for (int j = 0; j < map[i].length; j++) {map[i][j] = 'H';}} else {map[i][0] = 'H';map[i][9] = 'H';}}map[1][3] = 'H';// 地图内墙壁map[2][3] = 'H';map[3][3] = 'H';map[2][5] = 'H';map[3][5] = 'H';map[3][6] = 'H';map[3][8] = 'H';map[4][8] = 'H';map[6][4] = 'H';map[5][4] = 'H';map[5][5] = 'H';map[5][6] = 'H';map[x][y] = '&';// 玩家⾓⾊map[2][2] = 'o';// 箱⼦map[6][5] = '*';// ⽬的地while (true) {// 循环游戏/* 打印游戏画⾯ *//* 打印游戏画⾯ */System.out.println("--------------------");for (char row[] : map) {for (char column : row) {System.out.print(column + " ");}System.out.println();}System.out.println("--------------------");if (finish) {// 如果游戏结束则停⽌循环break;}System.out.println("A左移,D右移,W上移,S下移,请输⼊你的指令:"); String code = sc.nextLine();// 获取玩家输⼊的指令switch (code.toLowerCase()) {// 将执⾏转为⼩写并判断case "a" :// 如果输⼊的是aif (map[x][y - 1] == 0) {// 如果玩家左边是空区map[x][y] = 0;// 原位置变为空区map[x][y - 1] = '&';// 玩家移动到新位置y--;// 玩家坐标左移} else if (map[x][y - 1] == 'o') {// 如果玩家左边是箱⼦if (map[x][y - 2] != 'H') {// 如果箱⼦左边不是墙if (map[x][y - 2] == '*') {// 如果箱⼦左边是⽬的地finish = true;// 游戏结束}map[x][y] = 0;// 原位置变为空区map[x][y - 1] = '&';// 玩家移动到新位置map[x][y - 2] = 'o';// 箱⼦移动到新位置y--;// 玩家位置左移}}break;// 结束判断case "d" :// 如果输⼊的是dif (map[x][y + 1] == 0) {// 如果玩家右边是空区map[x][y] = 0;// 原位置变为空区map[x][y + 1] = '&';// 玩家移动到新位置y++;// 玩家坐标右移} else if (map[x][y + 1] == 'o') {// 如果玩家右边是箱⼦if (map[x][y + 2] != 'H') {// 如果箱⼦右边不是墙if (map[x][y + 2] == '*') {// 如果箱⼦右边是⽬的地finish = true;// 游戏结束}map[x][y] = 0;// 原位置变为空区map[x][y + 1] = '&';// 玩家移动到新位置map[x][y + 2] = 'o';// 箱⼦移动到新位置y++;// 玩家坐标右移}}break;// 结束判断case "w" :// 如果输⼊的是wif (map[x - 1][y] == 0) {// 如果玩家上⽅是空区map[x][y] = 0;// 原位置变为空区map[x - 1][y] = '&';// 玩家移动到新位置x--;// 玩家坐标上移} else if (map[x - 1][y] == 'o') {// 如果玩家上⽅是箱⼦if (map[x - 2][y] != 'H') {// 如果箱⼦上⽅不是墙if (map[x - 2][y] == '*') {// 如果箱⼦上⽅是⽬的地finish = true;// 游戏结束}map[x][y] = 0;// 原位置变为空区map[x - 1][y] = '&';// 玩家移动到新位置map[x - 2][y] = 'o';// 箱⼦移动到新位置x--;// 玩家坐标上移x--;// 玩家坐标上移}}break;// 结束判断case "s" :// 如果输⼊的是sif (map[x + 1][y] == 0) {// 如果玩家下⽅是空区map[x][y] = 0;// 原位置变为空区map[x + 1][y] = '&';// 玩家移动到新位置x++;// 玩家坐标下移} else if (map[x + 1][y] == 'o') {// 如果玩家下⽅是箱⼦ if (map[x + 2][y] != 'H') {// 如果箱⼦下⽅不是墙if (map[x + 2][y] == '*') {// 如果箱⼦下⽅是⽬的地 finish = true;// 游戏结束}map[x][y] = 0;// 原位置变为空区map[x + 1][y] = '&';// 玩家移动到新位置map[x + 2][y] = 'o';// 箱⼦移动到新位置x++;// 玩家坐标下移}}break;// 结束判断default :// 如果输⼊的是其他指令System.out.println("您输⼊的指令有误!");}}System.out.println("游戏结束");sc.close();}}。
推箱子总结完整(附有源代码)推箱子复习总结推箱子基本概括思路:/* 定义二维数组ghouse来记录屏幕上各点的状态,其中:0表示什么都没有,'b'表示箱子,'w'表示墙壁,'m'表示目的地,'i'表示箱子在目的地。
*/1.人物设置:即在特定的坐标将人画出。
(1)1个,在ghouse数组中特定的坐标点用printman函数画出小人:如/* 在特定的坐标上画人的函数*/void printman(int x,int y){gotoxy(y,x);_AL=02;_CX=01;_AH=0xa;geninterrupt(0x10);}printman(2+4,4+10);/* 在特定的坐标上画人*/2.箱子设置:在特定的坐标点画出箱子,并写下'b'箱子:3个,在ghouse数组中特定的三个坐标设置三个箱子并由printbox函数给箱子写下'b':如/* 在特定的坐标上画箱子并用数组记录状态的函数*/void printbox(int x,int y){putchxy(y-1,x-1,10,WHITE,BLACK); /*设置箱子,样式10,前景色白色,背景色黑色*/ ghouse[x][y]='b';}printbox(3+4,6+10); /*在特定的坐标点写下箱子*/printbox(3+4,7+10);3.墙壁设置:在ghouse数组中画出墙壁,并写下'w'在ghouse数组中画出墙壁,并用printwall函数写下'w':如(通过for循环实现)/* 在特定的坐标上画墙壁并用数组记录状态的函数*/void printwall(int x,int y){putchxy(y-1,x-1,219,MAGENTA,BLACK);/*x,y,219 样式参数,MAGENTA前景色,BLACK 背景色(x,y初始值为1,所以减1)*/ ghouse[x][y]='w';}for(x=1,y=5;y<=9;y++)/*初始化墙壁,根据printwall函数设置墙,重点:写上‘w’*/ printwall(x+4,y+10);for(y=5,x=2;x<=5;x++)printwall(x+4,y+10);for(y=9,x=2;x<=5;x++)printwall(x+4,y+10);for(y=1,x=3;x<=8;x++)printwall(x+4,y+10);for(x=3,y=3;x<=5;x++)printwall(x+4,y+10);for(x=5,y=8;x<=9;x++)printwall(x+4,y+10);for(x=7,y=4;x<=9;x++)printwall(x+4,y+10);for(x=9,y=5;y<=7;y++)printwall(x+4,y+10);for(x=8,y=2;y<=3;y++)printwall(x+4,y+10);printwall(5+4,4+10);printwall(3+4,2+10);4.目的地的设置:通过特定的坐标点画出目的地,并写下'm',并用链表与ghouse数组记录目的地的信息,用链表记录目的地在ghouse 数字组中位置(下标)目的地:3个,在ghouse函数中在特定的三个坐标点画出目的地,并用printwhither1函数写下'm'并记录记录'm':如//目的地的坐标是由链表记录的,6个值表示坐标,由三个节点的链表来记录/* 在特定的坐标上画目的地并用数组记录状态的函数*/winer *qw;putchxy(y-1,x-1,'*',YELLOW,BLACK);ghouse[x][y]='m';if(*win==NULL) /*刚输入时*win==null,if语句执行,将第一个目的地存入第一节点*/ {*win=*pw=qw=(winer* )malloc(sizeof(winer));(*pw)->x=x;(*pw)->y=y;(*pw)->p=NULL; /* -> 结构体成员符*/}else /*存入信息后执行else语句,将链表进行连接*/{qw=(winer* )malloc(sizeof(winer));qw->x=x;qw->y=y;(*pw)->p=qw;(*pw)=qw;qw->p=NULL;}5.关卡设置:初始化箱子、目的地、墙壁、小人:通过for循环与printman,printbox,printwhither1,printwall函数的调用进行初始化:如(其他三关同理)/* 第一关的图象初始化*/winer *inithouse1(){int x,y;winer *win=NULL,*pw;gotoxy(8,2);printf("Level No.1");/*在指定地点显示关卡*/for(x=1,y=5;y<=9;y++)/*初始化墙壁,根据printwall函数设置墙,重点:写上‘w’*/ printwall(x+4,y+10);for(y=5,x=2;x<=5;x++)printwall(x+4,y+10);for(y=9,x=2;x<=5;x++)printwall(x+4,y+10);for(y=1,x=3;x<=8;x++)printwall(x+4,y+10);for(x=3,y=3;x<=5;x++)printwall(x+4,y+10);for(x=5,y=8;x<=9;x++)printwall(x+4,y+10);for(x=7,y=4;x<=9;x++)printwall(x+4,y+10);for(x=9,y=5;y<=7;y++)printwall(x+4,y+10);for(x=8,y=2;y<=3;y++)printwall(x+4,y+10);printwall(5+4,4+10);printwall(5+4,7+10);printwall(3+4,2+10);printbox(3+4,6+10); /*在特定的坐标点画箱子,并写下'b'*/printbox(3+4,7+10);printbox(4+4,7+10);printwhither1(4+4,2+10,&win,&pw); /* 在特定的坐标上画目的地,写下'm'并用数组记录状态*/printwhither1(5+4,2+10,&win,&pw);printwhither1(6+4,2+10,&win,&pw);printman(2+4,8+10); /* 在特定的坐标上画人*/return win;}6.箱子的下一个位置的情况:/* 在特定的坐标上画箱子在目的地上并用数组记录状态的函数*/1)下一个位置是目的地,空地:当下一个位置为目的地时写下'i',当下一个位置为空地时写下'b',并擦去原位置的状态(将原位置ghouse数组==0)如/* 移动在空地上的箱子到空地上*/movebox(int x,int y,char a){switch(a){case 'u':ghouse[x-1][y]=0;printf(" ");printbox(x-2,y);printman(x-1,y);ghouse[x-2][y]='b';break;case 'd':ghouse[x+1][y]=0;printf(" ");printbox(x+2,y);printman(x+1,y);ghouse[x+2][y]='b';break;case 'l':ghouse[x][y-1]=0;printf(" ");printbox(x,y-2);printman(x,y-1);ghouse[x][y-2]='b';break;case 'r':ghouse[x][y+1]=0;printf(" ");printbox(x,y+2);printman(x,y+1);ghouse[x][y+2]='b';break;default: break;}}2)下一个位置是箱子:如果上面是箱子则有b标记,两个b相撞则不能移动3)下一个位置是箱子或墙壁:b与b,b与w相碰则不能移动2),3)例子case 'u':if(!judge(x-1,y)) {gotoxy(y,x);break;} /*(1)人的上面是墙*/else if(judge(x-1,y)==1||judge(x-1,y)==3) /*(2)人的上面是空地或是目的地*/ {if(judge(x,y)==3) /*人的上面是目的地*/ { printwhither(x,y);printman(x-1,y);break;}else{printf(" ");printman(x-1,y);break;} /*人的上面是空地*/}else if(judge(x-1,y)==2) /*人的上面是箱子*/{ if(judge(x-2,y)==1) /*箱子上面是空地*/{movebox(x,y,'u');if(judge(x,y)==3) printwhither(x,y); gotoxy(y,x-1);}else if(judge(x-2,y)==3) /*箱子上面是目的地*/{ moveboxin(x,y,'u');if(judge(x,y)==3) printwhither(x,y); gotoxy(y,x-1);}else gotoxy(y,x);break;}else if(judge(x-1,y)==4) /*人的上面是箱子在目的地*/{ if(judge(x-2,y)==1) /*箱子上面是空地*/{moveinbox(x,y,'u');if(judge(x,y)==3) printwhither(x,y);gotoxy(y,x-1);}else if(judge(x-2,y)==3) /*箱子上面是目的地*/{ moveinboxin(x,y,'u');if(judge(x,y)==3) printwhither(x,y);gotoxy(y,x-1);}else gotoxy(y,x); /*else 情况则包括箱子的下一个状态是箱子或箱子的下一个状态是障碍物(箱子或墙壁)*/break;}7./* 按下空格键后,回到本关开头的函数*/ 如何实现的1)当按下空格键时返回一个i的值2)调用/* 初始化函数,初始化数组和屏幕*/3)调用关卡函数如inithouse1()进行重新开始/* 按下空格键后,回到本关开头的函数*/void reset(int i){switch(i){case 0: init();inithouse1();break;case 1: init();inithouse2();break;case 2: init();inithouse3();break;case 3: init();inithouse4();break;default:break;}}8.主函数设计:1)首先定义了一些变量和指针,然后初始化数组、屏幕和第一关main(){int key,x,y,s,i=0;winer *win,*pw;_AL=3;_AH=0;geninterrupt(0x10);init(); /* 初始化函数,初始化数组和屏幕*/win=inithouse1(); /*设置第一关win指针接收inithouse1返回的图像*/2)设计了一个大的do,while循环条件:重点:是本游戏的主要部分do{_AH=3;geninterrupt(0x10);x=_DH+1;y=_DL+1;while(bioskey(1)==0);key=bioskey(0); /*bioskey 从键盘上返回数值*/switch(key){case 0x4800:move(x,y,'u');break; /* 按下向上键后*/case 0x5000:move(x,y,'d');break; /* 按下向下键后*/case 0x4b00:move(x,y,'l');break; /* 按下向左键后*/case 0x3920:reset(i);break; /* 按下空格键后*/default:break;}s=0; /**switch 每执行一次就触发一次判断**/pw=win;while(pw){if(ghouse[pw->x][pw->y]=='m') s++; /* m(目的地)能和i (箱子在目的地)进行转换*/pw=pw->p;}if(s==0) /* 过关*/{free(win);gotoxy(25,2);printf("Congratulate! Y ou have passed Level %d!",i+1);getch();i++;switch(i) /*调出关卡*/{case 1: init();win=inithouse2();break;case 2: init();win=inithouse3();break;case 3: init();win=inithouse4();break;case 4: gotoxy(8,14);printf("Great! Y ou have passed all the levels! Press any key to quit!");key=0x011b;getch();break;default: break;}}}while(key!=0x011b);_AL=3;_AH=0;geninterrupt(0x10);}3)do循环首先设计了一个while 死循环,接收键盘信息,在进行switch循环将得到的键盘码进行操作(输入的键盘码在case语句中时) while(bioskey(1)==0);key=bioskey(0); /*bioskey 从键盘上返回数值*/switch(key){case 0x5000:move(x,y,'d');break; /* 按下向下键后*/case 0x4b00:move(x,y,'l');break; /* 按下向左键后*/case 0x4d00:move(x,y,'r');break; /* 按下向右键后*/case 0x3920:reset(i);break; /* 按下空格键后*/default:break;}4)接下来又有一个while循环,作用:触发判断和判断是否过关。
推箱子游戏一、功能描述:➢可以通过面板上的按钮或是键盘上的pageup,pagedown键选择上下关➢可以通过面板上按钮或是键盘上的Backspace键后退,一直后退自己想要的位置,知道游戏开始时的位置。
➢可以通过面板上的按钮或是键盘上的字母r重新开始当前关卡游戏。
➢可以在复选框选择想要玩的关卡。
二、界面及运行截图三、源代码(三部分)1、地图类package box;import java.io.BufferedReader;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;//读取字符文件类FileReader import java.io.IOException;public class map {int[][] map=new int[20][20];int manX,manY;public map(int level){String filepath="mapc/"+level+".txt";File file = new File(filepath);FileReader fr = null;//利用FileReader流来读取一个文件中的数据BufferedReader br = null;//字符读到缓存里try {fr = new FileReader(file);br = new BufferedReader(fr);for (int i = 0; i < 15; i++){String line = br.readLine();//以行为单位,一次读一行利用BufferedReader 的readLine,读取分行文本byte[] point = line.getBytes();//将字符串转换为字节数组for (int j = 0; j < 15; j++) {map[i][j] = point[j] - 48;// 根据ASCall码表要减掉30H(十进制的48)if (map[i][j] == 5 || map[i][j] == 6 || map[i][j] == 7|| map[i][j] == 8){manX = i;manY = j;}}}}catch (FileNotFoundException e){e.printStackTrace();//深层次的输出异常调用的流程}catch (IOException e){e.printStackTrace();//深层次的输出异常调用的流程}catch(NullPointerException e){e.printStackTrace();//深层次的输出异常调用的流程}finally {if (br == null){try{br.close();}catch (IOException e){e.printStackTrace();}br = null;}if (fr == null){try {fr.close();} catch (IOException e){e.printStackTrace();}fr = null;}}}public int[][] getMap() {return map;}public int getManX() {return manX;}public int getManY() {return manY;}}2、游戏运行类package box;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.ItemEvent;import java.awt.event.ItemListener;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.util.*;import javax.swing.*;public class pushbox extends JFrame implements KeyListener,ActionListener{ map map_level=new map(1); //首次获取地图int[][] map=new int[15][15]; //地图上每个位置所对应的图片int[][] map_restart=new int[15][15]; //备用图片static int manX,manY; //人所处的位置static int level=1; //所处关卡static int step=0;Image[] picture; //地图上的所有图片ImageIcon[] image=new ImageIcon[10];Stack<Integer> back_stack = new Stack<Integer>(); //存储所前行的路径JButton next,previous,back,restart,exit; //按钮:下一关,上一关,重新开始,退出String current_level="第"+level+"关"; //当前所处关卡(右上角显示文本)String[] level_button=new String[13]; //复选框的容JComboBox selectBox; //选关复选框final int Up = 0;final int Down = 1;final int Left = 2;final int Right = 3;int[] dir_x = {-1, 1, 0, 0};int[] dir_y = {0, 0, -1, 1};public pushbox(){super("推箱子");getmap(map);previous=new JButton("上一关");next=new JButton("下一关");restart=new JButton("重新开始");back=new JButton("后退");exit=new JButton("退出游戏");for(int i=0;i<13;i++)level_button[i]="第"+Integer.toString(i+1)+"关";selectBox=new JComboBox(level_button);FlowLayout layout=new FlowLayout(); //布局模式Container c=getContentPane();c.setLayout(layout);layout.setAlignment(FlowLayout.CENTER); //控件在布局中的位置c.setBackground(Color.CYAN); //背景色c.add(previous);c.add(next);c.add(back);c.add(restart);c.add(selectBox);c.add(exit);previous.addActionListener((ActionListener) this);previous.addKeyListener(this);next.addActionListener((ActionListener) this);next.addKeyListener(this);back.addActionListener(this);back.addKeyListener(this);restart.addActionListener((ActionListener) this);restart.addKeyListener(this);exit.addActionListener((ActionListener) this);exit.addKeyListener(this);selectBox.addItemListener( //监听复选框点击事件new ItemListener(){public void itemStateChanged(ItemEvent e){if(e.getStateChange()==e.SELECTED){step=0;back_stack.clear(); //每次重新选关后都要清空路径栈level=selectBox.getSelectedIndex()+1; //获取所选的关卡map_level=new map(level); //重新获取对应关卡的地图getmap(map);current_level="第"+level+"关"; //右上角提示所处关卡文本的更新repaint(); //重画地图requestFocus(); //重新获取焦点(因为按钮事件后键盘事件不起作用)}}});for(int k=0;k<10;k++){image[k]=new ImageIcon("picture/"+k+".png"); //获取图片}picture=new Image[]{image[0].getImage(),image[1].getImage(),image[2].getImage(),image[3].getImage(),image[4].getImage(),image[5].getImage(),image[6].getImage(),image[7].getImage(),image[8].getImage(),image[9].getImage()};this.setFocusable(true);this.addKeyListener((KeyListener)this);setSize(640,640);setVisible(true);}//判断是否通关(方法是,检查地图中是否还有箱子编号4)public Boolean pass(){int p=0;for(int i=0;i<15;i++)for(int j=0;j<15;j++){if(map[i][j]==4) p++;}if(p==0) return true;else return false;}//获取地图上每个位置所对应的图片编号public void getmap(int[][] map){for(int i=0;i<15;i++)for(int j=0;j<15;j++)map[i][j]=map_level.map[i][j];manX=map_level.manX;manY=map_level.manY;}public void paint(Graphics g){super.paint(g);//提示信息back_stack.push(Down + 5); //这里是一个细节,先将“DOWN”存入栈g.drawString(current_level,500,90);g.drawString("第"+step+"步",400,90);g.drawString("用键盘上的R重新开始,Q退出游戏",200,565);g.drawString("用键盘pageup,pagedown切换关卡",200,580);g.drawString("用键盘上的上下左右键控制人的移动",200,600);g.drawString("用键盘上的Backspace键后退",200,620);//在面板上画地图for (int i = 0; i < 15; i++)for (int j = 0; j < 15; j++)g.drawImage(picture[map[i][j]],100+30*j,100+30*i, this);}public void Step(Graphics g){g.setColor(Color.cyan);g.drawString("第"+step+"步",400,90);step++;g.setColor(Color.BLACK);g.drawString("第"+step+"步",400,90);}public void move(int dir, Graphics g){int man = dir + 5;int dx = dir_x[dir];int dy = dir_y[dir];int x = manX;int y = manY;manX += dx;manY += dy;int origin_picture = map[manX][manY];int next_picture = map[manX + dx][manY + dy];if((map[manX][manY]==4||map[manX][manY]==3)&&(map[manX+dx][manY+dy]==2||map[ manX+dx][manY+dy]==4||map[manX+dx][manY+dy]==3)) //上面是箱子,箱子上面是墙或箱子{manX -= dx;manY -= dy;return ;}if(map[manX][manY]==2) //上面是墙{manX -= dx;manY -= dy;return ;}if(map[manX][manY]==1||map[manX][manY]==9){ //人上面是草地或是目的地g.drawImage(picture[man],100+30*manY,manX*30+100,this); //人的朝向变化if(map[x][y]==9) //原来位置是目的地g.drawImage(picture[9],100+30*y,100+30*x,this);else{ //原来位置是草地g.drawImage(picture[1],100+30*y,x*30+100,this);map[x][y]=1;}Step(g);}if((map[manX][manY]==4||map[manX][manY]==3)&&map[manX+dx][manY+dy]==1){//上面是箱子,箱子上面是草地g.drawImage(picture[man],100+30*manY,manX*30+100,this); //人的朝向变化if(map[manX][manY]==3) //若是移动一大目的地的箱子,原箱子位置值为9map[manX][manY]=9;if(map[x][y]==9) //原来位置是目的地g.drawImage(picture[9],100+30*y,100+30*x,this);else{ //原来位置是草地g.drawImage(picture[1],100+30*y,x*30+100,this);map[x][y]=1;}g.drawImage(picture[4],100+30*(manY+dy),(manX+dx)*30+100,this); //草地位置变箱子map[manX+dx][manY+dy]=4;Step(g);}if((map[manX][manY]==4||map[manX][manY]==3)&&map[manX+dx][manY+dy]==9){ //上面是箱子,箱子上面是目的地g.drawImage(picture[man],100+30*manY,manX*30+100,this); //人的朝向变化if(map[manX][manY]==3) //若是移动一大目的地的箱子,原箱子位置值为9map[manX][manY]=9;else map[manX][manY]=0;if(map[x][y]==9) //原来位置是目的地g.drawImage(picture[9],100+30*y,100+30*x,this);else { //原来位置是草地g.drawImage(picture[1],100+30*y,x*30+100,this);map[x][y]=1;}g.drawImage(picture[3],100+30*(manY+dy),(manX+dx)*30+100,this); //目的地位置变箱子map[manX+dx][manY+dy]=3;Step(g);}back_stack.push(next_picture);back_stack.push(origin_picture);back_stack.push(manY);back_stack.push(manX);back_stack.push(man);if(pass())JOptionPane.showMessageDialog(null, "恭喜你过关了!"); }//键盘事件public void keyPressed(KeyEvent e) {Graphics g=getGraphics();int dir ;switch(e.getKeyCode()){case KeyEvent.VK_UP:dir = Up;move(dir, g);break;case KeyEvent.VK_DOWN :dir = Down;move(dir, g);break;case KeyEvent.VK_LEFT:dir = Left;move(dir, g);break;case KeyEvent.VK_RIGHT:dir = Right;move(dir, g);break;case KeyEvent.VK_BACK_SPACE:back.doClick();break;case KeyEvent.VK_PAGE_DOWN :next.doClick();break;case KeyEvent.VK_PAGE_UP:previous.doClick();break;case KeyEvent.VK_R:restart.doClick();break;case KeyEvent.VK_Q :exit.doClick();break;}}public void keyReleased(KeyEvent e) {}public void keyTyped(KeyEvent e) {}//悔步后退public void step_back(Graphics g){g.setColor(Color.cyan);g.drawString("第"+step+"步",400,90);step--;g.setColor(Color.BLACK);g.drawString("第"+step+"步",400,90);}public void Back(){if(back_stack.size()==2)return;int dir=back_stack.pop() - 5; //获取上一步的方向int s = back_stack.pop();int t = back_stack.pop();int origin_picture = back_stack.pop();int netx_picture = back_stack.pop();int pre_dir = back_stElement();Graphics g=getGraphics();int dx = dir_x[dir];int dy = dir_y[dir];g.drawImage(picture[origin_picture],100+30*t,100+30*s,this);g.drawImage(picture[netx_picture],100+30*(t+dy),100+30*(s+dx),this);g.drawImage(picture[pre_dir],100+30*(t-dy),100+30*(s-dx),this);manX = s - dx;manY = t - dy;map[s][t] = origin_picture;map[s+dx][t+dy] = netx_picture;map[s-dx][t-dy] = pre_dir;step_back(g);}//按钮事件监听public void actionPerformed(ActionEvent e) {if(e.getSource()==restart){ //重新开始back_stack.clear(); //清空路径栈step=0;getmap(map);repaint();}else if(e.getSource()==exit) //退出游戏this.setVisible(false);else if(e.getSource()==next){ //下一关back_stack.clear();step=0;level++;if(level!=14){map_level=new map(level);getmap(map);current_level="第"+level+"关";repaint();}}else if(e.getSource()==previous){ //上一关back_stack.clear();step=0;level--;if(level!=0){map_level=new map(level);getmap(map);current_level="第"+level+"关";repaint();}}else if(e.getSource()==back)Back();requestFocus();}}3、开始界面package box;import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Game extends JFrame implements ActionListener{ Image image[];ImageIcon icon;JButton start,tip,exit;Container c;public Game(){super("推箱子");c=getContentPane();FlowLayout layout=new FlowLayout();c.setLayout(layout);layout.setAlignment(FlowLayout.CENTER);icon=new ImageIcon("picture/game.png");image=new Image[]{icon.getImage()};start=new JButton("开始游戏");exit=new JButton("退出游戏");tip=new JButton("游戏说明");c.add(start);c.add(tip);c.add(exit);start.addActionListener(this);tip.addActionListener(this);exit.addActionListener(this);setSize(640,480);setVisible(true);}public void paint(Graphics g){super.paint(g);g.drawImage(image[0],10,65,this);}public static void main(String args[]){Game g=new Game();g.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}Overridepublic void actionPerformed(ActionEvent e) {if(e.getSource()==exit)this.setVisible(false);if(e.getSource()==start){this.setVisible(false);pushbox c=new pushbox();}if(e.getSource()==tip){String t="本游戏分为13关,难度逐关递增,可以自己选关";JOptionPane.showMessageDialog(null, t);}}}。
<!DOCTYPE html ><html xmlns="#" lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>推箱子</title><style type="text/css">*{margin:0px; padding:0px;}.bg{margin:0px;width:32px;height:32px;background-image: url(gameImg/01.jpg);float:left;} /*背景*/.box{margin:0px;width:32px;height:32px;background-image: url(gameImg/05.jpg);float:left;} /*箱子*/.box2{margin:0px;width:32px;height:32px;background-image: url(gameImg/06.jpg);float:left;} /*箱子2(放目标上)*/.wall{margin:0px;width:32px;height:32px;background-image: url(gameImg/03.jpg);float:left;} /*墙*/.goal{margin:0px;width:32px;height:32px;background-image: url(gameImg/02.jpg);float:left;} /*目标*/.role{margin:0px;width:32px;height:32px;background-image: url(gameImg/04.jpg);float:left;} /*角色*/</style><script type="text/javascript">var maxX = 10;var maxY = 10;var mapAry =[ //地图状态数组0:墙 1:路 2:目标[1,1,0,0,0,0,0,0,1,1],[0,0,0,1,1,2,1,0,0,0],[0,1,1,2,1,1,1,1,1,0],[0,1,0,1,0,2,1,0,1,0],[0,1,1,2,1,2,1,0,1,0],[0,0,0,1,1,1,1,1,1,0],[1,1,0,1,1,2,0,0,0,0],[1,1,0,1,1,1,0,1,1,1],[1,1,0,1,1,1,0,1,1,1],[1,1,0,0,0,0,0,1,1,1]];var imgAry = new Array(); //地图图片数组var role = new Point(4,2); //创建角色坐标var boxs = [new Point(2,2),new Point(2,4),new Point(2,5),new Point(2,6),new Point(6,4),new Point(5,5)]; //创建箱子坐标数组//定义坐标类function Point(x,y){this.x = x;this.y = y;}//创建单个方块function CreateDiv(obj,css){var d = document.createElement(obj); //创建一个DIV 元素d.className = css; //设置样式document.getElementById("main").appendChild(d);return d;}//初始化界面function Show(){//显示地图for (var i=0; i<maxX; i++) {imgAry[i] = new Array();for (var j=0; j<maxY; j++) {if(mapAry[i][j]==0){imgAry[i][j]= CreateDiv("div","wall");}else if(mapAry[i][j]==1){imgAry[i][j]= CreateDiv("div","bg");}else if(mapAry[i][j]==2){imgAry[i][j]= CreateDiv("div","goal");}}}//显示角色imgAry[role.x][role.y].className = "role";//显示箱子for (var i=0; i<boxs.length; i++) {imgAry[boxs[i].x][boxs[i].y].className = "box";}}//控制角色移动function RoleMove(k){var p = new Point(role.x,role.y); //保存角色移动前的坐标//改变角色坐标if(k==37){ //向左role.y--;}else if(k==38){ //向上role.x--;}else if(k==39){ //向右role.y++;}else if(k==40){ //向下role.x++;}//还原角色所在地图背景if(mapAry[role.x][role.y]==0){ //如果是墙,则不能移动role = p;}else{ //否则还原地图背景if(mapAry[p.x][p.y]==1){imgAry[p.x][p.y].className = "bg";}else if(mapAry[p.x][p.y]==2){imgAry[p.x][p.y].className = "goal";}//判断是否推到箱子for (var i=0; i<boxs.length; i++) {if(role.x==boxs[i].x &&role.y==boxs[i].y){//如果角色和箱子重叠,调用箱子移动方法,根据返回值来判断角色坐标是否还原if(BoxMove(role,k)==false){role = p;}break;}}}//显示角色imgAry[role.x][role.y].className = "role";}//箱子移动方法,p表示和角色重叠的箱子坐标,k表示键盘按钮function BoxMove(p,k){var bl = true; //箱子是否可以移动:true可以移动,false不能移动var tmpP; //保存箱子另一侧的坐标//获取箱子另一侧坐标if(k==37){ //向左tmpP = new Point(p.x,p.y-1);}else if(k==38){ //向上tmpP = new Point(p.x-1,p.y);}else if(k==39){ //向右tmpP = new Point(p.x,p.y+1);}else if(k==40){ //向下tmpP = new Point(p.x+1,p.y);}//判断该坐标是否是墙if(mapAry[tmpP.x][tmpP.y] == 0){bl = false;}//判断该坐标是否有箱子for (var i=0; i<boxs.length; i++) {if(tmpP.x==boxs[i].x && tmpP.y==boxs[i].y){bl = false;break;}}//如果箱子可以移动,则改变箱子坐标并在新坐标显示箱子if(bl == true){for (var i=0; i<boxs.length; i++) {if(boxs[i].x==p.x && boxs[i].y==p.y){boxs[i] = tmpP;break;}}imgAry[tmpP.x][tmpP.y].className = "box";//如果新坐标是目标,则显示成箱子2的样式if(mapAry[tmpP.x][tmpP.y] == 2){imgAry[tmpP.x][tmpP.y].className = "box2";}}return bl;}//按键控制移动function Move(){var k = event.keyCode;var count = 0; //与目标点重叠的箱子个数RoleMove(k);//判断游戏是否结束判断所有箱子的坐标点的状态,如果状态都是2则游戏结束for (var i=0; i<boxs.length; i++) {if(mapAry[boxs[i].x][boxs[i].y]==2){count++;}}if(count==6){alert("恭喜过关,游戏结束!");}}document.onkeydown = Move;</script></head><body onload="Show();"><div id="main" style="margin:50px auto; border:solid1px blue; width:320px; height:320px;"></div></body> </html>。
#include<stdio.h>#include<stdlib.h>#define X 6#define Y 1//输出函数void show(char b[9][9]){printf(" 推箱子游戏");printf("\n***************************\n\n");char a1=1,a2=5,a3=3,a4='#';printf(" 人:%c 墙:%c\n 箱子:%c 目的地:%c\n",a1,a4,a2,a3);printf("\n***************************\n\n");for(int i=0;i<9;i++){for(int k=0;k<9;k++){printf(" %c ",b[i][k]);}printf("\n");}printf("\n***************************\n");}//移动函数void move(char c[9][9],int *x,int *y){char t;scanf("%c",&t);////////////////////////////////////////////////////////////////////////////////// if(t=='a'){if(c[*x][*y-1]=='#')//遇到墙{}else{if(c[*x][*y-1]==5&&c[*x][*y-2]==0)//推箱子{c[*x][*y]=0;*y-=1;c[*x][*y]=1;c[*x][*y-1]=5;}else{if(c[*x][*y-1]==5&&c[*x][*y-2]=='#')//推不动箱子{}else{if(c[*x][*y-1]==c[X][Y])//进到目的地{c[*x][*y]=0;*y-=1;c[*x][*y]=1;}else{if(c[*x][*y-1]==c[X][Y])//离开目的地{c[*x][*y]=3;*y-=1;c[*x][*y]=1;}else //走到空地{c[*x][*y]=0;*y-=1;c[*x][*y]=1;}}}}}}else{//////////////////////////////////////////////////////////////////////////////////////// if(t=='s'){if(c[*x+1][*y]=='#')//遇到墙{}else{if(c[*x+1][*y]==5&&c[*x+2][*y]==0)//推箱子{c[*x][*y]=0;*x+=1;c[*x][*y]=1;c[*x+1][*y]=5;}else{if(c[*x+1][*y]==5&&c[*x+2][*y]=='#')//推不动箱子{}else{if(c[*x+1][*y]==c[X][Y])//进到目的地{c[*x][*y]=0;*x+=1;c[*x][*y]=1;}else{if(c[*x][*y]==c[X][Y])//走出目的地{c[*x][*y]=3;*x+=1;c[*x][*y]=1;}else //走到空地{c[*x][*y]=0;*x+=1;c[*x][*y]=1;}}}}}}else{////////////////////////////////////////////////////////////////////////////////////// if(t=='w'){if(c[*x-1][*y]=='#')//遇到墙{}else{if(c[*x-1][*y]==5&&c[*x-2][*y]!='#')//推箱子{c[*x][*y]=0;*x-=1;c[*x][*y]=1;c[*x-1][*y]=5;}else{if(c[*x-1][*y]==5&&c[*x-2][*y]=='#')//推不动箱子{}else{if(c[*x-1][*y]==c[X][Y])//进到目的地{c[*x][*y]=0;*x-=1;c[*x][*y]=1;}else{if(c[*x-1][*y]==c[X][Y])//走出目的地{c[*x][*y]=3;*x-=1;c[*x][*y]=1;}else //走到空地{c[*x][*y]=0;*x-=1;c[*x][*y]=1;}}}}}}else{//////////////////////////////////////////////////////////////////////////////////////////// if(t=='d'){if(c[*x][*y+1]=='#')//遇到墙{}else{if(c[*x][*y+1]==5&&c[*x][*y+2]==0)//推箱子{c[*x][*y]=0;*y+=1;c[*x][*y]=1;c[*x][*y+1]=5;}else{if(c[*x][*y+1]==5&&c[*x][*y+2]=='#')//推不动箱子{}else{if(c[*x][*y+1]==c[X][Y])//进到目的地{c[*x][*y]=0;*y+=1;c[*x][*y]=1;}else{if(c[*x][*y+1]==c[X][Y])//离开目的地{c[*x][*y]=3;*y+=1;c[*x][*y]=1;}else //走到空地{c[*x][*y]=0;*y+=1;c[*x][*y]=1;}}}}}}}}}system("cls");//刷屏}void main(){int x=1,y=7;//设置地图char a[9][9]={{'#','#','#','#','#','#','#','#','#'},{'#','#','#',0,0,'#',0,1,'#'},{'#',0,5,0,0,0,0,0,'#'},{'#',0,0,0,0,'#',0,0,'#'},{'#',0,'#','#',0,0,0,0,'#'},{'#','#',0,0,'#',0,'#','#','#'},{'#',3,0,0,0,0,'#','#','#'},{'#','#','#',0,0,'#','#','#','#'},{'#','#','#','#','#','#','#','#','#'}};show(a);loop: move(a,&x,&y);show(a);goto loop;}。
Java面向对象实现推箱子的源代码目录一、首先: (1)二、以下为工程中各个类的源代码: (1)1、Box (1)2、GameMainTest (3)3、Man (4)4、Map (6)5、MovingException (7)6、Out (8)一、首先:在eclipse中新建一个工程,包名和类名(工程结构)如下:二、以下为工程中各个类的源代码:源代码按对应的类名复制粘贴进去即可。
1、Boxpackage tuixiangzi;import java.util.Random;public class Box {private static Random ran = new Random();private static int x = ran.nextInt(10); //箱子所在的位置(随机) private static int y = ran.nextInt(10); //箱子所在的位置(随机) private int [][]map = Map.getArray();private int h = map.length - 1;private int l = map[h].length - 1;/*** 箱子左移*/public void boxLMove()throws MovingException{if(y-1 < 0) {throw new MovingException("You Can't Moving Left!");}if(Man.getX() == x && Man.getY() == y) {y=(y-1);}/*** 箱子右移*/public void boxRMove()throws MovingException{if(y+1 > l) {throw new MovingException("You Can't Moving Right!");}if(Man.getX() == x && Man.getY() == y) {y=(y+1);}}/*** 箱子上移*/public void boxUMove()throws MovingException{if(x-1 < 0) {throw new MovingException("You Can't Moving Up!");}if(Man.getX() == x && Man.getY() == y) {x=(x-1);}}/*** 箱子下移*/public void boxDMove()throws MovingException{if(x+1 > h) {throw new MovingException("You Can't Moving Down!");}if(Man.getX() == x && Man.getY() == y) {x=(x+1);}}/*** 判断箱子是否能移动(死亡)或者是否通关* @return*/public String judgOver() {String msg = null;if(x == Out.getX() && y == Out.getY()) {msg = "You Win!";return msg;if(x == 0 && y == 0 || x == h && y == l || x == 0 && y == l || x == h && y == 0) { msg = "Game Over!";return msg;}else {msg = " ";return msg;}}public static int getX() {return x;}public static void setX(int x) {Box.x = x;}public static int getY() {return y;}public static void setY(int y) {Box.y = y;}}2、GameMainTestpackage tuixiangzi;import java.util.Scanner;public class GameMainTest {private static Scanner sc;public static void main(String[] args){Map map = new Map();Man man = new Man();Box box = new Box();sc = new Scanner(System.in);map.printMap();//游戏开始,打印地图System.out.println("推箱子游戏开始!");do {System.out.println("w:↑ s:↓ a:← d:→ 回车确认移动");String key = sc.next();switch (key){case"a": //左移try {man.leftMove(key);box.boxLMove();} catch (MovingException e) {System.out.println("走不下去啦!");}map.cleanManAfter(Man.getX(), Man.getY()+1);break;case"d": //右移try {man.rightMove(key);box.boxRMove();} catch (MovingException e) {System.out.println("走不下去啦!");}map.cleanManAfter(Man.getX(), Man.getY()-1);break;case"s": //下移try {man.downMove(key);box.boxDMove();} catch (MovingException e) {System.out.println("走不下去啦!");}map.cleanManAfter(Man.getX()-1, Man.getY());break;case"w": //上移try {man.upMove(key);box.boxUMove();} catch (MovingException e) {System.out.println("走不下去啦!");}map.cleanManAfter(Man.getX()+1, Man.getY());break;}System.out.println("\n\n\n\n");System.out.println(box.judgOver());map.printMap();}while(true);}}3、Manpackage tuixiangzi;public class Man {private static int x = 0; //人所在的行位置private static int y = 0; //人所在的列位置private int [][]map = Map.getArray();private int h = map.length-1;private int l = map[h].length-1;/*** 向左移动* @param key 移动按键* @throws MovingException 无法移动异常*/public void leftMove(String key)throws MovingException{if(y-1 < 0) {throw new MovingException("You Can't Moving Left!");}if(key.equals("a")) {y=(y-1);}}/*** 向右移动* @param key 移动按键* @throws MovingException 无法移动异常*/public void rightMove(String key)throws MovingException{ if(y+1 > l) {throw new MovingException("You Can't Moving Right!");}if(key.equals("d")) {y=(y+1);}}/*** 向上移动* @param key 移动按键* @throws MovingException 无法移动异常*/public void upMove(String key)throws MovingException{if(x-1 < 0) {throw new MovingException("You Can't Moving Up!");}if(key.equals("w")) {x=(x-1);}}/*** 向下移动* @param key 移动按键* @throws MovingException 无法移动异常*/public void downMove(String key)throws MovingException{ if(x+1 > h) {throw new MovingException("You Can't Moving Down!");}if(key.equals("s")) {x=(x+1);}}public static int getX() {return x;}public static void setX(int x) {Man.x = x;}public static int getY() {return y;}public static void setY(int y) {Man.y = y;}}4、Mappackage tuixiangzi;public class Map {private static int array[][] = new int[10][10];/*** 打印地图布局*/public void printMap() {array[Man.getX()][Man.getY()] = 1; //初始化人array[Box.getX()][Box.getY()] = 3; //初始化箱子array[Out.getX()][Out.getY()] = 2; //初始化出口for(int i = 0; i < array.length; i++) {for(int j = 0; j < array[i].length;j++) {if(array[i][j] == array[Man.getX()][Man.getY()]) {System.out.print("♀ ");} else if(array[i][j] == 0) {System.out.print("□ ");} else if(array[i][j] == array[Box.getX()][Box.getY()]) {System.out.print("■ ");} else if(array[i][j] == array[Out.getX()][Out.getY()]) {System.out.print("→ ");}}System.out.println();}}/*** 清除人和箱子移动后上一步的位置* @param x* @param y* @return*/public int cleanManAfter(int x,int y) {return array[x][y]=0;}public static int[][] getArray() {return array;}public static void setArray(int[][] array) {Map.array = array;}}5、MovingExceptionpackage tuixiangzi;public class MovingException extends Exception{private static final long serialVersionUID = 1L;public MovingException() {super();}public MovingException(String message) {super(message);}public MovingException(String message, Throwable cause) {super(message, cause);}public MovingException(Throwable cause) {super(cause);}}6、Outpackage tuixiangzi;public class Out {//后期可扩展为出口出现的位置随机private static int x = 9; //初始化出口的位置private static int y = 9; //初始化出口的位置public static int getX() {return x;}public static void setX(int x) {Out.x = x;}public static int getY() {return y;}public static void setY(int y) {Out.y = y;}}。