java推箱子游戏源代码(含推箱子的判断)
推箱子代码
for(i=0;i<N;i++){
for(j=0;j<N;j++)
printf("%d",arr[i][j]);
printf("\n");
}
if(sr==0&&sc==N-1) {
printf("恭喜你成功了!\n");
break;
{ for(j=0;j<N;j++)
printf("%d",arr[i][j]);
printf("\n");
}
//人移动
int fx;
for(;;)
{ arr[pr][pc]=0;
arr[sr][sc]=0;
for(;;){ //输入移动的方向 定义 1左移,2右移,3上移,4下移
if(pr!=sr&&pc!=sc){ //不在同行且同列
if(fx==1){
if(pc>0) pc--;
else ;
}
if(fx==2){
if(pc<N-1) pc++;
else ;
}
sr=rand()%8+1;//箱子的随机位置
sc=rand()%8+1;
if(pr!=sr||pc!=sc) break;
}
arr[pr][pc]=1;//标示人的位置
arr[sr][sc]=2;//标示箱子的位置
intN;i++) //打印初始位置图
Java实现经典游戏推箱子的示例代码
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背景⾳乐。
用java实现推箱子(sokoban)游戏
推箱子游戏一、功能描述:➢可以通过面板上的按钮或是键盘上的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);}}}。
推箱子代码
推箱子代码#include<iostream>#include<string>#include<iomanip>using namespace std;/*r 目的地O 箱子I 人X 墙路(空格)W 上A 左D 右S 下*/void menu();int level1();int level2();void swap();int opera();void dituprint();void menu(){cout<<" 推箱子"<<endl;cout<<" 1.新游戏 2.选关"<<endl;cout<<" 0.退出"<<endl;}void xuanguan(){int choice_level;while(1){cout<<"请选择关卡:"<<endl;cin>>choice_level;switch(choice_level){case 1:level1();break;case 2:level2();break;default:cout<<"输入有误请重新选择关卡!";}}}void swap(char *a,char *b){system("cls");char ch;ch=*a;*a=*b;*b=ch;}void dituprint(char *p){//system("cls");for(int i=0;i<9;i++){for(int j=0;j<9;j++)cout<<setw(2)<<p[i*9+j];cout<<endl;}}int opera(char *p,int *ren,int xzs) //xzs 箱子数ren 存有人与箱子目标的位置{dituprint(p);while(1){while(1){for(int i=1,panduan=0;i<=xzs;i++){if(p[ren[i]]=='O'){panduan+=1;cout<<"panduan="<<panduan<<endl;} //判断当前有几个已经推到目的地了if(panduan==xzs){cout<<"恭喜你过关啦!";getchar();return 0;}}char ch;cout<<"你的按键为:";cin>>ch;switch(ch){case 'w':{if(p[ren[0]]=='r') //当前人所在的位置为箱子最终要到的目的地的话{if(p[ren[0]-9]=='r') //要移到的位置是箱子最终目的地{ren[0]-=9;p[ren[0]]='I';p[ren[0]+9]='r';break;}if(p[ren[0]-9]=='X') //碰到墙了{cout<<"人碰到墙了换其他按键1哇>>>>>"; break;}if(p[ren[0]-9]==' ') //可以通过{ren[0]-=9;p[ren[0]]='I';p[ren[0]-9]='r';break;}if(p[ren[0]-9]=='O') //碰到箱子{if(p[ren[0]-18]=='X'||'O')cout<<"箱子碰到墙了换其他按键1哇>>>>>";break;if(p[ren[0]-18]=='r')p[ren[0]-18]='O';p[ren[0]-9]='I';p[ren[0]]='r';ren[0]-=9;break;}if(p[ren[0]-18]=='O')cout<<"推不动哎换其他按键1哇>>>>>";break; if(p[ren[0]-18]==' '){swap(p[ren[0]-9],p[ren[0]-18]);swap(p[ren[0]],p[ren[0]-9]);p[ren[0]]='r';ren[0]-=9;break;}}}else{if(p[ren[0]-9]=='X'){cout<<"人碰到墙了换其他按键哇2>>>>>";break;}if(p[ren[0]-9]==' '){swap(p[ren[0]],p[ren[0]-9]);ren[0]-=9;break;}if(p[ren[0]-9]=='O'){//遇到箱子代码if(p[ren[0]-18]=='O'||p[ren[0]-18]=='X'){cout<<"走不动了换按其他键哇......."<<endl;break;if(p[ren[0]-18]=='r'){p[ren[0]-18]='O';p[ren[0]-9]='I';p[ren[0]]=' ';ren[0]-=9;break;}if(p[ren[0]-18]==' '){p[ren[0]-18]='O';p[ren[0]-9]='I';p[ren[0]]=' ';ren[0]-=9;break;}}}}break;case 'a':{if(p[ren[0]]=='r') //当前人所在的位置为箱子最终要到的目的地的话{if(p[ren[0]-1]=='r') //要移到的位置是箱子最终目的地{ren[0]-=1;p[ren[0]]='I';p[ren[0]+1]='r';break;}if(p[ren[0]-1]=='X') //碰到墙了{cout<<"人碰到墙了换其他按键1哇>>>>>"; break;}if(p[ren[0]-1]==' ') //可以通过{p[ren[0]]='I';p[ren[0]+9]='r';break;}if(p[ren[0]-1]=='O') //碰到箱子{if(p[ren[0]-2]=='X'||'O')cout<<"箱子碰到墙了换其他按键1哇>>>>>";break;if(p[ren[0]-2]=='r'){p[ren[0]-2]='O';p[ren[0]-1]='I';p[ren[0]]='r';ren[0]-=1;break;}if(p[ren[0]-2]=='O')cout<<"推不动哎换其他按键1哇>>>>>";break; if(p[ren[0]-2]==' '){swap(p[ren[0]-1],p[ren[0]-2]);swap(p[ren[0]],p[ren[0]-1]);p[ren[0]]='r';ren[0]-=1;break;}}}else{if(p[ren[0]-1]=='X'){cout<<"人碰到墙了换其他按键哇2>>>>>"; break;}if(p[ren[0]-1]==' '){swap(p[ren[0]],p[ren[0]-1]);break;}if(p[ren[0]-1]=='O'){//遇到箱子代码if(p[ren[0]-2]=='O'||p[ren[0]-2]=='X'){cout<<"走不动了换按其他键哇......."<<endl;break;}if(p[ren[0]-2]=='r'){p[ren[0]-2]='O';p[ren[0]-1]='I';p[ren[0]]=' ';ren[0]-=1;break;}if(p[ren[0]-2]==' '){p[ren[0]-2]='O';p[ren[0]-1]='I';p[ren[0]]=' ';ren[0]-=1;break;}}}}break;case 's':{if(p[ren[0]]=='r') //当前人所在的位置为箱子最终要到的目的地的话{if(p[ren[0]+9]=='r') //要移到的位置是箱子最终目的地{ren[0]+=9;p[ren[0]]='I';p[ren[0]-9]='r';break;}if(p[ren[0]+9]=='X') //碰到墙了{cout<<"人碰到墙了换其他按键1哇>>>>>"; break;}if(p[ren[0]+9]==' ') //可以通过{ren[0]+=9;p[ren[0]]='I';p[ren[0]+9]='r';break;}if(p[ren[0]+9]=='O') //碰到箱子{if(p[ren[0]+18]=='X'||'O')cout<<"箱子碰到墙了换其他按键1哇>>>>>";break;if(p[ren[0]+18]=='r'){p[ren[0]+18]='O';p[ren[0]+9]='I';p[ren[0]]='r';ren[0]+=9;break;}if(p[ren[0]+18]=='O')cout<<"推不动哎换其他按键1哇>>>>>";break; if(p[ren[0]+18]==' '){swap(p[ren[0]+9],p[ren[0]+18]);swap(p[ren[0]],p[ren[0]-9]);p[ren[0]]='r';ren[0]+=9;break;}}else{if(p[ren[0]+9]=='X'){cout<<"人碰到墙了换其他按键哇2>>>>>"; break;}if(p[ren[0]+9]==' '){swap(p[ren[0]],p[ren[0]+9]);ren[0]+=9;break;}if(p[ren[0]+9]=='O'){//遇到箱子代码if(p[ren[0]+18]=='O'||p[ren[0]+18]=='X'){cout<<"走不动了换按其他键哇......."<<endl; break;}if(p[ren[0]+18]=='r'){p[ren[0]+18]='O';p[ren[0]+9]='I';p[ren[0]]=' ';ren[0]+=9;break;}if(p[ren[0]+18]==' '){p[ren[0]+18]='O';p[ren[0]+9]='I';p[ren[0]]=' ';ren[0]+=9;break;}}}}break;case 'd':{if(p[ren[0]]=='r') //当前人所在的位置为箱子最终要到的目的地的话{if(p[ren[0]+1]=='r') //要移到的位置是箱子最终目的地{ren[0]+=1;p[ren[0]]='I';p[ren[0]-1]='r';break;}if(p[ren[0]+1]=='X') //碰到墙了{cout<<"人碰到墙了换其他按键1哇>>>>>"; break;}if(p[ren[0]+1]==' ') //可以通过{ren[0]+=1;p[ren[0]]='I';p[ren[0]+1]='r';break;}if(p[ren[0]+1]=='O') //碰到箱子{if(p[ren[0]+2]=='X'||'O')cout<<"箱子碰到墙了换其他按键1哇>>>>>";break;if(p[ren[0]+2]=='r'){p[ren[0]+2]='O';p[ren[0]+1]='I';p[ren[0]]='r';ren[0]+=1;break;}if(p[ren[0]+2]=='O')cout<<"推不动哎换其他按键1哇>>>>>";break; if(p[ren[0]+2]==' '){swap(p[ren[0]+1],p[ren[0]+2]);swap(p[ren[0]],p[ren[0]-1]);p[ren[0]]='r';ren[0]+=1;break;}}}else{if(p[ren[0]+1]=='X'){cout<<"人碰到墙了换其他按键哇2>>>>>"; break;}if(p[ren[0]+1]==' '){swap(p[ren[0]],p[ren[0]+1]);ren[0]+=1;break;}if(p[ren[0]+1]=='O'){//遇到箱子代码if(p[ren[0]+2]=='O'||p[ren[0]+2]=='X'){cout<<"走不动了换按其他键哇......."<<endl; break;}if(p[ren[0]+2]=='r'){p[ren[0]+2]='O';p[ren[0]+1]='I';p[ren[0]]=' ';ren[0]+=1;break;}if(p[ren[0]+2]==' '){p[ren[0]+2]='O';p[ren[0]+1]='I';p[ren[0]]=' ';ren[0]+=1;break;}}}}break;default:cout<<"操作错误!请确认后再重新操作......."<<endl; }dituprint(p);}/*int panduan=0;for(int i=1;i<xzs;i++){if(p[ren[i]]=='O')panduan++;}if(panduan=(xzs-1)){getchar();break;}*/}return 0;}int level1(){cout<<"第一关"<<endl;char ditu1[9*9]={'0','1','2','3','4','5', '6','7','8','1',' ',' ','X','X','X',' ',' ',' ','2',' ',' ','X','r','X',' ',' ',' ','3',' ',' ','X',' ','X','X','X','X','4','X','X','X','O','','O','r','X','5','X','r','','O','I','X','X','X','6','X','X','X','X','O','X',' ',' ','7',' ',' ',' ','X','r','X',' ',' ','8',' ',' ',' ','X','X','X',' ',' '};int ren1[5]={50,22,47,43,68};opera(ditu1,ren1,4);level2();return 0;}int level2(){cout<<" 欢迎来到第二关"<<endl;char ditu1[9*9]={'0','1','2','3','4','5', '6','7','8','1',' ',' ','X','X','X',' ',' ',' ','2',' ',' ','X','r','X',' ',' ',' ','3',' ',' ','X',' ','X','X','X','X','4','X','X','X','O','','O','r','X','5','X','r','','O','I','X','X','X','6','X','X','X','X','O', 'X',' ',' ','7',' ',' ',' ','X','r','X',' ',' ','8',' ',' ',' ','X','X','X',' ',' '};int ren1[5]={50,22,47,43,68};opera(ditu1,ren1,4);level1();return 0;}int main(){int choice;menu();while(1){cin>>choice;switch(choice){case 0:exit(0);case 1:{level1();break;}case 2:{xuanguan();break;}default:{cout<<"操作错误!请确认正确后操作......."<<endl; }}}getchar();return 0;}。
java_推箱子讲解
总共四个包,因为不能上传图片所以在第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);}// 响应键盘事件,松开键盘才响应// 上下左右四个键,实现人物的移动。
推箱子代码
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版!!!提供友情下载。
基于java的推箱子游戏(含源文件)
基于JAVA的推箱子游戏前言在这个充满竞争的社会里,随着生活节奏的不断加快,人们的生活水平越来越繁忙,因此,越来越多人感到无比的烦躁与巨大的压力,这些压力也带给人们诸多烦恼。
所以如何解除现代人的生活压力,释放心中苦闷已经成为现代人的共同心愿。
而本次的这个基于JAVA的推箱子小游戏正是使用JAVA语言并且结合于EditPlus编译器,为大家开发了一款适合的、休闲娱乐的游戏,在娱乐的同时也给忙碌的上班族们开拓了另一个思考问题的空间。
基于JAVA的推箱子小游戏主要分为初始化模块,画图模块,移动小人模块,移动箱子模块以及功能控制模块。
玩家是通过控制小人的移动来推动箱子,需要避过障碍物与死角才能将其推放到指定位置从而达到过关的目的。
每关的难易程度各异,不仅适合人们休闲娱乐,还有助于开发智力,提高人们思考问题能力与想象能力,改善思考方式,拓展思维。
关键词:JAVA;解压;推箱子;休闲娱乐AbstractIn this competitive society, along with the accelerating pace of life, people's living standard more and busier, therefore, more and more people feel very upset and enormous pressure, the pressure also gives people a lot of trouble. So how to relieve the pressure of modern life, release the pain has become the common aspiration of the people. But this time based on the JAVA Push Box Game is the use of JAVA language and the combination of EditPlus compiler; we developed a suitable, recreational game, in the entertainment but also for busy office workers to develop another thinking space.Based on the JAVA Push Box Game consists of initialization module, drawing module, mobile SIM module, mobile box module and control module. Game player is controlled through a small mobile drive box, need to avoid obstacles and dead angle can be pushed into the specified location so as to achieve the purpose of clearance. Each level of difficulty degree is different, not only for recreation, also contribute to the development of intelligence, improve people's thinking ability and imagination ability, improve the way of thinking, the development of thinking.Key Words:JAVA; Relieve pressure; Push box; Recreation and entertainment目录前言............................................................................................................................................. I Abstract ..................................................................................................................................... II 1.可行性研究 (2)1.1设计目的 (2)1.2可行性研究前提 (2)1.3可行性分析 (2)1.4结论意见 (3)2.需求分析 (3)2.1引言 (3)2.2游戏需求 (3)2.3软硬件需求 (4)硬件环境需求: (4)软件环境: (4)2.4接口控制 (4)2.5方案论证 (4)2.5.1.C++语言的优点 (4)2.5.2.Java语言的优点 (5)2.5.3.方案选择 (6)3.概要设计 (7)3.1游戏设计分析 (7)3.3.1.地图文件的引用 (7)3.3.2.程序运逻辑 (7)3.3.3.绘图 (7)3.3.4.显示平台 (7)3.2 注意事项 (8)3.3 游戏流程图 (8)4.详细设计 (9)4.1游戏总体结构与代码 (9)结论 (20)参考文献 (21)致谢 (22)引言在人类的社会生活当中,游戏占有很大的比重,并且随着社会的发展而不断发展。
推箱子
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面向对象推箱子源代码(可扩展)
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("游戏结束!");}}。
推箱子java代码
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实现简单推箱子游戏
使⽤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();}}。
推箱子 源代码
#include"stdio.h"#include"conio.h"#include"stdlib.h"#include"time.h"void show(char b[9][9]){printf("\t\t\t\t***************************\n");printf("\t\t\t\t 推箱子游戏");printf("\n\t\t\t\t***************************\n");printf("\t\t\t\t 人:★墙:■\n\t\t\t\t 箱子:◎目的地:□\n\t\t\t\t 按d 键退出游戏\n\t\t\t\t 限时30秒!");printf("\n\t\t\t\t***************************\n");for(int i=0;i<9;i++) //使用循环将地图转换输出{printf("\t\t\t\t ");for(int k=0;k<9;k++){if(b[i][k]=='#'){printf("■");}else{if(b[i][k]==3){printf("□");}else{if(b[i][k]==5){printf("◎");}else{if(b[i][k]==1){printf("★");}else{if(b[i][k]=='!'){printf("⊙");}else{printf("%c ",b[i][k]);}}}}}}printf("\n");}printf("\t\t\t\t***************************\n");}下面的是cpp文件#include"show.h"/*============================================移动函数=============================================================*/void move(char c[9][9],int *x,int *y,int X,int Y,int A,int B,int N,int M,char *t){*t=getch();/*============================================结束=============================================================*/if(*t=='d')//遇到d返回{}/*============================================向左=============================================================*/if(*t==75){if(c[*x][*y-1]=='#'||c[*x][*y-1]==5&&c[*x][*y-2]==5||c[*x][*y-1]==5&&c[*x][*y-2]=='!')//遇到墙或推两个箱子{}else{if(c[*x][*y-1]=='!')//把箱子推出目的地{if(c[*x][*y-2]!=0){}else{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]!='#')//推箱子{if(c[*x][*y]==c[X][Y]||c[*x][*y]==c[A][B]||c[*x][*y]==c[N][M])//推着箱子离开目的地{c[*x][*y]=3;*y-=1;c[*x][*y]=1;c[*x][*y-1]=5;}else{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-1]==c[A][B]||c[*x][*y-1]==c[N][M])//进到目的地{c[*x][*y]=0;*y-=1;c[*x][*y]=1;}else{if(c[*x][*y]==c[X][Y]||c[*x][*y]==c[A][B]||c[*x][*y]==c[N][M])//离开目的地{c[*x][*y]=3;*y-=1;c[*x][*y]=1;}else //走到空地{c[*x][*y]=0;*y-=1;c[*x][*y]=1;}}}}}}if(c[X][Y]==5||c[A][B]==5||c[N][M]==5)//箱子推到目的地{c[*x][*y-1]='!';}}/*============================================向右=============================================================*/if(*t==77){if(c[*x][*y+1]=='#'||c[*x][*y+1]==5&&c[*x][*y+2]==5||c[*x][*y+1]==5&&c[*x][*y+2]=='!')//遇到墙或推两个箱子{}else{if(c[*x][*y+1]=='!')//把箱子推出目的地{if(c[*x][*y+2]!=0){}else{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]!='#')//推箱子{if(c[*x][*y]==c[X][Y]||c[*x][*y]==c[A][B]||c[*x][*y]==c[N][M]){c[*x][*y]=3;*y+=1;c[*x][*y]=1;c[*x][*y+1]=5;}else{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+1]==c[A][B]||c[*x][*y+1]==c[N][M])//进到目的地{c[*x][*y]=0;*y+=1;c[*x][*y]=1;}else{if(c[*x][*y]==c[X][Y]||c[*x][*y]==c[A][B]||c[*x][*y]==c[N][M])//离开目的地{c[*x][*y]=3;*y+=1;c[*x][*y]=1;}else //走到空地{c[*x][*y]=0;*y+=1;c[*x][*y]=1;}}}}}}if(c[X][Y]==5||c[A][B]==5||c[N][M]==5)//箱子进入目的地{c[*x][*y+1]='!';}}/*============================================向上=============================================================*/if(*t==72){if(c[*x-1][*y]=='#'||c[*x-1][*y]==5&&c[*x-2][*y]==5||c[*x-1][*y]==5&&c[*x-2][*y]=='!')//遇到墙或推两个箱子{}else{if(c[*x-1][*y]=='!')//把箱子推出目的地{if(c[*x-2][*y]!=0){}else{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]!='#')//推箱子{if(c[*x][*y]==c[X][Y]||c[*x][*y]==c[A][B]||c[*x][*y]==c[N][M]){c[*x][*y]=3;*x-=1;c[*x][*y]=1;c[*x-1][*y]=5;}else{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-1][*y]==c[A][B]||c[*x-1][*y]==c[N][M])//进到目的地{c[*x][*y]=0;*x-=1;c[*x][*y]=1;}else{if(c[*x][*y]==c[X][Y]||c[*x][*y]==c[A][B]||c[*x][*y]==c[N][M])//走出目的地{c[*x][*y]=3;*x-=1;c[*x][*y]=1;}else //走到空地{c[*x][*y]=0;*x-=1;c[*x][*y]=1;}}}}}}if(c[X][Y]==5||c[A][B]==5||c[N][M]==5)//箱子进入目的地{c[*x-1][*y]='!';}}/*============================================向下=============================================================*/if(*t==80){if(c[*x+1][*y]=='#'||c[*x+1][*y]==5&&c[*x+2][*y]==5||c[*x+1][*y]==5&&c[*x+2][*y]=='!')//遇到墙或推两个箱子{}else{if(c[*x+1][*y]=='!')//把箱子推出目的地{if(c[*x+2][*y]!=0){}else{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]!='#')//推箱子{if(c[*x][*y]==c[X][Y]||c[*x][*y]==c[A][B]||c[*x][*y]==c[N][M]){c[*x][*y]=3;*x+=1;c[*x][*y]=1;c[*x+1][*y]=5;}else{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+1][*y]==c[A][B]||c[*x+1][*y]==c[N][M])//进到目的地{c[*x][*y]=0;*x+=1;c[*x][*y]=1;}else{if(c[*x][*y]==c[X][Y]||c[*x][*y]==c[A][B]||c[*x][*y]==c[N][M])//走出目的地{c[*x][*y]=3;*x+=1;c[*x][*y]=1;}else //走到空地{c[*x][*y]=0;*x+=1;c[*x][*y]=1;}}}}}}if(c[X][Y]==5||c[A][B]==5||c[N][M]==5)//箱子进入目的地{c[*x+1][*y]='!';}}}/*============================================第一关=============================================================*/void map1(){time_t p,q,o;time(&p);int i=4,j=4,m=6,n=2,t=1,k=3;system("cls");//刷屏system("color 1E");int x=1,y=7;char z,a[9][9]={{'#','#','#','#','#','#','#','#','#'},{'#','#','#', 3 , 0 , 0 , 0 , 1 ,'#'},{'#','#', 0 , 0 , 0 ,'#', 0 ,'#','#'},{'#', 0 , 0 ,'#', 0 , 0 , 0 , 0 ,'#'},{'#', 0 , 5 , 0 , 3 , 5 , 5 , 0 ,'#'},{'#','#','#','#', 0 , 0 ,'#','#','#'},{'#','#', 3 , 0 , 0 , 0 ,'#','#','#'},{'#','#','#','#','#','#','#','#','#'},{'#','#','#','#','#','#','#','#','#'}};show(a);loop:move(a,&x,&y,i,j,m,n,t,k,&z);if(a[i][j]=='!'&&a[m][n]=='!'&&a[t][k]=='!'){system("cls");//刷屏show(a);printf("\t\t\t\t YOU ARE WIN!\n");time(&q);printf("\t\t\t\t\t 用时%.3d秒\n",q-p);printf("\t\t\t\t*******回车重新选择*******\n\t\t\t\t");getch();}else{time(&o);if(z=='d'){return;}if(o-p>30){loop1: system("cls");//刷屏printf("\n\n\n\n\t\t\t\t时间已过请重新回车选关!");int g=getch();if(g==13)//判断是否为回车符{return;}else{goto loop1;}}system("cls");//刷屏show(a);//调用输出函数goto loop;}}/*============================================第二关=============================================================*/void map2(){time_t p,q,o;time(&p);int i=1,j=3,m=6,n=2,t=2,k=1;system("cls");//刷屏system("color 2E");int x=4,y=1;char z,b[9][9]={{'#','#','#','#','#','#','#','#','#'},{'#','#','#', 3 , 0 ,'#','#','#','#'},{'#', 3 ,'#', 0 , 0 , 0 , 0 ,'#','#'},{'#', 0 , 0 , 0 ,'#','#', 0 , 0 ,'#'},{'#', 1 , 0 , 5 , 0 , 0 , 5 , 0 ,'#'},{'#', 0 , 0 ,'#', 0 , 0 , 0 ,'#','#'},{'#','#', 3 , 0 , 0 , 5 ,'#','#','#'},{'#','#','#','#', 0 , 0 ,'#','#','#'},{'#','#','#','#','#','#','#','#','#'}};show(b);loop:move(b,&x,&y,i,j,m,n,t,k,&z);if(b[i][j]=='!'&&b[m][n]=='!'&&b[t][k]=='!'){system("cls");//刷屏show(b);printf("\t\t\t\t YOU ARE WIN!\n");time(&q);printf("\t\t\t\t\t 用时%.3d秒\n",q-p);printf("\t\t\t\t*******回车重新选择*******\n\t\t\t\t");getch();}else{time(&o);if(z=='d'){return ;}if(o-p>30){loop1: system("cls");//刷屏printf("\n\n\n\n\t\t\t\t时间已过请重新回车选关!");int g=getch();if(g==13){return;}else{goto loop1;}}system("cls");//刷屏show(b);goto loop;}}/*============================================第三关=============================================================*/void map3(){time_t p,q,o;time(&p);int i=7,j=6,m=6,n=2,t=2,k=1;system("cls");//刷屏system("color 2F");int x=5,y=3;char z, b[9][9]={{'#','#','#','#','#','#','#','#','#'},{'#','#','#','#','#', 0 , 0 ,'#','#'},{'#', 3 ,'#', 0 , 5 , 0 , 0 , 0 ,'#'},{'#', 0 , 5 , 0 , 0 ,'#', 0 ,'#','#'},{'#', 0 , 0 , 0 , 0 , 0 , 5 , 0 ,'#'},{'#','#', 0 , 1 , 0 , 0 , 0 , 0 ,'#'},{'#','#', 3 , 0 ,'#', 0 ,'#', 0 ,'#'},{'#','#','#', 0 , 0 , 0 , 3 ,'#','#'},{'#','#','#','#','#','#','#','#','#'}};show(b);loop:move(b,&x,&y,i,j,m,n,t,k,&z);if(b[i][j]=='!'&&b[t][k]=='!'&&b[m][n]=='!'){system("cls");//刷屏show(b);printf("\t\t\t\t YOU ARE WIN!\n");time(&q);printf("\t\t\t\t\t 用时%.3d秒\n",q-p);printf("\t\t\t\t*******回车重新选择*******\n\t\t\t\t");getch();}else{time(&o);if(z=='d'){return;}if(o-p>30){loop1: system("cls");//刷屏printf("\n\n\n\n\t\t\t\t时间已过请重新回车选关!");int g=getch();if(g==13){return;}else{goto loop1;}}system("cls");//刷屏show(b);goto loop;}}/*============================================主函数=============================================================*/void main(int argc,char*argv[]){time_t a,b;time(&a);system("color 4E");loop1: {system("cls");//刷屏printf("\n\n\n\n\n\n\t\t\t\t欢迎进入推箱子游戏\n\n\t\t\t\t 请按a b c选择游戏\n\n\t\t\t\t 按 d 键结束");int t=getch();if(t=='d'){printf("\n\t\t\t ");}else{if(t=='a'){map1();goto loop1;}if(t=='b'){map2();goto loop1;}if(t=='c'){map3();goto loop1;}else{printf("\n\n\t\t\t\t 请重新输入:");goto loop1;}}}time(&b);printf("\n\n\n\n\t\t\t\t 游戏总共用时%.3d秒\n\t\t\t ",b-a);getch();//等待读取回车符以结束程序}。
JAVA推箱子分解
主窗体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 { //面板private JPanel panel;//箱子private JLabel box;//目的地private JLabel goal;//工人private JLabel worker;//围墙private JLabel[] walls;//工人图片private String[] workerImgPaths;public GameFrame(String title) throws HeadlessException {super(title);super.setBounds(60, 15, 24 * 48, 15 * 48 + 30);super.setResizable(false);//初始化面板this.initPanel();this.addEvent();}//加载关卡信息public void loadLevel(Level level) {this.workerImgPaths =level.getWorkerImgPaths();//添加工人箱子目的地this.addComp(level.getBoxImgPath(),level.getBoxLocation());goal =this.addComp(level.getGoalImgPath(),level.getGoalLocation());worker =this.addComp(level.getWorkerImgPaths()[0], level.getWorkerLocation());//初始化围墙this.addWalls(level.getWallImgPath(), level.getWallsLocations());}private void addEvent() {super.addKeyListener(new KeyListener() {@Overridepublic void keyTyped(KeyEvent e) {}@Overridepublic void keyReleased(KeyEvent e) {@Overridepublic void keyPressed(KeyEvent e) {int keyCode = e.getKeyCode();int x = 0, y = 0;int workerImgIndex = 0;//String workerImgPath = workerImgPaths[0];if (keyCode ==KeyEvent.VK_LEFT || keyCode == KeyEvent.VK_A) {x = -24;} else if (keyCode == KeyEvent.VK_UP || keyCode == KeyEvent.VK_W) {y = -24;workerImgIndex = 1;//workerImgPath = workerImgPaths[1];} else if (keyCode == KeyEvent.VK_RIGHT || keyCode == KeyEvent.VK_D) {x = 24;workerImgIndex = 2;//workerImgPath = workerImgPaths[2];} else if (keyCode == KeyEvent.VK_DOWN || keyCode == KeyEvent.VK_S) {y = 24;workerImgIndex = 3;//workerImgPath = workerImgPaths[3];}ImageIcon workerImg = new ImageIcon("imgs/" +workerImgPaths[workerImgIndex]);worker.setIcon(workerImg);worker.setBounds(worker.getBounds().x + x, worker.getBounds().y + y, 48, 48);//判断工人是否穿墙for (int i = 0; i <walls.length; i++) {//如果工人与某一块围墙有交集if(worker.getBounds().intersects(walls[i].getBou nds())) {//工人退后worker.setBounds(worker.getBounds().x - x, worker.getBounds().y - y, 48, 48);break;}}//如果工人与箱子有交集if(worker.getBounds().intersects(box.getBounds() )) {//让工人推动箱子box.setBounds(box.getBounds().x + x,box.getBounds().y + y, 48, 48);}//判断箱子是否穿墙for (int i = 0; i <walls.length; i++) {//如果箱子与某个围墙有交集if(box.getBounds().intersects(walls[i].getBounds ())) {box.setBounds(box.getBounds().x - x,box.getBounds().y - y, 48, 48);worker.setBounds(worker.getBounds().x - x, worker.getBounds().y - y, 48, 48);break;}}if(worker.getBounds().intersects(goal.getBounds( ))) {worker.setBounds(worker.getBounds().x - x, worker.getBounds().y - y, 48, 48);}//判断输赢if(box.getBounds().contains(goal.getBounds())) {JOptionPane.showMessageDialog(null, "恭喜你,赢了!");System.exit(0);}}});}/*** 向面板中添加一个组件并返回添加的组件* @param imgPath 图片路径* @param location 位置* @return 添加的组件*/private JLabel addComp(String imgPath,int[] location) {int x = location[0];int y = location[1];ImageIcon img = new ImageIcon("imgs/" + imgPath);JLabel comp = new JLabel(img);comp.setBounds(x * 48, y * 48, 48, 48);panel.add(comp);return comp;}/*** 向面板中添加一个组件并返回添加的组件* @param imgPath 图片路径* @param x y 位置* @return 添加的组件*/private JLabel addComp(String imgPath, int x, int y) {ImageIcon img = new ImageIcon("imgs/" + imgPath);JLabel comp = new JLabel(img);comp.setBounds(x * 48, y * 48, 48, 48);panel.add(comp);return comp;}/*** 添加围墙* @param wallImgPath 围墙使用的图片* @param wallsLocations 中间障碍物的个数与位置*/private void addWalls(String wallImgPath, int[][] wallsLocations) {ImageIcon wallImg = newImageIcon("imgs/" + wallImgPath);this.walls = new JLabel[24 * 2 + 13 * 2 + wallsLocations.length];for (int i = 0; i < walls.length; i++) {walls[i] = new JLabel(wallImg);}//记录使用到了围墙数组中的那个元素int index = 0;for (int i = 0; i < 24; i++) {walls[index].setBounds(i * 48, 0, 48, 48);panel.add(walls[index]);index ++;walls[index].setBounds(i * 48, 14 * 48, 48, 48);panel.add(walls[index]);index ++;}for (int i = 1; i <= 13; i++) {walls[index].setBounds(0, i * 48, 48, 48);panel.add(walls[index]);index ++;walls[index].setBounds(23 * 48, i * 48, 48, 48);panel.add(walls[index]);index ++;}//添加障碍物for (int i = 0; i <wallsLocations.length; i++) {int[] location = wallsLocations[i];walls[index].setBounds(location[0] * 48, location[1] * 48, 48, 48);panel.add(walls[index]);index ++;}}//初始化面板private void initPanel() {panel = new JPanel();//设置背静颜色panel.setBackground(Color.GREEN);//自定义布局panel.setLayout(null);//内容面板super.setContentPane(panel);}}设置关卡public class Level {//箱子使用图片private String boxImgPath;//箱子初始位置 {3, 3}private int[] boxLocation;//工人使用图片数组长度为4private String[] workerImgPaths;//工人初始位置长度为2 {19, 12}private int[] workerLocation;//目的地使用图片private String goalImgPath;//目的地初始位置长度为2 {10, 10}private int[] goalLocation;//围墙图片private String wallImgPath;//障碍物个数与位置private int[][] wallsLocations;public Level() {super();// TODO Auto-generated constructor stub}public String getBoxImgPath() {return boxImgPath;}public void setBoxImgPath(String boxImgPath) {this.boxImgPath = boxImgPath;}public int[] getBoxLocation() {return boxLocation;}public void setBoxLocation(int[] boxLocation) {this.boxLocation = boxLocation;}public String[] getWorkerImgPaths() {return workerImgPaths;}public void setWorkerImgPaths(String[] workerImgPaths) {this.workerImgPaths = workerImgPaths;}public int[] getWorkerLocation() {return workerLocation;}public void setWorkerLocation(int[] workerLocation) {this.workerLocation = workerLocation;}public String getGoalImgPath() {return goalImgPath;}public void setGoalImgPath(String goalImgPath) {this.goalImgPath = goalImgPath;}public int[] getGoalLocation() {return goalLocation;}public void setGoalLocation(int[] goalLocation) {this.goalLocation = goalLocation;}public String getWallImgPath() {return wallImgPath;}public void setWallImgPath(String wallImgPath) {this.wallImgPath = wallImgPath;}public int[][] getWallsLocations() {return wallsLocations;}public void setWallsLocations(int[][] wallsLocations) {this.wallsLocations = wallsLocations;}}关卡管理public class LevelManager {/*** 根据关卡编号得到本关卡的详细信息* @param index* @return*/public static Level getNowLevel(int index) {Level level = new Level();if (index == 1) {level.setBoxImgPath("box2.png");level.setBoxLocation(new int[]{3, 3});level.setGoalImgPath("goal2.png");level.setGoalLocation(new int[]{10, 10});String[] workerImgPaths = {"workerLeft2.png","workerUp2.png","workerRight2.png","workerDown2.png"};level.setWorkerImgPaths(workerImgPaths);level.setWorkerLocation(newint[]{19, 12});level.setWallImgPath("wall2.png");int[][] wallsLocations = {{7, 2},{8, 2},{9, 2},{10, 2},{11, 2},{12, 2},{13, 2},{10, 3},{10, 4}};level.setWallsLocations(wallsLocations);} else if(index == 2) {level.setBoxImgPath("box.png");level.setBoxLocation(new int[]{3, 3});level.setGoalImgPath("goal.png");level.setGoalLocation(new int[]{10, 10});String[] workerImgPaths = {"workerLeft.png","workerUp.png","workerRight.png","workerDown.png"};level.setWorkerImgPaths(workerImgPaths);level.setWorkerLocation(newint[]{19, 12});level.setWallImgPath("wall.png");int[][] wallsLocations = {{7, 2},{8, 2},{9, 2},{10, 2},{11, 2},{12, 2},{13, 2},{10, 3},{10, 4}};level.setWallsLocations(wallsLocations);} else {return null;}return level;}}运行游戏public class Start {public static void main(String[] args) { //1 创建游戏窗体GameFrame gameFrame = new GameFrame("推箱子3.0");//2 得到关卡数据Level level =LevelManager.getNowLevel(1);//3 让游戏窗体加载关卡数据gameFrame.loadLevel(level);//4 窗体可见gameFrame.setVisible(true);}}。
推箱子总结完整(附有源代码)
推箱子总结完整(附有源代码)推箱子复习总结推箱子基本概括思路:/* 定义二维数组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循环,作用:触发判断和判断是否过关。
推箱子源小游戏代码
<!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<windows.h>#include<conio.h>int i=0;//记录所走步数//人的结构体struct person{int x;int y;}per={3,3};//定义光标移动函数void gotoxy(int x,int y){COORD coord={x,y};SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord); }//初始化图形界面int arr_set(char arr[9][9]){int i=0;int j=0;for(i=0;i<9;i++)for(j=0;j<9;j++)arr[i][j]='*';arr[1][1]='';arr[1][2]='';arr[1][3]='';arr[2][1]='';arr[2][2]='';arr[2][3]='';arr[3][1]='';arr[3][2]='';arr[3][3]='';arr[3][7]='';arr[4][3]='';arr[4][7]='';arr[5][3]='';arr[5][4]='';arr[5][5]='';arr[5][6]='';arr[5][7]='';arr[6][2]='';arr[6][3]='';arr[6][4]='';arr[6][6]='';arr[6][7]='';arr[7][2]='';arr[7][3]='';arr[7][4]='';arr[2][2]=2;arr[3][2]=2;arr[4][3]=2;arr[3][3]=12;arr[3][7]=4;arr[4][7]=4;arr[5][7]=4;return0;}//打印图形界面int prin(char arr[9][9]){int i=0;int j=0;for(i=0;i<9;i++){for(j=0;j<9;j++){if('*'==arr[i][j])printf("▓");if(2==arr[i][j])printf("□");if(12==arr[i][j])printf("♀");if(4==arr[i][j])printf("○");if(''==arr[i][j])printf("");}printf("\n");}//操作提示gotoxy(30,2);printf("WSAD分别操作上移、下移、左移、右移");gotoxy(30,4);printf("□代表箱子、♀代表人、○代表目的地");gotoxy(30,6);printf("把所有箱子推到目的地即完成任务");gotoxy(2*per.x,per.y);return0;}//向上移动int move_up(char arr[9][9]){//如果上面没有东西if(''==arr[per.y-1][per.x]||4==arr[per.y-1][per.x]){gotoxy(2*per.x,per.y);printf("");arr[per.y][per.x]='';gotoxy(2*per.x,per.y-1);printf("♀");gotoxy(2*per.x,per.y-1);arr[per.y-1][per.x]=12;per.y--;i++;}//如果上面是箱子并且箱子上面是空格则箱子和人同时上移光标回到人处if(2==arr[per.y-1][per.x]&&(''==arr[per.y-2][per.x]||4==arr[per.y-2][per.x])) {gotoxy(2*per.x,per.y);printf("");arr[per.y][per.x]='';gotoxy(2*per.x,per.y-1);printf("♀");arr[per.y-1][per.x]=12;gotoxy(2*per.x,per.y-2);printf("□");arr[per.y-2][per.x]=2;per.y--;gotoxy(2*per.x,per.y);i++;}if(arr[3][7]==''){gotoxy(14,3);printf("○");arr[3][7]=4;}if(arr[4][7]==''){gotoxy(14,4);printf("○");arr[4][7]=4;}if(arr[5][7]==''){gotoxy(14,5);printf("○");arr[5][7]=4;}return0;}//向下移动int move_down(char arr[9][9]){//如果下面没有东西if(''==arr[per.y+1][per.x]||4==arr[per.y+1][per.x]){gotoxy(2*per.x,per.y);printf("");arr[per.y][per.x]='';gotoxy(2*per.x,per.y+1);printf("♀");gotoxy(2*per.x,per.y+1);arr[per.y+1][per.x]=12;per.y++;i++;}//如果下面是箱子并且箱子下面是空格则箱子和人同时下移光标回到人处不用boxz if(2==arr[per.y+1][per.x]&&(''==arr[per.y+2][per.x]||''==arr[per.y+2][per.x])) {gotoxy(2*per.x,per.y);printf("");arr[per.y][per.x]='';gotoxy(2*per.x,per.y+1);printf("♀");arr[per.y+1][per.x]=12;gotoxy(2*per.x,per.y+2);printf("□");arr[per.y+2][per.x]=2;per.y++;gotoxy(2*per.x,per.y);i++;}if(arr[3][7]==''){gotoxy(14,3);printf("○");arr[3][7]=4;}if(arr[4][7]==''){gotoxy(14,4);printf("○");arr[4][7]=4;}if(arr[5][7]==''){gotoxy(14,5);printf("○");arr[5][7]=4;}return0;}//向左移动int move_left(char arr[9][9]){//如果左边没有东西if(''==arr[per.y][per.x-1]||4==arr[per.y][per.x-1]){gotoxy(2*per.x,per.y);printf("");arr[per.y][per.x]='';gotoxy(2*per.x-2,per.y);printf("♀");gotoxy(2*per.x-2,per.y);arr[per.y][per.x-1]=12;per.x--;i++;}//如果左面是箱子并且箱子左面是空格则箱子和人同时左移光标回到人处if(2==arr[per.y][per.x-1]&&(''==arr[per.y][per.x-2]||4==arr[per.y][per.x-2])) {gotoxy(2*per.x,per.y);printf("");arr[per.y][per.x]='';gotoxy(2*per.x-2,per.y);printf("♀");arr[per.y][per.x-1]=12;gotoxy(2*per.x-4,per.y);printf("□");arr[per.y][per.x-2]=2;per.x--;gotoxy(2*per.x,per.y);i++;}if(arr[3][7]==''){gotoxy(14,3);printf("○");arr[3][7]=4;}if(arr[4][7]==''){gotoxy(14,4);printf("○");arr[4][7]=4;}if(arr[5][7]==''){gotoxy(14,5);printf("○");arr[5][7]=4;}return0;}//向右移动int move_right(char arr[9][9]){//如果右边没有东西if(''==arr[per.y][per.x+1]||4==arr[per.y][per.x+1]) {gotoxy(2*per.x,per.y);printf("");arr[per.y][per.x]='';gotoxy(2*per.x+2,per.y);printf("♀");gotoxy(2*per.x+2,per.y);arr[per.y][per.x+1]=12;per.x++;i++;}//如果右面是箱子并且箱子右面是空格则箱子和人同时右移光标回到人处if(2==arr[per.y][per.x+1]&&(''==arr[per.y][per.x+2]||4==arr[per.y][per.x+2])) {gotoxy(2*per.x,per.y);printf("");arr[per.y][per.x]='';gotoxy(2*per.x+2,per.y);printf("♀");arr[per.y][per.x+1]=12;gotoxy(2*per.x+4,per.y);printf("□");arr[per.y][per.x+2]=2;per.x++;gotoxy(2*per.x,per.y);i++;}if(arr[3][7]==''){gotoxy(14,3);printf("○");arr[3][7]=4;}if(arr[4][7]==''){gotoxy(14,4);printf("○");arr[4][7]=4;}if(arr[5][7]==''){gotoxy(14,5);printf("○");arr[5][7]=4;}return0;}//主函数int main(void){char ch=0;char arr[9][9]={0};//构建界面arr_set(arr);prin(arr);//游戏运行while(1){ch=_getch();switch(ch){case'w':move_up(arr);break;case's':move_down(arr);break;case'a':move_left(arr);break;case'd':move_right(arr);break;}if(arr[3][7]==2&&arr[4][7]==2&&arr[5][7]==2){gotoxy(15,15);printf("恭喜过关!共%d步",i);goto_out;}}_out:return0;}。
java推箱子游戏源代码(含推箱子的判断)
第一个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, "您赢啦!");}}}public void keyReleased(KeyEvent e) {}public void keyTyped(KeyEvent e) {}});}/***设置内容面板*/public void initContentPane() {zhuobu.setBackground(Color.red);zhuobu.setLayout(null);//调用父类的属性和方法super.setContentPane(zhuobu);}/***把某个图片以组件的方式加入窗体*@param imgPath图片路径*@param x x*@param y y*@param width宽度*@param height高度*@return添加完的组件*/public void addComponent(int tag, String imgPath, int x, int y) { ImageIcon img = new ImageIcon(imgPath);//创建JLabel并把ImageIcon通过构造方法传参传入//把食物放到盘子里JLabel componet = new JLabel(img);//设置盘子在桌布上的位置和大小componet.setBounds(x, y, imgSize, imgSize);//把盘子放到桌布上zhuobu.add(componet);switch (tag) {case 1:box = componet;break;case 2:goal = componet;break;case 3:worker = componet;break;}}public void addWall(String imgPath, int[][] loactions) { ImageIcon wallImg = new ImageIcon(imgPath);walls = new JLabel[66 + loactions.length];for (int i = 0; i < walls.length; i++) {//创建没每一个围墙,他们使用的是同一个图片walls[i] = new JLabel(wallImg);}for (int i = 0; i < walls.length; i++) {//创建没每一个围墙,他们使用的是同一个图片walls[i] = new JLabel(wallImg);}int index = 0;/*分别设置各个图片位置*/for (int i = 0; i < 14; i++) {//左边墙walls[index].setBounds(0, i * imgSize, imgSize, imgSize);zhuobu.add(walls[index]);index++;//右边墙walls[index].setBounds(20 * imgSize, i * imgSize, imgSize, imgSize);zhuobu.add(walls[index]);index++;}for (int i = 0; i < 19; i++) {//上边墙walls[index].setBounds((i + 1) * imgSize, 0, imgSize, imgSize);zhuobu.add(walls[index]);index++;//下边墙walls[index].setBounds((i + 1) * imgSize, 13 * imgSize, imgSize, imgSize);zhuobu.add(walls[index]);index++;}//添加中间障碍耦合解耦for (int i = 0; i < loactions.length; i++) {walls[index].setBounds(loactions[i][0]* imgSize, loactions[i][1]* imgSize, imgSize, imgSize);zhuobu.add(walls[index]);index++;}}}第二个Java文件:public class Run {public static void main(String[] args) {GameFrame gameFrame = new GameFrame("推箱子游戏…");//设置大小gameFrame.setBounds(100, 50, 21 * 48 + 5, 14 * 48 + 25);//窗体大小不可变gameFrame.setResizable(false);gameFrame.setImgSize(48);gameFrame.addComponent(3, "workerUp.png", 400, 100);gameFrame.addComponent(1, "box.png", 160, 60);gameFrame.addComponent(2, "goal.png", 80, 520);int[][] wallLocations ={{4, 5},{5, 5},{6, 5},{7, 5},{8, 5},{9, 5},{10, 5},{6, 8},{7, 8},{8, 8},{9, 8},{10, 8},{11, 5}};gameFrame.addWall("wall.png", wallLocations);gameFrame.setVisible(true);}}。
推箱子之完美游戏程序清单
//.推箱子源代码.#include <stdio.h> //标准输入输出头文件#include <stdlib.h> //system函数的头文件#include <conio.h> //getch函数的头文件#include <windows.h>int i,j;void drawmap(int map[10][12]); //声明画图函数void setback();int main(){char input;int count=0; //定义记分变量/*下面定义一个二维数组,其中的元素是不同图像的ID号,不同数字分别代表的图像元素*/ setback ();int map[10][12] = {{2,2,2,2,2,1,1,1,1,1,2,2},{1,1,1,1,2,1,0,0,0,1,1,2},{1,0,0,1,1,1,0,1,0,0,1,2},{1,0,4,3,3,3,3,3,1,0,1,1},{1,0,0,1,1,3,3,3,4,0,0,1},{1,0,0,0,0,4,1,0,4,1,0,1},{1,0,4,1,4,0,0,0,4,0,0,1},{1,1,0,6,0,1,1,1,4,1,0,1},{2,1,1,1,1,1,2,1,0,0,0,1},{2,2,2,2,2,2,2,1,1,1,1,1}};while (1) //死循环,等待用户命令{system("cls");printf(" 由范占伟,刘艳威制:\n\n\n");drawmap(map);printf(" 你的当前得分=%d\n\n",count);//找初始位置for (i=0;i<10;i++){for (j=0;j<12;j++){if (map[i][j]==6||map[i][j]==9) break;}if (map[i][j]==6||map[i][j]==9) break;}printf(" 您的当前坐标(%d,%d)\n",i,j);input = getch(); //用getch()函数无需回车确认地获取用户输入,用于控制行走方向。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 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, "您赢啦!");}}}public void keyReleased(KeyEvent e) {}public void keyTyped(KeyEvent e) {}});}/***设置内容面板*/public void initContentPane() {zhuobu.setBackground(Color.red);zhuobu.setLayout(null);//调用父类的属性和方法super.setContentPane(zhuobu);}/***把某个图片以组件的方式加入窗体*@param imgPath图片路径*@param x x*@param y y*@param width宽度*@param height高度*@return添加完的组件*/public void addComponent(int tag, String imgPath, int x, int y) { ImageIcon img = new ImageIcon(imgPath);//创建JLabel并把ImageIcon通过构造方法传参传入//把食物放到盘子里JLabel componet = new JLabel(img);//设置盘子在桌布上的位置和大小componet.setBounds(x, y, imgSize, imgSize);//把盘子放到桌布上zhuobu.add(componet);switch (tag) {case 1:box = componet;break;case 2:goal = componet;break;case 3:worker = componet;break;}}public void addWall(String imgPath, int[][] loactions) { ImageIcon wallImg = new ImageIcon(imgPath);walls = new JLabel[66 + loactions.length];for (int i = 0; i < walls.length; i++) {//创建没每一个围墙,他们使用的是同一个图片walls[i] = new JLabel(wallImg);}for (int i = 0; i < walls.length; i++) {//创建没每一个围墙,他们使用的是同一个图片walls[i] = new JLabel(wallImg);}int index = 0;/*分别设置各个图片位置*/for (int i = 0; i < 14; i++) {//左边墙walls[index].setBounds(0, i * imgSize, imgSize, imgSize);zhuobu.add(walls[index]);index++;//右边墙walls[index].setBounds(20 * imgSize, i * imgSize, imgSize, imgSize);zhuobu.add(walls[index]);index++;}for (int i = 0; i < 19; i++) {//上边墙walls[index].setBounds((i + 1) * imgSize, 0, imgSize, imgSize);zhuobu.add(walls[index]);index++;//下边墙walls[index].setBounds((i + 1) * imgSize, 13 * imgSize, imgSize, imgSize);zhuobu.add(walls[index]);index++;}//添加中间障碍耦合解耦for (int i = 0; i < loactions.length; i++) {walls[index].setBounds(loactions[i][0]* imgSize, loactions[i][1]* imgSize, imgSize, imgSize);zhuobu.add(walls[index]);index++;}}}第二个Java文件:public class Run {public static void main(String[] args) {GameFrame gameFrame = new GameFrame("推箱子游戏…");//设置大小gameFrame.setBounds(100, 50, 21 * 48 + 5, 14 * 48 + 25);//窗体大小不可变gameFrame.setResizable(false);gameFrame.setImgSize(48);gameFrame.addComponent(3, "workerUp.png", 400, 100);gameFrame.addComponent(1, "box.png", 160, 60);gameFrame.addComponent(2, "goal.png", 80, 520);int[][] wallLocations ={{4, 5},{5, 5},{6, 5},{7, 5},{8, 5},{9, 5},{10, 5},{6, 8},{7, 8},{8, 8},{9, 8},{10, 8},{11, 5}};gameFrame.addWall("wall.png", wallLocations);gameFrame.setVisible(true);}}。