拼图游戏源代码

合集下载

拼图游戏源代码

拼图游戏源代码

//*关卡开始前 booleanfirstStart=true;//是否首次运行标志 musicNum=1;//音乐不够,以此变量做两首歌更换标志 privatevoiddoStartPa ...{ //*关卡化 lm=LayerManager; puzzlePic=creatPuzzlePic; //*测试用 //puzzlePic=creatTestPuzzlePic;//测试用 lm.append(puzzlePic);
//播放声音 //西门子模拟器不支持下面这段代码,但实体机子完美支持 try ...{ InputStreamin; //in=getClass.getResourceAsStream(\"/res/music\"+stageNum+\".mid\");这是有5首音乐时候使用 //只有两首歌时候使用 (musicNum1) ...{ in=getClass.getResourceAsStream(\"/res/music1.mid\"); [Page] musicNum=2; } ...{ in=getClass.getResourceAsStream(\"/res/music2.mid\"); musicNum=1; } player=Manager.createPlayer(in,\"audio/midi\"); player.LoopCount(10); player.start; } catch(IOExceptione)...{}
/***//**储存损耗时间,普通模式用到*/ privatelongusedTime; [Page] /***//**储存单关通过最短时间*/ privatelongquicklyPassOneStageTime; /***//**游戏过程暂停状态所用标志*/ privatebooleanisGamePaused; /***//**储存显示对象*/ privateDisplaydisplay;

12.JavaScript实现拼图游戏源码

12.JavaScript实现拼图游戏源码

12.JavaScript实现拼图游戏源码⽬前代码没有放到GitHub上,之后会放出链接1.⽬录结构:2.index.html⽂件:<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title></head><body><div class="clearfix"><!-- 拼图游戏 --><div style="float:left;" class="picture-puzzle"></div><!-- 对⽐图⽚ --><div style="float:right;"><img src="./image/dog.jpg" alt=""></div></div><script src="./js/index.js"></script></body></html>index.html3.index.js⽂件:// 游戏参数var gameConfig = {width: 589, //整张图⽚的宽度height: 416, //整张图⽚的⾼度row: 3, //⼩⽅块的⾏数cols: 3, //⼩⽅块的列数imageurl: "./image/dog.jpg", //图⽚的路径dom: document.getElementsByClassName("picture-puzzle")[0], //游戏容器的domisOver: false, //游戏是否结束minStep: 30,//打乱拼图的最⼩步数maxStep: 100//打乱拼图的最⼤步数// isHaveSolution: false //游戏是否有解}gameConfig.pieceWidth = gameConfig.width / gameConfig.row; //每个⼩块的宽度gameConfig.pieceHeight = gameConfig.height / gameConfig.cols; //每个⼩块的⾼度var blocks = []; //存储每个⼩块的信息//⼩⽅块构造函数function Block(row, cols) {// this.sequenceNumber; //⽅块的编号从1到(row*cols)-1;空⽩格编号为0this.width = gameConfig.pieceWidth; //宽this.height = gameConfig.pieceHeight; //⾼this.correctRow = row; //⼩⽅块所在正确的⾏数,⽤来判断⽅块⾏数是否正确this.correctCols = cols; //⼩⽅块所在正确的列数,⽤来判断⽅块列数是否正确this.row = row; //⼩⽅块当前所在⾏数this.cols = cols; //⼩⽅块当前所在列数this.isDisplay = false; //是否是空⽩块:true.是;false:否;this.div = document.createElement("div");this.div.style.width = gameConfig.pieceWidth + "px";this.div.style.height = gameConfig.pieceHeight + "px";this.div.style.background = `url("${gameConfig.imageurl}") -${this.correctCols * this.width}px -${this.correctRow * this.height}px`;this.div.style.border = "1px solid #fff";this.div.style['box-sizing'] = "border-box";this.div.style.position = "absolute";this.show = function () { //展⽰⼩⽅块显⽰的位置this.div.style.left = this.cols * gameConfig.pieceWidth + "px";this.div.style.top = this.row * gameConfig.pieceHeight + "px";}this.show();if (row === gameConfig.row - 1 && cols === gameConfig.cols - 1) { //最后⼀⽅块隐藏this.div.style.display = "none";this.isDisplay = true; //是否是空⽩块:true.是;false:否;}gameConfig.dom.appendChild(this.div);this.isCorrect = function () { //判断⽅块当前位置的⾏列是否等于正确位置的⾏列if (this.row === this.correctRow && this.cols === this.correctCols) {return true;}return false;}}//初始化游戏function init() {//1.初始化游戏容器宽度initGameDom();//2.初始化每个⼩⽅块基本信息initBlocksArray();//3.乱序拼图可解的算法没有看懂,只能程序⾃动⾛100步// while (!gameConfig.isHaveSolution) {randomSort();// }//4.注册点击事件registerEvent();//初始化游戏容器function initGameDom() {gameConfig.dom.style.width = gameConfig.width + "px";gameConfig.dom.style.height = gameConfig.height + "px";gameConfig.dom.style.border = "2px solid #ccc";gameConfig.dom.style.position = "relative";}//初始化⼩⽅块数组信息function initBlocksArray() {for (var i = 0; i < gameConfig.row; i++) {for (var j = 0; j < gameConfig.cols; j++) {// 每个⼩块的基本信息var block = new Block(i, j);blocks.push(block);}}// blocks.forEach(function (item, index) {// item.sequenceNumber = index + 1;// });// blocks[gameConfig.row * gameConfig.cols - 1].sequenceNumber = 0; //最后⼀个空⽩块编号为0}//把⼩⽅块打乱顺序function randomSort() {var step = getRandom(gameConfig.minStep, gameConfig.maxStep);//随机在[30,100)区间⾥取出⼀个数,作为打乱拼图的步数 console.log(step);//程序⾃⾛step步,将拼图顺序打乱for (var i = 0; i < step; i++) {// 找到空⽩块所在的⾏和列var blankBlock = blocks.filter(function (item) {return item.isDisplay;});for (var j = 0; j < blocks.length; j++) {//判断是否可以交换,横坐标相同则纵坐标相差1||纵坐标相同则横坐标相差为1if (blocks[j].row === blankBlock[0].row && Math.abs(blocks[j].cols - blankBlock[0].cols) === 1 ||blocks[j].cols === blankBlock[0].cols && Math.abs(blocks[j].row - blankBlock[0].row) === 1) {exchangeBlocks(blocks[j], blankBlock[0]);continue; //交换⼀次后进⼊下个循环,保障交换次数为step次}}}// for (var i = 0; i < (gameConfig.row * gameConfig.cols - 1); i++) {// //1.产⽣⼀个随机数// //2.将当前⼩⽅块信息和随机选中的⼩⽅块信息互换,最后⼀个空⽩块位置不变// var index = getRandom(0, blocks.length - 2);// //交换数据// exchangeBlocks(blocks[i], blocks[index]);// }blocks.forEach(function (item) {item.show();});//判断拼图是否有解// haveSolution();}//判断乱序的拼图是否有解// function haveSolution() {// var count = 0;// //计算逆序列个数,逆序数:前⾯的编号⼤于后⾯的编号的个数// for (var i = 0; i < blocks.length; i++) {// for (var j = i + 1; j < (blocks.length - 1 - i); j++) {// console.log(i, j, blocks[i].sequenceNumber);// if (blocks[i].sequenceNumber > blocks[j].sequenceNumber) {// count++;// }// }// }// console.log(count);// //计算空⽩块编号为0所在的位置// var blankBlock = gameConfig.row * gameConfig.cols - 1;// //奇偶性不同则⽆解// gameConfig.isHaveSolution = (count % 2 != blankBlock % 2) ? false : true;// console.log(gameConfig.isHaveSolution);// }//为⽅块注册事件function registerEvent() {//找到空⽩块var isDisplayBlock = blocks.find(function (item) {return item.isDisplay;});blocks.forEach(function (item) {item.div.onclick = function () {if (gameConfig.isOver) { //游戏结束,则不在继续以下操作return;}//判断是否可以交换,横坐标相同则纵坐标相差1||纵坐标相同则横坐标相差为1if (item.row === isDisplayBlock.row && Math.abs(item.cols - isDisplayBlock.cols) === 1 ||item.cols === isDisplayBlock.cols && Math.abs(item.row - isDisplayBlock.row) === 1) {exchangeBlocks(item, isDisplayBlock);}//游戏结束isWin();}});}//交换两个⽅块的位置function exchangeBlocks(b1, b2) {var temp = b1.row;b1.row = b2.row;b2.row = temp;var temp = b1.cols;b1.cols = b2.cols;b2.cols = temp;// var temp = b1.sequenceNumber;// b1.sequenceNumber = b2.sequenceNumber;// b2.sequenceNumber = temp;b1.show();b2.show();}//游戏结束function isWin() {var wrongBlocks = blocks.filter(function (item) { //筛选出位置错误的⽅块return !item.isCorrect();});if (wrongBlocks.length === 0) { //所有⽅块都在正确位置gameConfig.isOver = true; //游戏结束blocks.forEach(function (item) {item.div.style.display = "block";item.div.style.border = "none";});}}//-------------通⽤函数----begin-----------////返回⼀个[min,max)区间的随机数function getRandom(min, max) {return Math.floor(Math.random() * (max - min)) + min;}//-------------通⽤函数----end-----------//}init();index.js代码中都有简单注释,有什么问题请在评论中提出,这⾥只讲解拼图初始化时打乱拼图顺序所⽤的⽅法。

Java语言实现拼图游戏源代码

Java语言实现拼图游戏源代码

Java语言实现拼图游戏源代码/** JA V A小游戏-拼图我做的第一个小游戏* Cell类是继承的按钮类,并加上相应图形,形成方格*MyCanvas是一个面板,加载Cell类的对象(方格),是这三个类中的核心*/import java.awt.Rectangle;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import javax.swing.Icon;import javax.swing.ImageIcon;import javax.swing.JOptionPane;import javax.swing.JPanel;import java.awt.BorderLayout;import java.awt.Button;import java.awt.Choice;import java.awt.Color;import java.awt.Container;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.Icon;import javax.swing.ImageIcon;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.Icon;import javax.swing.JButton;public class MyMainFrame extends JFrame implements ActionListener { MyCanvas myCanvas;JPanel panelNorth,panelPreview;//定义上方的面板,及预览所需的面板Button start,preview,set;//定义开始,预览,设定按钮Container container;//容器,得到内容面板public MyMainFrame() {//初使化container=this.getContentPane();start=new Button("开始");start.addActionListener(this);preview=new Button("预览");preview.addActionListener(this);set = new Button("设置");set.addActionListener(this);panelPreview=new JPanel();panelPreview.setLayout(null);Icon icon=new ImageIcon("pic_"+MyCanvas.pictureID+".jpg");JLabel label=new JLabel(icon);label.setBounds(0,0,300,300);panelPreview.add(label);panelNorth=new JPanel();panelNorth.setBackground(Color.red);panelNorth.add(start);panelNorth.add(preview);panelNorth.add(set);myCanvas=new MyCanvas();container.add(myCanvas,BorderLayout.CENTER);container.add(panelNorth,BorderLayout.NORTH);this.setTitle("拼图小游戏-明");this.setLocation(300,200);this.setSize(308,365);this.setResizable(false);this.setVisible(true);this.setDefaultCloseOperation(3);}public static void main(String[] args) {// TODO 自动生成方法存根new MyMainFrame();}public void actionPerformed(ActionEvent arg0) {//对三个按钮事件的处理// TODO 自动生成方法存根Button button=(Button)arg0.getSource();if(button==start){myCanvas.Start();}else if(button==preview){if(button.getLabel()=="预览"){container.remove(myCanvas);container.add(panelPreview);panelPreview.updateUI();container.repaint();button.setLabel("返回");}else{container.remove(panelPreview);container.add(myCanvas);container.repaint();button.setLabel("预览");}}else if(button==set){//修改所选图片Choice pic = new Choice();pic.add("小猫");pic.add("小猪");pic.add("云");pic.add("QQ");pic.add("卡通");pic.add("花");int i=JOptionPane.showConfirmDialog(this, pic, "选择图片", JOptionPane.OK_CANCEL_OPTION);if(i==JOptionPane.YES_OPTION){MyCanvas.pictureID=pic.getSelectedIndex()+1;myCanvas.reLoadPictrue();Icon icon=new ImageIcon("pic_"+MyCanvas.pictureID+".jpg");JLabel label=new JLabel(icon);label.setBounds(0,0,300,300);panelPreview.removeAll();panelPreview.add(label);panelPreview.repaint();}}}}class MyCanvas extends JPanel implements MouseListener {boolean hasAddActionListener=false;//设置方格的动作监听器的标志位,TRUE为已经添加上动作事件,FALSE是尚未添加动作事件Cell cell[];//定义方格Rectangle cellNull;//定义空方格区域public static int pictureID=1;//当前选择的图片代号public MyCanvas() {this.setLayout(null);this.setSize(400,400);cellNull=new Rectangle(200,200,100,100);//空方格区域在第三行每三列cell=new Cell[9];Icon icon;for (int i = 0; i < 3; i++) {//为9个方格加载图片,并初使化坐标,形成三行三列for(int j=0;j<3;j++){icon=new ImageIcon("pic_"+pictureID+"_"+(i*3+j+1)+".jpg");cell[i*3+j]=new Cell(icon);cell[i*3+j].setLocation(j*100,i*100);this.add(cell[i*3+j]);}}this.remove(cell[8]);//移除最后一个多余的方格}文章转自上海青大实训:。

拼图游戏源代码

拼图游戏源代码

import java.awt.BorderLayout;import java.awt.CardLayout;import java.awt.Font;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.util.ArrayList;import java.util.Collections;import java.util.List;import javax.swing.Icon;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JOptionPane;import javax.swing.JPanel;@SuppressWarnings("serial")public class NumberGame extends JFrame implements ActionListener{ String path="LookingGirl/";int i=3;//定义一个卡片布局CardLayout card = new CardLayout();JMenuBar bar = new JMenuBar();JMenu menu=new JMenu("功能");JMenuItem jmi_start= new JMenuItem("开始游戏");JMenuItem jmi_viewImage= new JMenuItem("查看原图3");JMenuItem jmi_returnGame= new JMenuItem("返回游戏");JMenuItem jmi_exit = new JMenuItem("退出");//定义两个面板,一个用来显示原图,一个用来显示游戏区JPanel jp_game = new JPanel();JPanel jp_image = new JPanel();JLabel jl_image = new JLabel(new ImageIcon(path+"pic.jpg"));//定义一个二维数组,用来存储16个按钮JButton[][] number = new JButton[4][4];List<JButton> list = new ArrayList<JButton>();private void initMenu(){this.setJMenuBar(bar);bar.add(menu);menu.add(jmi_start);menu.add(jmi_viewImage);menu.add(jmi_returnGame);menu.addSeparator();menu.add(jmi_exit);MenuListener li = new MenuListener();jmi_start.addActionListener(li);jmi_viewImage.addActionListener(li);jmi_returnGame.addActionListener(li);jmi_exit.addActionListener(li);}//初使化图像区public void initImage(){jp_image.setLayout(new BorderLayout());jp_image.add(jl_image);}//初使化按钮数组,并将按钮放到面板中public void initGame(){//将面板的布局改成gridjp_game.setLayout(new GridLayout(4,4));for(int i=1;i<16;i++){JButton jb= new JButton();jb.setIcon(new ImageIcon(path+Integer.toString(i-1)+".jpg"));jb.setName(Integer.toString(i)); //给每个按钮起一个名字来区分list.add(jb);}//打乱顺序Collections.shuffle(list);JButton jb = new JButton();jb.setName("16");jb.setIcon(new ImageIcon(path+"15.jpg"));jb.setVisible(false);list.add(jb);for(int i=0;i<list.size();i++){number[i/4][i%4] = list.get(i);//为每个按钮加上监听number[i/4][i%4].addActionListener(this);number[i/4][i%4].setFont(new Font("宋体",Font.BOLD,24));jp_game.add(number[i/4][i%4]);}}//构造方法public NumberGame(){this.setBounds(100, 100, 400, 460);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置布局管理器this.setLayout(card);initMenu();initGame();initImage();this.add(jp_image,"image");this.add(jp_game,"game");//显示this.setVisible(true);}//交换两个按钮private void change(JButton a,JButton b){Icon str= a.getIcon();a.setIcon(b.getIcon());b.setIcon(str);String name = a.getName();a.setName(b.getName());b.setName(name);a.setVisible(!a.isVisible());b.setVisible(!b.isVisible());}//判断是否成功private void success(){boolean flag=true;for(int i=0;i<16;i++){if(!number[i/4][i%4].getName().equals(Integer.toString(i+1))){ System.out.println(i);flag=false;break;}}if(flag){//成功了number[3][3].setVisible(true);JOptionPane.showMessageDialog(this, "恭喜你,成功了","成功",JOptionPane.OK_OPTION,new ImageIcon("success.png"));}}@Overridepublic void actionPerformed(ActionEvent e) {JButton n=(JButton)e.getSource();//判断当前点击的是哪个按钮for(int i=0;i<4;i++){for(int j=0;j<4;j++){if(n==number[i][j]){//上if(i>0 && !number[i-1][j].isVisible()){change(n,number[i-1][j]);}else if(i<3 && !number[i+1][j].isVisible()){//下change(n,number[i+1][j]);}else if(j>0 && !number[i][j-1].isVisible()){//左change(n,number[i][j-1]);}else if(j<3 && !number[i][j+1].isVisible()){//右change(n,number[i][j+1]);}success();}}}}class MenuListener implements ActionListener{@Overridepublic void actionPerformed(ActionEvent e) {if(e.getSource()==jmi_start){//开始游戏card.show(NumberGame.this.getContentPane(), "game");}else if(e.getSource()==jmi_viewImage){i--;jmi_viewImage.setText("查看原图"+i);card.show(NumberGame.this.getContentPane(), "image");if(i<1){jmi_viewImage.setEnabled(false);}}else if(e.getSource()==jmi_returnGame){card.show(NumberGame.this.getContentPane(), "game");}else{int i=JOptionPane.showConfirmDialog(NumberGame.this, "你真的要退出吗?","提示",JOptionPane.OK_CANCEL_OPTION);if(i==JOptionPane.YES_OPTION){System.exit(0);}}}}public static void main(String[] args) {new NumberGame();}}。

java语言实现拼图游戏源代码

java语言实现拼图游戏源代码

java语言实现拼图游戏源代码Java语言实现拼图游戏源代码 /** JAVA小游戏,拼图我做的第一个小游戏* Cell类是继承的按钮类,并加上相应图形,形成方格*MyCanvas是一个面板,加载Cell类的对象(方格),是这三个类中的核心 */ import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.awt.event.MouseListener;import javax.swing.Icon;import javax.swing.ImageIcon; import javax.swing.JOptionPane; import javax.swing.JPanel; import java.awt.BorderLayout; import java.awt.Button;import java.awt.Choice;import java.awt.Color;import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener;import javax.swing.Icon;import javax.swing.ImageIcon; import javax.swing.JFrame; importjavax.swing.JLabel; import javax.swing.JOptionPane; importjavax.swing.JPanel; import javax.swing.Icon;import javax.swing.JButton;public class MyMainFrame extends JFrame implements ActionListener { MyCanvas myCanvas;JPanel panelNorth,panelPreview;//定义上方的面板,及预览所需的面板Button start,preview,set;//定义开始,预览,设定按钮Container container;//容器,得到内容面板public MyMainFrame() {//初使化container=this.getContentPane(); start=new Button("开始");start.addActionListener(this); preview=new Button("预览");preview.addActionListener(this); set = new Button("设置");set.addActionListener(this); panelPreview=new JPanel();panelPreview.setLayout(null); Icon icon=newImageIcon("pic_"+MyCanvas.pictureID+".jpg");JLabel label=new JLabel(icon); label.setBounds(0,0,300,300); panelPreview.add(label);panelNorth=new JPanel();panelNorth.setBackground(Color.red); panelNorth.add(start);panelNorth.add(preview);panelNorth.add(set);myCanvas=new MyCanvas();container.add(myCanvas,BorderLayout.CENTER);container.add(panelNorth,BorderLayout.NORTH);this.setTitle("拼图小游戏-明");this.setLocation(300,200);this.setSize(308,365);this.setResizable(false);this.setVisible(true);this.setDefaultCloseOperation(3); }public static void main(String[] args) {// TODO 自动生成方法存根new MyMainFrame();}public void actionPerformed(ActionEvent arg0) {//对三个按钮事件的处理 // TODO 自动生成方法存根Button button=(Button)arg0.getSource(); if(button==start){myCanvas.Start();}else if(button==preview){if(button.getLabel()=="预览"){container.remove(myCanvas); container.add(panelPreview); panelPreview.updateUI();container.repaint();button.setLabel("返回");}else{container.remove(panelPreview); container.add(myCanvas); container.repaint();button.setLabel("预览");}}else if(button==set){//修改所选图片Choice pic = new Choice(); pic.add("小猫");pic.add("小猪");pic.add("云");pic.add("QQ");pic.add("卡通");pic.add("花");int i=JOptionPane.showConfirmDialog(this, pic, "选择图片",JOptionPane.OK_CANCEL_OPTION);if(i==JOptionPane.YES_OPTION){ MyCanvas.pictureID=pic.getSelectedIndex() +1;myCanvas.reLoadPictrue(); Icon icon=newImageIcon("pic_"+MyCanvas.pictureID+".jpg");JLabel label=new JLabel(icon); label.setBounds(0,0,300,300); panelPreview.removeAll(); panelPreview.add(label);panelPreview.repaint();}}}}class MyCanvas extends JPanel implements MouseListener {boolean hasAddActionListener=false;//设置方格的动作监听器的标志位,TRUE为已经添加上动作事件,FALSE是尚未添加动作事件Cell cell[];//定义方格Rectangle cellNull;//定义空方格区域public static int pictureID=1;//当前选择的图片代号public MyCanvas() {this.setLayout(null);this.setSize(400,400);cellNull=new Rectangle(200,200,100,100);//空方格区域在第三行每三列cell=new Cell[9];Icon icon;for (int i = 0; i < 3; i++) {//为9个方格加载图片,并初使化坐标,形成三行三列 for(int j=0;j<3;j++){icon=new ImageIcon("pic_"+pictureID+"_"+(i*3+j+1)+".jpg");cell[i*3+j]=new Cell(icon); cell[i*3+j].setLocation(j*100,i*100); this.add(cell[i*3+j]);}}this.remove(cell[8]);//移除最后一个多余的方格}文章转自上海青大实训:谣言:吃太咸了会得病,导语:“人体每日摄入食盐不应过多,否则易患多种疾病。

C语言实现拼图游戏源码

C语言实现拼图游戏源码

C语⾔实现拼图游戏源码本⽂实例为⼤家分享了C语⾔实现拼图游戏的具体代码,供⼤家参考,具体内容如下#include<stdio.h>#include<stdlib.h>#include<time.h>#include<conio.h>int step=0;void map()//游戏菜单函数。

{ printf("▇▇▇▇▇▇▇▇▇▇▇▇▇▇\n");printf("█拼图游戏█\n");printf("█ 1. 3×3 █\n");printf("█ 2. 4×4 █\n");printf("█ 3. 5×5 █\n");printf("█ 4. 退出█\n");printf("▇▇▇▇▇▇▇▇▇▇▇▇▇▇\n");}void fun(int *a,int t,int m,int r){int i;int g;for(i=0;i<m;i++){if(i%r==(r-1)&&(i+t)%r==0)//让数组不能跨⾏转换。

continue;if(i%r==0&&(i+t)%r==(r-1))continue;if(a[i+t]==0 && (i+t)>=0 && (i+t)<m){g=a[i];a[i]=a[i+t];a[i+t]=g;step++;return ;}}}void move(int *a,int m,int r){//上下左右移动函数。

char ch;int i,j;while(ch=getch()){system("cls");if(ch=='w'){i=-r;fun(a,i,m,r);}else if(ch=='s'){i=r;fun(a,i,m,r);}else if(ch=='a'){i=-1;{i=1;fun(a,i,m,r);}else if(ch=='4'){printf("您已退出游戏,请下次再玩!\n");exit(0);}for(i=0;i<m;i++){if(a[i]==0)printf(" ");elseprintf("%2d ",a[i]);if((i+1)%r==0)putchar(10);}printf("共⾛:%d步!\n",step);}}void map_x(int m,int r){int i=1,j,a[25],n;srand(time(NULL));printf("拼图游戏开始了:\n");while(i<m){n=1+rand()%(m-1);for(j=1;j<i;j++){if(n==a[j])break;}if(j==i){a[i]=n;i++;}}a[0]=0;for(i=0;i<m;i++){if(a[i]==0)printf(" ");elseprintf("%2d ",a[i]);if((i+1)%r==0)putchar(10);}printf("共⾛:%d步!\n",step);move(a,m,r);}int main(){int i,n;char ch;map();//显⽰菜单。

拼图源代码

拼图源代码

头文件#include "windows.h"#include "stdio.h"#include <mmsystem.h>#pragma comment(lib,"winmm.lib")//全局变量声明HINSTANCE hInst;HBITMAP hbmp;HDC mdc, hdc;HWND hWnd;DWORD tPre,tNow;inti,j,count=0,flg=1;HINSTANCE hInstance; intnCmdShow;//全局函数的声明ATOM MyRegisterClass(HINSTANCE hInstance);BOOL InitInstance(HINSTANCE, int);LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);voidMyPaint();voidPlayGame(WPARAM );void Win();//****﹚设计一个窗口类,类似填空题,使用窗口结构体************************* ATOM MyRegisterClass(HINSTANCE hInstance){WNDCLASSEX wcex;wcex.cbSize = sizeof(WNDCLASSEX);wcex.style= CS_HREDRAW | CS_VREDRAW;wcex.lpfnWndProc= (WNDPROC)WndProc;wcex.cbClsExtra= 0;wcex.cbWndExtra= 0;wcex.hInstance= hInstance;wcex.hIcon= NULL;wcex.hCursor= NULL;wcex.hCursor= LoadCursor(NULL, IDC_ARROW);wcex.hbrBackground= (HBRUSH)GetStockObject(WHITE_BRUSH);wcex.lpszMenuName= NULL;wcex.lpszClassName= "canvas";wcex.hIconSm= NULL;returnRegisterClassEx(&wcex);}//****初始化函数*************************************// 1.建立与窗口DC兼容的内存DC// 2.从文件加载位图并存至内存DC中BOOL InitInstance(HINSTANCE hInstance, intnCmdShow){hInst = hInstance;hWnd = CreateWindow("canvas", "ytu.小翅膀之拼图" , WS_OVERLAPPEDWINDOW&~WS_THICKFRAME&~WS_MAXIMIZEBOX,0, 0, 600, 450, NULL, NULL, hInstance, NULL);if (!hWnd){return FALSE;}MoveWindow(hWnd,10,100,1000,500,true);ShowWindow(hWnd, nCmdShow);UpdateWindow(hWnd);PlaySound("sound.wav",NULL,SND_ASYNC|SND_LOOP);MyPaint();ReleaseDC(hWnd,hdc);return TRUE;}源文件#include "header.h"int a[4][4]={{1,4},{2,3}};int b[4][4]={{2,5,3},{4,8,6},{7,1,9}};int c[4][4]={{2,3,7,4},{5,6,11,8},{9,10,15,12},{13,14,1,16}};int d[4][4]={{1,4},{2,3}};//****Winmain函数,程序入口点函数**************************************int APIENTRY WinMain(HINSTANCE hInstance,HINSTANCEhPrevInstance,LPSTRlpCmdLine,intnCmdShow){MSG msg;MyRegisterClass(hInstance);if (!InitInstance (hInstance, nCmdShow)){return FALSE;}//消息循环while (GetMessage(&msg, NULL, 0, 0)){TranslateMessage(&msg);DispatchMessage(&msg);}returnmsg.wParam;}//****自定义绘图函数*********************************voidMyPaint(){hdc = GetDC(hWnd);mdc = CreateCompatibleDC(hdc);intnum=(flg+1);int w=600/num,h=450/num;for(i=0;i<=flg;i++){for(j=0;j<=flg;j++){char picName[10];if(flg==1)sprintf(picName,"1/%d.bmp",a[i][j]);else if(flg==2)sprintf(picName,"2/%d.bmp",a[i][j]);else if(flg==3)sprintf(picName,"3/%d.bmp",a[i][j]);hbmp=(HBITMAP)LoadImage(NULL,picName,IMAGE_BITMAP,w,h,LR_LOADFROMFILE);SelectObject(mdc,hbmp);//采用BitBlt函数贴图BitBlt(hdc,w*j,h*i,w,h,mdc,0,0,SRCCOPY);}}char step[30]; //定义一个字符型数组,用来存放以下字符串sprintf(step,"您已经走了<%d>步",count); SetTextColor(hdc,0x000FFF);//字体的颜色TextOut(hdc,600,0, step,(int)strlen(step));sprintf(step,"组长:xx"); SetTextColor(hdc,0xFF000F);//字体的颜色TextOut(hdc,600,20, step,(int)strlen(step));sprintf(step,"组员:xx"); SetTextColor(hdc,0xFF000F);//字体的颜色TextOut(hdc,600,40, step,(int)strlen(step));sprintf(step," xx"); SetTextColor(hdc,0xFF000F);//字体的颜色TextOut(hdc,600,60, step,(int)strlen(step));sprintf(step," xx"); SetTextColor(hdc,0xFF000F);//字体的颜色TextOut(hdc,600,80, step,(int)strlen(step));sprintf(step," xx"); SetTextColor(hdc,0xFF000F);//字体的颜色TextOut(hdc,600,100, step,(int)strlen(step));sprintf(step," xx"); SetTextColor(hdc,0xFF000F);//字体的颜色TextOut(hdc,600,120, step,(int)strlen(step));sprintf(step," xx”); SetTextColor(hdc,0xFF000F);//字体的颜色TextOut(hdc,600,140, step,(int)strlen(step));sprintf(step," xx"); SetTextColor(hdc,0xFF000F);//字体的颜色TextOut(hdc,600,160, step,(int)strlen(step));sprintf(step,"倾力之作!!!!"); SetTextColor(hdc,0xFF000F);//字体的颜色TextOut(hdc,600,180, step,(int)strlen(step));if(flg==1){hbmp=(HBITMAP)LoadImage(NULL,"1/yuantu.bmp",IMAGE_BITMAP,400,250,LR_LOADFRO MFILE);}else if(flg==2)hbmp=(HBITMAP)LoadImage(NULL,"2/yuantu.bmp",IMAGE_BITMAP,400,250,LR_LOADFRO MFILE);else if(flg==3)hbmp=(HBITMAP)LoadImage(NULL,"3/yuantu.bmp",IMAGE_BITMAP,400,250,LR_LOADFRO MFILE);SelectObject(mdc,hbmp);//采用BitBlt函数贴图BitBlt(hdc,600,200,400,300,mdc,0,0,SRCCOPY);}//****消息处理函数**********************************LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {PAINTSTRUCT ps;HDC hdc;switch (message){case WM_KEYDOWN://监听键盘事件(判断你按的是哪个键)PlayGame(wParam);break;//窗口重绘消息case WM_PAINT:hdc = BeginPaint(hWnd, &ps);MyPaint();EndPaint(hWnd, &ps);break;//窗口结束消息case WM_DESTROY:DeleteDC(mdc);DeleteObject(hbmp);PostQuitMessage(0);break;//其他消息default:returnDefWindowProc(hWnd, message, wParam, lParam);}return 0;}voidPlayGame(WPARAM wParam){switch(wParam){int temp;case VK_UP:count++;for(i=0;i<=flg;i++){for(j=0;j<=flg;j++){if(i>0&&a[i][j]==1){temp=a[i-1][j];a[i-1][j]=a[i][j];a[i][j]=temp;MyPaint();Win();}}}break;case VK_DOWN:count++;for(i=0;i<=flg;i++){for(j=0;j<=flg;j++){if(i<flg&&a[i][j]==1){temp=a[i+1][j];a[i+1][j]=a[i][j];a[i][j]=temp;MyPaint();Win();}}}break;case VK_RIGHT:count++;for(i=0;i<=flg;i++){for(j=0;j<=flg;j++){if(j<flg&&a[i][j]==1){temp=a[i][j+1];a[i][j+1]=a[i][j];a[i][j]=temp;MyPaint();Win();}}}break;case VK_LEFT:count++;for(i=0;i<=flg;i++){for(j=0;j<=flg;j++){if(j>0&&a[i][j]==1){temp=a[i][j-1];a[i][j-1]=a[i][j];a[i][j]=temp;MyPaint();Win();}}}break;}}void Win(){int n=0,m=0;for(i=0;i<=flg;i++){for(j=0;j<=flg;j++){n++;if (a[i][j]==n){m++;}}}if(m==n){if(flg>=3){if(IDYES==MessageBox(NULL,"恭喜您,通关了!!!\n是否重玩?","提示",MB_YESNO)){flg=1;for(i=0;i<=flg;i++){for(j=0;j<=flg;j++){a[i][j]=d[i][j];}}count=0;MyPaint();}elsePostQuitMessage(0);}elseif(IDYES==MessageBox(NULL,"你赢了!是否进入下一关?","提示",MB_YESNO)){flg++;if(flg==2){ for(i=0;i<=flg;i++){for(j=0;j<=flg;j++){a[i][j]=b[i][j];}}}else if(flg==3){for(i=0;i<=flg;i++){for(j=0;j<=flg;j++){a[i][j]=c[i][j];}}}count=0;MyPaint();}elsePostQuitMessage(0);}}。

拼图游戏源代码

拼图游戏源代码

Option ExplicitDim imageid(8) As Integer '记录图片排列的顺序的数组Dim position As Integer '被点击的图片位置Dim xposition As Integer '空图片的位置Dim movetimes As Integer '记录移动次数Dim calposition As Integer '用于计算位置Dim started As Boolean '是否开始Dim win As Boolean '是否胜利Dim pic(9) As Picture '存储图像的数组对象Dim pic1 As PicturePrivate Sub Command1_Click()Dim i As IntegerDim temp(8) As IntegerDim chosennumber As IntegerFor i = 0 To 7temp(i) = iNextRandomizeFor i = 7 To 0 Step -1chosennumber = Int(i * Rnd)imageid(7 - i) = temp(chosennumber)temp(chosennumber) = temp(i)NextFor i = 0 To 7Picture1(i).Picture = pic(imageid(i))NextPicture1(9).Picture = pic(8)Picture1(8).Picture = pic(9)xposition = 8started = Truemovetimes = 0End SubPrivate Sub Form_Load()Dim i As IntegerFor i = 0 To 8Set pic(i) = Picture1(i).PictureNextEnd SubPrivate Sub Picture1_Click(Index As Integer)Dim i As IntegerDim response As Integerposition = IndexIf started = False ThenExit SubEnd IfIf (position <> 0) And (position <> 3) And (position <> 6) Thencalposition = position - 1If calposition = xposition ThencvaleEnd IfEnd IfIf (position <> 2) And (position <> 5) And (position <> 9) Thencalposition = position + 1If calposition = xposition ThencvaleEnd IfEnd IfText1.Text = Str(position)If position <= 5 Thencalposition = position + 3Text2.Text = Str(calposition)If calposition = xposition ThencvaleEnd IfEnd IfIf position >= 3 And position <> 9 Thencalposition = position - 3If calposition = xposition ThencvaleEnd IfEnd Ifwin = TrueFor i = 0 To 7If imageid(i) <> i Thenwin = FalseExit ForEnd IfNextIf win = True ThenMsgBox "恭喜恭喜!您很聪明" & "共移动" & vbCrLf & movetimes & "次", vbOKOnly started = FalseEnd IfEnd SubPrivate Sub cvale()Set pic1 = Picture1(position).PicturePicture1(position).Picture = Picture1(calposition).Picture Picture1(calposition).Picture = pic1xposition = positionEnd Sub。

拼图游戏C语言代码

拼图游戏C语言代码

#include<stdio.h>#include<string.h>#include<stdlib.h>#include<time.h>#include<conio.h>int s[20][20],map[20][20];void input(int n){srand(time(0));int i,j,k,a,b,t;for (i=1;i<=n;i++)for (j=1;j<=n;j++){s[i][j]=(i-1)*n+j-1;map[i][j]=s[i][j]+1;}map[n][n]=0;for (i=n;i>0;i--)for (j=n;j>0;j--){a=rand()%i+1;b=rand()%j+1;t=s[a][b];s[a][b]=s[i][j];s[i][j]=t;}}int ins(int n){int i,j;for(i=1;i<=n;i++)for(j=1;j<=n;j++)if(s[i][j]!=map[i][j]) return 0;return 1;}void output(int n){int i,j,k;system("cls");for(i=1;i<=n;i++){for(j=1;j<=n;j++)printf(s[i][j]?"%-3d":" ",s[i][j]);printf(" ");for(j=1;j<=n;j++) printf(map[i][j]?"%-3d":" ",map[i][j]);printf("\n");}}void des(){printf("\t\t本游戏为数字拼图1.1版本,在w,a,s,d基础\n\\t上增加方向键控制数字板移动\n\n\\t界面仍然很简陋,仅有控制台,但已很接近图形界面\n\n\\t其中数字为可移动板,空格为可移动位置\n\n\\t按任意键返回...");if((char)getch()<0) getch();system("cls");}int main(){int x,y,i,j,t,k,key;char ch;begin:printf("\t\t##拼图游戏1.1版本欢迎您的使用##\n\n");printf("请输入指令1:游戏介绍2:开始游戏Esc:退出游戏\n");ch=getch();system("cls");if(ch==' ') return 0;else if(ch=='1') {des();goto begin;}else if(ch=='2')while(1){t=1;printf("请输入拼图大小(3~9) Esc:上一步\n");ch=getch();if(ch==' ') {system("cls");goto begin;}k=ch-'0';if(2<k&&k<10)input(k);else{system("cls");printf("\n输入有误,请重新输入!\n\n");continue;}for(i=1;i<=k;i++)for(j=1;j<=k;j++)if(s[i][j]==0) {x=i;y=j;}output(k);while(1){printf("请输入操作w/↑:上a/←:左s/↓:下d/右:右Esc:重新开始\n");ch=getch();if(ch<0) ch=getch();key=1;switch(ch){case 'w':case 72:case 'W':if(x<k) {s[x][y]=s[x+1][y];x++;key=0;}else t--;break;case 'a':case 75:case 'A':if(y<k) {s[x][y]=s[x][y+1];y++;key=0;}else t--;break;case 's':case 80:case 'S':if(x>1) {s[x][y]=s[x-1][y];x--;key=0;}else t--;break;case 'd':case 77:case 'D':if(y>1) {s[x][y]=s[x][y-1];y--;key=0;}else t--;break;case ' ':system("cls"); goto begin;default :key=1;t--;break;}s[x][y]=0;output(k);if(key) printf("输入有误\n");if(ins(k)){printf("****G O O D !****\n共用%d步\n\n按任意键继续...\n\n",t-1);if((char)getch()<0) getch();system("cls");break;}else printf(" 已用%d步\n",t++);}}else {system("cls"); printf("输入有误请重新输入\n");goto begin;}return 0;}友情提示:范文可能无法思考和涵盖全面,供参考!最好找专业人士起草或审核后使用,感谢您的下载!。

python 拼图游戏代码

python 拼图游戏代码

# -*- coding: utf-8 -*-import simpleguitk as simpleguiimport random# 载入外部图像baymax = simplegui.load_image("/c4x/XJAU/CS101/asset/baymax.jpg")# 定义常量# 画布的尺寸WIDTH = 600HEIGHT = WIDTH + 100# 图像块的边长IMAGE_SIZE = WIDTH / 3# 图像块坐标列表all_coordinates = [[IMAGE_SIZE*0.5, IMAGE_SIZE*0.5], [IMAGE_SIZE*1.5, IMAGE_SIZE*0.5],[IMAGE_SIZE*2.5, IMAGE_SIZE*0.5], [IMAGE_SIZE*0.5, IMAGE_SIZE*1.5],[IMAGE_SIZE*1.5, IMAGE_SIZE*1.5], [IMAGE_SIZE*2.5, IMAGE_SIZE*1.5],[IMAGE_SIZE*0.5, IMAGE_SIZE*2.5], [IMAGE_SIZE*1.5, IMAGE_SIZE*2.5], None] # 棋盘行列数ROWS = 3COLS = 3# 移动步数steps = 0# 保存所有图像块的列表board = [[None, None, None],[None, None, None],[None, None, None]]# 图像块类class Square:def __init__(self, coordinate):self.center = coordinatedef draw(self, canvas, board_pos):canvas.draw_image(baymax, self.center, [IMAGE_SIZE,IMAGE_SIZE],[(board_pos[1]+0.5)*IMAGE_SIZE, (board_pos[0]+0.5)*IMAGE_SIZE], [IMAGE_SIZE, IMAGE_SIZE])# 初始化拼图板def init_board():# 打乱图像块坐标random.shuffle(all_coordinates)# 填充拼图板for i in range(ROWS):for j in range(COLS):idx = i * ROWS + jsquare_center = all_coordinates[idx]if square_center is None:board[i][j] = Noneelse:board[i][j] = Square(square_center)# 重置游戏def play_game():global stepssteps = 0init_board()# 绘制游戏界面各元素def draw(canvas):# 画黑框canvas.draw_polygon([[0, 0], [WIDTH, 0], [WIDTH, WIDTH], [0, WIDTH]], 1, 'Black')# 画目标图像canvas.draw_image(baymax, [WIDTH/2, WIDTH/2], [WIDTH, WIDTH], [50, WIDTH+50], [98, 98]) # 画步数canvas.draw_text("步数:"+str(steps), [400, 680], 22, "White")# 画图像块# 代码写在这里for i in range(ROWS):for j in range(COLS):if board[i][j] is not None:board[i][j].draw(canvas, [i, j])def mouseclick(pos):global steps# 将点击位置换算成拼图板上的坐标r = int(pos[1] // IMAGE_SIZE)c = int(pos[0] // IMAGE_SIZE)if r < 3 and c < 3: # 点击位置在拼图板内才移动图片if board[r][c] is None: # 点到空位置上什么也不移动returnelse:# 依次检查当前图像块的上,下,左,右是否有空位置,如果有就移动当前图像块# 代码写在这里current_square = board[r][c]if r - 1 >= 0 and board[r-1][c] is None: # 判断上面board[r][c] = Noneboard[r-1][c] = current_squaresteps += 1elif c + 1 <= 2 and board[r][c+1] is None: # 判断右面board[r][c] = Noneboard[r][c+1] = current_squaresteps += 1elif r + 1 <= 2 and board[r+1][c] is None: # 判断下面board[r][c] = Noneboard[r+1][c] = current_squaresteps += 1elif c - 1 >= 0 and board[r][c-1] is None: # 判断左面board[r][c] = Noneboard[r][c-1] = current_squaresteps += 1# 创建框架frame = simplegui.create_frame("拼图", WIDTH, HEIGHT)frame.set_canvas_background("Black")frame.set_draw_handler(draw)frame.add_button("重新开始", play_game, 60)# 注册鼠标事件frame.set_mouseclick_handler(mouseclick) # 初始化游戏play_game()# 启动框架frame.start()。

flash拼图代码

flash拼图代码

Flash拼图游戏程序代码var data1=new Array("羞","遮","掩","躲","探","嫩","符","触","鹊","脱","冻","溪","棉","摇","野","解","宜","层","染","叠","翠","淡","爽","壮");var data2=new Array("枯","容","宿","徐","篱","疏","未","追","店","烧","菜","笋","唤","揉","漆","轰","扭","钻","唠","辫","抚","滋","润","冈");var data3=new Array("豪","世","界","芽","喊","呼","玫","瑰","骨","终","瘸","拐","惋","莺","弟","哥","抽","浇","静","躺","谢","渐","微","哦");var data4=new Array("股","缝","罐","塔","杜","鹃","脆","瓦","泉","然","结","锋","叔","曾","泞","窝","迈","荆","棘","瓣","莹","觅","需","冒");var data5=new Array("雷","迷","迹","滴","洒","泥","弱","末","萨","托","铃","簇","随","芬","芳","聊","倾","递","娇","掀","扑","摸","利","夏");//字地赋值//开始时间function kaishishijian(){var oldDate:Date=new Date();oldTime=oldDate.getTime();}kaishishijian();//dengzixiemingfunction dengzixieming(){for(i=1;i<=24;i++){var pymc2:MovieClip=_root["d"+i].attachMovie(("p"+(kk*1000+i)),"pmc1",i);with(pymc2){_x=30;_y=10;}}}dengzixieming();//初始摆凳子function chushi(){m=0;for(i=1;i<=24;i++){m=rand_arry[i-1];_root["d"+i]._x=_root["kz"+m]._x+25;_root["d"+i]._y=_root["kz"+m]._y-40;}}//随机产生数字function suijishu(){i = 0;total = 24;rand_arry = new Array();do {rand_arry[i] = Math.ceil(Math.random()*24);k = true;for (j=0; j<i; j++) {if (rand_arry[i] == rand_arry[j]) {k = false;break;}}if (k) {i++;}} while (i<24);}suijishu();chushi();//人的赋值function fuzi(kk){for(i=1;i<=24;i++){eval(("r"+i)+(".zi"+i)).text=eval(("data"+kk))[i-1];}}fuzi(kk);//标题赋值var my_fmt:TextFormat=new TextFormat();my_fmt.bold=true;my_fmt.font="Arial";my_fmt.size=36;my_fmt.color=000000;this.createTextField("stats_txt",4000,200,50,900,60);stats_txt.setNewTextFormat(my_fmt);stats_txt.selectable=false;//更新记分\判断function gengxin(){var newDate:Date=new Date();myTime=Math.floor((newDate.getTime()-oldTime)/1000);//时间限制if(myTime>=300){_root.gotoAndPlay(4);delete(this.onEnterFrame) ;}panduan=0;weiwangzhi=0;//判断位置是否正确for(i=1;i<=24;i++){if(_root["r"+i]._x==_root["d"+i]._x and _root["r"+i]._y==_root["d"+i]._y){panduan+=1;}}weiwangzhi=weiwangzhi+panduan*10;weiwangzhi=weiwangzhi-Math.floor(myTime/3);//完成并跳出if(panduan==24){if(weiwangzhi>=200){_root.gotoAndPlay(3);delete(this.onEnterFrame) ;}else {_root.gotoAndPlay(4);delete(this.onEnterFrame) ;}}}_root.onEnterFrame=function(){gengxin();if(weiwangzhi<=0){weiwangzhi=0;}stats_txt.text="威望值: "+weiwangzhi+" 用时: "+myTime;}。

拼图游戏代码

拼图游戏代码

拼图游戏代码# include# include# include# include# include# include/* 七种拼块的形状数据 */char fk[7][4][2]={1,1,1,2,1,3,1,4,1,1,1,2,1,3,2,3,2,1,2,2,1,3,2,3,1,1,1,2,2,2,2,3,2,1,2,2,1,3,2,3,1,1,2,1,1,2,2,2,1,1,1,2,1,3,2,2};/* 存放组成拼块的四个小方块X和Y坐标 */ int kx[4],ky[4];/* 桶 */int tong[13][25];/* 等待按键并延时的函数 */char key(int s){clock_t t1,t2;char c;t1=clock();dot2=clock();while (((t2-t1)if (kbhit())c=getch();elsec=0;return c;}/* 显示或清除方块的函数 */ void kuai(int x,int y,int c) {char cc[3];if(c==1)strcpy(cc,"[]");elsestrcpy(cc," ");gotoxy(x*2,y);puts(cc);gotoxy(79,24);}/* 画出拼块 */void hua(){int i;for(i=0;i<4;i++)kuai(kx[i],ky[i],1);}/* 清除拼块的函数 */void ca(){int i;for(i=0;i<4;i++)kuai(kx[i],ky[i],0);}/* 拼块下落一行 */int xialuo(){int t,i;ca();t=1;for(i=0;i<4;i++){if(ky[i]==24) {t=0; break;};if(tong[kx[i]][ky[i]+1]==1) {t=0; break;}; }if(t==1)for(i=0;i<4;i++)ky[i]=ky[i]+1;elsefor(i=0;i<4;i++)tong[kx[i]][ky[i]]=1;hua();return t;}/* 拼块左右移动函数 */void yidong(int p){int t,i;ca();t=1;i=0;do{if((kx[i]==1)&&(p==-1)) {t=0; break;}; if((kx[i]==12)&&(p==1)) {t=0; break;}; if (tong[kx[i]+p][ky[i]]==1) {t=0; break;}; i++;} while (i<4);if(t==1)for(i=0;i<4;i++)kx[i]=kx[i]+p;hua();}/* 旋转拼块的函数 */void zhuan(){int i,t,x,y;int kx1[4],ky1[4];ca();x=kx[1]; y=ky[1];for(i=0;i<4;i++) {kx1[i]=x+y-ky[i]; ky1[i]=y-x+kx[i];}t=1;for(i=0;i<4;i++){if((kx1[i]<1)||(kx1[i]>12)||(ky1[i]<1)||(ky1[i]>24)) {t=0; break;}; if (tong[kx1[i]][ky1[i]]==1) {t=0; break;};}if(t==1)for(i=0;i<4;i++){kx[i]=kx1[i]; ky[i]=ky1[i];};hua();}/* 计算一行中的方块数 */int fangkuaishu(int h){int i,p=0;for(i=1;i<=12;i++)p=p+tong[i][h];if(p==12)for(i=1000;i<=4000;i+=80){sound(i);delay(10);}nosound();return p;}/* 桶中方块除去一行,在此行上面的方块下移一行 */void yihang(int h){int k,j,q;for(k=h;k>0;k--){q=0;for(j=1;j<=12;j++){if(tong[j][k]!=tong[j][k-1]){ kuai(j,k,tong[j][k-1]);tong[j][k]=tong[j][k-1];}q=q+tong[j][k];}if(q==0) break;}}/* 检查有无完成的行,并处理之 */ void jiancha(){int i,n;i=24;do{n=fangkuaishu(i);if(n==12) yihang(i); else i--;} while((i>0)&&(n>0));}/* 开始函数,初始化,画出空桶*/ void kaishi(){int i,j;for(i=1;i<=24;i++)for(j=1;j<=12;j++)tong[j][i]=0;for(i=0;i<24;i++)puts("||");printf("`------------------------'");randomize();}/**********************************************//* 主程序 */main(){int i,j,k,s;int m,t;char kk;kaishi(); /* 屏幕初始化,显示空桶 */for(;;){ /* 开始一个循环,在此循环中不断检测按键并处理之 */m=rand()%7; /* 随机产生一种拼块 */for(i=0;i<4;i++){ /* 计算拼块在桶中的坐标 */kx[i]=fk[m][i][0]+5;ky[i]=fk[m][i][1];}t=1;for(i=0;i<4;i++) /* 检查拼块是否能放入桶中,不能放则退出游戏*/if (tong[kx[i]][ky[i]]==1)hua(); /* 画出拼块 */s=0; /* S是一个标志,指示是否按了空格键 */for(;;){ /* 此循环中处理一个拼块的下落过程 */if(s==0) kk=key(9); else kk=key(0); /* 按过了空格键则不延时 */ if((kk>='a')&&(kk<='z')) kk=kk-32; /* 将小写字母转换为大写*/switch (kk){ /* 根据按键作相应处理 */case ' ' : s=1; break; /* 按空格, 快速下落 */case 'K': zhuan(); break; /* 按K,旋转拼块 */case 'J': yidong(-1); break; /* 按J,左移拼块 */case 'L': yidong(1); break; /* 按L,右移拼块 */case 'S': while(kbhit()==0);break; /* 按S,暂停游戏 */case 'E': exit(0); break; /* 按E,结束游戏 */default : t=xialuo(); /* 没按上面的键,或未按任何键,拼块下落一格*/}if(t==0) break; /* 拼块落到桶底或不能再下落退出循环 */}jiancha(); /* 检查是否有完成的行,并处理之 */}}。

JAVA拼图游戏完整代码

JAVA拼图游戏完整代码

cell[num].setText("");
}
}
}
//start 对小方格重新排序 public void start() {
//如果没有给小方格添加监听,则添加监听 if(!hasAddActionListener){
for(int i=0;i<11;i++){ cell[i].addMouseListener(this);
"); }
//判断若完成,则提示完成 if(isFinish()){
JOptionPane.showMessageDialog(this, "恭喜你完成了,共用"+stepNum+"步。
//撤销小方格的监听 for(int i=0;i<11;i++){
cell[i].removeMouseListener(this); } hasAddActionListener=false; }
private Cell[] cell; private boolean hasAddActionListener = false;//表示是否为小方格添加了点击监听, 有为 true private Rectangle nullCell;
//构造方法 public PictureCanvas() {
}
}
}
private void cellMove(int nullX, int nullY, String direction) { for(int i=0;i<11;i++){ if(cell[i].getBounds().x == nullX && cell[i].getBounds().y == nullY){ //当前方格移动 cell[i].move(direction); //空方格移动(nullX,nullY) nullCell.setLocation(nullX,nullY); break; } }

Python拼图游戏代码

Python拼图游戏代码

Python拼图游戏代码编写一个完整的拼图游戏同样需要使用图形界面库来实现游戏画面和交互。

以下是一个简化的拼图游戏示例代码的框架,其中使用了`pygame`库实现游戏界面:```pythonimport pygameimport random# 游戏窗口大小WINDOW_WIDTH = 600WINDOW_HEIGHT = 600# 拼图格子数量GRID_SIZE = 3# 颜色定义WHITE = (255, 255, 255)BLACK = (0, 0, 0)# 图片路径IMAGE_PATH = "images/"# 初始化Pygamepygame.init()# 创建游戏窗口window = pygame.display.set_mode([WINDOW_WIDTH, WINDOW_HEIGHT]) pygame.display.set_caption("拼图游戏")# 设置游戏时钟clock = pygame.time.Clock()# 加载图片def load_image(file_name, size):image = pygame.image.load(IMAGE_PATH + file_name)image = pygame.transform.scale(image, size)return image# 游戏元素类class Tile:def __init__(self, image, row, column, target_row, target_column):self.image = imageself.rect = image.get_rect()self.row = rowself.column = columnself.target_row = target_rowself.target_column = target_columndef draw(self):x = self.column * (WINDOW_WIDTH // GRID_SIZE)y = self.row * (WINDOW_HEIGHT // GRID_SIZE)self.rect.topleft = (x, y)window.blit(self.image, self.rect)# 创建拼图游戏image_size = (WINDOW_WIDTH // GRID_SIZE, WINDOW_HEIGHT // GRID_SIZE)tiles = []for row in range(GRID_SIZE):for column in range(GRID_SIZE):if row == GRID_SIZE - 1 and column == GRID_SIZE - 1:continuetile_image = load_image(f"image{row * GRID_SIZE + column + 1}.png", image_size)target_row = rowtarget_column = columntile = Tile(tile_image, row, column, target_row, target_column)tiles.append(tile)# 打乱拼图顺序random.shuffle(tiles)# 标记被拖动的拼图方块dragging_tile = None# 游戏主循环running = Truewhile running:# 处理事件for event in pygame.event.get():if event.type == pygame.QUIT:running = Falseelif event.type == pygame.MOUSEBUTTONDOWN:if event.button == 1:mouse_pos = pygame.mouse.get_pos()for tile in tiles:if tile.rect.collidepoint(mouse_pos):dragging_tile = tilebreakelif event.type == pygame.MOUSEBUTTONUP:if event.button == 1:if dragging_tile is not None:mouse_pos = pygame.mouse.get_pos()for tile in tiles:if tile != dragging_tile and tile.rect.collidepoint(mouse_pos):dragging_tile.row, tile.row = tile.row, dragging_tile.rowdragging_tile.column, tile.column = tile.column, dragging_tile.columndragging_tile = None# 绘制游戏画面window.fill(WHITE)for tile in tiles:tile.draw()pygame.display.update()# 控制游戏帧率clock.tick(60)# 退出游戏pygame.quit()这个示例代码实现了一个简化的拼图游戏框架。

手机拼图源码(java)

手机拼图源码(java)
temp[k/Y][k%Y]=t;
}
return temp;
}
public void keyPressed(int keyCode){
switch(state){
case 1:
switch(screen){
for(int j=0;j<Y;j++){
TL.setCell(i,j,X*j+i+1);
Board.setCell(i,j,0);
Mess.setCell(i,j,temp[i][j]);
Main.instance.pause=false;
Main.instance.curState=3;
new Thread(Main.instance).start();
public void run() {load();}
}).start();
p.drawWait(Main.bg,Main.wait,Main.width,Main.height,"正在初始化,请稍等。",Main.g);
i1--;
if(i1<0)i1=X-1;
x1=Main.instance.width/2-pintu.getWidth()/2+i1*pintu.getWidth()/X;
y1=Main.instance.height/2-pintu.getHeight()/2+j1*pintu.getHeight()/Y;
dst[i][j]=0;
}
LM.append(TL);
LM.append(Board);
LM.append(Mess);
TL.setVisible(false);

java课程设计-拼图游戏代码

java课程设计-拼图游戏代码

package love;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.util.Random;import javax.swing.*;public class Games extends JFrame implements ActionListener {private JButton buttons[][];//存储按键的数组private Container container;//一个容器private GridLayout layout;//布局方式为GridLayoutprivate int count =0,is[]=new int[8];//count的作用是计算按键移动的次数,is[]储存一个随机产生的1到8数字数组public Games() {super("拼图游戏");//设置标题layout = new GridLayout(3, 3);// 3行3列container = getContentPane();//该容器的布局方式,及其重要,否则产生空引用异常container.setLayout(layout);//将该布局方式作用于容器buttons = new JButton[3][3];//给按键数组分配储存空间int locate1,locate2;//locate1用来指示当前产生的元素locate2用来指示locate1之前的元素for (locate1 = 0; locate1 < 8; locate1++) {//该方法作用是产生1到8这8个数,随机分配给数组,即无序排列int g = new Random().nextInt(8) + 1;//随机产生一个空白按键,即不显示的那个is[locate1] = g;for (locate2 = locate1 - 1; 0 <= locate2; locate2--) {if (is[locate1] == is[locate2])break;}if (locate2 != -1)locate1--;}int temp = 0;int r = new Random().nextInt(3);//随机产生一个0到3的数,代表空白按键的行int l = newRandom().nextInt(3);//随机产生一个0到3的数,代表空白按键的列for (int i = 0; i < 3; i++) {for (int j = 0; j < 3; j++) {if (r == i && l == j) {//空白按键设置为9,不显示buttons[i][j] = new JButton("9");container.add(buttons[i][j]);buttons[i][j].setVisible(false);} else {buttons[i][j] = new JButton("" + is[temp++]);//将数组的值作为显示的8个按键的名字container.add(buttons[i][j]);}buttons[i][j].addActionListener(this);//注册监听事件}}setSize(300, 300);//设置显示容器区域大小setVisible(true);}public void actionPerformed(ActionEvent event) {//事件处理,由于计算量小该处将所有按键单独分析JButton b = (JButton) event.getSource();if (b == buttons[0][0]) {if (buttons[0][1].getText().equals("9")) {buttons[0][1].setText("" + buttons[0][0].getText());buttons[0][1].setVisible(true);buttons[0][0].setText("9");buttons[0][0].setVisible(false);count++;} else if (buttons[1][0].getText().equals("9")) {buttons[1][0].setText("" + buttons[0][0].getText());buttons[1][0].setVisible(true);buttons[0][0].setText("9");buttons[0][0].setVisible(false);count++;}}else if (b == buttons[0][1]) {if (buttons[0][0].getText().equals("9")) {buttons[0][0].setText("" + buttons[0][1].getText());buttons[0][0].setVisible(true);buttons[0][1].setText("9");buttons[0][1].setVisible(false);count++;} else if (buttons[0][2].getText().equals("9")) { buttons[0][2].setText("" + buttons[0][1].getText()); buttons[0][2].setVisible(true);buttons[0][1].setText("9");buttons[0][1].setVisible(false);count++;} else if (buttons[1][1].getText().equals("9")) { buttons[1][1].setText("" + buttons[0][1].getText()); buttons[1][1].setVisible(true);buttons[0][1].setText("9");buttons[0][1].setVisible(false);count++;}} else if (b == buttons[0][2]) {if (buttons[0][1].getText().equals("9")) {buttons[0][1].setText("" + buttons[0][2].getText()); buttons[0][1].setVisible(true);buttons[0][2].setText("9");buttons[0][2].setVisible(false);count++;} else if (buttons[1][2].getText().equals("9")) {buttons[1][2].setText("" + buttons[0][2].getText()); buttons[1][2].setVisible(true);buttons[0][2].setText("9");buttons[0][2].setVisible(false);count++;}} else if (b == buttons[1][0]) {if (buttons[0][0].getText().equals("9")) {buttons[0][0].setText("" + buttons[1][0].getText()); buttons[0][0].setVisible(true);buttons[1][0].setText("9");buttons[1][0].setVisible(false);count++;} else if (buttons[1][1].getText().equals("9")) { buttons[1][1].setText("" + buttons[1][0].getText()); buttons[1][1].setVisible(true);buttons[1][0].setText("9");buttons[1][0].setVisible(false);count++;} else if (buttons[2][0].getText().equals("9")) { buttons[2][0].setText("" + buttons[1][0].getText()); buttons[2][0].setVisible(true);buttons[1][0].setText("9");buttons[1][0].setVisible(false);count++;}} else if (b == buttons[1][1]) {if (buttons[0][1].getText().equals("9")) {buttons[0][1].setText("" + buttons[1][1].getText()); buttons[0][1].setVisible(true);buttons[1][1].setText("9");buttons[1][1].setVisible(false);count++;} else if (buttons[1][0].getText().equals("9")) { buttons[1][0].setText("" + buttons[1][1].getText()); buttons[1][0].setVisible(true);buttons[1][1].setText("9");buttons[1][1].setVisible(false);count++;} else if (buttons[1][2].getText().equals("9")) { buttons[1][2].setText("" + buttons[1][1].getText()); buttons[1][2].setVisible(true);buttons[1][1].setText("9");buttons[1][1].setVisible(false);count++;} else if (buttons[2][1].getText().equals("9")) {buttons[2][1].setText("" + buttons[1][1].getText()); buttons[2][1].setVisible(true);buttons[1][1].setText("9");buttons[1][1].setVisible(false);count++;}} else if (b == buttons[1][2]) {if (buttons[0][2].getText().equals("9")) {buttons[0][2].setText("" + buttons[1][2].getText()); buttons[0][2].setVisible(true);buttons[1][2].setText("9");buttons[1][2].setVisible(false);count++;} else if (buttons[2][2].getText().equals("9")) { buttons[2][2].setText("" + buttons[1][2].getText()); buttons[2][2].setVisible(true);buttons[1][2].setText("9");buttons[1][2].setVisible(false);count++;} else if (buttons[1][1].getText().equals("9")) { buttons[1][1].setText("" + buttons[1][2].getText()); buttons[1][1].setVisible(true);buttons[1][2].setText("9");buttons[1][2].setVisible(false);count++;}} else if (b == buttons[2][0]) {if (buttons[1][0].getText().equals("9")) {buttons[1][0].setText("" + buttons[2][0].getText()); buttons[1][0].setVisible(true);buttons[2][0].setText("9");buttons[2][0].setVisible(false);count++;} else if (buttons[2][1].getText().equals("9")) { buttons[2][1].setText("" + buttons[2][0].getText()); buttons[2][1].setVisible(true);buttons[2][0].setText("9");buttons[2][0].setVisible(false);count++;}}else if (b == buttons[2][1]) {if (buttons[2][0].getText().equals("9")) {buttons[2][0].setText("" + buttons[2][1].getText()); buttons[2][0].setVisible(true);buttons[2][1].setText("9");buttons[2][1].setVisible(false);count++;} else if (buttons[2][2].getText().equals("9")) { buttons[2][2].setText("" + buttons[2][1].getText()); buttons[2][2].setVisible(true);buttons[2][1].setText("9");buttons[2][1].setVisible(false);count++;} else if (buttons[1][1].getText().equals("9")) { buttons[1][1].setText("" + buttons[2][1].getText()); buttons[1][1].setVisible(true);buttons[2][1].setText("9");buttons[2][1].setVisible(false);count++;}} else if (b == buttons[2][2]) {if (buttons[2][1].getText().equals("9")) {buttons[2][1].setText("" + buttons[2][2].getText()); buttons[2][1].setVisible(true);buttons[2][2].setText("9");buttons[2][2].setVisible(false);count++;} else if (buttons[1][2].getText().equals("9")) { buttons[1][2].setText("" + buttons[2][2].getText()); buttons[1][2].setVisible(true);buttons[2][2].setText("9");buttons[2][2].setVisible(false);count++;}}if (buttons[0][0].getText().equals("1")//假如1到8已经排列完成,则执行该语句&& buttons[0][1].getText().equals("2")&& buttons[0][2].getText().equals("3")&& buttons[1][0].getText().equals("4")&& buttons[1][1].getText().equals("5")&& buttons[1][2].getText().equals("6")&& buttons[2][0].getText().equals("7")&& buttons[2][1].getText().equals("8")) {JOptionPane.showMessageDialog(null, "您一共花费了" + count + "步完成了游戏!");//弹出对话框,显示共移动步数System.exit(0);//退出程序}}public static void main(String[] args) {Games game = new Games();game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}}。

最经典的C语言拼图小游戏源代码

最经典的C语言拼图小游戏源代码
int i;
for(i=0;i<=8;i++){
if (num[i]==0)
return i;
}
}
change(int a,int b){ /*交换num[a],num[b]*/
int temp;
int i,j;
for(i=0;i<=2;i++){
gotoxy(24,8+i*3);
for(j=0;j<=2;j++){
if (num[j+i*3]!=0)
printf("\332\304\304\304\304\267");
break;
case 80: /*按上*/
if(pos>=3) change(pos,pos-3);
break;
case 77: /*按左*/
temp=num[a];
num[a]=num[b];
num[b]=temp;
}

这涉及有没有解的问题
不管怎么样,九格游戏最后的结果只有两个:
123 | 123
456 | 456
78 | 87 (证明从略)
而要两两交换而始终有解的话,(从原序列开始)必须:相邻交换的次数为偶
但我们用一种更有效的方法:
每一个总与其下第二个交换.
第7,8个与0,1交换,只要交换次数多,仍可获得相同的效果.
gotoxy(26,14);
printf("\324\315\315\315\315\315\315\315\315\315\315\315\315\274\n");

c#拼图小游戏源码

c#拼图小游戏源码

c#拼图小游戏源码c#程序源码打包下载using System;using System.Collections.Generic;using ponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Drawing.Drawing2D;namespace 拼图2{public partial class Form1 : Form{boolBoFang = true;Point[] a = new Point[6]{new Point(3, 3), new Point(85, 3), new Point(167, 3) ,new Point(3, 104), new Point(85,104), new Point(167, 104), };PictureBox[] picture = new PictureBox[6];int[] ximeng = new int[6];Random Wzl = new Random();public Form1(){InitializeComponent();axWindowsMediaPlayer1.settings.autoStart =true;axWindowsMediaPlayer1.URL = @"/swf/the garden.MP3";//设置音乐地址label1_Click(null, null);}private void Form1_KeyDown(object sender, KeyEventArgs e)//窗体接收键盘事件进行判断拼图移动方向{label6.BackColor = Color.White;label7.BackColor = Color.White;label8.BackColor = Color.White;label9.BackColor = Color.White;boolyanZheng = true;if (e.KeyCode == Keys.Right){label9.BackColor = Color.Gray;if (picture[5].Location.X == 3)return;picture[5].Location = new Point(picture[5].Location.X - 82, picture[5].Location.Y);for (int i = 0; i <5; i++){if (picture[i].Location == picture[5].Location){ picture[i].Location = new Point(picture[i].Location.X + 82, picture[i].Location.Y); break; }}}if (e.KeyCode == Keys.Left){label7.BackColor = Color.Gray;if ( picture[5].Location.X == 167 )return;picture[5].Location = new Point(picture[5].Location.X + 82, picture[5].Location.Y);for (int i = 0; i <5; i++){if (picture[i].Location == picture[5].Location){ picture[i].Location = new Point(picture[i].Location.X - 82, picture[i].Location.Y); break; }}}if (e.KeyCode == Keys.Up){label6.BackColor = Color.Gray;if (picture[5].Location.Y == 104)return;picture[5].Location = new Point(picture[5].Location.X,picture[5].Location.Y + 101);for (int i = 0; i < 5; i++){if (picture[i].Location == picture[5].Location){ picture[i].Location = new Point(picture[i].Location.X, picture[i].Location.Y-101); break; }}}if (e.KeyCode == Keys.Down){label8.BackColor = Color.Gray;if (picture[5].Location.Y == 3)return;picture[5].Location = new Point(picture[5].Location.X,picture[5].Location.Y - 101);for (int i = 0; i < 5; i++){if (picture[i].Location == picture[5].Location){ picture[i].Location = new Point(picture[i].Location.X, picture[i].Location.Y + 101); break; }}}if (e.KeyData== (Keys.Control | Keys.W))//作弊组合键Ctrl+w{for (int i = 0; i < 6; i++){picture[i].Location = a[i];}}for (int i = 0; i < 6; i++)//验证用户拼图结果是否正确{if (picture[i].Location != a[i])yanZheng = false;}if (yanZheng)label2.Text = "拼图结果:正确";elselabel2.Text = "拼图结果:错误";}private void label1_Click(object sender, EventArgs e){panel1.Controls.Clear();//清除panel1容器的控件for (int i = 0; i < 6; i++)//循环向panel1容器添加图片控件并设置属性 {picture[i] = new PictureBox();picture[i].BackgroundImage = imageList1.Images[i];picture[i].Size = new Size(81, 100);picture[i].BorderStyle = BorderStyle.Fixed3D;chongxin: ximeng[i] = Wzl.Next(6);for (int j = 0; j < i; j++){if (ximeng[j] == ximeng[i])gotochongxin;}picture[i].Location = a[ximeng[i]];panel1.Controls.Add(picture[i]);toolTip1.SetToolTip(picture[i],"边框为黑色的位置为空位置,图片可移动到空位置");}//将空位的图片风格模式与其他位置的图片风格区分,便于用户分辨出空位 picture[5].BorderStyle = BorderStyle.FixedSingle;}private void label2_Click(object sender, EventArgs e){}private void timer1_Tick(object sender, EventArgs e)//文字-拼图游戏颜色变换控制{label3.ForeColor = Color.FromArgb(Wzl.Next(255), Wzl.Next(255), Wzl.Next(255), Wzl.Next(255));}private void label4_Click(object sender, EventArgs e){Application.Exit();}private void label5_Click(object sender, EventArgs e)//判断音乐该暂定或继续{if (BoFang){BoFang = false;axWindowsMediaPlayer1.Ctlcontrols.pause();}else{axWindowsMediaPlayer1.Ctlcontrols.play();BoFang = true;}}}}。

HTML5拼图游戏代码

HTML5拼图游戏代码

sliding.html0<!doctype html>0<html>0<head>0<meta http-equiv="content-type" content="text/html;charset=utf-8" />0<meta name="viewport"content="width=device-width,initial-scale=1.0,user-scalable=yes" /> 0<meta name="HandheldFriendly" content="true" />0<link rel="stylesheet" href="jquery.mobile-1.4.3.min.css" /> 0<script src="jquery-2.1.1.min.js"></script> 0<script src="jquery.mobile-1.4.3.min.js"></script> 0<script type="text/javascript">0</script>0<title>拼图游戏</title>0<style>0.picture {0border: 1px solid black;0}0</style>0</head>0<body>0<div id="title">0<h2>拼图游戏</h2>0</div>0<div id="slider">0<form>0<label>简单</label>0<input type="range" id="scale" value="4" min="3" max="5" step="1">0<label>困难</label>0<div data-role="controlgroup">0<a data-ajax="false" href="menu.html" data-role="button">返回菜单</a>0</div> 0</form>0<br>0</div>0<div id="main" class="main"> 0<canvas id="puzzle" width="480px" height="480px"></canvas>0</div>0<script src="sliding.js"></script>0</body>0</html>0Sliding.js0var context = document.getElementById('puzzle').getContext('2d');0var img = new Image();0img.src = 'fizz2.jpg';0img.addEventListener('load', drawTiles, false);0var boardSize = document.getElementById('puzzle').width;0var tileCount = document.getElementById('scale').value;0var tileSize = boardSize / tileCount;0var clickLoc = new Object;0clickLoc.x = 0;0clickLoc.y = 0;0var emptyLoc = new Object;0emptyLoc.x = 0;0emptyLoc.y = 0;0var solved = false;0var boardParts = new Object;0setBoard();0document.getElementById('scale').onchange = function() {0 tileCount = this.value;0tileSize = boardSize / tileCount;0setBoard();0drawTiles();0};0document.getElementById('puzzle').onmousemove = function(e) {0 clickLoc.x = Math.floor((e.pageX - this.offsetLeft) / tileSize);0 clickLoc.y = Math.floor((e.pageY - this.offsetTop) / tileSize);0 };0document.getElementById('puzzle').onclick = function() {0if (distance(clickLoc.x, clickLoc.y, emptyLoc.x, emptyLoc.y) == 1) {0slideTile(emptyLoc, clickLoc);0drawTiles();0}0if (solved) {0setTimeout(function() {alert("Y ou solved it!");}, 500);0}0};0function setBoard() {0boardParts = new Array(tileCount);0for (var i = 0; i < tileCount; ++i) {0boardParts[i] = new Array(tileCount);0for (var j = 0; j < tileCount; ++j) {0boardParts[i][j] = new Object;0boardParts[i][j].x = (tileCount - 1) - i;0boardParts[i][j].y = (tileCount - 1) - j;0}0}0emptyLoc.x = boardParts[tileCount - 1][tileCount - 1].x;0emptyLoc.y = boardParts[tileCount - 1][tileCount - 1].y;0solved = false;0}0function drawTiles() {0context.clearRect ( 0 , 0 , boardSize , boardSize );0for (var i = 0; i < tileCount; ++i) {0for (var j = 0; j < tileCount; ++j) {0var x = boardParts[i][j].x;0var y = boardParts[i][j].y;0if(i != emptyLoc.x || j != emptyLoc.y || solved == true) {0context.drawImage(img, x * tileSize, y * tileSize, tileSize, tileSize,0i * tileSize, j * tileSize, tileSize, tileSize);0}0}0}0}0function distance(x1, y1, x2, y2) {0return Math.abs(x1 - x2) + Math.abs(y1 - y2);0}0function slideTile(toLoc, fromLoc) {0if (!solved) {0boardParts[toLoc.x][toLoc.y].x = boardParts[fromLoc.x][fromLoc.y].x;0 boardParts[toLoc.x][toLoc.y].y = boardParts[fromLoc.x][fromLoc.y].y;0 boardParts[fromLoc.x][fromLoc.y].x = tileCount - 1;0boardParts[fromLoc.x][fromLoc.y].y = tileCount - 1;0toLoc.x = fromLoc.x;0toLoc.y = fromLoc.y;0checkSolved();0}0}0function checkSolved() {0var flag = true;0for (var i = 0; i < tileCount; ++i) {0for (var j = 0; j < tileCount; ++j) {0if (boardParts[i][j].x != i || boardParts[i][j].y != j) {0flag = false;0}0}0}0solved = flag;0}0。

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

list.add(jb);
}
//打乱顺序
Collections.shuffle(list);
JButton jb = new JButton();
jb.setName("16");
jb.setIcon(new ImageIcon(path+"15.jpg"));
jb.setVisible(false);
} } } class MenuListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e) {
if(e.getSource()==jmi_start){ //开始游戏 card.show(NumberGame.this.getContentPane(), "game");
@SuppressWarnings("serial") public class NumberGame extends JFrame implements ActionListener{
String path="LookingGirl/"; int i=3;
//定义一个卡片布局 CardLayout card = new CardLayout();
import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel;
System.exit(0); } } } } public static void main(String[] args) {
new NumberGame(); } }
//定义一个二维数组,用来存储 16 个按钮
JButton[][] number = new JButton[4][4];
List<JButton> list = new ArrayList<JButton>();
private void initMenu(){ this.setJMenuBar(bar); bar.add(menu); menu.add(jmi_start); menu.add(jmi_viewImage); menu.add(jmi_returnGame); menu.addSeparator(); menu.add(jmi_exit); MenuListener li = new MenuListener(); jmi_start.addActionListener(li); jmi_viewImage.addActionListener(li); jmi_returnGame.addActionListener(li); jmi_exit.addActionListener(li);
this.add(jp_image,"image"); this.add(jp_game,"game");
//显示 this.setVisible(true); } //交换两个按钮 private void change(JButton a,JButton b){ Icon str= a.getIcon(); a.setIcon(b.getIcon()); b.setIcon(str); String name = a.getName(); a.setName(b.getName()); b.setName(name); a.setVisible(!a.isVisible()); b.setVisible(!b.isVisible()); } //判断是否成功 private void success(){ boolean flag=true; for(int i=0;i<16;i++){
if(!number[i/4][i%4].getName().equals(Integer.toString(i+1))){ System.out.println(i); flag=false; break;
} }
if(flag){ //成功了 number[3][3].setVisible(true); JOptionPane.showMessageDialog(this, " 恭 喜 你 , 成 功 了 "," 成 功
}else if(e.getSource()==jmi_viewImage){ i--; jmi_viewImage.setText("查看原图 "+i); card.show(NumberGame.this.getContentPane(), "image"); if(i<1){
jmi_viewImage.setEnabled(false); } }else if(e.getSource()==jmi_returnGame){ card.show(NumberGame.this.getContentPane(), "game"); }else{ int i=JOptionPane.showConfirmDialog(NumberGame.this, " 你 真 的 要 退 出 吗?","提示",JOptionPane.OK_CANCEL_OPTION); if(i==JOptionPane.YES_OPTION){
for(int j=0;j<4;j++){ if(n==number[i][j]){ //上 if(i>0 && !number[i-1][j].isVisible()){ change(n,number[i-1][j]); }else if(i<3 && !number[i+1][j].isVisible()){ //下 change(n,number[i+1]p; !number[i][j-1].isVisible()){ //左 change(n,number[i][j-1]); }else if(j<3 && !number[i][j+1].isVisible()){ //右 change(n,number[i][j+1]); } success(); }
import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Collections; import java.util.List;
list.add(jb);
for(int i=0;i<list.size();i++){
number[i/4][i%4] = list.get(i); //为每个按钮加上监听 number[i/4][i%4].addActionListener(this); number[i/4][i%4].setFont(new Font("宋体",Font.BOLD,24)); jp_game.add(number[i/4][i%4]); } } //构造方法 public NumberGame(){ this.setBounds(100, 100, 400, 460); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设置布局管理器 this.setLayout(card); initMenu(); initGame(); initImage();
JMenuBar bar = new JMenuBar(); JMenu menu=new JMenu("功能"); JMenuItem jmi_start= new JMenuItem("开始游戏"); JMenuItem jmi_viewImage= new JMenuItem("查看原图 3"); JMenuItem jmi_returnGame= new JMenuItem("返回游戏");
}
//初使化图像区 public void initImage(){
jp_image.setLayout(new BorderLayout()); jp_image.add(jl_image); }
//初使化按钮数组,并将按钮放到面板中 public void initGame(){
//将面板的布局改成 grid jp_game.setLayout(new GridLayout(4,4));
",JOptionPane.OK_OPTION,new ImageIcon("success.png")); }
}
@Override public void actionPerformed(ActionEvent e) {
JButton n=(JButton)e.getSource(); //判断当前点击的是哪 个按钮 for(int i=0;i<4;i++){
相关文档
最新文档