五子棋教程电脑单机版

发布时间: 2023-04-10 16:24 阅读: 文章来源:转载

Java五子棋设计流程:

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

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

3.能够判断输赢

4.添加按钮功能

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\\a\\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

•••展开全文