java拼图

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.File;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.UIManager;
import static java.lang.Math.sqrt;

public class GameView extends JFrame{//窗口框架

    private GamePanel mainJPanel=new GamePanel();//拼图面板
    private  int rows=4;
    private  int cols=4;
    private PazzlePieces pp[]=new PazzlePieces[rows*cols];
    private static int initx=20;
    private static int inity=20;
    private int width=100;//100
    private int height=100;
    private JButton Onbutton= new JButton("S T A R T");
    private JButton Overbutton=new JButton("D O N E");

    private GameView() {
        this.setLayout(null);
        this.getContentPane().setBackground(Color.decode("#FFFFCC"));
        this.setBounds(0,0,1000,800);
        int i = 0;
       // mainJPanel.setOpaque(false);

        Onbutton.setBounds(900,30,80,50);
        setVisible(true);
        add(Onbutton);
        Onbutton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                for(int k=0;k<pp.length;k++){
                    pp[k].resetsite(pp[k].oriX,pp[k].oriY);
                }
                JOptionPane.showMessageDialog(GameView.this, "Are you Ready ?");
                for(int k=0;k<pp.length;k++) {
                    pp[k].ReOrder(k);
                }
                Onbutton.setEnabled(false);
            }
        });
        Overbutton.setBounds(900,110,80,50);
        setVisible(true);
        add(Overbutton);
        Overbutton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                super.mouseClicked(e);
                CheckResult();
                Onbutton.setEnabled(false);
                Onbutton.setText("Restart");
                Onbutton.setEnabled(true);
            }
        });
        cut("pic\\1.jpg","pic\\",cols,rows);
        for(;i<rows*cols;i++){
            pp[i]=new PazzlePieces();
            pp[i].setBounds(width*(int)(i%cols),height*(int)(i/rows),width,height);
                ImageIcon icon=new ImageIcon("pic\\" + "pre_map_" + (i/cols)+ "_" + (i%rows)+ ".jpg");
                Image tmp=icon.getImage().getScaledInstance(pp[i].getWidth(),pp[i].getHeight(),icon.getImage().SCALE_DEFAULT);
                icon=new ImageIcon(tmp);
                pp[i].setIcon(icon);
                pp[i].initsite();



            final int j=i;
                pp[i].addMouseMotionListener( new MouseMotionAdapter(){
                    int preX,preY;
                    @Override
                    public void mouseDragged(MouseEvent e){
                        super.mouseDragged(e);
                       Point p=pp[j].getLocation();
                        pp[j].setLocation(p.x+(e.getX()-preX),p.y+(e.getY()-preY));//移动前坐标位置+鼠标移动前后的位置差
                      //  System.out.println("pp"+j+"移动:"+pp[j].getLocation());
                    }

            });
            pp[i].addMouseListener(new MouseAdapter() {
                int preX,preY;
                double min=50,tmp;
                int no=0;
                @Override
                public void mousePressed(MouseEvent e) {
                    super.mousePressed(e);

                   for(int n=0;n<pp.length;n++){
                        tmp=pp[j].caldis(pp[n].oriX,pp[n].oriY);
                        if(tmp<min){
                            min=tmp;
                            no=n;
                        }
                    }
                    if(pp[no].flag==1&no>0) {
                       //pp[j].setLocation();
                        pp[j].disordX=pp[j].getX();
                        pp[j].disordY=pp[j].getY();
                        pp[no].flag=0;
                       // pp[j].setEnabled(false);
                    }

                }

                @Override
                public void mouseReleased(MouseEvent e) {
                    super.mouseReleased(e);
                    double min=50;
                    double tmp;
                    int no=0;
                    for(int n=0;n<pp.length;n++){
                        tmp=pp[j].caldis(pp[n].oriX,pp[n].oriY);
                        if(tmp<min){
                            min=tmp;
                            no=n;
                        }
                    }
                    if(pp[no].flag==0&no>0) {
                        pp[j].setLocation(pp[no].oriX, pp[no].oriY);
                        pp[j].disordX=pp[no].oriX;
                        pp[j].disordY=pp[no].oriY;
                        pp[no].flag=1;
                      //  pp[j].setEnabled(true);
                    }
                    else if(pp[no].flag==1&no>0){
                        pp[j].setLocation(pp[j].disordX,pp[j].disordY);
                    }
                   // System.out.println("鼠标释放");
                }
            });
            mainJPanel.add(pp[i]);
            }
            //ReOrder();
            add(mainJPanel);
       mainJPanel.setBackground(Color.decode("#99CC99"));

        }
        private class GamePanel extends JPanel{
        private GamePanel(){
            this.setLayout(null);
            this.setBounds(initx, inity,800,750);
        }
    }

    private void CheckResult(){
        int result=1;
        for(int n=0;n<pp.length;n++){
            if(pp[n].getX()==pp[n].oriX&&pp[n].getY()==pp[n].oriY) {result*=1;pp[n].setEnabled(true);}
            else result*=0;
        }
        if(result==1) {
            JOptionPane.showMessageDialog(GameView.this, "同九年,汝何秀!");
        }
        if(result==0) JOptionPane.showMessageDialog(GameView.this, "emmm..没点亮的就是拼错了");
    }
    private int IsR(int a,int b,int xdis,int ydis){
        int difx=pp[a].getX()-pp[b].getX();
        int dify=pp[a].getY()-pp[b].getY();
        if(difx<=xdis&dify<=ydis)
            return 1;
        else return 0;
    }

    //图片切割算法改自百度文库
    public static void cut(String srcImageFile, String descDir, int cols,int rows) {
        try {
            Image img;
            ImageFilter cropFilter;
            // 读取源图像
            BufferedImage bi = ImageIO.read(new File(srcImageFile));
            int srcWidth = bi.getHeight(); // 源图宽度
            int srcHeight = bi.getWidth(); // 源图高度
            int destWidth=srcWidth/cols;
            int destHeight=srcHeight/rows;
            if (srcWidth > destWidth && srcHeight > destHeight) {
                Image image = bi.getScaledInstance(srcWidth, srcHeight,
                        Image.SCALE_DEFAULT);
                // 循环建立切片
                // 改进的想法:是否可用多线程加快切割速度
                for (int i = 0; i < rows; i++) {
                    for (int j = 0; j < cols; j++) {
                        // 四个参数分别为图像起点坐标和宽高
                        // 即: CropImageFilter(int x,int y,int width,int height)
                        cropFilter = new CropImageFilter(j * destWidth, i * destHeight,
                                destWidth, destHeight);
                        img = Toolkit.getDefaultToolkit().createImage(
                                new FilteredImageSource(image.getSource(),
                                        cropFilter));
                        BufferedImage tag = new BufferedImage(destWidth,
                                destHeight, BufferedImage.TYPE_INT_RGB);
                        Graphics g = tag.getGraphics();
                        g.drawImage(img, 0, 0, null); // 绘制缩小后的图
                        g.dispose();
                        // 输出为文件
                        ImageIO.write(tag, "JPEG", new File(descDir
                                + "pre_map_" + i + "_" + j + ".jpg"));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public class PazzlePieces extends JButton {//拼图按钮类
            public int oriX, oriY;
            public int disordX, disordY;
            public int flag;
            private PazzlePieces() {
                //  this.setSize(ImgW,ImgH);
                this.setVisible(true);
                this.setBorderPainted(false);
                this.flag=0;
                oriX=0;
                oriY=0;
            }
            private void initsite(){
                oriX=this.getX();
                oriY=this.getY();
                this.setEnabled(true);
            }
            public void resetsite(int newx,int newy){
                this.setLocation(newx,newy);
                this.flag=0;
                this.setEnabled(true);
            }
            public double caldis(int x,int y){
                int xx=this.getX()-x;
                int yy=this.getY()-y;
                return sqrt(xx*xx+yy*yy);
            }
            public void ReOrder(int k){
                Random random=new Random();
                    int w=width;
                    int h=height;
                    if(k!=0) {
                        disordX = (k % 4+1) * random.nextInt(80) + (k%3+3)*80;
                        disordY = (k % 4+1) * random.nextInt(80) + (k%3+3)*80;
                        pp[k].setLocation(new Point(disordX, disordY));
                    }
                    pp[k].setEnabled(false);
            }
        }

    public static void main(String[] args){

        try {
           UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");//Nimbus风格,jdk6 update10版本以后的才会出现
            //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());//当前系统风格
            GameView mypazzle=new GameView();
            mypazzle.setTitle("有本事你拼拼看啊");
           mypazzle.setVisible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

得赶作业,先贴代码

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
import java.awt.*; import java.applet.*; import java.awt.event.*; public class PPuzzle extends Applet{ Image imgPuzzle,buff; Point fifteen=new Point(3,3); int[][] map={{0,4,8,12},{1,5,9,13},{2,6,10,14},{3,7,11,15}}; int sx,sy; Canvas screen; Graphics gs,gb; boolean running=false; Button bStart= new Button("新游戏"); Button bSee=new Button("显示正确图像"); public void init(){ prepareImage(); sx=imgPuzzle.getWidth(this)/4; sy=imgPuzzle.getHeight(this)/4; setBackground(Color.blue); initScreen(); initButtons(); add(screen); add(bStart); add(bSee); } void prepareImage(){ imgPuzzle=getImage(getCodeBase(),"images/3.jpg");// MediaTracker mt=new MediaTracker(this); mt.addImage(imgPuzzle, 0); try{ mt.waitForAll(); }catch(Exception e){} //创建buffer并获取graphics对象 buff=createImage(imgPuzzle.getWidth(this),imgPuzzle.getHeight(this)); gb=buff.getGraphics(); } void initMap(){ java.util.Random rnd=new java.util.Random(); int temp,x1,x2,y1,y2; for(int i=0;i<100;i++){ x1=rnd.nextInt(4); x2=rnd.nextInt(4); y1=rnd.nextInt(4); y2=rnd.nextInt(4); temp=map[x1][y1]; map[x1][y1]=map[x2][y2]; map[x2][y2]=temp; } outer:for(int j=0;j<4;j++) for(int i=0;i<4;i++) if(map[i][j]==15){ fifteen.setLocation(i,j); break outer; } } void initScreen(){ screen=new Canvas(){ public void paint(Graphics g){ if(gs==null) gs=getGraphics(); if(running) drawScreen(); else g.drawImage(imgPuzzle,0,0,this); } }; screen.setSize(imgPuzzle.getWidth(this), imgPuzzle.getHeight(this)); screen.addMouseListener(new MouseAdapter(){ public void mousePressed(MouseEvent me){ if(!running)return; int x=me.getX()/sx,y=me.getY()/sy; int fx=(int)fifteen.getX(),fy=(int)fifteen.getY(); if (Math.abs(fx-x)+Math.abs(fy-y)>=2)return; map[fx][fy]=map[x][y]; map[x][y]=15; fifteen.setLocation(x,y); drawScreen(); } }); } void initButtons(){ //新游戏 按钮事件的处理 bStart.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ initMap(); drawScreen(); running=true; bSee.setLabel("显示正确图像"); } }); //显示正确图像 按钮事件处理 bSee.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ //bsee 按钮标题为”继续游戏“ if(bSee.getLabel().equals("继续游戏")){ drawScreen(); bSee.setLabel("继续游戏"); } else{ //bsee的标题显示为”显示正确图像“ gs.drawImage(imgPuzzle,0,0,screen); bSee.setLabel("继续游戏"); } } }); } void drawScreen(){ gb.clearRect(0, 0, sx*4, sy*4); //将指定位置的图像块绘制到Buffer中 for(int j=0;j<4;j++) for(int i=0;i<4;i++) if(map[i][j]!=15) drawSegment(map[i][j],i,j); //向Screen绘制buffer中的图像 gs.drawImage(buff,0,0,screen); } void drawSegment(int seg,int x,int y){ int dx=seg%4*sx,dy=seg/4*sy; //可能有错误 gb.drawImage(imgPuzzle, x*sx,y*sy ,x*sx+sx-1 ,y*sy+sy-1 , dx , dy,dx+sx-1,dy+sy-1 ,screen ); } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值