您好,登錄后才能下訂單哦!
本篇內容介紹了“Java如何實現五子棋游戲”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
相比之前,做出了以下修改:
1.新增菜單欄,將重新開始和退出的按鈕移到了菜單欄;
2.可以實時顯示時間(多線程);
3.下棋時可以顯示當前是哪一方在下棋;
4.可以更改背景顏色;
5.可以更改先行方(默認黑子)。
結果
1.Frame.java(主界面)
package Gobang; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.image.*; //import java.applet.*; //import java.net.*; //import java.io.*; //import javax.imageio.*; public class Frame extends JFrame implements MouseListener,ActionListener{//JFrame的擴展類 //ImageIcon image; //JLayeredPane layeredPane; //JPanel jp; /*本來想用于播放背景音樂,但是沒有成功,,,先暫時放棄 File f; URI uri; URL url; @SuppressWarnings("deprecation") */ private static final long serialVersionUID = 1L; public JButton AdmitDefeatButton,RegretButton;//兩個按鈕,各有其功能。 JLabel TimeLabel;//用來顯示時間 JLabel jl1,jl2,jl3;//游戲信息 Graphics g;//畫筆 BufferedImage buf; int x;//鼠標的坐標 int y; int[][] Chess = new int[20][20]; // 保存棋子,1表示黑子,2表示白子 boolean IsBlack = true; //表示當前要下的是黑子還是白子,true表示黑子,false表示白子 boolean IsFinish = false; //表示當前游戲是否結束 int xRange; int yRange; int[] chessX = new int[400];//用來保存從開始到當前的所有棋子,用于悔棋; int[] chessY = new int[400]; int countX = 0; int countY = 0; //菜單欄 JMenuBar menubar; JMenu menu; JMenu setmenu; JMenuItem RestartItem,ExitItem,IntroItem,BackgroundItem,FirstItem; //獲取屏幕的寬度和高度 Toolkit kit = Toolkit.getDefaultToolkit(); Dimension screenSize = kit.getScreenSize(); int screenWidth = screenSize.width; int screenHeight = screenSize.height; public Frame() { /*插入背景圖片 //layeredPane=new JLayeredPane(); //image=new ImageIcon("F:\\JAVA\\eclipse-workspace\\Gobang\\src\\1.jpg");//隨便找一張圖就可以看到效果。 //jp=new JPanel(); //jp.setBounds(0,0,600,600); //jl=new JLabel(image); //jl.setBounds(0,0,image.getIconWidth(),image.getIconHeight()); //jp.add(jl); //layeredPane.add(jp,JLayeredPane.DEFAULT_LAYER); //this.setLayeredPane(layeredPane); */ /*音頻播放部分 try { f = new File(""); uri = f.toURI(); url = uri.toURL(); AudioClip aau; aau = Applet.newAudioClip(url); aau.loop(); //循環播放 } catch (Exception e) { e.printStackTrace(); } */ //設置標題、大小、排列方式等 this.setTitle("五子棋"); this.setSize(600,600); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); this.setLayout(null); int height = this.getHeight(); int width = this.getWidth(); this.setLocation(screenWidth/2-width/2, screenHeight/2-height/2); //實時顯示時間,用到多線程來實時顯示。 jl1 = new JLabel("北京時間"); jl1.setLocation(430, 120); jl1.setSize(80,20); this.add(jl1); TimeLabel = new JLabel(); new Thread(new Time(TimeLabel)).start();//新建一個線程 TimeLabel.setLocation(510, 120); TimeLabel.setSize(80,20); this.add(TimeLabel); //顯示游戲信息,當前是誰執子; jl2 = new JLabel("游戲信息"); jl2.setLocation(430, 150); jl2.setSize(80,20); jl3 = new JLabel("黑方先行"); jl3.setLocation(510, 150); jl3.setSize(80,20); this.add(jl2); this.add(jl3); //設置背景顏色 this.getContentPane().setBackground(new Color(255, 239 ,213)); this.getContentPane().setVisible(true); //設置菜單欄 menubar = new JMenuBar();//菜單欄 menu = new JMenu("游戲操作"); RestartItem = new JMenuItem("重新開始"); ExitItem = new JMenuItem("退出"); menu.add(RestartItem); menu.add(ExitItem); menubar.add(menu); setmenu = new JMenu("設置"); IntroItem = new JMenuItem("游戲說明"); BackgroundItem = new JMenuItem("背景顏色"); FirstItem = new JMenuItem("先行方"); setmenu.add(IntroItem); setmenu.add(BackgroundItem); setmenu.add(FirstItem); menubar.add(setmenu); menubar.setBackground(new Color(249,205,173)); menubar.setVisible(true); this.setJMenuBar(menubar); //兩個按鈕,認輸和悔棋; AdmitDefeatButton = new JButton("認輸"); AdmitDefeatButton.setSize(80,40); AdmitDefeatButton.setLocation(120, 480); RegretButton = new JButton("悔棋" ); RegretButton.setSize(80,40); RegretButton.setLocation(240, 480); this.add(AdmitDefeatButton); this.add(RegretButton); /* 五個按鈕添加到中間容器; panel1 = new JPanel(); panel1.setBorder(BorderFactory.createLoweredBevelBorder()); //設置邊框 panel1.setLayout(new GridLayout(1,5)); panel1.add(RestartButton); panel1.add(SetButton); panel1.add(AdmitDefeatButton); panel1.add(RegretButton); panel1.add(ExitButton); this.add(panel1); panel1.setSize(460,30); panel1.setLocation(0, 460); */ this.repaint();//表示重新繪制畫布,可以自動調用paint函數; //本類作為監聽類,包括鼠標監聽和按鈕動作監聽; this.addMouseListener(this); IntroItem.addActionListener(this); BackgroundItem.addActionListener(this); FirstItem.addActionListener(this); RestartItem.addActionListener(this); AdmitDefeatButton.addActionListener(this); RegretButton.addActionListener(this); ExitItem.addActionListener(this); } //畫布繪制 public void paint(Graphics g) { if(g == null)//如果第一次繪制,新建一個圖片,并且創建畫布。 { buf = new BufferedImage(450, 450, BufferedImage.TYPE_INT_RGB); g = buf.createGraphics(); } if(g != null)// { super.paint(g);//表示在原來圖像的基礎上,再畫圖 g.setColor(new Color(249,205,173));//畫筆顏色調成褐色; g.fill3DRect(20, 130, 400, 400,true);//用畫筆畫一個邊長為400的正方形;邊距為20,130 for(int i = 0; i <= 20; i++)//用畫筆橫豎各畫19條線 { g.setColor(Color.BLACK);//畫筆顏色調為黑色; g.drawLine(20,130+i*20,420,130+i*20); g.drawLine(20+i*20,130,20+i*20,530); } } for(int i=0; i<20; i++){ for (int j = 0; j < 20; j++) { //畫實心黑子,直徑16 if(Chess[i][j] == 1){ int tempX = i*20+12; int tempY = j*20+122; g.setColor(Color.BLACK); g.fillOval(tempX, tempY, 16, 16); g.setColor(Color.BLACK); g.drawOval(tempX, tempY, 16, 16); } //畫實心白子,直徑16 if(Chess[i][j] == 2){ int tempX = i*20+12; int tempY = j*20+122; g.setColor(Color.WHITE); g.fillOval(tempX, tempY, 16, 16); g.setColor(Color.WHITE); g.drawOval(tempX, tempY, 16, 16); } } } g.drawImage(buf, 0, 0,this); } public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub if(!IsFinish) //判斷棋局是否結束 { x = e.getX(); //獲取當前鼠標點擊位置 y = e.getY(); if(x >= 20 && x < 420 && y >= 130 && y<= 530)//判斷鼠標是否在棋局內 { xRange = (x-20)%20; if(xRange > 10 && xRange < 20) //如果在交叉點的邊長為10的范圍內,就把棋子下在這; { x = (x - 20) / 20 + 1; } else { x = (x - 20) / 20; } yRange = (y-130)%20; if(yRange > 10 && yRange < 20) { y = (y - 130) / 20 + 1; } else { y = (y - 130) / 20; } if(Chess[x][y] == 0) //如果該交叉點沒有被下過; { chessX[countX++] = x; //存儲當前棋子的位置; chessY[countY++] = y; if(jl3.getText().equals("黑方先行")) //如果是黑子 { Chess[x][y] = 1; IsBlack = false; jl3.setText("白方先行"); } else if(jl3.getText().equals("白方先行")) { Chess[x][y] = 2; IsBlack = true; jl3.setText("黑方先行"); } this.repaint();//重新繪制畫布 } if(this.isWin())//如果下棋之后贏了,彈出對話框 { if(Chess[x][y] == 1) { JOptionPane.showMessageDialog(this, "黑方勝利"); } else { JOptionPane.showMessageDialog(this, "白方勝利"); } this.IsFinish = true; //游戲結束 } } } } public boolean isWin(){ boolean flag = false; int count = 1; int color = Chess[x][y]; //判斷橫向是否有5個棋子相連 count = this.checkCount(1,0,color); if(count >= 5){ flag = true; }else { //判斷縱向 count = this.checkCount(0,1,color); if(count >= 5){ flag = true; }else { //判斷右上,左下 count = this.checkCount(1,-1,color); if(count >= 5){ flag = true; }else { //判斷右下,左上 count = this.checkCount(1,1,color); if(count >= 5){ flag = true; } } } } return flag; } // 檢查棋盤中的五子棋是否連成五子,xChange,yChange為相對于當前棋子位置的變化量 public int checkCount(int xChange , int yChange ,int color){ int count = 1;//統計總共有幾個連著的棋子; int tempX = xChange; int tempy = yChange; //判斷棋子右邊有沒有相同顏色的棋子; while(x + xChange >=0 && x+xChange <20 && y+yChange >=0 && y+yChange < 20 && color == Chess[x+xChange][y+yChange]) { count++; //如果有,棋子數加一 if(xChange != 0) xChange++; //如果橫向方向變化,x相對位置加一 if(yChange != 0 ) { if(yChange != 0) { if(yChange > 0) //如果縱向方向增加,y相對位置加一 { yChange++; } else //如果縱向方向減小,y相對位置減一 { yChange--; } } } } xChange = tempX; yChange = tempy; //判斷棋子左邊有沒有相同顏色的棋子; while(x-xChange >=0 && x-xChange <20 && y-yChange >=0 && y-yChange <20 && color == Chess[x-xChange][y-yChange]) { count++; if(xChange != 0) { xChange++; } if(yChange != 0) { if (yChange > 0) { yChange++; } else { yChange--; } } } return count; } //監聽動作函數 //@SuppressWarnings("deprecation") public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(e.getActionCommand()=="重新開始")//如果點擊的按鈕是RestartButton,清空畫板,還原設置 { if(JOptionPane.showConfirmDialog(this, "是否重新開始游戲?") == 0) { for (int i = 0; i < 20; i++) { for (int j = 0; j < 20; j++) { Chess[i][j] = 0; //清空棋盤的棋子 } } //清空下棋棋子坐標的記錄 for (int i = 0; i < 400; i++) { chessX[i] = 0; chessY[i] = 0; } countX =0; countY =0; IsBlack = true; jl3.setText("黑方先行"); IsFinish = false; this.repaint(); } } if(e.getSource() == AdmitDefeatButton)//如果點擊的按鈕是AdmitDefeatButton,結束游戲,并提示 { if(!IsFinish) //判斷棋局是否結束 { if(JOptionPane.showConfirmDialog(this, "是否確定認輸?") == 0) { if(IsBlack == true) { JOptionPane.showMessageDialog(this,"白方獲勝"); } else { JOptionPane.showMessageDialog(this,"黑方獲勝"); } IsFinish = true; } } } if(e.getActionCommand()=="退出")//如果點擊的按鈕是ExitButton,退出程序 { if(JOptionPane.showConfirmDialog(this, "是否確定退出?") == 0) { System.exit(0); } } if(e.getSource() == RegretButton)///如果點擊的按鈕是RegretButton,悔棋一步 { if(!IsFinish) //判斷棋局是否結束 { if(IsBlack == true) //如果現在是黑子要下,表示悔棋的是白子 { if(JOptionPane.showConfirmDialog(this, "白方想要悔棋,是否同意?") == 0) { int tempX = chessX[--countX]; //獲取上一步白子下的位置; int tempY = chessY[--countY]; Chess[tempX][tempY] = 0; //撤回白子 IsBlack = false; //當前要下的變為白方 jl3.setText("白方先行"); } } else { if(JOptionPane.showConfirmDialog(this, "黑方想要悔棋?") == 0) { int tempX = chessX[--countX]; int tempY = chessY[--countY]; Chess[tempX][tempY] = 0; IsBlack = true; jl3.setText("黑方先行"); } } this.repaint(); //重新繪制畫布 } } if(e.getActionCommand()=="游戲說明") { JDialog frame1 = new JDialog();//新建對話框 frame1.setSize(200,200); int height = frame1.getHeight(); int width = frame1.getWidth(); frame1.setLocation(screenWidth/2-width/2, screenHeight/2-height/2); JTextArea ta = new JTextArea();//新建文本框 ta.setText("雙方分別使用黑白兩色的棋子,下在棋盤直線與橫線的交叉點上,先形成五子連線者獲勝。"); ta.setEditable(false); JScrollPane jsp = new JScrollPane(ta); frame1.setTitle("規則"); frame1.getContentPane().add(jsp); //添加文本框 frame1.setModalityType(Dialog.ModalityType.APPLICATION_MODAL); // 設置模式類型 frame1.setVisible(true); } if(e.getActionCommand()=="背景顏色") { JDialog frame2 = new JDialog();//新建對話框 frame2.setSize(150,200); int height = frame2.getHeight(); int width = frame2.getWidth(); frame2.setLocation(screenWidth/2-width/2, screenHeight/2-height/2); frame2.setLayout(new GridLayout(3,2,10,10)); //三個文本框; JLabel label1 = new JLabel("Red"); JLabel label2 = new JLabel("Green"); JLabel label3 = new JLabel("Blue"); JTextField tf1 = new JTextField("255"); //tf1.setSize(80, 20); JTextField tf2 = new JTextField("239"); //tf2.setBounds(10, 40, 80, 20); JTextField tf3 = new JTextField("213"); //tf3.setBounds(10, 70, 80, 20); frame2.setTitle("設置背景顏色"); frame2.getContentPane().add(label1); frame2.getContentPane().add(tf1); // frame2.getContentPane().add(label2); frame2.getContentPane().add(tf2); frame2.getContentPane().add(label3); frame2.getContentPane().add(tf3); frame2.setModalityType(Dialog.ModalityType.APPLICATION_MODAL); // 設置模式類型 frame2.setVisible(true); //改變背景顏色 int Red =Integer.parseInt(tf1.getText()); int Green =Integer.parseInt(tf2.getText()); int Blue =Integer.parseInt(tf3.getText()); this.getContentPane().setBackground(new Color(Red,Green,Blue)); this.repaint(); } if(e.getActionCommand() == "先行方") { new FirstDialog(IsBlack,jl3);//新建對話框,改變先行方 } } public static void main(String[] args) { new Frame(); } @Override public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } } //改變先行方 class FirstDialog extends JDialog implements ItemListener{ /** * */ private static final long serialVersionUID = 1L; Toolkit kit = Toolkit.getDefaultToolkit(); Dimension screenSize = kit.getScreenSize(); int screenWidth = screenSize.width; int screenHeight = screenSize.height; Boolean IsBlack; JLabel jl = new JLabel(); JRadioButton rbWhite,rbBlack; FirstDialog(Boolean IsBlack,JLabel jl) { this.IsBlack = IsBlack; this.jl = jl; this.setSize(150,200); int height = this.getHeight(); int width = this.getWidth(); this.setLocation(screenWidth/2-width/2, screenHeight/2-height/2); this.setTitle("先行方"); //一個單選組合; rbWhite = new JRadioButton("白子"); rbBlack = new JRadioButton("黑子"); this.setLayout(new FlowLayout()); this.getContentPane().add(rbWhite); this.getContentPane().add(rbBlack); // ButtonGroup bgroup = new ButtonGroup(); bgroup.add(rbWhite); bgroup.add(rbBlack); //本類做監聽類 rbWhite.addItemListener(this); rbBlack.addItemListener(this); this.setModalityType(Dialog.ModalityType.APPLICATION_MODAL); // 設置模式類型 this.setVisible(true); } public void itemStateChanged(ItemEvent e) { if(rbWhite.isSelected())//選中白子時,將先行方設為白子; { IsBlack = false; jl.setText("白方先行"); } else if(rbBlack.isSelected()) { IsBlack = true; jl.setText("黑方先行"); } } }
2.Time.java(實時顯示時間)
package Gobang; import java.awt.*; import javax.swing.*; import java.util.*; import java.text.*; public class Time implements Runnable{ private JLabel lab = new JLabel(); public Time(JLabel lab) { this.lab = lab; } public void run() { while(true) { SimpleDateFormat simpleFormat = new SimpleDateFormat("HH:mm:ss"); Calendar c = Calendar.getInstance(); lab.setText(simpleFormat.format(c.getTime())); lab.setForeground(Color.RED); try { Thread.sleep(1000); }catch(Exception e) { e.printStackTrace(); } } } }
“Java如何實現五子棋游戲”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。