java五子棋小游戏实验报告(附源代码)
- 格式:doc
- 大小:310.00 KB
- 文档页数:27
经典的五子棋java程序(源带码)直接复制粘贴importjava.awt.*;importjava.awt.event.*;importjava.applet.Applet;importjava.awt.Color;publicclassenzitextends Applet implements ActionListener,MouseListener,MouseMotionListener,ItemListener{intcolor_Qizi=0;//旗子的颜色标识0:白子1:黑子intintGame_Start=0;//游戏开始标志0未开始1游戏中intintGame_Body[][]=newint[16][16]; //设置棋盘棋子状态0 无子1 白子2 黑子Button b1=new Button("游戏开始");Button b2=new Button("重置游戏");Label lblWin=new Label(" ");Checkbox ckbHB[]=new Checkbox[2];CheckboxGroupckgHB=new CheckboxGroup();publicvoidinit(){setLayout(null);addMouseListener(this);add(b1);b1.setBounds(330,50,80,30);b1.addActionListener(this);add(b2);b2.setBounds(330,90,80,30);b2.addActionListener(this);ckbHB[0]=new Checkbox("白子先",ckgHB,false);ckbHB[0].setBounds(320,20,60,30);ckbHB[1]=new Checkbox("黑子先",ckgHB,false);ckbHB[1].setBounds(380,20,60,30);add(ckbHB[0]);add(ckbHB[1]);ckbHB[0].addItemListener(this);ckbHB[1].addItemListener(this);add(lblWin);lblWin.setBounds(330,130,80,30);Game_start_csh();}publicvoiditemStateChanged(ItemEvent e){if (ckbHB[0].getState()) //选择黑子先还是白子先{color_Qizi=0;}else{color_Qizi=1;}}publicvoidactionPerformed(ActionEvent e){Graphics g=getGraphics();if (e.getSource()==b1){Game_start();}else{Game_re();}}publicvoidmousePressed(MouseEvent e){}publicvoidmouseClicked(MouseEvent e){Graphics g=getGraphics();int x1,y1;x1=e.getX();y1=e.getY();if (e.getX()<20 || e.getX()>300 || e.getY()<20 || e.getY()>300) {return;}if (x1%20>10){x1+=20;}if(y1%20>10){y1+=20;}x1=x1/20*20;y1=y1/20*20;set_Qizi(x1,y1);}publicvoidmouseEntered(MouseEvent e){}publicvoidmouseExited(MouseEvent e){}publicvoidmouseReleased(MouseEvent e){}publicvoidmouseDragged(MouseEvent e){}publicvoidmouseMoved(MouseEvent e){}publicvoid paint(Graphics g){draw_qipan(g);}publicvoid set_Qizi(intx,int y) //落子{if (intGame_Start==0) //判断游戏未开始{return;}if (intGame_Body[x/20][y/20]!=0){return;}Graphics g=getGraphics();if (color_Qizi==1)//判断黑子还是白子{g.setColor(Color.black);color_Qizi=0;}else{g.setColor(Color.white);color_Qizi=1;}g.fillOval(x-10,y-10,20,20);intGame_Body[x/20][y/20]=color_Qizi+1;if (Game_win_1(x/20,y/20)) //判断输赢{lblWin.setText(Get_qizi_color(color_Qizi)+"赢了!"); intGame_Start=0;}if (Game_win_2(x/20,y/20)) //判断输赢{lblWin.setText(Get_qizi_color(color_Qizi)+"赢了!"); intGame_Start=0;}if (Game_win_3(x/20,y/20)) //判断输赢{lblWin.setText(Get_qizi_color(color_Qizi)+"赢了!"); intGame_Start=0;}if (Game_win_4(x/20,y/20)) //判断输赢{lblWin.setText(Get_qizi_color(color_Qizi)+"赢了!"); intGame_Start=0;}}public String Get_qizi_color(int x){if (x==0){return"黑子";}else{return"白子";}}publicvoid draw_qipan(Graphics G) //画棋盘15*15{G.setColor(Color.lightGray);G.fill3DRect(10,10,300,300,true);G.setColor(Color.black);for(inti=1;i<16;i++){G.drawLine(20,20*i,300,20*i);G.drawLine(20*i,20,20*i,300);}}publicvoid Game_start() //游戏开始{intGame_Start=1;Game_btn_enable(false);b2.setEnabled(true);}publicvoid Game_start_csh() //游戏开始初始化{intGame_Start=0;Game_btn_enable(true);b2.setEnabled(false);ckbHB[0].setState(true);for (inti=0;i<16 ;i++ ){for (int j=0;j<16 ;j++ ){intGame_Body[j]=0;}}lblWin.setText("");}publicvoid Game_re() //游戏重新开始{repaint();Game_start_csh();}publicvoid Game_btn_enable(boolean e) //设置组件状态{b1.setEnabled(e);b2.setEnabled(e);ckbHB[0].setEnabled(e);ckbHB[1].setEnabled(e);}publicboolean Game_win_1(intx,int y) //判断输赢横{int x1,y1,t=1;x1=x;y1=y;for (inti=1;i<5 ;i++ ){if (x1>15){break;}if (intGame_Body[x1+i][y1]==intGame_Body[x][y]) {t+=1;}else{break;}}for (inti=1;i<5 ;i++ ){if (x1<1){break;}if(intGame_Body[x1-i][y1]==intGame_Body[x][y]) {t+=1;}else{break;}}if (t>4){returntrue;}else{returnfalse;}}publicboolean Game_win_2(intx,int y) //判断输赢竖{int x1,y1,t=1;x1=x;y1=y;for (inti=1;i<5 ;i++ ){if (x1>15){break;}if (intGame_Body[x1][y1+i]==intGame_Body[x][y]){t+=1;}else{break;}}for (inti=1;i<5 ;i++ ){if (x1<1){break;}if(intGame_Body[x1][y1-i]==intGame_Body[x][y]) {t+=1;}else{break;}}if (t>4){returntrue;}else{returnfalse;}}publicboolean Game_win_3(intx,int y) //判断输赢左斜{int x1,y1,t=1;x1=x;y1=y;for (inti=1;i<5 ;i++ ){if (x1>15){break;}if (intGame_Body[x1+i][y1-i]==intGame_Body[x][y]) {t+=1;}else{break;}}for (inti=1;i<5 ;i++ ){if (x1<1){break;}if(intGame_Body[x1-i][y1+i]==intGame_Body[x][y]) {t+=1;}else{break;}}if (t>4){returntrue;}else{returnfalse;}}publicboolean Game_win_4(intx,int y) //判断输赢左斜{int x1,y1,t=1;x1=x;y1=y;for (inti=1;i<5 ;i++ ){if (x1>15){break;}if (intGame_Body[x1+i][y1+i]==intGame_Body[x][y]) {t+=1;}else{break;}}for (inti=1;i<5 ;i++ ){if (x1<1){break;}if(intGame_Body[x1-i][y1-i]==intGame_Body[x][y]) {t+=1;}else{break;}}if (t>4){returntrue;}else{returnfalse;}}}。
//Java编程:五子棋游戏源代码import java.awt.*;import java.awt.event.*;import java.applet.*;import javax.swing.*;import java.io.PrintStream;import javax.swing.JComponent;import javax.swing.JPanel;/**main方法创建了ChessFrame类的一个实例对象(cf),*并启动屏幕显示显示该实例对象。
**/public class FiveChessAppletDemo {public static void main(String args[]){ChessFrame cf = new ChessFrame();cf.show();}}/**类ChessFrame主要功能是创建五子棋游戏主窗体和菜单**/class ChessFrame extends JFrame implements ActionListener { private String[] strsize={"20x15","30x20","40x30"};private String[] strmode={"人机对弈","人人对弈"};public static boolean iscomputer=true,checkcomputer=true; private int width,height;private ChessModel cm;private MainPanel mp;//构造五子棋游戏的主窗体public ChessFrame() {this.setTitle("五子棋游戏");cm=new ChessModel(1);mp=new MainPanel(cm);Container con=this.getContentPane();con.add(mp,"Center");this.setResizable(false);this.addWindowListener(new ChessWindowEvent());MapSize(20,15);JMenuBar mbar = new JMenuBar();this.setJMenuBar(mbar);JMenu gameMenu = new JMenu("游戏");mbar.add(makeMenu(gameMenu, new Object[] {"开局", "棋盘","模式", null, "退出"}, this));JMenu lookMenu =new JMenu("视图");mbar.add(makeMenu(lookMenu,new Object[] {"Metal","Motif","Windows"},this));JMenu helpMenu = new JMenu("帮助");mbar.add(makeMenu(helpMenu, new Object[] {"关于"}, this));}//构造五子棋游戏的主菜单public JMenu makeMenu(Object parent, Object items[], Object target){ JMenu m = null;if(parent instanceof JMenu)m = (JMenu)parent;else if(parent instanceof String)m = new JMenu((String)parent);elsereturn null;for(int i = 0; i < items.length; i++)if(items[i] == null)m.addSeparator();else if(items[i] == "棋盘"){JMenu jm = new JMenu("棋盘");ButtonGroup group=new ButtonGroup();JRadioButtonMenuItem rmenu;for (int j=0;j<strsize.length;j++){rmenu=makeRadioButtonMenuItem(strsize[j],target);if (j==0)rmenu.setSelected(true);jm.add(rmenu);group.add(rmenu);}m.add(jm);}else if(items[i] == "模式"){JMenu jm = new JMenu("模式");ButtonGroup group=new ButtonGroup();JRadioButtonMenuItem rmenu;for (int h=0;h<strmode.length;h++){rmenu=makeRadioButtonMenuItem(strmode[h],target);if(h==0)rmenu.setSelected(true);jm.add(rmenu);group.add(rmenu);}m.add(jm);}elsem.add(makeMenuItem(items[i], target));return m;}//构造五子棋游戏的菜单项public JMenuItem makeMenuItem(Object item, Object target){ JMenuItem r = null;if(item instanceof String)r = new JMenuItem((String)item);else if(item instanceof JMenuItem)r = (JMenuItem)item;elsereturn null;if(target instanceof ActionListener)r.addActionListener((ActionListener)target);return r;}//构造五子棋游戏的单选按钮式菜单项public JRadioButtonMenuItem makeRadioButtonMenuItem( Object item, Object target){JRadioButtonMenuItem r = null;if(item instanceof String)r = new JRadioButtonMenuItem((String)item);else if(item instanceof JRadioButtonMenuItem)r = (JRadioButtonMenuItem)item;elsereturn null;if(target instanceof ActionListener)r.addActionListener((ActionListener)target);return r;}public void MapSize(int w,int h){setSize(w * 20+50 , h * 20+100 );if(this.checkcomputer)this.iscomputer=true;elsethis.iscomputer=false;mp.setModel(cm);mp.repaint();}public boolean getiscomputer(){return this.iscomputer;}public void restart(){int modeChess = cm.getModeChess();if(modeChess <= 3 && modeChess >= 1){cm = new ChessModel(modeChess);MapSize(cm.getWidth(),cm.getHeight());}else{System.out.println("\u81EA\u5B9A\u4E49");}}public void actionPerformed(ActionEvent e){String arg=e.getActionCommand();try{if (arg.equals("Windows"))UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");else if(arg.equals("Motif"))UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");elseUIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel" ); SwingUtilities.updateComponentTreeUI(this);}catch(Exception ee){}if(arg.equals("20x15")){this.width=20;this.height=15;cm=new ChessModel(1);MapSize(this.width,this.height);SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("30x20")){this.width=30;this.height=20;cm=new ChessModel(2);MapSize(this.width,this.height);SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("40x30")){this.width=40;this.height=30;cm=new ChessModel(3);MapSize(this.width,this.height);SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("人机对弈")){this.checkcomputer=true;this.iscomputer=true;cm=new ChessModel(cm.getModeChess());MapSize(cm.getWidth(),cm.getHeight());SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("人人对弈")){this.checkcomputer=false;this.iscomputer=false;cm=new ChessModel(cm.getModeChess());MapSize(cm.getWidth(),cm.getHeight());SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("开局")){restart();}if(arg.equals("关于"))JOptionPane.showMessageDialog(this, "五子棋游戏测试版本", "关于", 0);if(arg.equals("退出"))System.exit(0);}}/**类ChessModel实现了整个五子棋程序算法的核心*/class ChessModel {//棋盘的宽度、高度、棋盘的模式(如20×15)private int width,height,modeChess;//棋盘方格的横向、纵向坐标private int x=0,y=0;//棋盘方格的横向、纵向坐标所对应的棋子颜色,//数组arrMapShow只有3个值:1,2,3,-5,//其中1代表该棋盘方格上下的棋子为黑子,//2代表该棋盘方格上下的棋子为白子,//3代表为该棋盘方格上没有棋子,//-5代表该棋盘方格不能够下棋子private int[][] arrMapShow;//交换棋手的标识,棋盘方格上是否有棋子的标识符private boolean isOdd,isExist;public ChessModel() {}//该构造方法根据不同的棋盘模式(modeChess)来构建对应大小的棋盘public ChessModel(int modeChess){this.isOdd=true;if(modeChess == 1){PanelInit(20, 15, modeChess);}if(modeChess == 2){PanelInit(30, 20, modeChess);}if(modeChess == 3){PanelInit(40, 30, modeChess);}}//按照棋盘模式构建棋盘大小private void PanelInit(int width, int height, int modeChess){this.width = width;this.height = height;this.modeChess = modeChess;arrMapShow = new int[width+1][height+1];for(int i = 0; i <= width; i++){for(int j = 0; j <= height; j++){arrMapShow[i][j] = -5;}}}//获取是否交换棋手的标识符public boolean getisOdd(){return this.isOdd;}//设置交换棋手的标识符public void setisOdd(boolean isodd){if(isodd)this.isOdd=true;elsethis.isOdd=false;}//获取某棋盘方格是否有棋子的标识值public boolean getisExist(){return this.isExist;}//获取棋盘宽度public int getWidth(){return this.width;}//获取棋盘高度public int getHeight(){return this.height;}//获取棋盘模式public int getModeChess(){return this.modeChess;}//获取棋盘方格上棋子的信息public int[][] getarrMapShow(){return arrMapShow;}//判断下子的横向、纵向坐标是否越界private boolean badxy(int x, int y){if(x >= width+20 || x < 0)return true;return y >= height+20 || y < 0;}//计算棋盘上某一方格上八个方向棋子的最大值,//这八个方向分别是:左、右、上、下、左上、左下、右上、右下public boolean chessExist(int i,int j){if(this.arrMapShow[i][j]==1 || this.arrMapShow[i][j]==2)return true;return false;}//判断该坐标位置是否可下棋子public void readyplay(int x,int y){if(badxy(x,y))return;if (chessExist(x,y))return;this.arrMapShow[x][y]=3;}//在该坐标位置下棋子public void play(int x,int y){if(badxy(x,y))return;if(chessExist(x,y)){this.isExist=true;return;}elsethis.isExist=false;if(getisOdd()){setisOdd(false);this.arrMapShow[x][y]=1;}else{setisOdd(true);this.arrMapShow[x][y]=2;}}//计算机走棋/**说明:用穷举法判断每一个坐标点的四个方向的的最大棋子数,*最后得出棋子数最大值的坐标,下子**/public void computerDo(int width,int height){int max_black,max_white,max_temp,max=0;setisOdd(true);System.out.println("计算机走棋...");for(int i = 0; i <= width; i++){for(int j = 0; j <= height; j++){if(!chessExist(i,j)){//算法判断是否下子max_white=checkMax(i,j,2);//判断白子的最大值max_black=checkMax(i,j,1);//判断黑子的最大值max_temp=Math.max(max_white,max_black);if(max_temp>max){max=max_temp;this.x=i;this.y=j;}}}}setX(this.x);setY(this.y);this.arrMapShow[this.x][this.y]=2;}//记录电脑下子后的横向坐标public void setX(int x){this.x=x;}//记录电脑下子后的纵向坐标public void setY(int y){this.y=y;}//获取电脑下子的横向坐标public int getX(){return this.x;}//获取电脑下子的纵向坐标public int getY(){return this.y;}//计算棋盘上某一方格上八个方向棋子的最大值,//这八个方向分别是:左、右、上、下、左上、左下、右上、右下public int checkMax(int x, int y,int black_or_white){int num=0,max_num,max_temp=0;int x_temp=x,y_temp=y;int x_temp1=x_temp,y_temp1=y_temp;//judge rightfor(int i=1;i<5;i++){x_temp1+=1;if(x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}//judge leftx_temp1=x_temp;for(int i=1;i<5;i++){x_temp1-=1;if(x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}if(num<5)max_temp=num;//judge upx_temp1=x_temp;y_temp1=y_temp;num=0;for(int i=1;i<5;i++){y_temp1-=1;if(y_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}//judge downy_temp1=y_temp;for(int i=1;i<5;i++){y_temp1+=1;if(y_temp1>this.height)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}if(num>max_temp&&num<5)max_temp=num;//judge left_upx_temp1=x_temp;y_temp1=y_temp;num=0;for(int i=1;i<5;i++){x_temp1-=1;y_temp1-=1;if(y_temp1<0 || x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}//judge right_downx_temp1=x_temp;y_temp1=y_temp;for(int i=1;i<5;i++){x_temp1+=1;y_temp1+=1;if(y_temp1>this.height || x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}if(num>max_temp&&num<5)max_temp=num;//judge right_upx_temp1=x_temp;y_temp1=y_temp;num=0;for(int i=1;i<5;i++){x_temp1+=1;y_temp1-=1;if(y_temp1<0 || x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}//judge left_downx_temp1=x_temp;y_temp1=y_temp;for(int i=1;i<5;i++){x_temp1-=1;y_temp1+=1;if(y_temp1>this.height || x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}if(num>max_temp&&num<5)max_temp=num;max_num=max_temp;return max_num;}//判断胜负public boolean judgeSuccess(int x,int y,boolean isodd){ int num=1;int arrvalue;int x_temp=x,y_temp=y;if(isodd)arrvalue=2;elsearrvalue=1;int x_temp1=x_temp,y_temp1=y_temp;//判断右边for(int i=1;i<6;i++){x_temp1+=1;if(x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue)num++;elsebreak;}//判断左边x_temp1=x_temp;for(int i=1;i<6;i++){if(x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}if(num==5)return true;//判断上方x_temp1=x_temp;y_temp1=y_temp;num=1;for(int i=1;i<6;i++){y_temp1-=1;if(y_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}//判断下方y_temp1=y_temp;for(int i=1;i<6;i++){y_temp1+=1;if(y_temp1>this.height)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}if(num==5)return true;//判断左上x_temp1=x_temp;y_temp1=y_temp;num=1;for(int i=1;i<6;i++){x_temp1-=1;if(y_temp1<0 || x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}//判断右下x_temp1=x_temp;y_temp1=y_temp;for(int i=1;i<6;i++){x_temp1+=1;y_temp1+=1;if(y_temp1>this.height || x_temp1>this.width) break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}if(num==5)return true;//判断右上x_temp1=x_temp;y_temp1=y_temp;num=1;for(int i=1;i<6;i++){x_temp1+=1;y_temp1-=1;if(y_temp1<0 || x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}//判断左下x_temp1=x_temp;y_temp1=y_temp;for(int i=1;i<6;i++){x_temp1-=1;y_temp1+=1;if(y_temp1>this.height || x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue)num++;elsebreak;}if(num==5)return true;return false;}//赢棋后的提示public void showSuccess(JPanel jp){JOptionPane.showMessageDialog(jp,"你赢了,好厉害!","win",RMATION_MESSAGE);}//输棋后的提示public void showDefeat(JPanel jp){JOptionPane.showMessageDialog(jp,"你输了,请重新开始!","lost",RMATION_MESSAGE);}}/**类MainPanel主要完成如下功能:*1、构建一个面板,在该面板上画上棋盘;*2、处理在该棋盘上的鼠标事件(如鼠标左键点击、鼠标右键点击、鼠标拖动等)**/class MainPanel extends JPanelimplements MouseListener,MouseMotionListener{private int width,height;//棋盘的宽度和高度private ChessModel cm;//根据棋盘模式设定面板的大小MainPanel(ChessModel mm){cm=mm;width=cm.getWidth();height=cm.getHeight();addMouseListener(this);}//根据棋盘模式设定棋盘的宽度和高度public void setModel(ChessModel mm){cm = mm;width = cm.getWidth();height = cm.getHeight();}//根据坐标计算出棋盘方格棋子的信息(如白子还是黑子),//然后调用draw方法在棋盘上画出相应的棋子public void paintComponent(Graphics g){super.paintComponent(g);for(int j = 0; j <= height; j++){for(int i = 0; i <= width; i++){int v = cm.getarrMapShow()[i][j];draw(g, i, j, v);}}}//根据提供的棋子信息(颜色、坐标)画棋子public void draw(Graphics g, int i, int j, int v){int x = 20 * i+20;int y = 20 * j+20;//画棋盘if(i!=width && j!=height){g.setColor(Color.white);g.drawRect(x,y,20,20);}//画黑色棋子if(v == 1 ){g.setColor(Color.gray);g.drawOval(x-8,y-8,16,16);g.setColor(Color.black);g.fillOval(x-8,y-8,16,16);}//画白色棋子if(v == 2 ){g.setColor(Color.gray);g.drawOval(x-8,y-8,16,16);g.setColor(Color.white);g.fillOval(x-8,y-8,16,16);}if(v ==3){g.setColor(Color.cyan);g.drawOval(x-8,y-8,16,16);}}//响应鼠标的点击事件,根据鼠标的点击来下棋,//根据下棋判断胜负等public void mousePressed(MouseEvent evt){int x = (evt.getX()-10) / 20;int y = (evt.getY()-10) / 20;System.out.println(x+" "+y);if (evt.getModifiers()==MouseEvent.BUTTON1_MASK){cm.play(x,y);System.out.println(cm.getisOdd()+" "+cm.getarrMapShow()[x][y]);repaint();if(cm.judgeSuccess(x,y,cm.getisOdd())){cm.showSuccess(this);evt.consume();ChessFrame.iscomputer=false;}//判断是否为人机对弈if(ChessFrame.iscomputer&&!cm.getisExist()){puterDo(cm.getWidth(),cm.getHeight());repaint();if(cm.judgeSuccess(cm.getX(),cm.getY(),cm.getisOdd())){cm.showDefeat(this);evt.consume();}}}}public void mouseClicked(MouseEvent evt){}public void mouseReleased(MouseEvent evt){}public void mouseEntered(MouseEvent mouseevt){}public void mouseExited(MouseEvent mouseevent){}public void mouseDragged(MouseEvent evt){}//响应鼠标的拖动事件public void mouseMoved(MouseEvent moveevt){int x = (moveevt.getX()-10) / 20;int y = (moveevt.getY()-10) / 20;cm.readyplay(x,y);repaint();}}class ChessWindowEvent extends WindowAdapter{ public void windowClosing(WindowEvent e){ System.exit(0);}ChessWindowEvent(){}}。
五子棋JAVA实验报告目录五子棋JA V A实验报告 (1)一、实验目的和要求 (2)二、五子棋的基本常识与原理 (2)三、五子棋的系统设计 (3)四、五子棋的实现与测试 (7)五、分析与总结 (10)六、附录 (12)一、实验目的和要求1、能够用编程语言实现一个简单的五子棋程序2、在实际系统中使用、实现人工智能的相关算法3、进一步加深对人工智能算法的理解二、五子棋的基本常识与原理1、五子棋的起源五子棋,是一种两人对弈的纯策略型棋类游戏,亦称“串珠”、“连五子”;是中国民间非常熟知的一个古老棋种。
相传,它起源于四千多年前的尧帝时期,比围棋的历史还要悠久。
亦有传说,五子棋最初流行于少数民族地区,以后渐渐演变成围棋并在炎黄子孙后代中遍及开来。
五子棋发展于日本,流行于欧美。
容易上手,老少皆宜,而且趣味横生,引人入胜;不仅能增强思维能力,提高智力,而且富含哲理,有助于修身养性。
传统五子棋的棋具与围棋相同,棋子分为黑白两色,棋盘为19X19,棋子放置于棋盘线交叉点上。
两人对局,各执一色,轮流下一子,先将横、竖或斜线的5个或5个以上同色棋子连成不间断的一排者为胜。
因为传统五子棋在落子后不能移动或拿掉,所以也可以用纸和笔来进行游戏。
2、五子棋的基本常识与任何一种竞技棋一样,五子棋的每一局棋也分为三个阶段:开局,中局和残局。
五子棋的开始阶段称为开局,或称布局。
其开局阶段是十分短暂的,大约在七着与十几着之间。
在这一阶段的争夺中,双方的布局,应对将对以后的胜负起着极为关键的作用。
在开局阶段取得的形势好坏,主动与被动,先手与后手的优劣程度,往往直接影响中局的战斗。
因此积极处理好开局和开局向中局的过渡十分重要。
五子棋是从一至五,逐渐布子,发展连系,同时运用限制和反限制的智慧,在连子的过程中为自己的棋子争得相对的主动权和优势,逐步扩展优势,或者从劣势转化为优势,击溃对方的防线,最后连五取胜或抓禁手取胜或迫使对方投子认负。
手机五子棋游戏的设计与实现专业::班级:学号:指导教师:J2ME(Java 2 Micro Edition)是近年来随着各种不同设备,尤其是移动通信设备的飞速发展而诞生的一项开发技术。
它因其“write once,run anywhere”的Java特性而提高了开发的效率。
随着手机性能的不断提高,手机休闲娱乐应用将成为PC休闲娱乐应用之后又一重要业务增长点。
棋类游戏规则单一,比较适合在手机等便携终端推广。
由于具有跨平台、易于移植、占用空间小的优势,J2ME成为移动应用开发平台的主流,并提供了很多用以支持移动应用软件的开发的API。
现将该技术用于这次的手机游戏开发,可以实现游戏的快速开发,不但便于查看游戏运行过程中存的占用量和程序的每一部分代码消耗了多少处理器时间,而且可以不断地优化代码,使代码具有高度的复用性、可扩展性、可维护性。
游戏的开发以J2ME为平台,利用Java技术,结合J2ME的MIDP技术,并对于程序设计思想,重要类、方法等展开讨论。
在对弈部分,分析设计走棋算法,选择合适的方式组织成代码,实现基本的人工智能。
过程中使用了J2ME中的CLDC/MIDP软件体系,主要运用了MID Profile的特定类的支持,来完成游戏的开发。
关键词:J2ME;CLDC;MIDPJ2ME is a kind of fast developing technology implemented on various devices especially mobile communication equipments. It improves the efficiency of the development process because of its "write once, run anywhere" nature. The development trend of the entertainment market based on the cell phone is very obvious because the handset performance enhances unceasingly. The entertainment market based on the cell phone will to be the new important business growth point follow the PC entertainment market. As the rules of a single chess game, it is more suitable for mobile phones and other portable terminal extension.J2ME has been the preferred platform for development because of its platform independent and compatibility, and provides a lot of APIs to support the development of mobile application software. The technology for mobile game development, can achieve the rapid development of the game. It is not only easy to observe the memory consumption and processor consumed time during the operation of the game, but also can optimize the code, so that the code has a high degree of reusability, scalability, maintainability.The game has designed by J2ME, the Java technology and the MIDP technology. I studied the procedure thought, the important class and the method. In the playing chess part, I have analyzed the algorithm, choosed the appropriate way to organize the code and realized the basic artificial intelligence. On the other hand,I learned software system of CLDC/MIDP and the specific class of the MID Profile to complete the game development.Key words: J2ME;CLDC;MIDP目录1 概述 (5)1.1 课题研究背景 (5)1.2 课题研究意义 (5)2 开发技术背景 (6)2.1 JAVA语言概述 (6)2.2 J2ME简介 (6)2.3 移动信息设备简表 (6)3 系统分析及总体设计 (7)3.1 可行性分析 (7)3.2 需求分析 (8)3.3 系统概要设计 (8)4 系统详细设计 (9)4.1 界面设计 (9)4.1.1 图形的低级绘制 (10)4.1.2 用户按键设计 (10)4.2 走棋算法 (11)4.3 胜负判断 (11)5 系统测试 (11)5.1 测试方案 (11)5.2 测试结果 (12)6总结 (14)基于J2ME的手机五子棋游戏的设计与实现1 概述1.1 课题研究背景五子棋是当前非常流行的一种棋。
目录第一章软件平台……………………………游戏设计思路…………………………第二章小游戏五子棋的开发过程………………第一节JAVA基础知识………………………第二节启动程序的分析……………………第三节游戏设计过程………………………第三章总结…………………………………………第四章参考文献……………………………………第五章附录…………………………………………第一章游戏设计思路:第二章第一节java程序基础知识本系统有4个程序每个程序都导入了不同的包和类运用了不同的所学知识。
不同的类和包提供的方法、类型等都不同,本程序还使用了继承。
以至使其能够完成不同的功能。
本节主要讲述本系统所使用的基础知识。
1、类的基础<1、类的定义JAVA中的类实质上是一种对象类型,它是对具有相同属性和相同行为对象的一种抽象。
类是java程序中最小的组成单位。
<2、Java中类定义的格式为:[类修饰符] class 类名[extends 基类] [implements 接口]{// 成员变量声明(Member variable declaration)// 成员方法声明(Member method declaration)}其中,class、extends和implements都是Java的关键字。
类修饰符、extends和implements是关于修饰符、继承和接口的内容。
2、继承继承性是面向对象程序设计语言的一个重要特征,通过继承可以实现代码的复用。
Java语言中,所有的类都是直接或间接的继承ng.object类而得到的。
被继承的类称为基类或父类,继承而的来的类成为子类。
子类继承基类的方法和属性,同时也可以修改基类的方法和属性,并增加自己新的属性和方法。
Java不支持多重继承。
即一个子类不能拥有两个或以上的父类。
3、包<1、包的定义在Java中,把相关的代码组织到一起,称为“包”。
包市一种将相关类、接口或其他包组织起来的集合体,目的是为了将包含类代码的文件组织起来,易于查找和使用。
Java课程设计说明书----五子棋小游戏院系; 管理学院专业班级: 信管151学生学号: 201500705009学生姓名: 雷晓指导教师: 伍良启日期2017.01.05成绩:指导老师签名:批改日期:目录 (1)课程设计的目的 (5)课程设计思路 (5)(1)棋盘界面设计 (5)(2)算法设计 (6)(3)五子棋规则 (6)程序流程图 (7)程序的设计方法 (8)程序中主要方法的说明 (8)程序中类及成员变量的说明 (9)主要成员变量(属性) (9)java源文件及其功能 (10)五子棋游戏中的注册监听 (10)游戏整体设计 (11)(1)五子棋的游戏主界面 (11)(2)机器人部分的设计 (11)(3)五子棋面板的设计 (12)设计结果与分析 (12)设计体会 (13)参考文献 (15)附录:程序源代码 (15)课程设计的目的学习任何知识得目的都是要将它运用到实践中去,所以我们要运用已有的知识,独立得将这个课程设计完成,只有这样,我们才能将知识变成本领,变成属于自己得东西,通过一个学习得学习,我们已经有可一定得Java基础,现在我们就要利用这些基础,来完成课程设计。
这次课程设计我主要研究了利用已学的Java知识编辑一个五子棋小游戏。
通过此次课程设计,来巩固所学Java语言基本知识,增进Java语言编辑基本功,掌握JDK、JCreator等开发工具的运用,拓宽常用类库的应用。
课程设计思路(1)棋盘界面设计在对棋盘界面设计方面要考虑简洁友好,符合游戏者需求。
棋子的设计方面系统中设置了两种棋子颜色,yellow或者red,游戏者可自行选择。
棋子怎样画出来,怎样使棋子按我们所想的方式来绘制出来是设计的主要难题。
运行时要求当每次点击鼠标的时候就在点击鼠标的地方画一个棋子,所以得定义一个棋子的类使点击鼠标时系统把棋子绘制出来。
这样主界面里的棋子就确定了,而且也确定了几个所需要的类。
可以先定义好这些类了。
实习报告课程名称信息系统认知实习实习题目java五子棋专业班级学号学生姓名实习成绩指导教师2010年1月前言摘要五子棋作为一个棋类竞技运动,在民间十分流行,为了熟悉五子棋规则及技巧,以及研究简单的人工智能,决定用Java开发五子棋游戏。
主要完成了人机对战和玩家之间联网对战2个功能。
网络连接部分为Socket编程应用,客户端和服务器端的交互用Class Message定义,有很好的可扩展性,客户端负责界面维护和收集用户输入的信息,及错误处理。
服务器维护在线用户的基本信息和任意两个对战用户的棋盘信息,动态维护用户列表。
在人机对弈中通过深度搜索和估值模块,来提高电脑棋手的智能。
分析估值模块中的影响精准性的几个要素,以及提出若干提高精准性的办法,以及对它们搜索的节点数进行比较,在这些算法的基础上分析一些提高电脑AI方案,如递归算法、电脑学习等。
算法的研究有助于理解程序结构,增强逻辑思维能力,在其他人工智能方面也有很大的参考作用。
1引言1.1课题背景五子棋是起源于中国古代的传统黑白棋种之一。
现代五子棋日文称之为连珠,英译为Renju,英文称之为Gobang或FIR(Five in a Row 的缩写),亦有连五子、五子连、串珠、五目、五目碰、五格等多种称谓。
五子棋起源于古代中国,发展于日本,风靡于欧洲。
对于它与围棋的关系有两种说法,一说早于围棋,早在“尧造围棋”之前,民间就已有五子棋游戏;一说源于围棋,是围棋发展的一个分支。
在中国的文化里,倍受人们的青睐。
本世纪初五子棋传入欧洲并迅速风靡全欧。
通过一系列的变化,使五子棋这一简单的游戏复杂化、规范化,而最终成为今天的职业连珠五子棋,同时也成为一种国际比赛棋。
Java语言是当今最为流行的程序设计语言之一作为一门非常优秀和极为健壮的编程语言,它同时具有的面向对象,与平台无关,分布式应用,安全,稳定和多线程等优良的特征,使用Java语言,不仅可以开发出功能强大的大型应用程序,而且Java语言本身突出的跨平台的特性也使得它特别适合于Internet上的应用开发,可以这样说,Java的出现使得所开发的应用程序“一次编写,处处可用”的实现成为了可能。
本人学会的一个五子棋网络版和单机版游戏,有老师指导完成,详细的解释和代码都在下面,希望可以帮助到大家!1.客户端连接新建个gobangClient类package gobang;public class gobangClient {public static void main(String[] args) throws Exception { new ChessBoard("localhost",8866);}}2.服务端连接新建个gobangServer类package gobang;public class gobangServer {public static void main(String[] args) throws Exception { new ChessBoard(8866);}}3.源代码,有详细解释package gobang;import java.awt.BorderLayout;import java.awt.Container;import java.awt.Dimension;import java.awt.FlowLayout;import java.awt.Toolkit;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.awt.image.BufferedImage;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.PrintWriter;import .ServerSocket;import .Socket;import java.util.ArrayList;import java.awt.Graphics;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JOptionPane;import javax.swing.JPanel;public class ChessBoard extends JFrame{private boolean myPlay=false;//(默认是false)是否轮到我落子private JButton button1 =new JButton("开始");private JButton button2 =new JButton("悔棋");private JPanel p1 = new JPanel();private PicPane pp = null;private int side=1;//1表示黑private int n=0;//记录点击开始的次数public static final int SIZE=15;public static int[][]board=new int[SIZE][SIZE];//用来保存棋盘上棋子状态//1为黑,2为白,0为无public static final int BLACK=1;public static final int WHITE=-1;private NetService service;private static ArrayList<String> list =new ArrayList<String>(); //保存了下棋的步骤private boolean end=true;//true表示游戏已经结束private int currentColor=1;//服务端的构造器public ChessBoard(int port) throws Exception{//调用本类的无参构造树this();//构造器调用规则:1,只能调用本类或父类的构造器2. 调用构造器的代码写在新构造器的第一行3.构造器的调用只能使用this(本类)或者(父类) //将按钮设置能无效的button1.setEnabled(false);button2.setEnabled(false);//3.创建ServerSocket对象ServerSocket ss=new ServerSocket(port);//4.等待连接Socket s=ss.accept();//5.连接成功后创建一个线程来处理请求service=new NetService(s);service.start();//6.将按钮设置成有效的button1.setEnabled(true);button2.setEnabled(true);}//客户端的构造器public ChessBoard(String ip,int port) throws Exception{ //调用本类无参构造器this();//连接服务器Socket s=new Socket(ip,port);//初始化服务类service=new NetService(s);service.start();}public ChessBoard() throws IOException{Container c = this.getContentPane();c.setLayout(new BorderLayout());pp = new PicPane();BorderLayout bl = new BorderLayout();c.setLayout(bl);FlowLayout fl = new FlowLayout();p1.setLayout(fl);p1.add(button1);p1.add(button2);c.add(p1,BorderLayout.NORTH);c.add(pp,BorderLayout.CENTER);setSize(pp.getWidth()+6,pp.getHeight()+65);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setResizable(false);setVisible(true);button1.addActionListener(new SomeListener());button2.addActionListener(new button2Listener());}class SomeListener implements ActionListener{public void actionPerformed(ActionEvent e){// button2.setVisible(true);// if(n==0)// {// JOptionPane.showMessageDialog(// ChessBoard.this, "开始游戏啦!",// "提示",RMATION_MESSAGE);// }// else// {// JOptionPane.showMessageDialog(// ChessBoard.this, "确定要重新开始?",// "提示",RMATION_MESSAGE); // }// board=new int[15][15];// //调用重绘// pp.repaint();// end=false;// n++;start();}}private void start(){netStart();localStart();myPlay=true;//谁先点了开始按钮,谁先开始}private void localStart(){//重新初始化棋盘board=new int[SIZE][SIZE];//重新设置当前颜色currentColor=BLACK;//清空下棋步骤list=new ArrayList<String>();//重绘棋盘pp.repaint();//重新设置使下期没有结束end=false;}private void netStart(){service.send("start");}class button2Listener implements ActionListener{public void actionPerformed(ActionEvent e){back();// if(end==true)// {// JOptionPane.showMessageDialog(// ChessBoard.this, "人家都赢了你不能悔棋啦!", // "提示",RMATION_MESSAGE); // return;// }// int length = list.size();// if(list.size()<0)// {return;}// String str1 = list.remove(list.size() - 1);// String[] str3s = str1.split(",");// String str31 = str3s[0];// String str32 = str3s[1];// int row = Integer.parseInt(str31);// int col = Integer.parseInt(str32);// board[row][col]=0;// pp.repaint();// side = (side==1?2:1);//同下// if(side==1)// side=2;// else// side=1;}}public void back(){netBack();localBack();myPlay=!myPlay;//经典啊boolean的好处啊,悔棋了还是我下棋}private void localBack(){//如果结束不能悔棋if(end){return;}//if(list.isEmpty()){return;}//String str1 = list.remove(list.size() - 1);String[] str3s = str1.split(",");String str31 = str3s[0];String str32 = str3s[1];int row = Integer.parseInt(str31);int col = Integer.parseInt(str32);board[row][col]=0;currentColor=-currentColor;//pp.repaint();//}private void netBack(){if(end){//节省时间return;}service.send("back");}public static void toCenter(JFrame frame){int width = frame.getWidth();int height = frame.getHeight();Toolkit tookie = Toolkit.getDefaultToolkit();Dimension dim = tookie.getScreenSize();int screenWidth = dim.width;int screenHeight = dim.height;frame.setLocation((screenWidth - width)/2,(screenHeight-height)/2);}class PicPane extends JPanel{private int width;private int height;private BufferedImage bImg;//棋盘private BufferedImage chessImg;//黑子private BufferedImage wImg;//白子public PicPane() throws IOException{InputStreamips =PicPane.class.getResourceAsStream("images/chessboard.jpg");bImg = javax.imageio.ImageIO.read(ips);ips =PicPane.class.getResourceAsStream("images/b.gif");chessImg = javax.imageio.ImageIO.read(ips);ips =PicPane.class.getResourceAsStream("images/w.gif");wImg = javax.imageio.ImageIO.read(ips);width = bImg.getWidth();height = bImg.getHeight();addMouseListener(new boardListener());}@Overridepublic void paint(Graphics g){super.paint(g);g.drawImage(bImg,0,0,null);//加上画棋子的代码//依据board数组中的数据for(int i=0;i<board.length;i++){for(int j=0;j<board[i].length;j++){if(board[i][j]==1){g.drawImage(chessImg,j*35+3,i*35+3,null);}else if(board[i][j]==-1){g.drawImage(wImg,j*35+3,i*35+3,null);}}}}public int getHeight(){return height;}public int getWidth(){return width;}class boardListener extends MouseAdapter//只对感兴趣的方法实现,不用借口全部实现{@Overridepublic void mouseClicked(MouseEvent ae){int x=ae.getX();int y=ae.getY();int row=(y-4)/35;int col=(x-4)/35;play(row,col);// //判断游戏的状态,游戏是否结束的逻辑// if(end)// {// return;// }// //获得点击的坐标// int x=e.getX();// int y=e.getY();// int row=y/35;// int col=x/35;// if(row>=15||col>=15)// {// return;// }// if(board[row][col]==0)// switch(side)// {// case 1:// {//e.getComponent().getGraphics().drawImage(chessImg,col*35+3,row *35+3,null);// board[row][col]=1;//记录棋子// side=2;//改为白方// list.add(row+","+col);// break;// }// case 2:// {//e.getComponent().getGraphics().drawImage(wImg,col*35+3,row*35+ 3,null);// board[row][col]=2;// side=1;//改为黑方// list.add(row+","+col);// break;//改为黑方// }// }// //判断输赢// if(isWin(row,col))// {// //如果赢了:// end=true;// //提示用户,谁赢了// JOptionPane.showMessageDialog(ChessBoard.this,// (side==1?"白方胜":"黑方胜"),"提示",RMATION_MESSAGE);// }//}}}private void play(int row,int col){if(!myPlay){//如果不是我落子,直接返回,什么也不做return;}netPlay(row,col);//使另一方的棋盘上落子localPlay(row,col);//在本地的棋盘上落子myPlay=false;}private void netPlay(int row, int col){ if(end){//只打开服务器,会报错的问题return;}service.send(row+","+col);}private void localPlay(int row, int col){if(end){return;}if(row>=SIZE||col>=SIZE||row<0||col<0){return;}if(board[row][col]!=0){return;}//保存棋子board[row][col]=currentColor;//保存下棋步骤list.add(row+","+col);//重绘棋盘pp.repaint();if(isWin(row,col)){end=true;JOptionPane.showMessageDialog(ChessBoard.this,((currentColor==BLACK?"黑方":"白方")+"胜!"),"提示",RMATION_MESSAGE);}currentColor=-currentColor;}private boolean isWin(int currRow,int currCol){ // 需要比较四个方向的棋子(是否同色)int color=board[currRow][currCol];int[][]directions={{1,0},{1,1},{0,1},{-1,1}};//从四个方向比较for(int i=0;i<directions.length;i++){//计数器int num=1;//控制正反的for(int j=-1;j<2;j+=2){//比较次数for(int k=1;k<5;k++){//获得相邻的棋子的坐标int row=currRow+j*k*directions[i][0];int col=currCol+j*k*directions[i][1];//有可能行和列越界if(row<0||row>=15||col<0||row>=15){break;}if(board[row][col]==color){num++;if(num==5){return true;}}elsebreak;}}return false;}class NetService extends Thread{Socket s;BufferedReader in;PrintWriter out;public NetService(Socket s){try {this.s=s;in=new BufferedReader(new InputStreamReader(s.getInputStream()));out=new PrintWriter(s.getOutputStream());} catch (IOException e) {e.printStackTrace();}}public void send(String message){out.println(message);out.flush(); //刷新缓冲区}public void run(){try {while(true){String command=in.readLine();if(command.equals("start")){localStart();myPlay=false;}else if(command.equals("back")){localBack();myPlay=!myPlay;}else{String[]arr=command.split(",");int row=Integer.parseInt(arr[0]);int col=Integer.parseInt(arr[1]);localPlay(row,col);myPlay=true;}}} catch (IOException e) {e.printStackTrace();}}}public static void main(String[] args) throws IOException {ChessBoard chessboard = new ChessBoard();toCenter(chessboard);}}。
五子棋一、程序功能介绍设计一个20*20的五子棋盘,由两个玩家交替下子,并且可以实现以下功能:1.鼠标点击横竖线交汇处落子2.通过落子使得五个黑子或者五个白子在一条横线、竖线或斜线上2.重新开始按钮刷新重新开始3. 检查是否实现了五子连珠4. 有一方五子连珠时提示结果5.结束按钮结束程序二、课程设计过程1.如图一:程序流程图2.程序功能设计(1)先写draw类,在类中先画出一个Jframe窗口体,在这个窗口体上增加重新开始,退出,和主棋盘按钮。
并且设置监听按钮的监听。
并在draw类中设置主函数启动程序。
(2)fivechess类实现程序的功能,定义wh_array二维数组表示棋盘。
定义wh_arr一维数组,将wh_array值通过从上往下转换成一维,可用于判断输赢。
定义paintComponent(Graphics g)绘图函数,将整个棋盘给画出。
3.程序中用的变量、方法、类等class fivechess extends JPanel{} //定义变量,落子监听,判断输赢int[][] wh_array = new int[20][20]; // 定义二维数组,表示棋子在棋盘的位置int[] wh_arr = new int[430]; // 定义一维数组,转换二维数组,判断是否连线public void mouseClicked(MouseEvent e) // 单击鼠标落子并且判断输赢public fivechess() {} // 鼠标操作protected void paintComponent(Graphics g) // 绘图函数public Dimension getPerferredSize() //返回期盼大小public class draw extends JFrame {} //添加按钮,设置监听,启动程序public draw() //绘制窗口,增加重新开始和退出按钮b.addActionListener() //重新开始按钮设置监听exit. addActionListener()//退出按钮设置监听public static void main(String args[]){}//主函数启动程序三、程序设计的完整代码及注解//双人对战五子棋import java.awt.*;import java.awt.event.*;import javax.swing.*;class fivechess extends JPanel { // 函数int wh_color, x1, y1, wh_x, wh_y, wh_i, wh_j, wh_arri, wh_stop = 3;// 定义各种整型变量//x1,y1表示坐标wh_x,wh_y圆大小坐标wh_i,wh_j二维数组boolean wh_rf; // 定义布尔型变量,判断玩家String s;int[][] wh_array = new int[20][20]; // 定义二维数组int[] wh_arr = new int[430]; // 定义一维数组public fivechess() { // 鼠标操作for (int i = 0; i < 20; i++) { // 给二维数组赋值为0for (int j = 0; j < 20; j++) {wh_array[i][j] = 0; // 赋值为0}}for (int i = 0; i < 400; i++) { // 给一维数组赋初始值0wh_arr[i] = 0;}addMouseListener(new MouseListener() { // 鼠标监听器public void mouseClicked(MouseEvent e) // 单击鼠标{Graphics g = getGraphics();if (wh_stop == 3) // 当wh_stop==3时运行程序{x1 = e.getX(); // 返回鼠标当前x坐标y1 = e.getY(); // 返回鼠标当前y坐标wh_i = (x1 - 54) / 32; // 计算列值wh_j = (y1 - 34) / 32; // 计算行值wh_arri = 20 * wh_j + wh_i; // 计算二维数组变为一维数组时的对应值if (x1 > 54 && x1 < 694 && y1 > 34 && y1 < 674) // 在棋盘范围内单击鼠标才运行程序{if (wh_array[wh_i][wh_j] == 0) // 当二维数组取值为0时运行程序{wh_rf = !wh_rf; // Boolean值单击后循环变化if (wh_rf == true) // Boolean值为TRUE时{wh_color = 1; // 令wh_color=1s = "黑棋";wh_array[wh_i][wh_j] = 1; // 对应的二维数组值赋为1wh_arr[wh_arri] = 1; // 对应的一维数组赋值为1}if (wh_rf == false) // Boolean值为FALSE时{wh_color = 2; // wh_color为2s = "白棋";wh_array[wh_i][wh_j] = 2; // 对应的二维数组值赋为2wh_arr[wh_arri] = 2; // 对应的一维数组值赋为2}for (int i = 0; i < 20; i++) // 确定鼠标位置的范围{for (int j = 0; j < 20; j++) {if (x1 >= 54 + i * 32&& x1 < 54 + (i + 1) * 32&& y1 >= 34 + j * 32&& y1 < 34 + (j + 1) * 32)// 鼠标在此范围内时{wh_x = 54 + (i) * 32 + 1; // 取这个小方格的左上角x坐标值+1wh_y = 34 + (j) * 32 + 1; // 取这个小方格的左上角y坐标值+1}}}if (wh_color == 1) // 当棋子为黑色时{g.setColor(Color.BLACK); // 设置颜色}if (wh_color == 2) // 如果棋子为白色{g.setColor(Color.WHITE); // 设置颜色}g.fillOval(wh_x, wh_y, 30, 30); // 在这个小方格范围内画圆形}}for (int i = 0; i < 395; i++) // 判断黑白双方谁胜利{g.setColor(Color.RED);if ((wh_arr[i] == 1 && wh_arr[i + 1] == 1&& wh_arr[i + 2] == 1 && wh_arr[i + 3] == 1&& wh_arr[i + 4] == 1 && (i + 4) / 20 == i / 20)|| // 判断横行黑子连续为5个(wh_arr[i] == 1 && wh_arr[i + 20] == 1&& wh_arr[i + 40] == 1&& wh_arr[i + 60] == 1&& wh_arr[i + 80] == 1 && (i + 4) / 20 == i / 20)|| // 判断竖行黑子连续为5个(wh_arr[i] == 1 && wh_arr[i + 19] == 1&& wh_arr[i + 2 * 19] == 1&& wh_arr[i + 3 * 19] == 1&& wh_arr[i + 4 * 19] == 1 && (i - 4) / 20 == i / 20)|| // 判断斜左黑子连续为5个(wh_arr[i] == 1 && wh_arr[i + 21] == 1&& wh_arr[i + 2 * 21] == 1&& wh_arr[i + 3 * 21] == 1 && wh_arr[i + 4 * 21] == 1)) // 判断斜右黑子连续为5个{g.drawString("黑棋胜利", 300, 300); // 显示黑棋胜利wh_stop = 0; // 当胜利时赋值为0,再次运行时将停止}if ((wh_arr[i] == 2 && wh_arr[i + 1] == 2&& // 判断白棋子wh_arr[i + 2] == 2 && wh_arr[i + 3] == 2&& wh_arr[i + 4] == 2 && (i + 4) / 20 == i / 20)|| // 判断横行白子连续为5个(wh_arr[i] == 2 && wh_arr[i + 20] == 2&& wh_arr[i + 40] == 2&& wh_arr[i + 60] == 2&& wh_arr[i + 80] == 2 && (i + 4) / 20 == i / 20)|| // 判断竖行白子连续为5个(wh_arr[i] == 2 && wh_arr[i + 19] == 2&& wh_arr[i + 2 * 19] == 2&& wh_arr[i + 3 * 19] == 2&& wh_arr[i + 4 * 19] == 2 && (i - 4) / 20 == i / 20)|| // 判断斜左白子连续为5个(wh_arr[i] == 2 && wh_arr[i + 21] == 2&& wh_arr[i + 2 * 21] == 2&& wh_arr[i + 3 * 21] == 2 && wh_arr[i + 4 * 21] == 2)) // 判断斜行连续5子{g.drawString("白棋胜利", 300, 300);wh_stop = 0;}}}} // 单击事件结束public void mouseEntered(MouseEvent e) // 鼠标进入组件的事件{}public void mouseExited(MouseEvent e) // 鼠标离开组件的事件{}public void mousePressed(MouseEvent e) // 鼠标按下时的事件{}public void mouseReleased(MouseEvent e) // 鼠标放开时的事件{}}); // 监听器结束addMouseMotionListener(new MouseMotionListener() // 鼠标motion监听{public void mouseMoved(MouseEvent e) // 处理鼠标移动事件{}public void mouseDragged(MouseEvent e) // 处理鼠标拖动事件{}});}protected void paintComponent(Graphics g) // 绘图函数{g.setColor(Color.gray);g.fill3DRect(0, 0, 748, 728, true);g.setColor(Color.BLACK); // 设置颜色for (int i = 0; i < 20; i++) // 循环画棋盘{g.drawLine(70, 50 + i * 32, 678, 50 + i * 32); // 画棋盘的横线g.drawLine(70 + i * 32, 50, 70 + i * 32, 658); // 画棋盘的纵线}g.drawString("五子棋", 300, 30); // 在面板上输出"五子棋"wh_stop = 3; // 刷新后wh_stop由0变为3可以响应buttonfor (int i = 0; i < 20; i++) // 给二维数组赋值为0{for (int j = 0; j < 20; j++) {wh_array[i][j] = 0; // 赋值为0}}for (int i = 0; i < 400; i++) { // 给一维数组赋初始值0 wh_arr[i] = 0;}}public Dimension getPerferredSize() {return new Dimension(748, 728);}}public class draw extends JFrame { // 函数JTextField t;public draw() //{super("五子棋"); // 窗口名Container c = getContentPane(); // 返回当前内容窗值c.setLayout(null);fivechess wh = new fivechess();wh.setBounds(0, 0, 748, 728); // 设置panel大小JButton b = new JButton("重新开始"); // 定义按钮JButton exit = new JButton("退出"); // 定义按钮c.add(exit);c.add(b); // 添加按钮c.add(wh); // 添加panelb.setBounds(70, 20, 100, 20); // 设置按钮大小exit.setBounds(580, 20, 80, 20);b.addActionListener(new ActionListener() // 设置监听{public void actionPerformed(ActionEvent e) {repaint(); // 重画}});exit.addActionListener(new ActionListener() // 设置监听{public void actionPerformed(ActionEvent e) {System.exit(0);}});}public static void main(String args[]) // 主函数{draw app = new draw(); //app.setLocation(300, 0); // 设置窗口位置app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 关闭框架行为属性app.setSize(748, 728); // 设置面板框架frame大小app.setVisible(true); // 设置可见app.setResizable(false);}}四、程序运行的结果分析1.如图二:进入游戏界面2.如图三:落子图三落子3.如图四:结束游戏图四游戏结束五、课程设计总结通过短短的一个学期java的学习,我们从一个对JAVA编程不懂的学生到现在可以试着用JAVA 进行简单程序的设计和编写,也更加了解了面向对象的思想。
手机五子棋游戏的设计与实现专业:姓名:班级:学号:指导教师:J2ME(Java 2 Micro Edition)是近年来随着各种不同设备,尤其是移动通信设备的飞速发展而诞生的一项开发技术。
它因其“write once,run anywhere”的Java特性而提高了开发的效率。
随着手机性能的不断提高,手机休闲娱乐应用将成为PC休闲娱乐应用之后又一重要业务增长点。
棋类游戏规则单一,比较适合在手机等便携终端推广。
由于具有跨平台、易于移植、占用空间小的优势,J2ME成为移动应用开发平台的主流,并提供了很多用以支持移动应用软件的开发的API。
现将该技术用于这次的手机游戏开发,可以实现游戏的快速开发,不但便于查看游戏运行过程中内存的占用量和程序的每一部分代码消耗了多少处理器时间,而且可以不断地优化代码,使代码具有高度的复用性、可扩展性、可维护性。
游戏的开发以J2ME为平台,利用Java技术,结合J2ME的MIDP技术,并对于程序设计思想,重要类、方法等展开讨论。
在对弈部分,分析设计走棋算法,选择合适的方式组织成代码,实现基本的人工智能。
过程中使用了J2ME中的CLDC/MIDP软件体系,主要运用了MID Profile的特定类的支持,来完成游戏的开发。
关键词:J2ME;CLDC;MIDPJ2ME is a kind of fast developing technology implemented on various devices especially mobile communication equipments. It improves the efficiency of the development process because of its "write once, run anywhere" nature. The development trend of the entertainment market based on the cell phone is very obvious because the handset performance enhances unceasingly. The entertainment market based on the cell phone will to be the new important business growth point follow the PC entertainment market. As the rules of a single chess game, it is more suitable for mobile phones and other portable terminal extension.J2ME has been the preferred platform for development because of its platform independent and compatibility, and provides a lot of APIs to support the development of mobile application software. The technology for mobile game development, can achieve the rapid development of the game. It is not only easy to observe the memory consumption and processor consumed time during the operation of the game, but also can optimize the code, so that the code has a high degree of reusability, scalability, maintainability.The game has designed by J2ME, the Java technology and the MIDP technology. I studied the procedure thought, the important class and the method. In the playing chess part, I have analyzed the algorithm, choosed the appropriate way to organize the code and realized the basic artificial intelligence. On the other hand,I learned software system of CLDC/MIDP and the specific class of the MID Profile to complete the game development.Key words: J2ME;CLDC;MIDP目录1 概述 (5)1.1 课题研究背景 (5)1.2 课题研究意义 (5)2 开发技术背景 (6)2.1 JAVA语言概述 (6)2.2 J2ME简介 (6)2.3 移动信息设备简表 (6)3 系统分析及总体设计 (7)3.1 可行性分析 (7)3.2 需求分析 (8)3.3 系统概要设计 (8)4 系统详细设计 (9)4.1 界面设计 (9)4.1.1 图形的低级绘制 (10)4.1.2 用户按键设计 (10)4.2 走棋算法 (11)4.3 胜负判断 (11)5 系统测试 (11)5.1 测试方案 (11)5.2 测试结果 (12)6总结 (13)基于J2ME的手机五子棋游戏的设计与实现1 概述1.1 课题研究背景五子棋是当前非常流行的一种棋。
五子棋不仅能增强思维能力,提高智力,而且富含哲理,有助于修身养性。
手机游戏的实现方式主要包括嵌入式游戏、浏览器游戏、短消息服务游戏、J2ME和其它的解释语言。
Java 2 Micro Edition是一种针对移动电话和PDA这样的小型设备的Java语言。
J2ME与台式机中的Java相比还是有一定的限制,但是它已经极大的提高了移动电话支持游戏的能力。
并且具备一定的优势:庞大的潜在用户群、便携性、开发门槛较低。
手机是现代生活方式的产物,如同因特网的普及导致网络游戏的高速发展一样,手机的普及,对满足不同功能的手机软件的需求也就越来越迫切,这就需要比较好的手机软件开发平台,此时具有平台无关性优点的J2ME开发平台也就应运而生。
与传统的主流的PC游戏相比,手机游戏的价值在于打发一些无聊的时间,作为一个移动的娱乐终端,手机游戏施展身手的机会永远可能是在地铁站、公交车或者是洗手间这些地方,也许在庞大的游戏行业里,手机游戏将永远扮演着一个边缘者的角色,因为谁也不能指望一个人在家的时候用手机玩游戏或者看电影。
但是手机游戏的市场是巨大的,即便是只有十分之一的用户来购买游戏,那也将是不可忽视的商业机遇。
手机游戏是手机的一种高附加值操作软件,游戏编程是手机软件编程的重要组成,同时也持续推动手机软件技术升级进步。
手机游戏按手机平台分类,主要有J2ME、Brew、UniJa等。
其中J2ME手机开发平台使用最为广泛。
作为SUN公司针对微型嵌入式消费电子产品开发的编程系统,J2ME技术是当前手机软件开发的主流平台,各大手机生产厂商目前的主流产品绝大都使用J2ME技术。
基于J2ME技术开发手机软件可以实现手机功能的多样化与专业化,极大的满足了人们对手机要求更高的需求。
1.2 课题研究意义本设计基于J2ME技术,开发一款五子棋游戏软件,可以供人们闲暇时间随时随地娱乐,提高棋艺。
五子棋不但容易上手,而且它区别于别的游戏,它不但使人娱乐,而且能使人的头脑变得更加聪明。
通过对该课题的研究,首先,进一步熟悉面向对象语言,加深对J2ME层次结构的了解。
通过eclipse集成开发环境创建软件,最终形成一个具备基本功能的手机五子棋游戏,可应用于便携式设备,适合于棋类爱好者。
其次,了解手机游戏开发的特点和现状。
2 开发技术背景2.1 JAVA语言概述Java的出现是源于对独立于平台语言的需要,希望这种编程语言能编写出嵌入各种家用电器等设备的芯片上、且易于维护的程序。
人们发现当时的编程语言都有一个共同的缺点,就是针对CPU芯片进行编译。
这样,一旦电器设备更换了芯片就不能保证程序正确运行。
九零年Sun公司成立了开发小组,开始致力于开发一种可移植的、跨平台的编程语言,该语言能生成正确运行于各种操作系统、各种芯片上的代码。
Java的出现标志着真正的分布式系统的到来。
Java是一种跨平台的、面向对象的、分布式的、解释的、安全的、结构的、可移植的、性能很优异的多线程的动态语言。
Java的特点:平台无关性;安全性;面向对象;分布式;健壮性。
2.2 J2ME简介J2ME是SUN公司针对嵌入式、消费类电子产品推出的开发平台,与J2SE和J2EE 共同组成Java技术的三个重要的分支。
J2ME实际上是一系列规范的集合,由JCP 组织制定相关的Java Specification Request(JSR)并发布,各个厂商会按照规范在自己的产品上进行实现,但是必须要通过TCK测试,这样确保兼容性。
J2ME 是JAVA的三大分支之一,专门用于开发基于消费性电子产品的应用。
J2ME支持个人手持移动设备,如手机、PDA等。
手机用户可以通过支持JAVA功能的终端,使用多种全新图形化、动态化和个性化的移动增值服务。
2.3 移动信息设备简表移动信息设备简表(MIDP)为移动电话和入门级PDA设计,为移动应用程序提供了所需的全部核心功能,包括应用程序模型、用户界面、持久性数据存储、联网能力及应用程序管理功能,目前应用非常广泛的MIDlet就是在MIDP中定义的。
MIDP框架如图2-1所示。
图2-1 MIDP框架图MIDP提供核心应用程序功能,包括用户界面、网络连接、本地数据存储和应用程序生命周期管理。
MIDlet生命周期流程图如图2-2所示。
MIDP中含有下列API包:A. javax.microedition.lcdui: 用户界面(UI)API,它为MIDP应用提供了一整套实现用户界面的功能特性。
B. javax.microediton.rms: 移动信息设备描述提供了一种让MIDlets持久性储存并在以后可以取回数据的机制。
C. javax.microedition.midlet: 这个MIDlet包明确定义了MIDP应用,也定义了和应用环境之间的交互。