Home Java javaTutorial How to implement the stand-alone version of backgammon in Java

How to implement the stand-alone version of backgammon in Java

May 04, 2023 pm 06:46 PM
java

Java五子棋设计流程:

1.创建窗口和设计一个棋盘界面

2.实现鼠标点击,棋子出现,黑白棋轮流下

3.能够判断输赢

4.添加按钮功能

How to implement the stand-alone version of backgammon in Java

实现结果图:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
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 java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
 
public class Test {
 
    public static void main(String[] args) {
        new MyFrame();
        
    }
}
 
class MyFrame extends JFrame implements MouseListener{
    
    //保存坐标
    int x;
    int y;
    int x1;
    int y1;
    //黑子数
    //白子数
    //1是黑下,2是白下
    //默认开始是黑旗先下
    int flag=1;
    //表示游戏是否结束
    //true游戏开始,false游戏结束,不能再下
    boolean canPlay=true;
    //保存之前下过的棋子的坐标
    //'0'代表没有棋子,'1'代表黑棋,'2'代表白棋
    int [][]allChess=new int[19][19];
    //int [][]allChess=new int[25][25];
    //当前棋子的总数
    int chessSum=0;
    BufferedImage bgImage =null;
    
    JButton withdraw=new JButton("悔棋");
    JButton restart=new JButton("重新开始");
    JButton exit=new JButton("退出");
    JPanel south=new JPanel();
    
    public MyFrame() {
        this.setTitle("五子棋");
        setSize(630,700);
        setLayout(new BorderLayout()); 
        setLocationRelativeTo(null); 
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        try {
            bgImage=ImageIO.read(new File("C:\\Users\\us\\Desktop\\1.jpg"));
        } catch (IOException e1) {
            
            e1.printStackTrace();
        }
        addMouseListener(this);//将窗体加入监听
        
        south.setLayout(new FlowLayout(FlowLayout.LEFT,60,30));
        
        south.add(restart);
        south.add(withdraw);
        south.add(exit);
        //初始化按钮事件监听器内部类 
        MybuttonListener buttonListener =new MybuttonListener();
        //将三个按钮事件注册监听事件
        restart.addActionListener(buttonListener);
        withdraw.addActionListener(buttonListener);
        exit.addActionListener(buttonListener);
        //将按钮面板加到窗体的南部
        this.add(south,BorderLayout.SOUTH);
        
        setVisible(true);
    }
    
    public void paint(Graphics g) {
        
        int tempSum=chessSum;
        //棋盘
        g.drawImage(bgImage,8,30,this);
        
        for(int colum=58;colum<600 ;colum=colum+30){//行
         g.drawLine(38,colum,578,colum);
        }
        for(int rand=38;rand<600;rand=rand+30){//列
         g.drawLine(rand, 58,rand, 598);
        }
        //黑点
        g.fillOval(122, 143, 10, 10); 
        g.fillOval(484, 143, 10, 10);
        g.fillOval(122, 504, 10, 10);
        g.fillOval(303, 353, 10, 10);
        g.fillOval(484, 503, 10, 10);
        g.fillOval(122, 355, 10, 10);
        g.fillOval(484, 355, 10, 10);
        g.fillOval(303, 145, 10, 10);
        g.fillOval(303, 503, 10, 10);
        
        for(int i=0;i<allChess.length;i++) {
            for(int j=0;j<allChess.length;++j) {
             //下黑子
                if(allChess[i][j]==1) {
                    int tempX=i*30+38;//左边界到棋盘的距离
                    int tempY=j*30+58;//上边界到棋盘的距离
                     g.setColor(Color.black);
                     g.fillOval(tempX-13,tempY-13,25,25);
                    
                    
                }
                 
                 
                //下白子
                if(allChess[i][j]==2) {
                    int tempX=i*30+38;
                    int tempY=j*30+58;
                    g.setColor(Color.white);
                    g.fillOval(tempX-13,tempY-13,25,25);
                    
                    
                        
                    
                    
                }
                
                
                 
            }
        }
        //最后棋子用红框表示
        if(chessSum>0) {
         g.setColor(Color.red);
         g.drawRect(x*30+38-13, y*30+58-13, 25,25);
        }
        //g.setColor(Color.red);
        //g.drawRect(x1*30+38-13, y1*30+58-13, 25,25);
        chessSum++;
        System.out.println("总数为"+(chessSum-1));
    }
 
    
    public void mouseClicked(MouseEvent e) {
             x=e.getX();
             y=e.getY();
         //System.out.println("x="+e.getX()+" "+"y="+e.getY());
       if(canPlay) {
           
         if(x>=38&&x<=588&&y>=58&&y<=620) {
             
            x=(x-38)/30;//38起点,适应19x19
            y=(y-58)/30;
            if(allChess[x][y]==0){//此点没有棋子,才可下
            //判断该由哪方下棋
            if(flag==1) {//&#39;1&#39;代表由黑方下
                allChess[x][y]=1;//&#39;1&#39;表示此处放黑棋
                this.checkFive();//判断黑棋是否五子相连
                
                flag=2;
            }
            else {
                allChess[x][y]=2;//&#39;2&#39;表示此处放白棋
                this.checkFive();//判断白棋是否五子相连
                
                flag=1;//&#39;1&#39;代表由黑方下
            }
          this.repaint();
        }
       }
      }
          
       }
    
    
    //判断五子相连
    public  void checkFive(){
        //把要下的棋子颜色保存
        int color=allChess[x][y];
        //计算已连棋子个数
        int count=1;
        
        //判断横向右边是否五子
        for(int i=1;i<5;i++) {
            if(x>=15)
                break;
            if(color==allChess[x+i][y]) {
                count++;
            }
            checkWin(count);
        }
        count=1;
        
        //判断横向左边是否五子
        for(int i=1;i<5;i++) {
            if(x<=3)//当棋子左边无法连成五子,直接退出
                break;
            
            if(color==allChess[x-i][y]) {
                count++;
            }
            checkWin(count);
        }
        count=1;
        
        //判断竖向下边是否五子
        for(int i=1;i<5;i++) {
            if(y>=15)//当棋子左边无法连成五子,直接退出
                break;
            if(color==allChess[x][y+i]) {
                count++;
            }
            checkWin(count);
        }
        count=1;
        
        //判断竖向上边是否五子
        for(int i=1;i<5;i++) {
            if(y<=3)//当棋子竖向上边无法连成五子,直接退出
                break;
            if(color==allChess[x][y-i]) {
                count++;
            }
            checkWin(count);
        }
        count=1;
        
        //判断右斜上边是否五子
        for(int i=1;i<5;i++) {
            if(y<=3||x>=15)//当棋子右斜上边无法连成五子,直接退出
                break;
            if(color==allChess[x+i][y-i]) {
                count++;
            }
            checkWin(count);
        }
        count=1;
        
        //判断左斜向下边是否五子
        for(int i=1;i<5;i++) {
            if(x<=3||y>=15)//当棋子左斜向下边无法连成五子,直接退出
                break;
            
            if(color==allChess[x-i][y+i]) {
                count++;
            }
            checkWin(count);
        }
        count=1;
        
        //判断左斜向上边是否五子
        for(int i=1;i<5;i++) {
            if(x<=3||y<=3)
                break;
            if(color==allChess[x-i][y-i]) {
                count++;
            }
            checkWin(count);
        }
        count=1;
        
        //判断右斜向下边是否五子
        for(int i=1;i<5;i++) {
            if(y>=15||x>=15)
                break;
            if(color==allChess[x+i][y+i]) {
                count++;
            }
            checkWin(count);                
            
        }
        count=1;
        
    }

    public void mouseEntered(MouseEvent e) {
         x1=e.getX();
         y1=e.getY();
         if(x1>=38&&x1<=588&&y1>=58&&y1<=620) {
             
             setCursor(new Cursor(Cursor.HAND_CURSOR));
            
         }
        
    }
        
    public void mouseExited(MouseEvent arg0) {
        // TODO Auto-generated method stub
        
    }
 
    public void mousePressed(MouseEvent arg0) {
        
        
    }
 
    public void mouseReleased(MouseEvent e) {
        
 }
     
    public void checkWin(int count) {
       
       if(count>=5) {//五子相连
          
         if(allChess[x][y]==1) {
            JOptionPane.showMessageDialog(this, "黑方胜出!!!!!!");
         }
         if(allChess[x][y]==2) {
            JOptionPane.showMessageDialog(this, "白方胜出!!!!!!");
         }
         canPlay=false;//游戏结束
       }
    }
    
    //重新开始
    public void restartGame(){
        for(int i=0;i<allChess.length;i++) {
            for(int j=0;j<allChess.length;j++) {
                allChess[i][j]=0;
            }
        }
        flag=1;//默认开始是黑旗先下
        canPlay=true;
        repaint();
    }
    
    //悔棋
    public void goback() {
      if(allChess[x][y]!=0) {//当棋盘有棋子,才能悔棋
        allChess[x][y]=0;
        if(flag==1) {
            flag=2;
            repaint();
        }
        else {
            flag=1;
            repaint();
        }
      }
    }
    
    //按钮事件监听器内部类 
    class MybuttonListener  implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            if(e.getSource()==restart) {
                restartGame();
            }
            if(e.getSource()==withdraw) {
                goback();
            }
            if(e.getSource()==exit) {
                System.exit(0);  
            }
        }
    }
}
Copy after login

The above is the detailed content of How to implement the stand-alone version of backgammon in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles