java拼图游戏完整代码
拼图游戏源代码
//*关卡开始前 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;
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]);//移除最后一个多余的方格}文章转自上海青大实训:。
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]);//移除最后一个多余的方格}文章转自上海青大实训:谣言:吃太咸了会得病,导语:“人体每日摄入食盐不应过多,否则易患多种疾病。
拼图游戏代码
Option ExplicitDim cpost%, cposl%, nowpost%, nowposl%, changet%, changel%, medium%, forno1%, forno2%, no(1 To 9) As Integer, steps%, timecount%, score%Dim checkwhetherdisorder%, checkdisordering%, disorderno%, continuedisorderSub checkcommand()If (Command1.Top = 0) And (Command1.Left = 0) _And (Command2.Top = 0) And (Command2.Left = 2000) _And (Command3.Top = 0) And (Command3.Left = 4000) _And (Command4.Top = 2000) And (Command4.Left = 0) _And (Command5.Top = 2000) And (Command5.Left = 2000) _And (Command6.Top = 2000) And (Command6.Left = 4000) _And (Command7.Top = 4000) And (Command7.Left = 0) _And (Command8.Top = 4000) And (Command8.Left = 2000) _And (recognize.Top = 4000) And (recognize.Left = 4000) ThenTimer1.Interval = 0If checkdisordering = 1 Then GoTo line1MsgBox ("恭喜你已经解出了正确的顺序")score = 500 - steps - timecountMsgBox ("您本次的得分为" & Str(score))checkwhetherdisorder = 0line1:End IfEnd SubPrivate Sub Form_Activate()MsgBox ("如果你已经了解规则,请点击关闭游戏规则")start.Enabled = FalseEnd SubPrivate Sub form_Load()changet = 0changel = 0steps = 0timecount = 0score = 0checkwhetherdisorder = 0Call orders_Clickcheckdisordering = 0End SubPrivate Sub Command1_Click()If (checkwhetherdisorder = 0) Or (Picture2.Visible = True) Then GoTo line0cpost = recognize.Topcposl = recognize.Leftnowpost = Command1.Topnowposl = Command1.LeftIf Abs(cpost - nowpost) = 2000 Then changet = 1If Abs(cposl - nowposl) = 2000 Then changel = 1If ((Abs(cpost - nowpost) = 2000) And (Abs(cposl - nowposl) = 4000)) Or ((Abs(cpost - nowpost) = 4000) And (Abs(cposl - nowposl) = 2000)) Thenchanget = 0changel = 0End Ifmedium = cpostcpost = nowpostnowpost = mediummedium = cposlcposl = nowposlnowposl = mediumIf changet + changel = 1 ThenCommand1.Move nowposl, nowpostrecognize.Move cposl, cpoststeps = steps + 1stepsdisplay.Clsstepsdisplay.Print "已进行步数"; stepsEnd Ifchanget = 0changel = 0Timer1.Interval = 1000checkcommandline0: If Picture2.Visible = True Then MsgBox ("点击关闭游戏规以开始游戏")End SubPrivate Sub Command2_Click()If (checkwhetherdisorder = 0) Or (Picture2.Visible = True) Then GoTo line0cpost = recognize.Topcposl = recognize.Leftnowpost = Command2.Topnowposl = Command2.LeftIf Abs(cpost - nowpost) = 2000 Then changet = 1If Abs(cposl - nowposl) = 2000 Then changel = 1If ((Abs(cpost - nowpost) = 2000) And (Abs(cposl - nowposl) = 4000)) Or ((Abs(cpost - nowpost) = 4000) And (Abs(cposl - nowposl) = 2000)) Thenchanget = 0changel = 0End Ifmedium = cpostcpost = nowpostnowpost = mediummedium = cposlcposl = nowposlnowposl = mediumIf changet + changel = 1 ThenCommand2.Move nowposl, nowpostrecognize.Move cposl, cpoststeps = steps + 1stepsdisplay.Clsstepsdisplay.Print "已进行步数"; stepsEnd Ifchanget = 0changel = 0Timer1.Interval = 1000checkcommandline0: If Picture2.Visible = True Then MsgBox ("点击关闭游戏规以开始游戏")End SubPrivate Sub Command3_Click()If (checkwhetherdisorder = 0) Or (Picture2.Visible = True) Then GoTo line0cpost = recognize.Topcposl = recognize.Leftnowpost = Command3.Topnowposl = Command3.LeftIf Abs(cpost - nowpost) = 2000 Then changet = 1If Abs(cposl - nowposl) = 2000 Then changel = 1If ((Abs(cpost - nowpost) = 2000) And (Abs(cposl - nowposl) = 4000)) Or ((Abs(cpost - nowpost) = 4000) And (Abs(cposl - nowposl) = 2000)) Thenchanget = 0changel = 0End Ifmedium = cpostcpost = nowpostnowpost = mediummedium = cposlcposl = nowposlnowposl = mediumIf changet + changel = 1 ThenCommand3.Move nowposl, nowpostrecognize.Move cposl, cpoststeps = steps + 1stepsdisplay.Clsstepsdisplay.Print "已进行步数"; stepsEnd Ifchanget = 0changel = 0Timer1.Interval = 1000checkcommandline0: If Picture2.Visible = True Then MsgBox ("点击关闭游戏规以开始游戏")End SubPrivate Sub Command4_Click()If (checkwhetherdisorder = 0) Or (Picture2.Visible = True) Then GoTo line0cpost = recognize.Topcposl = recognize.Leftnowpost = Command4.Topnowposl = Command4.LeftIf Abs(cpost - nowpost) = 2000 Then changet = 1If Abs(cposl - nowposl) = 2000 Then changel = 1If ((Abs(cpost - nowpost) = 2000) And (Abs(cposl - nowposl) = 4000)) Or ((Abs(cpost - nowpost) = 4000) And (Abs(cposl - nowposl) = 2000)) Thenchanget = 0changel = 0End Ifmedium = cpostcpost = nowpostnowpost = mediummedium = cposlcposl = nowposlnowposl = mediumIf changet + changel = 1 ThenCommand4.Move nowposl, nowpostrecognize.Move cposl, cpoststeps = steps + 1stepsdisplay.Clsstepsdisplay.Print "已进行步数"; stepsEnd Ifchanget = 0changel = 0Timer1.Interval = 1000checkcommandline0: If Picture2.Visible = True Then MsgBox ("点击关闭游戏规以开始游戏")End SubPrivate Sub Command5_Click()If (checkwhetherdisorder = 0) Or (Picture2.Visible = True) Then GoTo line0cpost = recognize.Topcposl = recognize.Leftnowpost = Command5.Topnowposl = Command5.LeftIf Abs(cpost - nowpost) = 2000 Then changet = 1If Abs(cposl - nowposl) = 2000 Then changel = 1If ((Abs(cpost - nowpost) = 2000) And (Abs(cposl - nowposl) = 4000)) Or ((Abs(cpost - nowpost) = 4000) And (Abs(cposl - nowposl) = 2000)) Thenchanget = 0changel = 0End Ifmedium = cpostcpost = nowpostnowpost = mediummedium = cposlcposl = nowposlnowposl = mediumIf changet + changel = 1 ThenCommand5.Move nowposl, nowpostrecognize.Move cposl, cpoststeps = steps + 1stepsdisplay.Clsstepsdisplay.Print "已进行步数"; stepsEnd Ifchanget = 0changel = 0Timer1.Interval = 1000checkcommandline0: If Picture2.Visible = True Then MsgBox ("点击关闭游戏规以开始游戏")End SubPrivate Sub Command6_Click()If (checkwhetherdisorder = 0) Or (Picture2.Visible = True) Then GoTo line0cpost = recognize.Topcposl = recognize.Leftnowpost = Command6.Topnowposl = Command6.LeftIf Abs(cpost - nowpost) = 2000 Then changet = 1If Abs(cposl - nowposl) = 2000 Then changel = 1If ((Abs(cpost - nowpost) = 2000) And (Abs(cposl - nowposl) = 4000)) Or ((Abs(cpost - nowpost) = 4000) And (Abs(cposl - nowposl) = 2000)) Thenchanget = 0changel = 0End Ifmedium = cpostcpost = nowpostnowpost = mediummedium = cposlcposl = nowposlnowposl = mediumIf changet + changel = 1 ThenCommand6.Move nowposl, nowpostrecognize.Move cposl, cpoststeps = steps + 1stepsdisplay.Clsstepsdisplay.Print "已进行步数"; stepsEnd Ifchanget = 0changel = 0Timer1.Interval = 1000checkcommandline0: If Picture2.Visible = True Then MsgBox ("点击关闭游戏规以开始游戏")End SubPrivate Sub Command7_Click()If (checkwhetherdisorder = 0) Or (Picture2.Visible = True) Then GoTo line0cpost = recognize.Topcposl = recognize.Leftnowpost = Command7.Topnowposl = Command7.LeftIf Abs(cpost - nowpost) = 2000 Then changet = 1If Abs(cposl - nowposl) = 2000 Then changel = 1If ((Abs(cpost - nowpost) = 2000) And (Abs(cposl - nowposl) = 4000)) Or ((Abs(cpost - nowpost) = 4000) And (Abs(cposl - nowposl) = 2000)) Thenchanget = 0changel = 0End Ifmedium = cpostcpost = nowpostnowpost = mediummedium = cposlcposl = nowposlnowposl = mediumIf changet + changel = 1 ThenCommand7.Move nowposl, nowpostrecognize.Move cposl, cpoststeps = steps + 1stepsdisplay.Clsstepsdisplay.Print "已进行步数"; stepsEnd Ifchanget = 0changel = 0Timer1.Interval = 1000checkcommandline0: If Picture2.Visible = True Then MsgBox ("点击关闭游戏规以开始游戏")End SubPrivate Sub Command8_Click()If (checkwhetherdisorder = 0) Or (Picture2.Visible = True) Then GoTo line0cpost = recognize.Topcposl = recognize.Leftnowpost = Command8.Topnowposl = Command8.LeftIf Abs(cpost - nowpost) = 2000 Then changet = 1If Abs(cposl - nowposl) = 2000 Then changel = 1If ((Abs(cpost - nowpost) = 2000) And (Abs(cposl - nowposl) = 4000)) Or ((Abs(cpost - nowpost) = 4000) And (Abs(cposl - nowposl) = 2000)) Thenchanget = 0changel = 0End Ifmedium = cpostcpost = nowpostnowpost = mediummedium = cposlcposl = nowposlnowposl = mediumIf changet + changel = 1 ThenCommand8.Move nowposl, nowpostrecognize.Move cposl, cpoststeps = steps + 1stepsdisplay.Clsstepsdisplay.Print "已进行步数"; stepsEnd Ifchanget = 0changel = 0Timer1.Interval = 1000checkcommandline0: If Picture2.Visible = True Then MsgBox ("点击关闭游戏规则即可使用")End SubPrivate Sub start_Click()Dodisorderno = Val(InputBox("请输入要打乱的程度(建议在30到2000之间)", , 200, 5500, 3000)) If disorderno = 0 Then Exit SubIf disorderno < 0 Then MsgBox ("输入无效,重新输入")If disorderno > 2000 Thencontinuedisorder = MsgBox("你确定此打乱程度吗?这可能会超出你的计算机的运算能力,请谨慎使用!", vbYesNo)If continuedisorder = vbYes ThenGoTo line1ElseExit SubEnd IfEnd IfIf disorderno > 0 And disorderno < 30 Then MsgBox ("数值过小无打乱效果,请重新输入") line1: Loop Until disorderno >= 30checkdisordering = 1stepsdisplay.Clstimedisplay.Clscheckwhetherdisorder = 1line0: RandomizeFor forno2 = 1 To disordernoFor forno1 = 1 To 9no(forno1) = Int(9 * Rnd + 1)Select Case no(forno1)Case 1Command1_ClickCase 2Command2_ClickCase 3Command3_ClickCase 4Command4_ClickCase 5Command5_ClickCase 6Command6_ClickCase 7Command7_ClickCase 8Command8_ClickCase 9End Selectsteps = 0Timer1.Interval = 0Next forno1Next forno2If checkwhetherdisorder = 0 Then GoTo line0checkdisordering = 0timecount = -1End SubPrivate Sub Timer1_Timer()timecount = timecount + 1timedisplay.Clstimedisplay.Print "用时"; timecount; "秒"End SubPrivate Sub orders_Click()Picture2.Visible = Trueorders.Enabled = Falsecloseorders.Enabled = TruePicture2.Print "本游戏是比拼谁将8个数字块最快还原为最初的顺序" Picture2.Print "点击“打乱”计算机会自动打乱8个数字块"Picture2.Print "点击数字块可以使之移动到相邻的空白位置上" Picture2.Print "从你开始改变数字块的顺序,会自动计时."Picture2.Print "当你完成的时候,计算机会对你的表现打分"Picture2.Print "现在就开始吧!"Picture2.Print "阅读完成后点击关闭游戏规则"start.Enabled = FalseEnd SubPrivate Sub closeorders_Click()Picture2.Visible = Falseorders.Enabled = Truecloseorders.Enabled = FalsePicture2.Clsstart.Enabled = TrueEnd Sub。
拼图游戏源代码
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。
积木游戏程序源代码
积木游戏程序源代码一、HTML网页文件名:JMYX6.html<html><head><title>积木游戏JMYX6</title></head><body><applet code="JMYX6.class" width=500 height=500></applet></body></html>二、源代码文件名:JMYX6.javaimport java.applet.*;import java.awt.*;import java.awt.event.*;public class JMYX6 extends Applet implements KeyListener,ActionListener{ Label label=new Label("鼠标点击任一积木,然后用光标键移动它。
");Button b[ ]=new Button[40];int x[ ]=new int[40];int y[ ]=new int[40];String s[ ]=new String[40];public void init( ){ setLayout(null);add(label);label.setBounds(0,0,250,30);int k1=70,k2=70,k3=70,k4=70;for(int i=0;i<40;i++){ b[i]=new Button(String.valueOf(i));if(i%3==0) b[i].setBackground(Color.red);if(i%3==1) b[i].setBackground(Color.blue);if(i%3==2) b[i].setBackground(Color.yellow);b[i].addKeyListener(this); //按钮获得键盘事件监视器b[i].addActionListener(this);add(b[i]);if(i%4==0) { b[i].setBounds(k1,40,30,30);k1=k1+31; }else if(i%4==1) { b[i].setBounds(k2,71,30,30);k2=k2+31; }else if(i%4==2) { b[i].setBounds(k3,102,30,30);k3=k3+31; }else if(i%4==3) { b[i].setBounds(k4,133,30,30);k4=k4+31; } }for(int i=0;i<40;i++){ x[i]=b[i].getBounds( ).x;y[i]=b[i].getBounds( ).y; //获得按钮左上角的x,y 坐标}}public void keyTyped(KeyEvent e){ }public void keyPressed(KeyEvent e){ if(e.getKeyCode( )==KeyEvent.VK_UP){ for(int i=0;i<=39;i++){ if(s[i].equals(String.valueOf(i))){ y[i]=y[i]-2;if(y[i]<=0) y[i]=0;b[i].setLocation(x[i],y[i]);}}}else if(e.getKeyCode( )==KeyEvent.VK_DOWN){ for(int i=0;i<=39;i++){ if(s[i].equals(String.valueOf(i))){ y[i]=y[i]+2;if(y[i]>=300) y[i]=300;b[i].setLocation(x[i],y[i]);}}}else if(e.getKeyCode( )==KeyEvent.VK_LEFT){ for(int i=0;i<=39;i++){ if(s[i].equals(String.valueOf(i))){ x[i]=x[i]-2;if(x[i]<=0) x[i]=0;b[i].setLocation(x[i],y[i]);}}}else if(e.getKeyCode( )==KeyEvent.VK_RIGHT){ for(int i=0;i<=39;i++){ if(s[i].equals(String.valueOf(i))){ x[i]=x[i]+2;if(x[i]>=300) x[i]=300;b[i].setLocation(x[i],y[i]);}}}}public void keyReleased(KeyEvent e){ }public void actionPerformed(ActionEvent e){ for(int i=0;i<40;i++){ if(e.getSource( )==b[i]){ for(int j=0;j<=39;j++)s[j]=b[i].getLabel( );}}}}。
java拼图游戏报告
目录1 需求分析 (2)1.1功能需求 (2)1.2系统需求 (2)2游戏详细设计 (3)2.1 程序类主要功能介绍 (3)2.2 程序源代码 (3)1)Arg.java (3)2) ButtonClick.java (4)3) CardFrame.java (5)4) GameOver.java (7)5) Grades.java (8)6) Matrix.java (11)7) MenuFrame.java (12)8) point.java (18)9) Puzzle.java (19)10) ShowImage.java (22)11) Split.java (23)12)FileTest.java (24)13)MusicPlay.java (25)3测试过程 (27)1 需求分析1.1功能需求1)让玩家能够用鼠标控制进行菜单的选择2)玩家可以通过点击空白区域来移动有图方块3)给玩家提供暂停游戏的功能4)提供图片预览,方便玩家查看5)提供图片导入功能,是玩家可以用自己喜爱的图片进行游戏6)提供背景音乐功能,优化玩家的游戏氛围7)提供游戏记录功能,让玩家可以不断挑战自己的水平,激发游戏乐趣8)提供关卡难度选择,使得游戏适应人群更为广泛9)提供游戏帮助功能,帮助玩家更快适应游戏10)游戏成功后能给出提示1.2系统需求1)性能需求:实时性好,可靠性强2)设计约束:1.开发工具:jdk 6.0以上2.运行环境:windows xp以上3.满足所定义的各种需求2游戏详细设计2.1 程序类主要功能介绍该游戏程序中包括11个类。
包括:ButtonClick.class、CardFrame.class、GameOver.class、Grades.class、Matrix.class、MenuFrame.class、point.class、Puzzle.class、ShowImage.class、Split.class、FileTest.class、MusicPlay.class。
java课程设计拼图游戏
import java.awt.*;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.awt.image.BufferedImage;import javax.swing.*;public class Pintu extends JFrame implements KeyListener{PicPanel picPanel;JLabel statusText = new JLabel("");JLabel statusimg = new JLabel("yuantu");public static void main(String[] args){Image img = Toolkit.getDefaultToolkit().getImage("D:/tierui/jsp/Pintu/src/img/pintu.jpg");Pintu pintu1 = new Pintu(img);pintu1.setVisible(true);}public Pintu(Image img) throws HeadlessException{picPanel = new PicPanel(img, statusText,statusimg);this.setLayout(new BorderLayout());add(picPanel, BorderLayout.CENTER);add(statusText, BorderLayout.SOUTH);setTitle("拼图游戏");this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setSize(600, 400);Dimension size = Toolkit.getDefaultToolkit().getScreenSize();//获得屏幕的标尺int screenWidth = size.width;int screenHeight = size.height;int x = (screenWidth - this.getWidth())/2;int y = (screenHeight - this.getHeight())/2;this.setLocation(x, y);addKeyListener(this);}public void keyPressed(KeyEvent e){int nDirection = picPanel.DIRECTION_NONE;switch (e.getKeyCode()){case KeyEvent.VK_DOWN:nDirection = picPanel.DIRECTION_DOWN;break;case KeyEvent.VK_UP:nDirection = picPanel.DIRECTION_UP;break;case KeyEvent.VK_LEFT:nDirection = picPanel.DIRECTION_LEFT;break;case KeyEvent.VK_RIGHT:nDirection = picPanel.DIRECTION_RIGHT;break;case KeyEvent.VK_F1: // F1键按下,重新开始游戏picPanel.initData();repaint();return;case KeyEvent.VK_Y: // 显示原图if (picPanel.bOnShowAll)picPanel.bOnShowAll = false;elsepicPanel.bOnShowAll = true;repaint();return;default:return;}boolean bCanMove = picPanel.move(nDirection);if (bCanMove){picPanel.nStep++;repaint();}}public void keyReleased(KeyEvent e){}public void keyTyped(KeyEvent e){}}class PicPanel extends JPanel implements MouseListener, Runnable{ BufferedImage[] m_Image = new BufferedImage[9]; // 9个用来装入拼图的图片对象Image m_ImgAll; // 总的大图片int m_nImageNo[][] = new int[3][3]; // 标志现在各个拼图的排列情况final int NO_IMAGE = -1; // 此位置没有拼图final int IMAGE_WIDTH = 120; // 每张拼图的宽final int IMAGE_HEIGHT = 120; // 每张拼图的高final int DIRECTION_UP = 1;final int DIRECTION_DOWN = 2;final int DIRECTION_LEFT = 3;final int DIRECTION_RIGHT = 4;final int DIRECTION_NONE = -1;final int DELTAX = 120; // 标志提示信息区的宽度Thread thTimer; // 计时器线程int nTime = 0; // 已经玩过的时间,以秒为单位boolean bWantStartNewGame = false; // 游戏是否结束,是否需要开始新游戏int nStep = 0; // 已经走的步数int nScore = 0; // 玩家所得的分数int m_nNumOfImg = 0; // 拼图底图所使用的图片的个数String m_sImgName = null; // 记录拼图底图的名字boolean bOnShowAll = false; // 预览的开关JLabel statusText;JPanel panel=new JPanel();public PicPanel(Image img, JLabel statusText,JLabel statusimg){this.statusText = statusText;setBackground(Color.white);m_sImgName = "pintu.jpg";MediaTracker mediaTracker = new MediaTracker(this); // 建立一个监视器.MediaTracker 类是一个跟踪多种媒体对象状态的实用工具类try{// 装载总的大图片m_ImgAll = Toolkit.getDefaultToolkit().getImage("D:/tierui/jsp/Pintu/src/img/" + m_sImgName);mediaTracker.addImage(m_ImgAll, 1);//addImage方法-向此媒体跟踪器正在跟踪的图像列表添加一个图像。
拼图游戏代码
拼图游戏代码# 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拼图游戏完整代码
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; } }
手机拼图源码(java)
}
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课程设计-拼图游戏代码
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);}}。
java实现简单的拼图游戏
java实现简单的拼图游戏⽤Java来实现简单的拼图游戏,供⼤家参考,具体内容如下⾸先我们看⼀下这个拼图⼩游戏的效果图:创建⼀个名称为MedleyGame的类,该类继承了JFrame类;然后在该类中分别声明⼀个⾯板对象和⼀个按钮对象,⾯板对象⽤来添加拼图按钮,按钮对象为当前显⽰空⽩图⽚的按钮;最后为该类编写⼀个main()⽅法和⼀个构造⽅法MedleyGame(),并在构造⽅法中设置窗体的相关属性,如窗体的标题、显⽰位置、⼤⼩等。
java项⽬结构如下:具体java代码如下:package pac;import java.awt.BorderLayout;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.border.TitledBorder;public class MedleyGame extends JFrame{private JPanel centerPanel;// 拼图按钮⾯板private JButton emptyButton;// 空⽩按钮对象public static void main(String[] args) {try {MedleyGame frame = new MedleyGame();//创建本类的对象frame.setVisible(true);//设置窗体为可见}catch(Exception e) {e.printStackTrace();}}public MedleyGame() {super();// 继承JFrame类的构造⽅法setResizable(false);// 设置窗体⼤⼩不可改变setTitle("拼图游戏");// 设置窗体的标题setBounds(100, 100, 354, 435);// 设置窗体的显⽰位置及⼤⼩setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 设置关闭窗体时退出程序final JPanel topPanel = new JPanel();// 创建⾯板对象topPanel.setBorder(new TitledBorder(null, "", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null));// 为⾯板添加边框topPanel.setLayout(new BorderLayout());// 设置⾯板采⽤边界布局getContentPane().add(topPanel,BorderLayout.NORTH);// 将⾯板添加到窗体顶部final JLabel modelLabel = new JLabel();// 创建显⽰参考图⽚的标签对象modelLabel.setIcon(new ImageIcon("img/model.jpg"));// 设置标签显⽰的参考图⽚topPanel.add(modelLabel, BorderLayout.WEST);// 将标签添加到⾯板的左侧final JButton startButton = new JButton();// 创建“下⼀局”按钮对象startButton.setText("下⼀局");// 设置按钮的标签⽂本startButton.addActionListener(new StartButtonAction());// 为按钮添加监听器topPanel.add(startButton, BorderLayout.CENTER);// 将按钮添加到⾯板的中间centerPanel = new JPanel();// 创建拼图按钮⾯板对象centerPanel.setBorder(new TitledBorder(null, "",TitledBorder.DEFAULT_JUSTIFICATION,TitledBorder.DEFAULT_POSITION, null, null));// 为⾯板添加边框centerPanel.setLayout(new GridLayout(0, 3));// 设置拼图按钮⾯板采⽤3列的⽹格布局 getContentPane().add(centerPanel, BorderLayout.CENTER);// 将⾯板添加到窗体的中间 String[][] stochasticOrder = reorder();// 获得⽹格图⽚的随机摆放顺序for (int row = 0; row < 3; row++) {// 遍例⾏for (int col = 0; col < 3; col++) {// 遍例列final JButton button = new JButton();// 创建拼图按钮对象button.setName(row + "" + col);// 设置按钮的名称button.setIcon(new ImageIcon(stochasticOrder[row][col])); // 为拼图按钮设置图⽚if (stochasticOrder[row][col].equals("img/22.jpg")) // 判断是否为空⽩按钮emptyButton = button;button.addActionListener(new ImgButtonAction()); // 为拼图按钮添加监听器centerPanel.add(button);// 将按钮添加到拼图按钮⾯板中}}//}private String[][] reorder(){// ⽤来获取⽹格图⽚的随机摆放顺序String[][] exactnessOrder = new String[3][3];// ⽹格图⽚的正确摆放顺序for (int row = 0; row < 3; row++) {// 遍例⾏for (int col = 0; col < 3; col++) {// 遍例列exactnessOrder[row][col] = "img/" + row + col + ".jpg";}}String[][] stochasticOrder = new String[3][3];// ⽹格图⽚的随机摆放顺序for (int row = 0; row < 3; row++) {// 遍例⾏for (int col = 0; col < 3; col++) {// 遍例列while (stochasticOrder[row][col] == null) { // 随机摆放顺序的指定⽹格为空int r = (int) (Math.random() * 3);// 取随机⾏int c = (int) (Math.random() * 3);// 取随机列if (exactnessOrder[r][c] != null) { // 正确摆放顺序的指定⽹格不为空// 将位于正确摆放顺序的指定⽹格的图⽚摆放到位于随机摆放顺序的指定⽹格中stochasticOrder[row][col] = exactnessOrder[r][c];// 将位于正确顺序的指定⽹格设置为空exactnessOrder[r][c] = null;}}}}return stochasticOrder;}class ImgButtonAction implements ActionListener {// 拼图按钮监听器public void actionPerformed(ActionEvent e) {String emptyName = emptyButton.getName();// 获得空⽩按钮的名称char emptyRow = emptyName.charAt(0);// 获得空⽩按钮所在的⾏char emptyCol = emptyName.charAt(1);// 获得空⽩按钮所在的列JButton clickButton = (JButton) e.getSource();// 获得被点击按钮对象String clickName = clickButton.getName();// 获得被点击按钮的名称char clickRow = clickName.charAt(0);// 获得被点击按钮所在的⾏char clickCol = clickName.charAt(1);// 获得被点击按钮所在的列// 判断被点击按钮与空⽩按钮是否相临if (Math.abs(clickRow - emptyRow) + Math.abs(clickCol - emptyCol) == 1) {// 将被点击按钮的图⽚移动到空⽩按钮上emptyButton.setIcon(clickButton.getIcon());// 设置被点击的按钮显⽰空⽩图⽚clickButton.setIcon(new ImageIcon("img/22.jpg"));emptyButton = clickButton;// 将被点击的按钮设置为空⽩按钮}}}class StartButtonAction implements ActionListener {// 下⼀局按钮监听器public void actionPerformed(ActionEvent e) {String[][] stochasticOrder = reorder();// 获得⽹格图⽚的随机摆放顺序int i = 0;// 拼图按钮在拼图按钮⾯板中的索引for (int row = 0; row < 3; row++) {// 遍例⾏for (int col = 0; col < 3; col++) {// 遍例列JButton button = (JButton) centerPanel.getComponent(i++); // 获得位于指定索引的拼图按钮 button.setIcon(new ImageIcon(stochasticOrder[row][col])); // 为拼图按钮设置图⽚if (stochasticOrder[row][col].equals("img/22.jpg")) // 判断是否为空⽩按钮emptyButton = button;}}}}}到这⾥代码程序就写完了,我们来运⾏⼀下:按步骤保存然后运⾏⼀下:结果没问题,单击“下⼀局”会重新刷新游戏,图⽚会进⾏随机排布:到此,⼀个简简单单的拼图⼩游戏就实现了。
拼图游戏代码
import java.awt.*;import java.applet.*;import java.awt.event.* ;public class pintu extends Applet implements MouseListener,MouseMotionListener {private Image picture;private Graphics buffer;private Image pic[];private Image off_pic[];private Graphics off_buf[];private Image off_screen;private Graphics off_buffer;private Image off_drag;private Graphics off_drag_buf;private int map[][];private int ran[];private int width=0;private int height=0;private int lastx;private int lasty;private int last_downx;private int last_downy;private int stepx;private int stepy;private boolean choose;private boolean click[][];private boolean m_down;private boolean m_drag;private boolean not_redraw;private boolean able;Font font1,font2;//程序的初始化public void init(){resize(640,480);pic = new Image [3];off_pic = new Image[16];off_buf = new Graphics [16];map = new int [4][4];ran = new int [15];for(int a=0;a<16;a++)map[a/4][a%4] = a;for(int a=0;a<15;a++)ran[a]=a;click=new boolean [4][4];MediaTracker tracker= new MediaTracker (this);//要载入的图片pic[0]=getImage(getCodeBase(),"PICTURE0.JPG"); pic[1]=getImage(getCodeBase(),"PICTURE1.JPG"); pic[2]=getImage(getCodeBase(),"PICTURE2.GIF"); tracker.addImage (pic[0],0);tracker.addImage (pic[1],0);tracker.addImage (pic[2],0);try{tracker.waitForID (0);}catch(InterruptedException e){}//设置字体font1= new Font ("TimesRoman", Font.BOLD, 48); font2= new Font ("TimesRoman", Font.BOLD, 32); width=640;height=480;//初始化主界面initForm();//添加鼠标监听事件addMouseListener(this);addMouseMotionListener(this);}//面板初始化void initForm(){this.setBackground (Color.orange);if(off_drag==null){off_drag = createImage(width/4,height/4);off_drag_buf = off_drag.getGraphics ();}}public void paint(Graphics g){if(off_screen==null){off_screen = createImage(width,height);off_buffer=off_screen.getGraphics ();}if(able){off_buffer.setColor (Color.black );for(int a=0;a<4;a++)for(int b=0;b<4;b++){if(map[a][b]!=15)off_buffer.drawImage (off_pic[map[a][b]],b*width/4,a*height/4,this); if(map[a][b]==15)off_buffer.fillRect (b*width/4,a*height/4,width/4,height/4);for(int c=0;c<2;c++)off_buffer.drawRect (b*width/4+c,a*height/4+c,width/4-c,height/4-c); if(click[a][b]){off_buffer.setColor(Color.red);for(int d=0;d<2;d++)off_buffer.drawOval (b*width/4-d,a*height/4-d,width/4+d,height/4+d); off_buffer.setColor (Color.black );}}}else{off_buffer.setColor (Color.orange );off_buffer.fillRect (0,0,640,480);off_buffer.setFont (font1);off_buffer.setColor(Color.red );off_buffer.drawImage (pic[2],30,50,250,180,this);off_buffer.drawImage (pic[0],370,160,250,180,this);off_buffer.drawImage (pic[1],60,270,250,180,this);off_buffer.drawString ("Choose One!",320,100);}g.drawImage (off_screen,0,0,this);}public void repaint(){paint(this.getGraphics ());}//单击鼠标时产生的事件public void mouseClicked(MouseEvent evt){}//鼠标进入某个区域时产生的事件public void mouseEntered(MouseEvent evt){}//鼠标退出某个区域时产生的事件public void mouseExited(MouseEvent evt){}//移动鼠标时产生的事件public void mouseMoved(MouseEvent evt){if(!able){Point point;point=evt.getPoint();if(point.x >30 && point.x<280 && point.y>50 && point.y<230) {off_buffer.setColor (Color.orange );off_buffer.fillRect (0,0,640,480);off_buffer.setFont (font1);off_buffer.drawImage (pic[2],25,45,250,180,this);off_buffer.drawImage (pic[0],370,160,250,180,this);off_buffer.drawImage (pic[1],60,270,250,180,this);off_buffer.setColor(Color.black );off_buffer.fillRect (30,225,250,5);off_buffer.fillRect (275,50,5,176);off_buffer.setColor(Color.red );off_buffer.drawString ("picture 2!",320,100);this.getGraphics ().drawImage (off_screen,0,0,this); }else if(point.x >370 && point.x<620 && point.y>160 && point.y<340) {off_buffer.setColor (Color.orange );off_buffer.fillRect (0,0,640,480);off_buffer.setFont (font1);off_buffer.drawImage (pic[2],30,50,250,180,this);off_buffer.drawImage (pic[0],365,155,250,180,this);off_buffer.drawImage (pic[1],60,270,250,180,this);off_buffer.setColor(Color.black );off_buffer.fillRect (370,335,250,5);off_buffer.fillRect (615,160,5,175);off_buffer.setColor(Color.red );off_buffer.drawString ("picture 0!",320,100);this.getGraphics ().drawImage (off_screen,0,0,this);}else if(point.x >60 && point.x<310 && point.y>270 && point.y<450) {off_buffer.setColor (Color.orange );off_buffer.fillRect (0,0,640,480);off_buffer.setFont (font1);off_buffer.drawImage (pic[2],30,50,250,180,this);off_buffer.drawImage (pic[0],370,160,250,180,this);off_buffer.drawImage (pic[1],55,265,250,180,this);off_buffer.setColor(Color.black );off_buffer.fillRect (60,445,250,5);off_buffer.fillRect (305,270,5,175);off_buffer.setColor(Color.red );off_buffer.drawString ("picture 1!",320,100);this.getGraphics ().drawImage (off_screen,0,0,this); }else{repaint();}}}//拖动鼠标时产生的事件public void mouseDragged(MouseEvent evt){if(!able)return;if(m_down){Point point;Point temp;point=evt.getPoint();m_drag=true;repaint();Graphics david = this.getGraphics ();if(!not_redraw)off_drag_buf.drawImage (off_pic[map[last_downy][last_downx]],0,0,this); david.drawImage (off_drag,point.x+stepx,point.y+stepy,this);not_redraw=true;}}//按下鼠标时产生的事件public void mousePressed(MouseEvent evt){if(!able)return;Point point;Point temp;point=evt.getPoint();if(getarea(point) == point)return;else {temp=getarea(point);if(!m_down){if(map[temp.y][temp.x]==15)return;else{m_down=true;last_downx=temp.x;last_downy=temp.y;stepx=temp.x*160-point.x;stepy=temp.y*120-point.y;}}else if(m_down){m_down=false;}}}//放开鼠标时产生的事件public void mouseReleased(MouseEvent evt){if(able){if(m_drag){m_down=false;m_drag=false;not_redraw=false;Point point;Point temp;point=evt.getPoint();if(getarea(point) == point){ repaint();return;}else {temp=getarea(point);if(map[temp.y][temp.x]!=15){repaint();return;}else{if(Math.abs (last_downx-temp.x)==1 && last_downy-temp.y==0) {int david;david=map[last_downy][last_downx];map[last_downy][last_downx] =15;map[temp.y][temp.x]=david;if(wingame())able=false;repaint();return;}else if(last_downx-temp.x==0 && Math.abs (last_downy-temp.y)==1) {int david;david=map[last_downy][last_downx];map[last_downy][last_downx] =15;map[temp.y][temp.x]=david;if(wingame())able=false;repaint();return;}else{repaint(); return;}}}}}else{Point point;point=evt.getPoint();if(point.x >30 && point.x<280 && point.y>50 && point.y<230){able=true; initmap(2);}if(point.x >370 && point.x<620 && point.y>160 && point.y<340){able=true;initmap(0);}if(point.x >60 && point.x<310 && point.y>270 && point.y<450){able=true;initmap(1);}else return;}}//转换坐标public Point getarea(Point point){if(point.x>640 || point.y>480)return point;else return point = new Point (point.x/160,point.y/120);}//图片初始化void initmap(int stage){picture = createImage(width,height);buffer = picture.getGraphics ();buffer.drawImage (pic[stage],0,0,640,480,this);for(int a=0;a<15;a++){off_pic[a] = createImage(width/4,height/4);off_buf[a] = off_pic[a].getGraphics ();off_buf[a].drawImage (picture,0,0,width/4,height/4,(a%4)*width/4,(a/4)*height/4,(a%4+1)*width/4,(a/4+1)*height/4,this); }initgame();repaint();}//程序是否结束boolean wingame(){for(int a=0;a<4;a++)for(int b=0;b<4;b++){if(map[a][b]==a*4+b);else return false;}return true;}//游戏初始化void initgame(){for(int a=0;a<4;a++)for(int b=0;b<4;b++){if(!(a==3 && b==3)){map[a][b] = (int)(Math.random()*14); if(ran[map[a][b]]==-1){int temp=map[a][b];while(ran[temp]==-1){temp++;if(temp>14)temp=0;}map[a][b]=ran[temp];ran[temp]=-1;}else{ran[map[a][b]]=-1;}}else map[3][3] = 15;}}}//July/整理/05.23/。
Java小项目之拼图游戏
Java⼩项⽬之拼图游戏⾸先声明,代码是⾃创的,如有雷同,不胜荣幸!先谈谈思路: 1.设计界⾯。
2.素材的处理。
3.设计图⽚加载区域的图⽚加载处理类。
4.设计按钮组中的按钮初始化⽅法。
5.设计按钮组中的随机图⽚加载⽅法。
6.设计重置按钮⽅法。
7.设计按钮监听器。
8.设计判定胜利的条件的⽅法。
1.界⾯的设计: a.使⽤了Windows Builder插件,安装⽹页:WindoswBuilder - /windowbuilder/WB/integration/4.6/ b.页⾯的整体整体样式: ⼀个JFram中添加三个带标题的JPanel,将整个分割为游戏选项区域,图⽚展⽰区域和游戏区域。
每个区域都有各⾃的控件,其中需要注意的是图⽚展⽰区域放置了⼀个JLable来加载展⽰图⽚。
c.代码:我将源码放在了com.rookie.view包下,并且类名为GameView。
1package com.rookie.view;23import java.awt.EventQueue;45import javax.swing.JFrame;6import javax.swing.JPanel;7import javax.swing.border.EmptyBorder;8import javax.swing.JMenuBar;9import javax.swing.JMenu;10import javax.swing.JMenuItem;11import javax.swing.JOptionPane;121314import java.awt.event.ActionListener;15import java.util.Timer;16import java.util.TimerTask;17import java.awt.event.ActionEvent;18import javax.swing.GroupLayout;19import javax.swing.GroupLayout.Alignment;20import javax.swing.border.TitledBorder;2122import com.rookie.dao.PicloadDao;23import com.rookie.dao.GameDao;2425import javax.swing.UIManager;26import java.awt.Color;27import ponentPlacement;28import javax.swing.JLabel;29import javax.swing.JRadioButton;30import javax.swing.ButtonGroup;31import javax.swing.JComboBox;32import javax.swing.DefaultComboBoxModel;33import javax.swing.JTextField;34import javax.swing.JButton;35import javax.swing.SwingConstants;3637public class GamerView extends JFrame {3839/**40 *41*/42private static final long serialVersionUID = 1L;43private JPanel mainPanel;44private final ButtonGroup buttonGroup = new ButtonGroup();45private static JTextField textField_time;46private static JButton bt_GameBegin = null;47private static JLabel jl_loadImage = null;48private static JComboBox comboBox_SelectPic = null;49private static JRadioButton rb_simple = null;50private static JRadioButton rb_difficulty = null;51private static JPanel panel_beginGame = null;52private static GameDao gameChoseDao;53private static int time = 0;54private static Timer timer;55/**56 * Launch the application.57*/58public static void main(String[] args) {59 EventQueue.invokeLater(new Runnable() {60public void run() {61try {62 GamerView frame = new GamerView();63 frame.setVisible(true);64 } catch (Exception e) {65 e.printStackTrace();66 }67 }68 });69 }7071/**72 * Create the frame.73*/74public GamerView() {75 setResizable(false);76 setTitle("\u62FC\u56FE\u6E38\u620F(\u6D4B\u8BD5\u7248)");77 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);78 setBounds(100, 100, 710, 550);7980 JMenuBar menuBar = new JMenuBar();81 setJMenuBar(menuBar);8283 JMenu m_About = new JMenu("\u5173\u4E8E");84 menuBar.add(m_About);8586 JMenuItem mI_aboutMe = new JMenuItem("\u56E2\u961F\u4ECB\u7ECD");87 mI_aboutMe.addActionListener(new ActionListener() {88public void actionPerformed(ActionEvent e) {89 showAboutActionListener(e);90 }91 });92 m_About.add(mI_aboutMe);93 mainPanel = new JPanel();94 mainPanel.setBorder(new EmptyBorder(5, 5, 5, 5));95 setContentPane(mainPanel);9697 JPanel panel_checkGame = new JPanel();98 panel_checkGame.setBorder(new TitledBorder(null, "\u6E38\u620F\u9009\u9879\uFF1A", TitledBorder.CENTER, TitledBorder.TOP, null, Color.RED));99100 JPanel panel_loadPic = new JPanel();101 panel_loadPic.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "\u539F\u56FE\u52A0\u8F7D\uFF1A", TitledBorder.CENTER, TitledBorder.TOP, null, Color.RED)); 102 panel_loadPic.setToolTipText("");103104 panel_beginGame = new JPanel();105 panel_beginGame.setBorder(new TitledBorder(null, "\u6E38\u620F\u5F00\u59CB\uFF1A", TitledBorder.CENTER, TitledBorder.TOP, null, Color.RED));106 GroupLayout gl_mainPanel = new GroupLayout(mainPanel);107 gl_mainPanel.setHorizontalGroup(108 gl_mainPanel.createParallelGroup(Alignment.TRAILING)109 .addGroup(gl_mainPanel.createSequentialGroup()110 .addContainerGap()111 .addGroup(gl_mainPanel.createParallelGroup(Alignment.TRAILING)112 .addComponent(panel_checkGame, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 674, Short.MAX_VALUE)113 .addGroup(Alignment.LEADING, gl_mainPanel.createSequentialGroup()114 .addComponent(panel_loadPic, GroupLayout.PREFERRED_SIZE, 336, GroupLayout.PREFERRED_SIZE)115 .addPreferredGap(ComponentPlacement.UNRELATED)116 .addComponent(panel_beginGame, GroupLayout.PREFERRED_SIZE, 332, GroupLayout.PREFERRED_SIZE)))117 .addContainerGap())118 );119 gl_mainPanel.setVerticalGroup(120 gl_mainPanel.createParallelGroup(Alignment.LEADING)121 .addGroup(gl_mainPanel.createSequentialGroup()122 .addContainerGap()123 .addComponent(panel_checkGame, GroupLayout.PREFERRED_SIZE, 83, GroupLayout.PREFERRED_SIZE)124 .addPreferredGap(ComponentPlacement.UNRELATED)125 .addGroup(gl_mainPanel.createParallelGroup(Alignment.BASELINE)126 .addComponent(panel_loadPic, GroupLayout.DEFAULT_SIZE, 377, Short.MAX_VALUE)127 .addComponent(panel_beginGame, GroupLayout.DEFAULT_SIZE, 377, Short.MAX_VALUE))128 .addContainerGap())129 );130131 jl_loadImage = new JLabel("");132 jl_loadImage.setIcon(null);133 panel_loadPic.add(jl_loadImage);134135136137 GroupLayout gl_panel_beginGame = new GroupLayout(panel_beginGame);138 gl_panel_beginGame.setHorizontalGroup(139 gl_panel_beginGame.createParallelGroup(Alignment.LEADING)140 .addGap(0, 320, Short.MAX_VALUE)141 );142 gl_panel_beginGame.setVerticalGroup(143 gl_panel_beginGame.createParallelGroup(Alignment.LEADING)144 .addGap(0, 322, Short.MAX_VALUE)145 );146 panel_beginGame.setLayout(gl_panel_beginGame);147148 JLabel label = new JLabel("\u6E38\u620F\u96BE\u5EA6\uFF1A");149 label.setForeground(Color.BLUE);150151 rb_simple = new JRadioButton("\u7B80\u5355");152 buttonGroup.add(rb_simple);153154 rb_difficulty = new JRadioButton("\u56F0\u96BE");155 buttonGroup.add(rb_difficulty);156157 rb_simple.setSelected(true);158159 JLabel label_1 = new JLabel("\u56FE\u7247\u9009\u62E9\uFF1A");160 label_1.setForeground(Color.BLUE);161162 comboBox_SelectPic = new JComboBox();163 comboBox_SelectPic.setModel(new DefaultComboBoxModel(new String[] {"\u98CE\u666F", "\u7F8E\u5973", "\u8C6A\u8F66", "\u6E38\u620F"}));164 comboBox_SelectPic.setMaximumRowCount(5);165166 JLabel label_2 = new JLabel("\u6E38\u620F\u65F6\u95F4\uFF1A");167 label_2.setForeground(Color.BLUE);168169 textField_time = new JTextField();170 textField_time.setHorizontalAlignment(SwingConstants.RIGHT);171 textField_time.setText("0");172 textField_time.setEditable(false);173 textField_time.setColumns(10);174175 JLabel lblNewLabel = new JLabel("\u79D2");176 lblNewLabel.setForeground(Color.BLUE);177178 bt_GameBegin = new JButton("\u5F00\u59CB\u6E38\u620F");179 bt_GameBegin.addActionListener(new ActionListener() {180public void actionPerformed(ActionEvent eve) {181 buttonClickAction(eve);182 }183 });184 GroupLayout gl_panel_checkGame = new GroupLayout(panel_checkGame);185 gl_panel_checkGame.setHorizontalGroup(186 gl_panel_checkGame.createParallelGroup(Alignment.LEADING)187 .addGroup(gl_panel_checkGame.createSequentialGroup()188 .addContainerGap()189 .addComponent(label)190 .addGap(6)191 .addGroup(gl_panel_checkGame.createParallelGroup(Alignment.TRAILING)192 .addComponent(rb_difficulty)193 .addGroup(gl_panel_checkGame.createSequentialGroup()194 .addComponent(rb_simple)195 .addPreferredGap(ComponentPlacement.RELATED)))196 .addGap(18)197 .addComponent(label_1)198 .addPreferredGap(ComponentPlacement.UNRELATED)199 .addComponent(comboBox_SelectPic, GroupLayout.PREFERRED_SIZE, 69, GroupLayout.PREFERRED_SIZE)200 .addGap(32)201 .addComponent(label_2)202 .addPreferredGap(ComponentPlacement.UNRELATED)203 .addComponent(textField_time, GroupLayout.PREFERRED_SIZE, 41, GroupLayout.PREFERRED_SIZE)204 .addPreferredGap(ComponentPlacement.RELATED)205 .addComponent(lblNewLabel)206 .addGap(52)207 .addComponent(bt_GameBegin, GroupLayout.PREFERRED_SIZE, 93, GroupLayout.PREFERRED_SIZE)208 .addContainerGap(76, Short.MAX_VALUE))209 );210 gl_panel_checkGame.setVerticalGroup(211 gl_panel_checkGame.createParallelGroup(Alignment.LEADING)212 .addGroup(gl_panel_checkGame.createSequentialGroup()213 .addGroup(gl_panel_checkGame.createParallelGroup(Alignment.LEADING)214 .addGroup(gl_panel_checkGame.createSequentialGroup()215 .addComponent(rb_simple)216 .addPreferredGap(ComponentPlacement.RELATED, 7, Short.MAX_VALUE)217 .addComponent(rb_difficulty))218 .addGroup(gl_panel_checkGame.createSequentialGroup()219 .addContainerGap()220 .addGroup(gl_panel_checkGame.createParallelGroup(Alignment.BASELINE)221 .addComponent(label_1)222 .addComponent(comboBox_SelectPic, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) 223 .addComponent(textField_time, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)224 .addComponent(lblNewLabel)225 .addComponent(label_2)226 .addComponent(bt_GameBegin, GroupLayout.PREFERRED_SIZE, 38, GroupLayout.PREFERRED_SIZE)))227 .addGroup(gl_panel_checkGame.createSequentialGroup()228 .addGap(22)229 .addComponent(label)))230 .addContainerGap())231 );232 panel_checkGame.setLayout(gl_panel_checkGame);233 mainPanel.setLayout(gl_mainPanel);234 }235236private void showAboutActionListener(ActionEvent e) {237// TODO Auto-generated method stub238 JOptionPane.showMessageDialog(null, "QQ:523980553");239 }240241private void buttonClickAction(ActionEvent eve) {242// TODO Auto-generated method stub243//设置按钮标题244if( bt_GameBegin.getText().equals("开始游戏") ) {245 beginGame();246 timer = new Timer();247 timer.scheduleAtFixedRate(new MyTase(), 0, 900);248 }249else {250 resetGame();251252 }253254 }255256public static void beginGame() {257 bt_GameBegin.setText("重置游戏");258//获取ComBox选项259int picId = comboBox_SelectPic.getSelectedIndex();260//加载图⽚261 PicloadDao pic = new PicloadDao();262 pic.loadPic(picId, jl_loadImage);263//获取难易度264if(rb_simple.isSelected()) {265 gameChoseDao = new GameDao();266 gameChoseDao.initButton(panel_beginGame);267 gameChoseDao.randomLoadPic(picId);268269 }else if(rb_difficulty.isSelected()) {270271 }272 }273274public static void resetGame() {275 bt_GameBegin.setText("开始游戏");276 rb_simple.setSelected(true);277 comboBox_SelectPic.setSelectedIndex(0);278 textField_time.setText(""+0);279 jl_loadImage.setIcon(null);280 gameChoseDao.resetButton();281 time = 0;282 timer.cancel();283 }284285class MyTase extends TimerTask{286 @Override287public void run() {288// TODO Auto-generated method stub289 time ++;290 textField_time.setText("" + time);291if(time == 60) {292 JOptionPane.showMessageDialog(null, "挑战失败");293 resetGame();294 }295 }296 }297 }代码被分成了⼏部分:⼀部分是界⾯的初始化,这些都可以通过Windows builder来完成,但是从按下“开始游戏”的按钮后,之后的任务都需要⼿动写代码,例如事件的处理,开始游戏和重置游戏的⽅法书写,计时器的书写。
java拼图游戏代码(完整版)
Pintu.java(class)import java.awt.Color;import java.awt.FileDialog;import java.awt.Graphics;import java.awt.Image;import java.awt.Rectangle;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;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.JRadioButtonMenuItem;public class Pintu extends JFrame implements ActionListener{JMenuBar menubar=new JMenuBar(); //菜单条JMenu menu1=new JMenu("操作"); //菜单JMenu menu2=new JMenu("设置");JMenu menu3=new JMenu("帮助");//菜单选项JMenuItem jitem1=new JMenuItem("开始游戏");JMenuItem jitem2=new JMenuItem("退出游戏");JMenuItem jitem3=new JMenuItem("游戏图片");JMenu jitem4=new JMenu("难度设置");JMenuItem jitem5=new JMenuItem("关于我们");JRadioButtonMenuItem nandu1=new JRadioButtonMenuItem("3*3");//单选菜单JRadioButtonMenuItem nandu2=new JRadioButtonMenuItem("4*4");String filename="a.jpg"; //默认图片路径ImageIcon preimage=null; //预览图对象JButton prebtn=null; //预览图片放置控件int m=3,n=3; //默认设置为3*3的阵列int w=80,h=80; //默认小方格的高度与宽度int step=0; //拼图步数JLabel lstep=new JLabel("步数:0步");JLabel isover=new JLabel("状态:未开始");ImageIcon[] pic=null; //存放小方格图片JButton btn[][]=null; //小方格控件Rectangle p[][]=null; //小方格的位置与大小public void init(){this.setTitle("拼图游戏");this.setLayout(null);this.setBounds(400,100,300,480);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);isover.setBounds(100,50,100,30);lstep.setBounds(100,10,100,30);this.add(isover);this.add(lstep);//菜单显示this.setJMenuBar(menubar);menubar.add(menu1);menubar.add(menu2);menubar.add(menu3);menu1.add(jitem1);menu1.add(jitem2);menu2.add(jitem3);menu2.add(jitem4);menu3.add(jitem5);jitem4.add(nandu1);jitem4.add(nandu2);nandu1.setSelected(true);//设置单选默认值为3*3jitem2.addActionListener(this); //注册监听事件jitem3.addActionListener(this); //注册监听事件nandu1.addActionListener(this); //注册监听事件nandu2.addActionListener(this); //注册监听事件jitem1.addActionListener(this); //注册监听事件jitem5.addActionListener(this); //注册监听事件this.setVisible(true);this.setResizable(false);//不能更改窗体大小setpic();//图片分割必须放置窗体显示以后}//判断我们的图片是否拼图完整如果完成返回true 未完成返回false public boolean check(){boolean b=true;for(int i=n;i<(m+1)*n;i++){int x1=i/n,y1=i%n;if(btn[x1][y1].getIcon()!=null&&btn[x1][y1].getIcon()==pic[i-n]){}else{b=false;}}return b;}//图片的放置public void setpic(){isover.setText("状态:未开始");step=0;lstep.setText("步数:"+step+"步");w=280/m;h=280/n;Image[] a=splitImage(filename,1,1,100,100); //缩放预览图preimage=new ImageIcon(a[0]); //图片转换image=》IMageIconif(prebtn==null) //*如果存在,就不需要重新分配控件只需要更新图标prebtn=new JButton(preimage);//把图片设置为JButton的图标elseprebtn.setIcon(preimage);prebtn.setBounds(200,5,100,100);this.add(prebtn);//图片分割pic=new ImageIcon[m*n];//分配空间大小if(btn==null) //*如果存在,就不需要重新分配控件只需要更新图标btn=new JButton[m+1][n]; //分配控件实例化p=new Rectangle[m+1][n]; //坐标Image[] t=splitImage(filename,m,n,w,h);//图片分割m*n个每个高度与宽度为w,hfor(int i=0;i<(m+1)*n;i++){int x1=i/n,y1=i%n;//下标转换if(btn[x1][y1]==null) //*如果存在,就不需要重新实例化控件btn[x1][y1]=new JButton();//实例化每个控件btn[x1][y1].setBounds(y1*w+5,x1*h+50,w,h);//控件坐标btn[x1][y1].addActionListener(this);//添加事件this.add(btn[x1][y1]);}for(int i=1;i<n;i++){btn[0][i].removeActionListener(this);//第一行除了第一个以外,其他都不注册事件btn[0][i].setVisible(false); //第一行除了第一个以外,其他都不显示}int temp[]=randarray(m*n);for(int i=0;i<m*n;i++) //把图片放到方格内{pic[i]=new ImageIcon(t[i]); //图片转换image=》ImageIcon }for(int i=0;i<m*n;i++) //把图片放到方格内{btn[(i+n)/n][(i+n)%n].setIcon(pic[temp[i]]);//设置图标}btn[0][0].setBackground(Color.BLUE); //设置背景btn[0][0].setIcon(null);this.repaint(); //图片及时刷新}//图片方格随机产生一组随机序列数组,不能重复public int[] randarray(int n){int re[]=new int[n];for(int i=0;i<n;i++)re[i]=i;for(int i=1;i<n;i++){int t;int a=(int)(Math.random()*(n-1)+1);//-1 +1是为了第一个数不使用随机数t=re[i];re[i]=re[a];re[a]=t;}return re;}@Overridepublic void actionPerformed(ActionEvent e) {if(e.getSource()==jitem5)//关于{JOptionPane.showMessageDialog(this,"四川师范大学成都学院开发实验室\n2010年12月12日");return;}if(e.getSource()==nandu1)//难度选择{nandu1.setSelected(true);//更改单选菜单nandu2.setSelected(false);for(int i=0;i<(m+1)*n;i++){int x1=i/n,y1=i%n;//下标转换this.remove(btn[x1][y1]);//清除所有button控件}m=n=3;//重新设置难度btn=null;//释放btn对象setpic();return;}if(e.getSource()==nandu2){nandu2.setSelected(true);nandu1.setSelected(false);for(int i=0;i<(m+1)*n;i++){int x1=i/n,y1=i%n;//下标转换this.remove(btn[x1][y1]);//实例化每个控件}m=n=4;btn=null;setpic();return;}if(e.getSource()==jitem1)//重新开始{for(int j=0;j<(m+1)*n;j++){int x2=j/n,y2=j%n;//下标转换btn[x2][y2].removeActionListener(this);//实例化每个控件}setpic();return;}if(e.getSource()==jitem2){System.exit(0);}if(e.getSource()==jitem3){FileDialog df=new FileDialog(this,"图片选择",FileDialog.LOAD);df.setVisible(true);if(df.getFile()==null)return;filename=df.getDirectory()+df.getFile();//文件路径+文件名for(int j=0;j<(m+1)*n;j++){int x2=j/n,y2=j%n;//下标转换btn[x2][y2].removeActionListener(this);//实例化每个控件}setpic();return;}for(int i=0;i<(m+1)*n;i++)//循环所有控件{int x1=i/n,y1=i%n;//下标转换if(e.getSource()==btn[x1][y1])//如果点击了小方格{step++;lstep.setText("步数:"+step+"步");isover.setText("状态:已开始");//向上移动if(x1>0&&btn[x1-1][y1].isVisible()&&btn[x1-1][y1].getIcon()==null){btn[x1-1][y1].setIcon(btn[x1][y1].getIcon());//获取当前图标给上一个控件为图标btn[x1][y1].setIcon(null);//当前图标设置为空}//向下移动if(x1<m&&btn[x1+1][y1].isVisible()&&btn[x1+1][y1].getIcon()==null){btn[x1+1][y1].setIcon(btn[x1][y1].getIcon());//获取当前图标给下一个控件为图标btn[x1][y1].setIcon(null);//当前图标设置为空}//向左移动if(y1>0&&btn[x1][y1-1].isVisible()&&btn[x1][y1-1].getIcon()==null){btn[x1][y1-1].setIcon(btn[x1][y1].getIcon());//获取当前图标给左一个控件为图标btn[x1][y1].setIcon(null);//当前图标设置为空}//向右移动if(y1<n-1&&btn[x1][y1+1].isVisible()&&btn[x1][y1+1].getIcon()==null){btn[x1][y1+1].setIcon(btn[x1][y1].getIcon());//获取当前图标给右一个控件为图标btn[x1][y1].setIcon(null);//当前图标设置为空}btn[x1][y1].setBackground(Color.BLUE);if(check()){isover.setText("状态:已完成");for(int j=0;j<(m+1)*n;j++){int x2=j/n,y2=j%n;//下标转换btn[x2][y2].removeActionListener(this);//完成以后清除所有的监听}}}}}// 图片分割方法public Image[] splitImage(String file, int rows, int cols) {Image t = new ImageIcon(file).getImage();int w = t.getWidth(this) / cols;int h = t.getHeight(this) / rows;return splitImage(t, rows, cols, w, h);}public Image[] splitImage(String file, int rows, int cols, int w, int h) {Image t = new ImageIcon(file).getImage();return splitImage(t, rows, cols, w, h);}public Image[] splitImage(Image t, int rows, int cols, int w, int h) {Image[] result = new Image[rows * cols];try {for (int i = 0; i < result.length; i++) {result[i] = createImage(w, h);Graphics g = result[i].getGraphics();g.translate((-i % cols) * w, (-i / cols) * h);g.drawImage(t, 0, 0, w * cols, rows * h, 0, 0,t.getWidth(this), t.getHeight(this), this);}} catch (Exception e) {}return result;}}Play.java(class)public class Play {/*** @param args*/public static void main(String[] args) {Pintu p= new Pintu();p.init();}}。
JAVA拼图游戏的核心代码
public void paint(Graphics g){ g.drawImage(im,0,0,BW-3,BH-3,BW*(ncol-1),BH*(nrow-1),BW*ncol,BH*nrow,this); } public void reSet(){ this.setLocation(BW*(col-1),BH*(row-1)); } class Mouse extends MouseAdapter{ @Override public void mousePressed(MouseEvent e) { Block b=(Block)e.getSource(); // b.setLocation(BW*(col-1),BH*(row)); if( p.map[row+1][col]==0){ b.setLocation(BW*(col-1),BH*row); p.map[row+1][col]=1; p.map[row][col]=0; row=row+1; } else if( p.map[row-1][col]==0){ b.setLocation(BW*(col-1),BH*(row-2)); p.map[row-1][col]=1; p.map[row][col]=0; row=row-1; } else if( p.map[row][col+1]==0){ b.setLocation(BW*col,BH*(row-1)); p.map[row][col+1]=1; p.map[row][col]=0; col=col+1; } else
一、PTFrame 类 public class PFrame extends Frame { Image im; PFrame(){ //im=Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("11.jpg")); GamePanel panel=new GamePanel(); this.setLocation(400,100); this.setSize(540,750); //this.add(b); this.add(panel); this.setVisible(true); this.addWindowListener(new WindowAdapter(){ @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); } public static void main(String[] args) { new PFrame(); } } 二、GamePanel 类的实现 public class GamePanel extends Panel { Block block[]=new Block[9]; //public int s=0; boolean win=false; public static final int HEIGHT=750; public static final int WIDTH=540; Random r=new Random(); int map[][]=new int [][]{ {1,1,1,1,1}, {1,1,1,1,1}, {1,1,1,1,1}, {1,1,1,1,1}, {1,1,1,1,1} }; GamePanel(){
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
// Cell.javapackage cn.itcast.picture.ui;import javax.swing.Icon;import javax.swing.JButton;/** 图片小方格类*/public class Cell extends JButton {//带有图片的小方格public Cell(Icon icon) {super(icon);//设置小方格大小this.setSize(150, 150);}//带有图片和文字的小方格public Cell(String text, Icon icon) {super(text, icon);//设置小方格大小this.setSize(150, 150);this.setHorizontalTextPosition(CENTER);//设置文字水平居中显示this.setVerticalTextPosition(CENTER);//设置文字垂直居中显示}//public void move(String direction) {switch (direction) {case "UP":this.setLocation(this.getBounds().x,this.getBounds().y-150);break;case "DOWN":this.setLocation(this.getBounds().x,this.getBounds().y+150);break;case "LEFT":this.setLocation(this.getBounds().x-150,this.getBounds().y);break;case "RIGHT":this.setLocation(this.getBounds().x+150,this.getBounds().y);break;default:break;}}}//PictureCanvas.javapackage cn.itcast.picture.ui;import java.awt.Rectangle;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import javax.swing.ImageIcon;import javax.swing.JOptionPane;import javax.swing.JPanel;/** 拼图类*/public class PictureCanvas extends JPanel implements MouseListener { //静态变量public static int pictureID = 1;//图片IDpublic static int stepNum = 0;//步数private Cell[] cell;private boolean hasAddActionListener = false;//表示是否为小方格添加了点击监听,有为trueprivate Rectangle nullCell;//构造方法public PictureCanvas() {initCanvas();}//初始化public void initCanvas(){//设置拼图区的位置this.setLayout(null);//帧布局//创建12个小方格,并添加到拼图区cell = new Cell[12];for(int i = 0;i < 4;i++){for(int j = 0;j < 3;j++){//加载图片int num = i*3+j;ImageIcon icon = new ImageIcon("picture/"+pictureID+"_"+(num+1)+".gif");//创建图片小方格cell[num] = new Cell(icon);//指定显示位置cell[num].setLocation(150*j+20, i*150+20);//把图片小方格添加到拼图区this.add(cell[num]);}}//删除第12个小方格this.remove(cell[11]);nullCell = new Rectangle(320, 470, 150, 150);hasAddActionListener = false;}//重新加载图片,并添加数字提示public void reloadPictureAddNumber() {for(int i = 0;i < 4;i++){for(int j = 0;j < 3;j++){int num = i*3+j;ImageIcon icon = new ImageIcon("picture/"+pictureID+"_"+(num+1)+".gif");cell[num].setIcon(icon);cell[num].setText(num+1+"");cell[num].setVerticalTextPosition(getY()/2);cell[num].setHorizontalTextPosition(getX()/2);}}}//重新加载图片,并清除数字提示public void reloadPictureClearNumber() {for(int i = 0;i < 4;i++){for(int j = 0;j < 3;j++){int num = i*3+j;ImageIcon icon = new ImageIcon("picture/"+pictureID+"_"+(num+1)+".gif");cell[num].setIcon(icon);cell[num].setText("");}}}//start 对小方格重新排序public void start() {//如果没有给小方格添加监听,则添加监听if(!hasAddActionListener){for(int i=0;i<11;i++){cell[i].addMouseListener(this);}hasAddActionListener=true;}//当第一个小方格离左上角比较近的话,进行空方格与就近方格的随机交换while(cell[0].getBounds().x<=170 && cell[0].getBounds().y<=170){ //获取空方格的位置int nullX = nullCell.getBounds().x;int nullY = nullCell.getBounds().y;//随机产生一个方向,进行空方格的移动互换//产生0-3之间的随机数,代表交换移动方向int direction = (int)(Math.random()*4);switch (direction){case 0://空方格向左交换移动,原左侧方格向右移动nullX -= 150;cellMove(nullX,nullY,"RIGHT");break;case 1://空方格向右交换移动,原右侧方格向左移动nullX += 150;cellMove(nullX, nullY, "LEFT");break;case 2://空方格向上交换移动,原上方方格向下移动nullY -= 150;cellMove(nullX, nullY, "DOWN");break;case 3://空方格向下交换移动,原下方方格向上移动nullY += 150;cellMove(nullX, nullY, "UP");break;}}}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;}}}@Overridepublic void mouseClicked(MouseEvent e) {}@Overridepublic void mousePressed(MouseEvent e) {//获取当前点击的小方格Cell button = (Cell)e.getSource();//获取所点击方格的x,yint clickX = button.getBounds().x;int clickY = button.getBounds().y;//获取空方格的x,yint nullX = nullCell.getBounds().x;int nullY = nullCell.getBounds().y;//比较如果满足条件,则互换位置if(clickX == nullX && clickY - nullY == 150){//点击为空方格下方方格button.move("UP");}else if (clickX == nullX && clickY - nullY == -150) {//点击为空方格上方方格button.move("DOWN");}else if (clickX - nullX == 150 && clickY == nullY) {//点击为空方格右方方格button.move("LEFT");}else if (clickX - nullX == -150 && clickY == nullY) {//点击为空方格左方方格button.move("RIGHT");}else {return;}//更新空方格位置nullCell.setLocation(clickX, clickY);//拼图区重新绘制this.repaint();//更新游戏移动步数stepNum++;PictureMainFrame.step.setText("步数:" + stepNum);//判断若完成,则提示完成if(isFinish()){JOptionPane.showMessageDialog(this, "恭喜你完成了,共用"+stepNum+"步。