java__含类图__五子棋小游戏
javaGUI实现五子棋游戏
javaGUI实现五⼦棋游戏本⽂实例为⼤家分享了java实现五⼦棋游戏GUI,供⼤家参考,具体内容如下引⽤包//{Cynthia Zhang}import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.border.LineBorder;import javax.swing.JOptionPane;import javax.swing.ImageIcon;import java.awt.Image;import com.sun.image.codec.jpeg.*;前期预设//extends JApplet {// Indicate which player has a turn, initially it is the X playerprivate char whoseTurn = 'X';final int SIZE = 15;static boolean ISOVER = false;// Create and initialize cellsprivate final Cell[][] cell = new Cell[SIZE][SIZE];// Create and initialize a status labelprivate final JLabel jlblStatus = new JLabel("X's turn to play",JLabel.CENTER);设置背景板// Initialize UI@Overridepublic void init() {// Panel p to hold cellsJPanel p = new JPanel();p.setLayout(new GridLayout(SIZE, SIZE, 0, 0));for (int i = 0; i < SIZE; i++) {for (int j = 0; j < SIZE; j++) {Cell ce = new Cell();ce.setBackground(new Color(150,88,42)); // 背景⾊绝美!p.add(cell[i][j] = ce);}}// Set line borders on the cells panel and the status labelp.setBackground(new Color(143,105,94)); // 背景⾊绝美!jlblStatus.setBorder(new LineBorder(new Color(255,255,255), 2)); // ⽩框框加宽!// Place the panel and the label to the appletthis.getContentPane().add(p, BorderLayout.CENTER);this.getContentPane().add(jlblStatus, BorderLayout.SOUTH);}主要框架段落// This main method enables the applet to run as an applicationpublic static void main(String[] args) {// Create a frameJFrame frame = new JFrame("Tic Tac Toe");// Create an instance of the appletHomework8 applet = new Homework8();// Add the applet instance to the frameframe.getContentPane().add(applet, BorderLayout.CENTER);// Invoke init() and start()applet.init();applet.start();// Display the frameframe.setSize(600, 600);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);}判断是否满了// Determine if the cells are all occupiedpublic boolean isFull() {for (int i = 0; i < SIZE; i++) {for (int j = 0; j < SIZE; j++) {if (cell[i][j].getToken() == ' ') {return false;}}}return true;}判断是否赢了和⼋皇后有点像,可以考虑那种数组优化四个⽅向,这⾥⽐较懒// Determine if the player with the specified token winspublic boolean isWon(char token) {int winNum = 5; // define the max num for a rulefor (int indexX = 0; indexX < SIZE; indexX++) {for (int indexY = 0; indexY < SIZE; indexY++){// in row check cell[indexX][indexY...indexY+winNum-1]if (indexY+winNum-1<SIZE){boolean flag=true;for (int y =indexY;y<indexY+winNum;y++)if (cell[indexX][y].getToken() != token){flag=false; break;}if (flag==true) return true;}// in row check cell[indexX...indexX+winNum-1][indexY]if (indexX+winNum-1<SIZE){boolean flag=true;for (int x =indexX;x<indexX+winNum;x++)if (cell[x][indexY].getToken() != token){flag=false; break;}if (flag==true) return true;}// check cell[indexX...indexX+winNum-1][indexY...indexY+winNum-1)if (indexX+winNum-1<SIZE && indexY+winNum-1<SIZE){boolean flag=true;for (int x =indexX,y=indexY;x<indexX+winNum;x++,y++)if (cell[x][y].getToken() != token){flag=false; break;}if (flag==true) return true;}// check cell[indexX...indexX+winNum-1][indexY...indexY+winNum-1)if (indexX+winNum-1<SIZE && indexY-winNum+1>=0){boolean flag=true;for (int x =indexX,y=indexY;x<indexX+winNum;x++,y--)if (cell[x][y].getToken() != token){flag=false; break;}if (flag==true) return true;}}}return false;}设置棋⼦// An inner class for a cellpublic class Cell extends JPanel implements MouseListener {// Token used for this cellprivate char token = ' ';public Cell() {setBorder(new LineBorder(Color.black, 1)); // Set cell's borderaddMouseListener(this); // Register listener}// The getter method for tokenpublic char getToken() {return token;}// The setter method for tokenpublic void setToken(char c) {token = c;repaint();}导⼊图⽚// Paint the cell@Overridepublic void paintComponent(Graphics g) {if (token == 'X') {ImageIcon icon = new ImageIcon("C:\\Users\\Lenovo\\Desktop\\Black.png");Image image = icon.getImage();g.drawImage(image,0,0,35,35,this);}else if (token=='O'){ImageIcon icon = new ImageIcon("C:\\Users\\Lenovo\\Desktop\\White.png");Image image = icon.getImage();g.drawImage(image,0,0,35,35,this);}super.paintComponents(g);}游戏结束的锁定与弹窗// Handle mouse click on a cell@Overridepublic void mouseClicked(MouseEvent e) {if (ISOVER) return; // if game is over, any issue should be forbiddenint response=-1;if (token == ' ') // If cell is not occupied{if (whoseTurn == 'X') // If it is the X player's turn{setToken('X'); // Set token in the cellwhoseTurn = 'O'; // Change the turnjlblStatus.setText("The White's Turn"); // Display statusif (isWon('X')) {jlblStatus.setText("The Black Won! The Game Is Over!");response = JOptionPane.showConfirmDialog(null, "The Black Won! The Game Is Over!\n" +"Do you want to quit?","提⽰",JOptionPane.YES_NO_OPTION);ISOVER = true;if (response == 0) System.exit(0); // choose "Yes" than quit;}} else if (whoseTurn == 'O') // If it is the O player's turn{setToken('O'); // Set token in the cellwhoseTurn = 'X'; // Change the turnjlblStatus.setText("The Black's Turn"); // Display statusif (isWon('O')) {jlblStatus.setText("The White Won! The Game Is Over!");response = JOptionPane.showConfirmDialog(null, "The White Won! The Game Is Over!\n" +"Do you want to quit?","提⽰",JOptionPane.YES_NO_OPTION);ISOVER = true;if (response == 0) System.exit(0); // choose "Yes" than quit;}}if (isFull()) {jlblStatus.setText("Plain Game! The Game Is Over!");response = JOptionPane.showConfirmDialog(null, "Plain Game! The Game Is Over!\n"+"Do you want to quit?","提⽰",JOptionPane.YES_NO_OPTION);ISOVER = true;if (response == 0) System.exit(0); // choose "Yes" than quit;}}}其他棋⼦信息@Overridepublic void mousePressed(MouseEvent e) {// TODO: implement this java.awt.event.MouseListener method;}@Overridepublic void mouseReleased(MouseEvent e) {// TODO: implement this java.awt.event.MouseListener method;}@Overridepublic void mouseEntered(MouseEvent e) {// TODO: implement this java.awt.event.MouseListener method;}@Overridepublic void mouseExited(MouseEvent e) {// TODO: implement this java.awt.event.MouseListener method;}}}图⽚显⽰以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
基于Java的“网络五子棋”游戏的设计和实现(含源文件)
基于Java的“网络五子棋”游戏的设计和实现——网络版客户端学生:xxx 指导教师:xx内容摘要:目前,随着计算机网络的发展,以计算机技术和网络技术为核心的现代网络技术已经在现实生活和生产中得到了广泛的使用,休闲类网络游戏集趣味性,娱乐性,互动性和益智性于一体,已经成为多数人群的休闲方式,也为多数人所喜好。
本设计收集了关于JAVA基础的书籍,着重收录了关于SOCKET编程的内容,找到了五子棋概述和规则的资料,查阅了网络通信技术的相关论文,同时也参考了很多关于五子棋实现的程序资料以及关于JAVA开发工具的介绍的文档。
在期间,我学习了多线程技术、双缓冲技术、数据传输技术、SOCKET编程技术,研究了网络通信原理、JAVA编写原理等一系列的原理。
开发了网络五子棋网络通信代码,实现了网络聊天、数据传输、网络通信、界面组织如:棋盘、建立服务器、连接到服务器、系统设置、我要参赛等功能。
通过对以上技术的学习和研究,利用SOCKET编程,能服务器与客户端之间的连接,利用多线程技术完成了服务器端与客户端之间的数据传输、网络通信,使得两个客户端能够同步的进行处理。
在加载图片以及绘制棋盘方面,采用双缓冲技术消除屏幕的闪烁现象。
达到了预期的效果。
关键词: 多线程 SOCKET 客户端网络通信Design and realization of the web gobang game based onjava——client moduleAbstract: At present, with the development of computer network, computer technology and network technology as the core of modern network technology has in real life and production has been widely used. Recreational type of network games consists of interesting, entertaining, interactivity and beneficial intelligence. It has become a way of entertainment to many people, and has been loved.Much of the information collected in this design,such as many books based on the JAVA, focus on the contents of SOCKET programming, Find information about the web gobang game, Access to the relevant papers, Reference to a lot of program information on achieving The web gobang game and introduction to JAVA development tools on the document. In the period, I learned a series of principles,For example Multi-threading technology, double-buffering technology, data transmission technology, SOCKET programming technique to study the principle of network communication, JAVA writing principles. Internet chat, data transmission, network communications, interfaces structure, such as: the board, establishing server, connecting server, option had been realized. I know these technologies through studying and researching, I using of SOCKET programming, server and client can be connecting, i using of multi-threading technology to complete the server side and client-side data transmission and the client can synchronize the two processtion. Pictures and drawing board loading, I using of double-buffering to eliminate screen flicker.Keywords:multi-threaded socket client network communication目录前言 (1)1 绪论 (1)1.1 背景 (1)1.2 选题的前提和目的 (1)1.3 五子棋介绍 (2)1.4 主要完成内容 (2)2 开发环境及工具介绍 (3)2.1 开发环境及运行环境 (3)2.1.1 开发环境 (3)2.1.2 运行环境 (3)2.1.2 开发工具 (3)2.2 Java 简介 (3)2.2.1 Java的起源和发展 (3)2.2.2 Java特点 (4)2.3 Java Socket网络编程简介 (5)2.3.1 Java Socket 网络编程基础 (5)2.4 Java 图形编程 (7)3 需求分析和总体设计 (7)3.1 需求分析作用 (7)3.1.1 基本需求分析 (7)3.1.2 高级需求分析 (7)3.2 总体设计 (8)3.2.1 系统设计思想 (8)3.2.2 系统总体设计 (9)3.3 功能模块及流程 (10)3.3.1 系统主要模块 (10)3.3.2 服务器端作用 (10)3.3.3 客户端作用 (11)3.3.4 系统主流程 (12)4 概要设计 (13)4.1 网络编程的模式和选取 (13)4.2 主要类与其作用 (13)4.2.1 服务器类 (13)4.2.2 客户端主类 (15)4.2.3 客户端副类 (15)4.2.4 棋盘类 (16)5 详细设计 (18)5.1 开发环境的搭建 (18)5.1.1 安装JDK (18)5.1.2 安装JRE (19)5.1.3 安装Eclipse (20)5.1.4 配置环境变量 (20)5.2 客户端界面设计 (23)5.3 客户端网络设计 (24)5.4 棋盘类设计 (25)5.5 系统各模块之间的关系 (26)6 软件测试和展示 (27)6.1 软件测试的方法 (27)6.2 网络客户端测试用例 (28)6.3 游戏界面展示 (29)7 总结语 (33)参考文献 (34)基于Java的“网络五子棋”游戏的设计和实现——网络版客户端前言随着经济社会的迅速发展,人们生活水平有了很大的提高,人们的生活观念也发生了巨大的改变。
javafx实现五子棋游戏
javafx实现五⼦棋游戏需求描述⼀个五⼦棋游戏,能实现双⽅⿊⽩对决,当⼀⽅获胜时给出提⽰信息,利⽤GUI界⾯实现项⽬结构如下图⼀、实体FiveChess类提供五⼦棋实体包含的所有信息判断游戏是否结束play⽅法改变chess[][]棋盘中的数据package entity;import javafx.scene.control.Alert;public class FiveChess{public double getWidth() {return width;}public void setWidth(double width) {this.width = width;}public double getHeight() {return height;}public void setHeight(double height) {this.height = height;}public double getCellLen() {return cellLen;}public void setCellLen(double cellLen) {this.cellLen = cellLen;}/*** 维度private int n;private double width;private double height;private double cellLen;private char currentSide='B';public char getFlag() {return flag;}private char flag=' ';private char[][] chess;public char[][] getChess() {return chess;}public void setChess(char[][] chess) {this.chess = chess;}public char getCurrentSide() {return currentSide;}public void setCurrentSide(char currentSide) {this.currentSide = currentSide;}//其他请补充public FiveChess(double width,double height,double cellLen){this.width=width;this.height=height;this.cellLen=cellLen;chess=new char[(int)height][(int)width];for(int i=0;i<height;i++)for(int j=0;j<width;j++)chess[i][j]=' ';}public void play(int x,int y){//将当前的棋⼦放置到(x,y)if(chess[x][y]==' '){chess[x][y]=currentSide;if(!judgeGame(x,y,currentSide)){//游戏结束弹出信息框Alert alert = new Alert(RMATION);alert.setTitle("五⼦棋游戏");alert.setHeaderText("提⽰信息");alert.setContentText(currentSide+"⽅取得胜利!");alert.showAndWait();}changeSide();}}public void changeSide(){//更换下棋⽅setCurrentSide(currentSide=='B'?'W':'B');}public boolean judgeGame(int row, int col, char chessColor){//判断游戏是否结束if(rowJudge(row,col,chessColor)&&colJudge(row,col,chessColor)&&mainDiagonalJudge(row,col,chessColor)&&DeputyDiagonalJudge(row,col,chessColor)) return true;return false;public boolean rowJudge(int row,int col,char chessColor){//判断⼀⾏是否五⼦连线int count=0;for(int j=col;j<width;j++){if(chess[row][j]!=chessColor)break;count++;}for(int j=col-1;j>=0;j--){if(chess[row][j]!=chessColor)break;count++;}if(count>=5)return false;return true;}public boolean colJudge(int row,int col,char chessColor){//判断⼀列是否五⼦连线int count=0;for(int i=row;i<height;i++){if(chess[i][col]!=chessColor)break;count++;}for(int i=row-1;i>=0;i--){if(chess[i][col]!=chessColor)break;count++;}if(count>=5)return false;return true;}public boolean mainDiagonalJudge(int row,int col,char chessColor){ //判断主对⾓线是否五⼦连线int count=0;for(int i=row,j=col;i<height&&j<width;i++,j++){if(chess[i][j]!=chessColor)break;count++;}for(int i=row-1,j=col-1;i>=0&&j>=0;i--,j--){if(chess[i][j]!=chessColor)break;count++;}if(count>=5)return false;return true;}public boolean DeputyDiagonalJudge(int row,int col,char chessColor){ //判断副对⾓线是否五⼦连线int count=0;for(int i=row,j=col;i>=0&&j<width;i--,j++){if(chess[i][j]!=chessColor)break;count++;}for(int i=row+1,j=col-1;i<height&&j>=0;i++,j--){if(chess[i][j]!=chessColor)break;count++;}if(count>=5)return false;return true;}⼆、视图ChessPane类继承Pane类实现棋盘和五⼦棋的绘制package view;import entity.FiveChess;import javafx.scene.canvas.Canvas;import javafx.scene.canvas.GraphicsContext;import yout.Pane;import javafx.scene.paint.Color;public class ChessPane extends Pane {public Canvas getCanvas() {return canvas;}public Canvas canvas;public GraphicsContext getGc() {return gc;}public GraphicsContext gc;public FiveChess getFiveChess() {return fiveChess;}public void setFiveChess(FiveChess fiveChess) {this.fiveChess = fiveChess;}public FiveChess fiveChess;public ChessPane(FiveChess fiveChess){this.fiveChess=fiveChess;double cell=fiveChess.getCellLen();drawPane(cell);drawChess(cell);getChildren().add(canvas);}public void drawPane(double cell){canvas = new Canvas(800,700);gc = canvas.getGraphicsContext2D();gc.clearRect(0,0,canvas.getWidth(),canvas.getHeight());//绘制棋盘gc.setStroke(Color.BLACK);for(int i=0;i<fiveChess.getWidth();i++)for(int j=0;j<fiveChess.getHeight();j++){gc.strokeRect(100+i*cell,100+cell*j,cell,cell);//清理⼀个矩形取区域的内容 }}public void drawChess(double cell){char[][] chess=fiveChess.getChess();for(int i=0;i<fiveChess.getHeight();i++)for(int j=0;j<fiveChess.getWidth();j++){if(chess[i][j]=='B'){gc.setFill(Color.BLACK);//设置填充⾊gc.fillOval(100+i*cell-cell/2,100+j*cell-cell/2,cell,cell);}else if(chess[i][j]=='W'){gc.setFill(Color.WHITE);gc.fillOval(100+i*cell-cell/2,100+j*cell-cell/2,cell,cell);//填充椭圆gc.strokeOval(100+i*cell-cell/2,100+j*cell-cell/2,cell,cell);//绘制轮廓 }}}}三、控制器playAction类继承⾃事件处理器EventHandler并传递的参数是⿏标事件,表⽰接受⿏标点击⾯板事件package controller;import entity.FiveChess;import javafx.event.EventHandler;import javafx.scene.control.Alert;import javafx.scene.input.MouseEvent;import view.ChessPane;public class PlayAction implements EventHandler<MouseEvent> {/**fiveChess表⽰五⼦棋游戏模型*/private FiveChess fiveChess;/**chessPane表⽰五⼦棋显⽰⾯板*/private ChessPane chessPane;public PlayAction(FiveChess fiveChess,ChessPane chessPane){this.chessPane=chessPane;this.fiveChess = fiveChess;}@Overridepublic void handle(MouseEvent event) {//处理⿏标点击事件double cell=fiveChess.getCellLen();//event.getX()获取⿏标点击x坐标,返回double类型double x=event.getX();double y=event.getY();int i=(int)((x-100+cell/2)/cell);int j=(int)((y-100+cell/2)/cell);System.out.println(i+" "+j);fiveChess.play(i,j);chessPane.drawChess(cell);if(!fiveChess.judgeGame(i,j,fiveChess.getCurrentSide()=='B'?'W':'B')){Alert alert = new Alert(RMATION);alert.setTitle("五⼦棋游戏");alert.setHeaderText("提⽰信息");alert.setContentText((fiveChess.getCurrentSide()=='B'?"⽩":"⿊")+"⽅取得胜利!");alert.showAndWait();}}}四、测试import controller.PlayAction;import entity.FiveChess;import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Alert;import javafx.stage.Stage;import view.ChessPane;import javax.print.attribute.standard.Fidelity;public class Test extends Application {public static void main(String[] args) {launch(args);}@Overridepublic void start(Stage primaryStage) {FiveChess fiveChess = new FiveChess(20,20,28.0);ChessPane chesspane=new ChessPane(fiveChess);chesspane.setOnMouseClicked(new PlayAction(fiveChess,chesspane));//事件源绑定处理器Scene scene=new Scene(chesspane,800,700);primaryStage.setScene(scene);primaryStage.setTitle("五⼦棋游戏");primaryStage.show();}}效果图以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
java语言写一个简易的五子棋
java语⾔写⼀个简易的五⼦棋经过16天的java学习,也学得了不少关于Java⽅⾯的知识,我想分享⼀下我⽤java写的⼀个简单的五⼦棋。
游戏规则:(1)对局双⽅各执⼀⾊棋⼦。
(2)空棋盘开局。
(3)⽩先、⿊后,交替下⼦,每次只能下⼀⼦。
(4)棋⼦下在棋盘的空⽩点上,棋⼦下定后,不得向其它点移动,不得从棋盘上拿掉或拿起另落别处。
(5)⽩⽅的第⼀枚棋⼦可下在棋盘任意交叉点上。
(6)任意⼀⽅达成五连⼦即可获胜整体如下:import java.util.Scanner;public class WuZiQi2 {static String[][] a = new String[10][10];public static void main(String[] args) {init();paint();XiaZi();}public static void init() {for (int i = 0; i < a.length; i++) {for (int j = 0; j < a[i].length; j++) {System.out.println(a[i][j]);a[i][j] = "+";}}}public static void paint() {for (int i = 0; i < a.length; i++) {for (int j = 0; j < a[i].length; j++) {System.out.print(a[/**/i][j] + "" + "\t");}System.out.println();}}public static void XiaZi() {boolean flag = true;Scanner s = new Scanner(System.in);int x = 0;int y = 0;while (true) {if (flag) {System.out.println("A下");System.out.println("请输⼊x坐标");x = s.nextInt();System.out.println("请输⼊y坐标");y = s.nextInt();if (x > 10 || y > 10 || x < 1 || y < 1) {System.out.println("请输⼊正确的xy坐标");continue;}if (isRepeat(x, y)) {a[y - 1][x - 1] = "○";paint();} else {continue;}} else {System.out.println("B下");System.out.println("请输⼊x坐标");x = s.nextInt();System.out.println("请输⼊y坐标");y = s.nextInt();if (x > 10 || y > 10 || x < 1 || y < 1) {System.out.println("请输⼊正确的xy坐标");continue;}if (isRepeat(x, y)) {a[y - 1][x - 1] = "●";paint();} else {continue;}}flag = !flag;boolean l = upDown(x - 1, y - 1, a[y - 1][x - 1]);if (l) {break;}boolean p = leftRight(x - 1, y - 1, a[y - 1][x - 1]);if (p) {break;}boolean o = lurd(x - 1, y - 1, a[y - 1][x - 1]);if (o) {break;}boolean f = ruld(x - 1, y - 1, a[y - 1][x - 1]);if (f){break;}}}public static boolean isRepeat(int x, int y) {if (!a[y - 1][x - 1].equals("○") && !a[y - 1][x - 1].equals("●")) { return true;}return false;}public static boolean upDown(int x, int y, String s) {//上下int count = 1;int i = x;int k = y - 1;for (; k >= 0; k--) {if (a[k][i].equals(s)) {count++;}else{break;}}int j = y + 1;for (; j <= 9; j++) {if (a[j][i].equals(s)) {count++;}else{break;}}if (count >= 5) {System.out.println(s + "Win");return true;}return false;}public static boolean leftRight(int x, int y, String s) {//左右int count = 1;int i = x - 1;int k = y;for (; i >= 0; i--) {if (a[k][i].equals(s)) {count++;}else{break;}}int j = x + 1;for (; j <= 9; j++) {if (a[k][j].equals(s)) {count++;}else{break;}}if (count >= 5) {System.out.println(s + "Win");return true;}return false;}public static boolean lurd(int x, int y, String s) {//左上右下int count = 1;int i = x - 1;int k = y - 1;for (; i >= 0 & k >= 0; i--, k--) {if (a[k][i].equals(s)) {count++;}else{break;}}int n = x + 1;int m = y + 1;for (; n <= 9 & m <= 9; n++, m++) {if (a[m][n].equals(s)) {count++;}else{break;}}if (count >= 5) {System.out.println(s + "Win");return true;}return false;}public static boolean ruld(int x, int y,String s){//右上左下 int count = 1;int q = x + 1;int e = y - 1;for (;q<=9&e>=0;q++,e--){if (a[e][q].equals(s)){count++;}else{break;}}int r = x - 1;int t = y + 1;for (;r>=0&t<=9;r--,t++){if (a[t][r].equals(s)){count++;}else{break;}}if (count>=5) {System.out.println(s+"Win");return true;}return false;}}。
java实现简易的五子棋游戏
java实现简易的五⼦棋游戏本⽂实例为⼤家分享了java实现简易五⼦棋游戏的具体代码,供⼤家参考,具体内容如下先上效果图⼀、问题分析1、五⼦棋游戏分析:五⼦棋作为较为普遍且简易的娱乐游戏,受到众多⼈的热爱,且五⼦棋AI也是⼀个较为容易实现的AI。
下⾯我们先来分析游戏规则。
(哈哈,虽然⼤家都知道,但我还是想写写)双⽅分别使⽤⿊⽩两⾊棋⼦,下在棋盘横线交叉处,先连成五⼦者胜利。
(⿊棋禁⼿啥的规则在我的程序⾥没加,就不赘述了)。
2、程序分析:(1)⾸先,五⼦棋开始,我们需要⼀个棋盘,15*15的棋盘,需要⿊⽩棋⼦。
(2)其次,我们需要实现棋⼦顺序的改变,就是实现先下⿊棋,再下⽩棋,然后实现⼀个基本的修正功能,就是通过点击交叉点周围的位置,使棋⼦下到交叉处。
(3)再之后呢,有了棋⼦棋盘,(其实这个时候已经能进⾏下棋了,⾃⼰判断胜负,哈哈),但是呢,我们接下来需要加⼀个判断输赢的功能。
(4)接下来,我们就来丰富我们的五⼦棋游戏,加⼀些功能键,例如重新开始,悔棋,认输,计时啥啥啥的。
(5)最后来⼀个⾼级点的,就是实现⼈机对战,实现AI下棋。
⼆、模块分析1、棋盘棋⼦模块棋盘嘛就⽤直线画就好,横线15条,竖线15条,棋⼦也就两个,可以画得花哨⼀点,⽐如3D棋⼦,也可以简单⼀点就⽤填充圆就好。
博主画了⼀个⿊⾊3D棋⼦,⽩的没画。
(这⾥继承了我之前的⼀个画板,实现直线的重绘,可以去翻⼀翻我的之前有关画板的博客)。
创建⼀个⼆维数组,存放棋⼦,⽤1代表⿊棋,2代表⽩棋,0代表没棋。
⽤count变量来计算到谁下棋了,以及记录下了第⼏颗棋⼦了。
以下是窗体代码public void outUI(){//设置标题this.setTitle("五⼦棋");this.setSize(1680,1380);this.setLayout(null);JButton btn = new JButton();JButton btn1 = new JButton();JButton btn2 = new JButton();JButton btn3 = new JButton();JButton btn4 = new JButton();btn.setBounds(1340, 780, 210, 65);btn1.setBounds(1340,860,210, 65);btn2.setBounds(1340,940,210, 65);btn3.setBounds(320,1200,210, 65);btn4.setBounds(780,1200,210, 65);//获取⼀个图⽚ImageIcon square=new ImageIcon(this.getClass().getResource("JButton1.jpg"));ImageIcon square1=new ImageIcon(this.getClass().getResource("JButton.jpg"));ImageIcon square2=new ImageIcon(this.getClass().getResource("JButton2.jpg"));ImageIcon square3=new ImageIcon(this.getClass().getResource("JButton3.jpg"));ImageIcon square4=new ImageIcon(this.getClass().getResource("JButton4.jpg"));//设置图⽚的⼤⼩square.setImage(square.getImage().getScaledInstance(210, 65, 0));square1.setImage(square1.getImage().getScaledInstance(210, 65, 0));square2.setImage(square2.getImage().getScaledInstance(210, 65, 0));square3.setImage(square3.getImage().getScaledInstance(210, 65, 0));square4.setImage(square4.getImage().getScaledInstance(210, 65, 0));//把图⽚放到按钮上btn.setIcon(square);btn1.setIcon(square1);btn2.setIcon(square2);btn3.setIcon(square3);btn4.setIcon(square4);btn.setText("开始");btn1.setText("悔棋");btn2.setText("认输");btn3.setText("⼈机对战");btn4.setText("⼈⼈对战");this.add(btn);this.add(btn1);this.add(btn2);this.add(btn3);this.add(btn4);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setVisible(true);MyGameListen bn=new MyGameListen();this.addMouseListener(bn);btn.addActionListener(bn);btn1.addActionListener(bn);btn2.addActionListener(bn);btn3.addActionListener(bn);btn4.addActionListener(bn);Graphics f= this.getGraphics();AI Ai=new AI();AI2 Ai2=new AI2();AIPlus Ai3=new AIPlus();bn.ai=Ai;bn.ai2=Ai2;bn.ai3=Ai3;bn.f1=f;Ai.f1=f;Ai2.f1=f;Ai3.f1=f;bn.sn=this;Ai.arr2=bn.arr;Ai2.arr2=bn.arr;Ai3.arr=bn.arr;arragain=bn.arr;showtime a=new showtime();a.count1=bn.count;}int[][] arragain;@Overridepublic void paint(Graphics g) {// TODO Auto-generated method stub//加背景图ImageIcon square5=new ImageIcon(this.getClass().getResource("game.jpeg"));ImageIcon square6=new ImageIcon(this.getClass().getResource("title.jpg"));square5.setImage(square5.getImage().getScaledInstance( 1200,1162,0));square6.setImage(square6.getImage().getScaledInstance( 366,683,0));g.drawImage(square5.getImage(),40,60,this);g.drawImage(square6.getImage(),1280,100,366,683,this);for(int i=1;i<=15;i++){g.drawLine(80, i*80, 1200, i*80);g.drawLine(i*80,80,i*80,1200);}g.drawLine(60,60 , 1220, 60);g.drawLine(60,60 , 60, 1220);g.drawLine(60, 1220, 1220,1220);g.drawLine(1220, 1220, 1220,60);g.fillOval(630, 630, 20, 20);g.fillOval(310, 950, 20, 20);g.fillOval(310, 310, 20, 20);g.fillOval(950, 950, 20, 20);g.fillOval(950, 310, 20, 20);// 绘制棋盘MyGameListen bn1=new MyGameListen();bn1.f1=g;for(int i=0;i<arragain.length;i++) {for(int j=0;j<arragain.length;j++){if(arragain[i][j]==1){Blackchessman(i*80-40,j*80-40,g);}else if(arragain[i][j]==2){whitechessman(i*80-40,j*80-40,g);}}}}public void Blackchessman(int x,int y,Graphics g){for(int i=0;i<80;i++){Color c=new Color(i*3,i*3,i*3);g.setColor(c);g.fillOval(x+i/3, y+i/3, 80-i, 80-i);}}public void whitechessman(int x,int y,Graphics g){g.setColor(Color.white);g.fillOval(x,y,80,80);}以下是⿏标监听器的代码,这⾥有部分变量没有给出,在⽂章末尾会附上完整代码public void mousePressed(MouseEvent e){x1=e.getX();y1=e.getY();m=correct(x1);n=correct(y1);if(x1<=1240&&y1<=1240){if(arr[m/80][n/80]==0){if(count%2!=0){x1=e.getX();y1=e.getY();m=correct(x1);n=correct(y1);Blackchessman(m-40,n-40);arr[m/80][n/80]=1;arr1[m/80][n/80]=count;count++;if( gobangiswin.isWin(arr, m/80, n/80)) {JOptionPane.showMessageDialog(null, "⿊棋WIN!!");}//ai下棋ai3.playchess();arr[ai3.q][ai3.w]=2;arr1[ai3.q][ai3.w]=count;count++;if( gobangiswin.isWin(arr,ai3.q ,ai3.w )) {JOptionPane.showMessageDialog(null, "⽩棋WIN!!");}}}else{x1=e.getX();y1=e.getY();m=correct(x1);n=correct(y1);whitechessman(m-40,n-40);arr[m/80][n/80]=2;arr1[m/80][n/80]=count;count++;if( gobangiswin.isWin(arr, m/80, n/80)) {JOptionPane.showMessageDialog(null, "⽩棋WIN!!");}}}elsereturn;}else {return;}}2、位置修正这个功能其实有很多种实现的⽅法,可以根据⾃⼰的棋盘位置啥的进⾏修正。
java五子棋小游戏
五子棋小游戏1.功能模块图2.游戏说明(1)黑棋先行,白棋随后。
从第一个棋子开始相互顺序落子。
五子棋游戏 开始游戏 执棋子颜色 黑子先行 判断胜负 游戏结束 图1.功能模块图(2)通过坐标索引算出最先在棋盘的横向、竖向、斜向形成连续的相同色五棋子的一方为胜利。
(3)设定游戏界面大小。
(4)在游戏过程中或下完时可选择开局重新开始。
(5)赢家对话框提示。
(6)游戏实现了基本的单机功能但为实现人机对战和人人对战。
3.游戏界面(1)五子棋游戏的主界面,如图2所示。
图2 程序主界面(2)五子棋游戏的结束界面,如图3所示。
图3 游戏结束界面(3)游戏游戏栏中的各个选项,如图4所示。
图4 Game栏中的选项(4)视图设置栏中的各个选项,如图5所示。
图5 Configure栏中的各个选项(5)Help帮助栏中的选项,如图6所示。
图6 Help栏中的选项(6)点击Help栏中的About选项弹出的界面,如图7所示。
图7 About选项弹出时的界面4.设计任务与目的用java语言编程并检验一个学期以来学习java语言的成果,通过编写一个简单的五子棋游戏实践,检验在学习java语言的过程中的特点及不足,进行集资料、查阅文献、方案制定等实践,促进对所学知识应用能力的提高,灵活运用Java使用方法和编程语法,更好的熟练掌握java语言的特点,并及时反省和提高自己的知识和技术。
研究目标:该五子棋游戏应主要包括下述方面:1.初始化界面时棋盘的规格;2.响应鼠标点击并在相应位置画出棋子;3.有一定的智能(可以判断胜负);4.利用java语言中的panel放置棋盘显示棋子(注:其内包含鼠标响应)。
5.参考文献[1]耿祥义.JAVA大学实用教程.北京:电子工业出版社.2005.3:85-113[2]朱战立,沈伟.Java程序设计实用指南.北京:电子工业出版社,2005.1:48-135[3] 唐大仕.Java程序设计[M]. 北京:北方交通大学出版社:2007.05:56-92[4]叶核亚. JAVA2程序设计实用教程[M].北京:电子工业出版社;2008.4:64-98[5]邢素萍. JAVA办公自动化项目方案精解[M].北京:航空工业出版社, 2006.9:35-1206.方法见表方法名功能备注Draw()方法在Graphics类中,绘制一些具体的东西paint()方法重绘图形setColor()设置颜色repaint() 一个具有刷新页面效果consume() 销毁实例的方法Show() 将所建窗口显示出来show()方法将所建窗口显示出来WindowEvent()方法用来处理点击窗体右上角关闭按钮的事件setSize ()方法设定固定大小4.设计任务与目的通过这次五子棋的课程设计,进一步加深对JA V A基础理论的理解,扩大专业知识面,对收集资料、查阅文献、方案制定等实践方面得到了很好的锻练,促进对所学知识应用能力的提高。
java 含类图 五子棋小游戏
Java 设计报告书课程名称:JA V A语言程序设计设计题目:五子棋小游戏院系: 计算机科学与信息工程系学生姓名:学号:专业班级:指导教师:2010 年12 月31 日目录一、题目描述 (3)二、设计思路 (3)三、运行结果 (8)四、源代码 (9)五、总结 (21)六、参考文献: (21)一、题目描述:五子棋是一种两人对弈的纯策略型棋类游戏,是起源于中国,传统五子棋的棋具与围棋相同,棋子分为黑白两色,棋盘为17×10,棋子放置于棋盘线交叉点上。
两人对局,各执一色,轮流下一子,先将横、竖或斜线的5个或5个以上同色棋子连成不间断的一排者为胜。
本课题的功能就是能按照五子棋的规则实现人机对战,并能顺利结束棋局。
二、设计思路:1 类图:2 说明:表2.6 Scan三、运行结果:四、源代码:import java.awt.*;import java.awt.event.*;class ChessPad extends Panel implements MouseListener,ActionListener{ int array[][]=new int[19][19];Scan scanp=new Scan();Scan scanc=new Scan();AutoPlay autoPlay=new AutoPlay();Evaluate evaluatep=new Evaluate();Evaluate evaluatec=new Evaluate();Sort sort=new Sort();int i=0;int x=-1,y=-1,棋子颜色=1;Button button=new Button("重新开局");TextField text_1=new TextField("请黑棋下子"),text_2=new TextField(),text_3=new TextField();ChessPad(){setSize(440,440);setLayout(null);setBackground(Color.pink);addMouseListener(this);add(button);button.setBounds(10,5,60,26);button.addActionListener(this);add(text_1); text_1.setBounds(90,5,90,24);add(text_2); text_2.setBounds(290,5,90,24);add(text_3); text_3.setBounds(200,5,80,24);for(int i=0;i<19;i++)for(int j=0;j<19;j++){array[i][j]=0;}for(int i=0;i<19;i++)for(int j=0;j<19;j++)for(int h=0;h<5;h++){scanp.shape[i][j][h]=0;scanc.shape[i][j][h]=0;}text_1.setEditable(false);text_2.setEditable(false);}public void paint(Graphics g){for (int i=40;i<=400;i=i+20){g.drawLine(40,i,400,i);}for(int j=40;j<=400;j=j+20){g.drawLine(j,40,j,400);}g.fillOval(97,97,6,6);g.fillOval(337,97,6,6);g.fillOval(97,337,6,6);g.fillOval(337,337,6,6);g.fillOval(217,217,6,6);}public void mousePressed(MouseEvent e){int a=0,b=0;if(e.getModifiers()==InputEvent.BUTTON1_MASK){x=(int)e.getX();y=(int)e.getY();ChessPoint_black chesspoint_black=new ChessPoint_black(this);ChessPoint_white chesspoint_white=new ChessPoint_white(this);i++;text_3.setText("这是第"+i+"步");if((x+5)/20<2||(y+5)/20<2||(x-5)/20>19||(y-5)/20>19){}else { a=(x+10)/20;b=(y+10)/20;if(array[b-2][a-2]==0&&棋子颜色==1){this.add(chesspoint_black);chesspoint_black.setBounds(a*20-9,b*20-9,18,18);棋子颜色=棋子颜色*(-1);array[b-2][a-2]=1;if (Judge.judge(array,1)){text_1.setText("黑棋赢!");棋子颜色=2;removeMouseListener(this);}else{text_1.setText(""); }}}if(i>2&&棋子颜色==-1){scanp.scan(array,1);scanc.scan(array,-1);sort.sort(scanp.shape);sort.sort(scanc.shape);evaluatep.evaluate(scanp.shape);evaluatec.evaluate(scanc.shape);棋子颜色=棋子颜色*(-1);this.add(chesspoint_white);if(evaluatep.max>evaluatec.max){text_2.setText(evaluatep.max_x+" "+evaluatep.max_y+" "+evaluatep.max);chesspoint_white.setBounds((evaluatep.max_y+2)*20-9,(evaluatep.max_x+2)*20-9,18,1 8);array[evaluatep.max_x][evaluatep.max_y]=-1;text_1.setText("请黑棋下子");for(int i=0;i<19;i++)for(int j=0;j<19;j++)for(int h=0;h<5;h++){scanp.shape[i][j][h]=0;scanc.shape[i][j][h]=0;}}else{text_2.setText(evaluatec.max_x+" "+evaluatec.max_y+" "+evaluatec.max);chesspoint_white.setBounds((evaluatec.max_y+2)*20-9,(evaluatec.max_x+2)*20-9,18,1 8);array[evaluatec.max_x][evaluatec.max_y]=-1;if (Judge.judge(array,-1)){text_2.setText("白棋赢!");棋子颜色=2;removeMouseListener(this);}else{text_1.setText("请黑棋下子");for(int i=0;i<19;i++)for(int j=0;j<19;j++)for(int h=0;h<5;h++){scanp.shape[i][j][h]=0;scanc.shape[i][j][h]=0;}}}}if(i<=2&&棋子颜色==-1){autoPlay.autoPlay(array,b-2,a-2);this.add(chesspoint_white);棋子颜色=棋子颜色*(-1);chesspoint_white.setBounds((autoPlay.y+2)*20-9,(autoPlay.x+2)*20-9,18,18);array[autoPlay.x][autoPlay.y]=-1;if (Judge.judge(array,-1)){text_2.setText("白棋赢!");棋子颜色=2;removeMouseListener(this);}else{text_1.setText("请黑棋下子");text_2.setText(autoPlay.x+" "+autoPlay.y); }}}}public void mouseReleased(MouseEvent e){}public void mouseEntered(MouseEvent e){}public void mouseExited(MouseEvent e){}public void mouseClicked(MouseEvent e){}public void actionPerformed(ActionEvent e){this.removeAll();棋子颜色=1;add(button);button.setBounds(10,5,60,26);add(text_1);text_1.setBounds(90,5,90,24);text_2.setText("");text_1.setText("请黑棋下子");add(text_2);text_2.setBounds(290,5,90,24);add(text_3); text_3.setBounds(200,5,80,24);i=0;text_3.setText("这是第"+i+"步");for(int i=0;i<19;i++)for(int j=0;j<19;j++){array[i][j]=0;}for(int i=0;i<19;i++)for(int j=0;j<19;j++)for(int h=0;h<5;h++){scanp.shape[i][j][h]=0;scanc.shape[i][j][h]=0;}addMouseListener(this);}}class ChessPoint_black extends Canvas implements MouseListener{ ChessPad chesspad=null;ChessPoint_black(ChessPad p){setSize(20,20);addMouseListener(this);chesspad=p;}public void paint(Graphics g){g.setColor(Color.black);g.fillOval(0,0,18,18);}public void mousePressed(MouseEvent e){/*if(e.getModifiers()==InputEvent.BUTTON3_MASK){chesspad.remove(this);chesspad.棋子颜色=1;chesspad.text_2.setText("");chesspad.text_1.setText("请黑棋下子");}*/}public void mouseReleased(MouseEvent e){}public void mouseEntered(MouseEvent e){}public void mouseExited(MouseEvent e){}public void mouseClicked(MouseEvent e){}}class ChessPoint_white extends Canvas implements MouseListener{ ChessPad chesspad=null;ChessPoint_white(ChessPad p){setSize(20,20);addMouseListener(this);chesspad=p;}public void paint(Graphics g){g.setColor(Color.white);g.fillOval(0,0,18,18);}public void mousePressed(MouseEvent e){/*if(e.getModifiers()==InputEvent.BUTTON3_MASK){chesspad.remove(this);chesspad.棋子颜色=-1;chesspad.text_2.setText("请白棋下子");chesspad.text_1.setText("");}*/}public void mouseReleased(MouseEvent e){}public void mouseEntered(MouseEvent e){}public void mouseExited(MouseEvent e){}public void mouseClicked(MouseEvent e){}}public class Chess extends Frame{ChessPad chesspad=new ChessPad();Chess(){setVisible(true);setLayout(null);Label label=new Label("五子棋",Label.CENTER);add(label);label.setBounds(70,55,440,26);label.setBackground(Color.orange);add(chesspad);chesspad.setBounds(70,90,440,440);addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});pack();setSize(600,550);}public static void main(String args[]){Chess chess=new Chess();}}class AutoPlay{int x,y;void autoPlay(int chesspad[][],int a,int b){int randomNumber=(int)(Math.random()*8)+1;switch(randomNumber){case(1):if(chesspad[a-1][b-1]==0){x=a-1;y=b-1;}else if(chesspad[a-2][b-2]==0){x=a-2;y=b-2;}else {x=a-3;y=b-3;}break;case(2):if(chesspad[a-1][b]==0){x=a-1;y=b;}else if(chesspad[a-2][b]==0){x=a-2;y=b;}else {x=a-3;y=b;}break;case(3):if(chesspad[a-1][b+1]==0){x=a-1;y=b+1;}else if(chesspad[a-2][b+2]==0){x=a-2;y=b+2;}else {x=a-3;y=b+3;}break;case(4):if(chesspad[a][b+1]==0){x=a;y=b+1;}else if(chesspad[a][b+2]==0){x=a;y=b+2;}else {x=a;y=b+3;}break;case(5):if(chesspad[a+1][b+1]==0){x=a+1;y=b+1;}else if(chesspad[a+2][b+2]==0){x=a+2;y=b+2;}else {x=a+3;y=b+3;}break;case(6):if(chesspad[a+1][b]==0){x=a+1;y=b;}else if(chesspad[a+2][b]==0){x=a+2;y=b;}else {x=a+3;y=b;}break;case(7):if(chesspad[a+1][b-1]==0){x=a+1;y=b-1;}else if(chesspad[a+2][b-2]==0){x=a+2;y=b-2;}else {x=a+3;y=b-3;}break;case(8):if(chesspad[a][b-1]==0){x=a;y=b-1;}else if(chesspad[a][b-2]==0){x=a;y=b-2;}else{x=a;y=b+3;}break;}}}class Evaluate{int max_x,max_y,max;public void evaluate(int shape[][][]){int i=0,j=0;for(i=0;i<19;i++)for(j=0;j<19;j++){switch(shape[i][j][0]) {case 5:shape[i][j][4]=200;break;case 4:switch(shape[i][j][1]){case 4:shape[i][j][4]=150+shape[i][j][2]+shape[i][j][3];break;case 3:shape[i][j][4]=100+shape[i][j][2]+shape[i][j][3];break;default:shape[i][j][4]=50+shape[i][j][2]+shape[i][j][3];}break;case 3:switch(shape[i][j][1]){case 3:shape[i][j][4]=75+shape[i][j][2]+shape[i][j][3];break;default:shape[i][j][4]=20+shape[i][j][2]+shape[i][j][3];}break;case 2:shape[i][j][4]=10+shape[i][j][1]+shape[i][j][2]+shape[i][j][3];break;case 1:shape[i][j][4]=shape[i][j][0]+shape[i][j][1]+shape[i][j][2]+shape[i][j][3];default : shape[i][j][4]=0;}}int x=0,y=0;max=0;for(x=0;x<19;x++)for(y=0;y<19;y++)if(max<shape[x][y][4]){max=shape[x][y][4];max_x=x;max_y=y;}}}class Judge{static boolean judge(int a[][],int color){int i,j,flag;for(i=0;i<19;i++){flag=0;for(j=0;j<19;j++)if(a[i][j]==color){flag++;if (flag==5)return true;}else flag=0;}for(j=0;j<19;j++){flag=0;for(i=0;i<19;i++)if(a[i][j]==color){flag++;if(flag==5)return true;}else flag=0;}for(j=4;j<19;j++){flag=0; int m=j;for(i=0;i<=j;i++){if(a[i][m--]==color){flag++;if(flag==5)return true;}else flag=0;}}for(j=14;j>=0;j--){flag=0; int m=j;for(i=0;i<=18-j;i++){if(a[i][m++]==color){flag++;if(flag==5)return true;}else flag=0;}}for(i=14;i>=0;i--){flag=0; int n=i;for(j=0;j<19-i;j++){if(a[n++][j]==color){flag++;if(flag==5)return true;}else flag=0;}}for(j=14;j>=0;j--){flag=0; int m=j;for(i=18;i>=j;i--){if(a[i][m++]==color){flag++;if(flag==5)return true;}else flag=0;}}return false;}}class Scan{int shape[][][]=new int[19][19][5];void scan(int chesspad[][],int colour){int i,j;for(i=0;i<=18;i++)for(j=0;j<=18;j++)if(chesspad[i][j]==0){int m=i,n=j;while(n-1>=0&&chesspad[m][--n]==colour){shape[i][j][0]++;}n=j;while(n+1<=18&&chesspad[m][++n]==colour){shape[i][j][0]++;}n=j;while(m-1>=0&&chesspad[--m][n]==colour){shape[i][j][1]++;}m=i;while(m+1<=18&&chesspad[++m][n]==colour){shape[i][j][1]++;}m=i;while(m-1>=0&&n+1<=18&&chesspad[--m][++n]==colour){shape[i][j][2]++;}m=i;n=j;while(m+1<=18&&n-1>=0&&chesspad[++m][--n]==colour){shape[i][j][2]++;}m=i;n=j;while(m-1>=0&&n-1>=0&&chesspad[--m][--n]==colour){shape[i][j][3]++;}m=i;n=j;while(m+1<=18&&n+1<=18&&chesspad[++m][++n]==colour){shape[i][j][3]++;}}}}class Sort{public void sort(int shape[][][]){int temp;for(int i=0;i<19;i++)for(int j=0;j<19;j++){for(int h=1;h<=4;h++){for(int w=3;w>=h;w--){if(shape[i][j][w-1]<shape[i][j][w]){temp=shape[i][j][w-1];shape[i][j][w-1]=shape[i][j][w];shape[i][j][w]=temp;}}}}}}五、总结:这个程序能够很好地实现它的功能,并且有非常好的界面。
《Java程序设计实训教程》教学课件—02网络五子棋
3. 创建棋子类(1)
• Chess 类
private int col; //棋子在棋盘中的列索引 private int row; //棋子在棋盘中的行索引 private Color color;//颜色 public static final int DIAMETER=GRID_SPAN-2; ChessBoard cb; //棋子是要画在棋盘中,需要一个棋盘的引用 public void draw(Graphics g)
2.9 完善“关闭程序”按钮的功能
1. 在Command类中添加命令
2. 客户端向服务器发送命令
修改“关闭程序”按钮的响应代码 Communication类添加方法disConnect()
3. 服务器处理quit命令 4. 客户端处理delete命令
作业
• 1.目前的程序每方总的用时是在程序中指定的,如果用 户希望在申请对局时自己指定用时时间,程序中应如何处 理?
2. 创建客户端界面右侧的三个类
• 图标: black.jpg, white.jpg • PanelTiming类 • PanelUserList类 • PanelMessage类 • 修改FiveClient类
PanelBoard
PanelTiming PanelUserList
PanelMessage
• 在Five类加入:
private ChessBoard boardPanel; • 准备图片Boad.jpg
Toolkit getDefaultToolkit() getImage()
paintComponent() getPreferredSize() : (Jfram在pack时,要知道board的大小)。
java五子棋报告
五子棋一、程序功能介绍设计一个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 进行简单程序的设计和编写,也更加了解了面向对象的思想。
java课程设计五子棋
下面的原始码分为4个文件;chessclient.java:客户端主程式。
chessinterface.java:客户端的界面。
chesspad.java:棋盘的绘制。
chessserver.java:服务器端。
可同时容纳50个人同时在线下棋,聊天。
没有加上周详注释,不过绝对能运行,j2sdk1.4下通过。
/****************************************************************** ***************************1.chessclient.java******************************************************************* ***************************/import java.awt.*;import java.awt.event.*;import java.io.*;import .*;import java.util.*;class clientthread extends thread{chessclient chessclient;clientthread(chessclient chessclient){this.chessclient=chessclient;}public void acceptmessage(string recmessage){if(recmessage.startswith("/userlist ")){stringtokenizer usertoken=new stringtokenizer(recmessage," "); int usernumber=0;erlist.removeall();erchoice.removeall();erchoice.additem("所有人");while(usertoken.hasmoretokens()){string user=(string)usertoken.nexttoken(" ");if(usernumber>0 && !user.startswith("[inchess]")){erlist.add(user);erchoice.additem(user);}usernumber++;}erchoice.select("所有人");}else if(recmessage.startswith("/yourname ")){chessclient.chessclientname=recmessage.substring(10);chessclient.settitle("java五子棋客户端 "+"用户名:"+chessclient.chessclientname);}else if(recmessage.equals("/reject")){try{chessclient.chesspad.statustext.settext("不能加入游戏");chessclient.controlpad.cancelgamebutton.setenabled(false);chessclient.controlpad.joingamebutton.setenabled(true);chessclient.controlpad.creatgamebutton.setenabled(true);}catch(exception ef){chessclient.chatpad.chatlinearea.settext("chessclient.chesspad.ches ssocket.close无法关闭");}chessclient.controlpad.joingamebutton.setenabled(true);}else if(recmessage.startswith("/peer ")){chessclient.chesspad.chesspeername=recmessage.substring(6);if(chessclient.isserver){chessclient.chesspad.chesscolor=1;chessclient.chesspad.ismouseenabled=true;chessclient.chesspad.statustext.settext("请黑棋下子");}else if(chessclient.isclient){chessclient.chesspad.chesscolor=-1;chessclient.chesspad.statustext.settext("已加入游戏,等待对方下子...");}}else if(recmessage.equals("/youwin")){chessclient.isonchess=false;chessclient.chesspad.chessvictory(chessclient.chesspad.chesscolor);chessclient.chesspad.statustext.settext("对方退出,请点放弃游戏退出连接");chessclient.chesspad.ismouseenabled=false;}else if(recmessage.equals("/ok")){chessclient.chesspad.statustext.settext("创建游戏成功,等待别人加入...");}else if(recmessage.equals("/error")){chessclient.chatpad.chatlinearea.append("传输错误:请退出程式,重新加入\n");}else{chessclient.chatpad.chatlinearea.append(recmessage+"\n");chessclient.chatpad.chatlinearea.setcaretposition(chessclient.chatpad.chatlinearea.gettext().length());}}public void run(){string message="";try{while(true){message=chessclient.in.readutf();acceptmessage(message);}}catch(ioexception es){}}}public class chessclient extends frame implements actionlistener,keylistener{userpad userpad=new userpad();chatpad chatpad=new chatpad();controlpad controlpad=new controlpad();chesspad chesspad=new chesspad();inputpad inputpad=new inputpad();socket chatsocket;datainputstream in;dataoutputstream out;string chessclientname=null;string host=null;int port=4331;boolean isonchat=false; //在聊天?boolean isonchess=false; //在下棋?boolean isgameconnected=false; //下棋的客户端连接?boolean isserver=false; //如果是下棋的主机boolean isclient=false; //如果是下棋的客户端panel southpanel=new panel();panel northpanel=new panel();panel centerpanel=new panel();panel westpanel=new panel();panel eastpanel=new panel();chessclient(){super("java五子棋客户端");setlayout(new borderlayout());host=controlpad.inputip.gettext(); westpanel.setlayout(new borderlayout()); westpanel.add(userpad,borderlayout.north); westpanel.add(chatpad,borderlayout.center); westpanel.setbackground(color.pink); inputpad.inputwords.addkeylistener(this); chesspad.host=controlpad.inputip.gettext(); centerpanel.add(chesspad,borderlayout.center); centerpanel.add(inputpad,borderlayout.south);centerpanel.setbackground(color.pink);controlpad.connectbutton.addactionlistener(this); controlpad.creatgamebutton.addactionlistener(this); controlpad.joingamebutton.addactionlistener(this); controlpad.cancelgamebutton.addactionlistener(this); controlpad.exitgamebutton.addactionlistener(this); controlpad.creatgamebutton.setenabled(false); controlpad.joingamebutton.setenabled(false); controlpad.cancelgamebutton.setenabled(false); southpanel.add(controlpad,borderlayout.center); southpanel.setbackground(color.pink); addwindowlistener(new windowadapter(){public void windowclosing(windowevent e){if(isonchat){try{chatsocket.close();}catch(exception ed){}}if(isonchess || isgameconnected) {try{chesspad.chesssocket.close();}catch(exception ee){}}system.exit(0);}public void windowactivated(windowevent ea) {}});add(westpanel,borderlayout.west);add(centerpanel,borderlayout.center);add(southpanel,borderlayout.south);pack();setsize(670,548);setvisible(true);setresizable(false);validate();}public boolean connectserver(string serverip,int serverport) throws exception{try{chatsocket=new socket(serverip,serverport);in=new datainputstream(chatsocket.getinputstream());out=new dataoutputstream(chatsocket.getoutputstream());clientthread clientthread=new clientthread(this);clientthread.start();isonchat=true;return true;}catch(ioexception ex){chatpad.chatlinearea.settext("chessclient:connectserver:无法连接,建议重新启动程式\n");}return false;}public void actionperformed(actionevent e){if(e.getsource()==controlpad.connectbutton){host=chesspad.host=controlpad.inputip.gettext();try{if(connectserver(host,port)){chatpad.chatlinearea.settext("");controlpad.connectbutton.setenabled(false);controlpad.creatgamebutton.setenabled(true);controlpad.joingamebutton.setenabled(true);chesspad.statustext.settext("连接成功,请创建游戏或加入游戏"); }}catch(exception ei){chatpad.chatlinearea.settext("controlpad.connectbutton:无法连接,建议重新启动程式\n");}}if(e.getsource()==controlpad.exitgamebutton){if(isonchat){try{chatsocket.close();}catch(exception ed){}}if(isonchess || isgameconnected){try{chesspad.chesssocket.close();}catch(exception ee){}}system.exit(0);}if(e.getsource()==controlpad.joingamebutton){string selecteduser=erlist.getselecteditem();if(selecteduser==null || selecteduser.startswith("[inchess]") || selecteduser.equals(chessclientname)){chesspad.statustext.settext("必须先选定一个有效用户");}else{try{if(!isgameconnected){if(chesspad.connectserver(chesspad.host,chesspad.port)){isgameconnected=true;isonchess=true;isclient=true;controlpad.creatgamebutton.setenabled(false);controlpad.joingamebutton.setenabled(false);controlpad.cancelgamebutton.setenabled(true);chesspad.chessthread.sendmessage("/joingame"+erlist.getselecteditem()+" "+chessclientname);}}else{isonchess=true;isclient=true;controlpad.creatgamebutton.setenabled(false);controlpad.joingamebutton.setenabled(false);controlpad.cancelgamebutton.setenabled(true);chesspad.chessthread.sendmessage("/joingame"+erlist.getselecteditem()+" "+chessclientname);}}catch(exception ee){isgameconnected=false;isonchess=false;isclient=false;controlpad.creatgamebutton.setenabled(true);controlpad.joingamebutton.setenabled(true);controlpad.cancelgamebutton.setenabled(false);chatpad.chatlinearea.settext("chesspad.connectserver无法连接\n"+ee);}}}if(e.getsource()==controlpad.creatgamebutton){try{if(!isgameconnected){if(chesspad.connectserver(chesspad.host,chesspad.port)){isgameconnected=true;isonchess=true;isserver=true;controlpad.creatgamebutton.setenabled(false);controlpad.joingamebutton.setenabled(false);controlpad.cancelgamebutton.setenabled(true);chesspad.chessthread.sendmessage("/creatgame "+"[inchess]"+chessclientname);}}else{isonchess=true;isserver=true;controlpad.creatgamebutton.setenabled(false);controlpad.joingamebutton.setenabled(false);controlpad.cancelgamebutton.setenabled(true);chesspad.chessthread.sendmessage("/creatgame "+"[inchess]"+chessclientname);}}catch(exception ec){isgameconnected=false;isonchess=false;isserver=false;controlpad.creatgamebutton.setenabled(true);controlpad.joingamebutton.setenabled(true);controlpad.cancelgamebutton.setenabled(false);ec.printstacktrace();chatpad.chatlinearea.settext("chesspad.connectserver无法连接\n"+ec);}}if(e.getsource()==controlpad.cancelgamebutton){if(isonchess){chesspad.chessthread.sendmessage("/giveup "+chessclientname); chesspad.chessvictory(-1*chesspad.chesscolor);controlpad.creatgamebutton.setenabled(true);controlpad.joingamebutton.setenabled(true);controlpad.cancelgamebutton.setenabled(false);chesspad.statustext.settext("请建立游戏或加入游戏");}if(!isonchess){controlpad.creatgamebutton.setenabled(true);controlpad.joingamebutton.setenabled(true);controlpad.cancelgamebutton.setenabled(false);chesspad.statustext.settext("请建立游戏或加入游戏");}isclient=isserver=false;}}public void keypressed(keyevent e){textfield inputwords=(textfield)e.getsource();if(e.getkeycode()==keyevent.vk_enter){if(erchoice.getselecteditem().equals("所有人")) {try{out.writeutf(inputwords.gettext());inputwords.settext("");}catch(exception ea){chatpad.chatlinearea.settext("chessclient:keypressed无法连接,建议重新连接\n");erlist.removeall();erchoice.removeall();inputwords.settext("");controlpad.connectbutton.setenabled(true);}}else{try{out.writeutf("/"+erchoice.getselecteditem()+""+inputwords.gettext());inputwords.settext("");}catch(exception ea){chatpad.chatlinearea.settext("chessclient:keypressed无法连接,建议重新连接\n");erlist.removeall();erchoice.removeall();inputwords.settext("");controlpad.connectbutton.setenabled(true);}}}}public void keytyped(keyevent e){}public void keyreleased(keyevent e){}public static void main(string args[]){chessclient chessclient=new chessclient();}}/****************************************************************** ************************下面是:chessinteface.java******************************************************************* ***********************/import java.awt.*;import java.awt.event.*;import java.io.*;import .*;class userpad extends panel{list userlist=new list(10);userpad(){setlayout(new borderlayout());for(int i=0;i<50;i++){userlist.add(i+"."+"没有用户");}add(userlist,borderlayout.center);}}class chatpad extends panel{textarea chatlinearea=newtextarea("",18,30,textarea.scrollbars_vertical_only);chatpad(){setlayout(new borderlayout());add(chatlinearea,borderlayout.center);}}class controlpad extends panel{label iplabel=new label("ip",label.left); textfield inputip=new textfield("localhost",10); button connectbutton=new button("连接主机"); button creatgamebutton=new button("建立游戏"); button joingamebutton=new button("加入游戏"); button cancelgamebutton=new button("放弃游戏"); button exitgamebutton=new button("关闭程式"); controlpad(){setlayout(new flowlayout(flowlayout.left));setbackground(color.pink);add(iplabel);add(inputip);add(connectbutton);add(creatgamebutton);add(joingamebutton);add(cancelgamebutton);add(exitgamebutton);}}class inputpad extends panel{textfield inputwords=new textfield("",40); choice userchoice=new choice();inputpad(){setlayout(new flowlayout(flowlayout.left));for(int i=0;i<50;i++){userchoice.additem(i+"."+"没有用户");}userchoice.setsize(60,24);add(userchoice);add(inputwords);}}/****************************************************************** ****************************下面是:chesspad.java******************************************************************* ***************************/import java.awt.*;import java.awt.event.*;import java.io.*;import .*;import java.util.*;class chessthread extends thread{chesspad chesspad;chessthread(chesspad chesspad){this.chesspad=chesspad;}public void sendmessage(string sndmessage){try{chesspad.outdata.writeutf(sndmessage);}catch(exception ea){system.out.println("chessthread.sendmessage:"+ea);}}public void acceptmessage(string recmessage){if(recmessage.startswith("/chess ")){stringtokenizer usertoken=new stringtokenizer(recmessage," "); string chesstoken;string[] chessopt={"-1","-1","0"};int chessoptnum=0;while(usertoken.hasmoretokens()){chesstoken=(string)usertoken.nexttoken(" ");if(chessoptnum>=1 && chessoptnum<=3){chessopt[chessoptnum-1]=chesstoken;}chessoptnum++;}chesspaint(integer.parseint(chessopt[0]),integer.parsei nt(chessopt[1]),integer.parseint(chessopt[2]));}else if(recmessage.startswith("/yourname ")){chesspad.chessselfname=recmessage.substring(10);}else if(recmessage.equals("/error")){chesspad.statustext.settext("错误:没有这个用户,请退出程式,重新加入");}else{//system.out.println(recmessage);}}public void run(){string message="";try{while(true){message=chesspad.indata.readutf(); acceptmessage(message);}}catch(ioexception es){}}}class chesspad extends panel implementsmouselistener,actionlistener{int chesspoint_x=-1,chesspoint_y=-1,chesscolor=1;int chessblack_x[]=new int[200];int chessblack_y[]=new int[200];int chesswhite_x[]=new int[200];int chesswhite_y[]=new int[200];int chessblackcount=0,chesswhitecount=0;int chessblackwin=0,chesswhitewin=0;boolean ismouseenabled=false,iswin=false,isingame=false;textfield statustext=new textfield("请先连接服务器");socket chesssocket;datainputstream indata;dataoutputstream outdata;string chessselfname=null;string chesspeername=null;string host=null;int port=4331;chessthread chessthread=new chessthread(this);chesspad(){setsize(440,440);setlayout(null);setbackground(color.pink);addmouselistener(this);add(statustext);statustext.setbounds(40,5,360,24);statustext.seteditable(false);}public boolean connectserver(string serverip,int serverport) throws exception{try{chesssocket=new socket(serverip,serverport);indata=new datainputstream(chesssocket.getinputstream()); outdata=new dataoutputstream(chesssocket.getoutputstream()); chessthread.start();return true;}catch(ioexception ex){statustext.settext("chesspad:connectserver:无法连接\n"); }return false;}public void chessvictory(int chesscolorwin){this.removeall();for(int i=0;i<=chessblackcount;i++) {chessblack_x[i]=0;chessblack_y[i]=0;}for(int i=0;i<=chesswhitecount;i++) {chesswhite_x[i]=0;chesswhite_y[i]=0;}chessblackcount=0;chesswhitecount=0;add(statustext);statustext.setbounds(40,5,360,24); if(chesscolorwin==1){ chessblackwin++;statustext.settext("黑棋胜,黑:白为"+chessblackwin+":"+chesswhitewin+",重新开局,等待白棋下子...");}else if(chesscolorwin==-1){chesswhitewin++;statustext.settext("白棋胜,黑:白为"+chessblackwin+":"+chesswhitewin+",重新开局,等待黑棋下子...");}}public void getlocation(int a,int b,int color){if(color==1){chessblack_x[chessblackcount]=a*20;chessblack_y[chessblackcount]=b*20;chessblackcount++;}else if(color==-1){chesswhite_x[chesswhitecount]=a*20;chesswhite_y[chesswhitecount]=b*20;chesswhitecount++;}}public boolean checkwin(int a,int b,int checkcolor){int step=1,chesslink=1,chesslinktest=1,chesscompare=0;if(checkcolor==1){chesslink=1;for(step=1;step<=4;step++){for(chesscompare=0;chesscompare<=chessblackcount;chesscompare++) {if(((a+step)*20==chessblack_x[chesscompare]) && ((b*20)==chessblack_y[chesscompare])){chesslink=chesslink+1;if(chesslink==5){return(true);}}}if(chesslink==(chesslinktest+1))chesslinktest++;elsebreak;}for(step=1;step<=4;step++){for(chesscompare=0;chesscompare<=chessblackcount;chesscompare++) {if(((a-step)*20==chessblack_x[chesscompare]) &&(b*20==chessblack_y[chesscompare])){chesslink++;if(chesslink==5){return(true);}}}if(chesslink==(chesslinktest+1))chesslinktest++;elsebreak;}chesslink=1;chesslinktest=1;for(step=1;step<=4;step++){for(chesscompare=0;chesscompare<=chessblackcount;chesscompare++) {if((a*20==chessblack_x[chesscompare]) &&((b+step)*20==chessblack_y[chesscompare])){chesslink++;if(chesslink==5){return(true);}}}if(chesslink==(chesslinktest+1))chesslinktest++;elsebreak;}for(step=1;step<=4;step++){for(chesscompare=0;chesscompare<=chessblackcount;chesscompare++) {if((a*20==chessblack_x[chesscompare]) && ((b-step)*20==chessblack_y[chesscompare])){chesslink++;if(chesslink==5){return(true);}}}if(chesslink==(chesslinktest+1))chesslinktest++;elsebreak;}chesslink=1;chesslinktest=1;for(step=1;step<=4;step++){for(chesscompare=0;chesscompare<=chessblackcount;chesscompare++) {if(((a-step)*20==chessblack_x[chesscompare]) &&((b+step)*20==chessblack_y[chesscompare])){chesslink++;if(chesslink==5){return(true);}}}if(chesslink==(chesslinktest+1))chesslinktest++;elsebreak;}for(step=1;step<=4;step++){for(chesscompare=0;chesscompare<=chessblackcount;chesscompare++) {if(((a+step)*20==chessblack_x[chesscompare]) && ((b-step)*20==chessblack_y[chesscompare])){chesslink++;if(chesslink==5){return(true);}}}if(chesslink==(chesslinktest+1))chesslinktest++;elsebreak;}chesslink=1;chesslinktest=1;for(step=1;step<=4;step++){for(chesscompare=0;chesscompare<=chessblackcount;chesscompare++){if(((a+step)*20==chessblack_x[chesscompare]) && ((b+step)*20==chessblack_y[chesscompare])){chesslink++;if(chesslink==5){return(true);}}}if(chesslink==(chesslinktest+1))chesslinktest++;elsebreak;}for(step=1;step<=4;step++){for(chesscompare=0;chesscompare<=chessblackcount;chesscompare++) {if(((a-step)*20==chessblack_x[chesscompare]) && ((b-step)*20==chessblack_y[chesscompare])){chesslink++;if(chesslink==5){return(true);}}}if(chesslink==(chesslinktest+1))chesslinktest++;elsebreak;。
Java实现五子棋(附详细源码)
Java实现五⼦棋(附详细源码)本⽂实例为⼤家分享了Java实现五⼦棋游戏的具体代码,供⼤家参考,具体内容如下学习⽬的:熟悉java中swing类与java基础知识的巩固.(⽂末有源代码⽂件和打包的jar⽂件)效果图:思路:**1.⾸先构建⼀个Frame框架,来设置菜单选项与按钮点击事件。
MyFrame.java⽂件代码如下package StartGame;import javax.swing.ButtonGroup;import javax.swing.Icon;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JOptionPane;import javax.swing.JRadioButtonMenuItem;import java.awt.Color;import ponent;import java.awt.Container;import java.awt.Graphics;import java.awt.Toolkit;import java.awt.event.ActionListener;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;//窗体框架类public class MyFrame extends JFrame {// static boolean canPlay1 = false;判断是否可以开始游戏final MyPanel panel = new MyPanel();public MyFrame() {// 设置窗体的⼤⼩并居中this.setSize(500, 600); // 设置窗体⼤⼩this.setTitle("五⼦棋游戏"); // 设置窗体标题int height = Toolkit.getDefaultToolkit().getScreenSize().height;// 获取屏幕的⾼度this.setLocation((width - 500) / 2, (height - 500) / 2); // 设置窗体的位置(居中)this.setResizable(false); // 设置窗体不可以放⼤// this.setLocationRelativeTo(null);//这句话也可以设置窗体居中/** 菜单栏的⽬录设置*/// 设置菜单栏JMenuBar bar = new JMenuBar();this.setJMenuBar(bar);// 添加菜单栏⽬录JMenu menu1 = new JMenu("游戏菜单"); // 实例化菜单栏⽬录JMenu menu2 = new JMenu("设置");JMenu menu3 = new JMenu("帮助");bar.add(menu1); // 将⽬录添加到菜单栏bar.add(menu2);bar.add(menu3);JMenu menu4 = new JMenu("博弈模式"); // 将“模式”菜单添加到“设置”⾥⾯menu2.add(menu4);// JMenuItem item1=new JMenuItem("⼈⼈博弈");// JMenuItem item2=new JMenuItem("⼈机博弈");// 设置“”⽬录下⾯的⼦⽬录JRadioButtonMenuItem item1 = new JRadioButtonMenuItem("⼈⼈博弈");JRadioButtonMenuItem item2 = new JRadioButtonMenuItem("⼈机博弈");// item1按钮添加时间并且为匿名类item1.addMouseListener(new MouseListener() {@Overridepublic void mouseReleased(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mousePressed(MouseEvent e) {// TODO Auto-generated method stubIcon icon = new Icon() {@Overridepublic void paintIcon(Component c, Graphics g, int x, int y) {// TODO Auto-generated method stub}@Overridepublic int getIconWidth() {// TODO Auto-generated method stubreturn 0;}@Overridepublic int getIconHeight() {// TODO Auto-generated method stubreturn 0;}};Object[] options = { "保存并重新开始游戏", "不,谢谢" };int n = JOptionPane.showOptionDialog(null, "是否保存设置并重新开始", "⼈机博弈设置", 0, 1, icon, options, "保存并重新开始游戏"); if (n == 0) {panel.setIsManAgainst(true);panel.Start();item1.setSelected(true);}}@Overridepublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}@Override// TODO Auto-generated method stub}@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stub}});// 设置item2按钮的事件监听事件,也就是设置⼈机博弈item2.addMouseListener(new MouseListener() {@Overridepublic void mouseReleased(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mousePressed(MouseEvent e) {// TODO Auto-generated method stubIcon icon = new Icon() {@Overridepublic void paintIcon(Component c, Graphics g, int x, int y) {// TODO Auto-generated method stub}@Overridepublic int getIconWidth() {// TODO Auto-generated method stubreturn 0;}@Overridepublic int getIconHeight() {// TODO Auto-generated method stubreturn 0;}};Object[] options = { "保存并重新开始游戏", "不,谢谢" };int n = JOptionPane.showOptionDialog(null, "是否保存设置并重新开始", "⼈机博弈设置", 0, 1, icon, options, "保存并重新开始游戏"); if (n == 0) {panel.setIsManAgainst(false);panel.Start();item2.setSelected(true);}}@Overridepublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseEntered(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stub}});// 设置按钮组并把⼈机博弈与⼈⼈博弈添加到⼀个按钮组⾥⾯ButtonGroup bg = new ButtonGroup();bg.add(item1);bg.add(item2);// 将按钮组添加到菜单⾥⾯menu4.add(item2);item2.setSelected(true);// 先⾏设置JMenu menu5 = new JMenu("先⾏设置"); // 将“先⾏设置”菜单添加到“设置”⾥⾯menu2.add(menu5);// 设置⿊⼦先⾏还是⽩字先⾏的按钮JRadioButtonMenuItem item3 = new JRadioButtonMenuItem("⿊⽅先⾏");JRadioButtonMenuItem item4 = new JRadioButtonMenuItem("⽩字先⾏");// 设置item3的⿏标点击事件,设置⿊⽅先⾏item3.addMouseListener(new MouseListener() {@Overridepublic void mouseReleased(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mousePressed(MouseEvent e) {// TODO Auto-generated method stubIcon icon = new Icon() {@Overridepublic void paintIcon(Component c, Graphics g, int x, int y) {// TODO Auto-generated method stub}@Overridepublic int getIconWidth() {// TODO Auto-generated method stubreturn 0;}@Overridepublic int getIconHeight() {// TODO Auto-generated method stubreturn 0;}};Object[] options = { "保存并重新开始游戏", "不,谢谢" };int n = JOptionPane.showOptionDialog(null, "是否保存设置并重新开始", "⼈机博弈设置", 0, 1, icon, options, "保存并重新开始游戏"); if (n == 0) {panel.setIsBlack(true);panel.Start();item3.setSelected(true);}}@Overridepublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseEntered(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stub}});// 设置item4的⿏标点击事件item4.addMouseListener(new MouseListener() {@Overridepublic void mouseReleased(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mousePressed(MouseEvent e) {// TODO Auto-generated method stubIcon icon = new Icon() {@Overridepublic void paintIcon(Component c, Graphics g, int x, int y) {// TODO Auto-generated method stub}@Overridepublic int getIconWidth() {// TODO Auto-generated method stubreturn 0;}@Overridepublic int getIconHeight() {// TODO Auto-generated method stubreturn 0;}};Object[] options = { "保存并重新开始游戏", "不,谢谢" };int n = JOptionPane.showOptionDialog(null, "是否保存设置并重新开始", "⼈机博弈设置", 0, 1, icon, options, "保存并重新开始游戏"); if (n == 0) {panel.setIsBlack(false);panel.Start();item4.setSelected(true);}}@Overridepublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseEntered(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stub}});// 设置按钮组并把⼈机博弈与⼈⼈博弈添加到⼀个按钮组⾥⾯ButtonGroup bg1 = new ButtonGroup();bg1.add(item3);bg1.add(item4);// 将按钮组添加到菜单⾥⾯menu5.add(item3);menu5.add(item4);item3.setSelected(true);// 设置“帮助”下⾯的⼦⽬录JMenuItem menu6 = new JMenuItem("帮助");menu3.add(menu6);/** 菜单栏的⽬录设置完毕*/// 开始游戏菜单设置JMenuItem menu7 = new JMenuItem("开始游戏");menu1.add(menu7);JMenuItem menu8 = new JMenuItem("重新开始");menu1.add(menu8);menu7.addMouseListener(new MouseListener() {@Override// TODO Auto-generated method stub}@Overridepublic void mousePressed(MouseEvent e) {// TODO Auto-generated method stubpanel.Start();// panel.repaint();}@Overridepublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseEntered(MouseEvent e) {// TODO Auto-generated method stub}});menu8.addMouseListener(new MouseListener() {@Overridepublic void mouseReleased(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mousePressed(MouseEvent e) {// TODO Auto-generated method stubIcon icon = new Icon() {@Overridepublic void paintIcon(Component c, Graphics g, int x, int y) {// TODO Auto-generated method stub}@Overridepublic int getIconWidth() {// TODO Auto-generated method stubreturn 0;}@Overridepublic int getIconHeight() {// TODO Auto-generated method stubreturn 0;}};Object[] options = { "重新开始游戏", "不,谢谢" };int n = JOptionPane.showOptionDialog(null, "是否重新开始", "消息", 0, 1, icon, options, "保存并重新开始游戏"); if (n == 0) {panel.Start();}// panel.repaint();}@Overridepublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseEntered(MouseEvent e) {// TODO Auto-generated method stub}});// 退出游戏选项设置JMenuItem menu9 = new JMenuItem("退出游戏");menu1.add(menu9);menu9.addMouseListener(new MouseListener() {@Overridepublic void mouseReleased(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mousePressed(MouseEvent e) {// TODO Auto-generated method stubIcon icon = new Icon() {@Overridepublic void paintIcon(Component c, Graphics g, int x, int y) {// TODO Auto-generated method stub}@Overridepublic int getIconWidth() {// TODO Auto-generated method stubreturn 0;}@Overridepublic int getIconHeight() {// TODO Auto-generated method stubreturn 0;}};Object[] options = { "退出游戏", "不,谢谢" };int n = JOptionPane.showOptionDialog(null, "是否退出游戏", "消息", 0, 1, icon, options, "保存并重新开始游戏"); if (n == 0) {System.exit(0);// 退出程序}// panel.repaint();}@Overridepublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseEntered(MouseEvent e) {// TODO Auto-generated method stub}// 游戏难度设置JRadioButtonMenuItem item5 = new JRadioButtonMenuItem("傻⽠");// 添加按钮JRadioButtonMenuItem item6 = new JRadioButtonMenuItem("简单");JRadioButtonMenuItem item7 = new JRadioButtonMenuItem("普通");// JRadioButtonMenuItem item8= new JRadioButtonMenuItem("困难");ButtonGroup bg3 = new ButtonGroup();// 设置按钮组bg3.add(item5);bg3.add(item6);bg3.add(item7);// bg3.add(item8);JMenu menu10 = new JMenu("游戏难度设置");// 添加菜单到主菜单menu2.add(menu10);menu10.add(item5);// 添加选项到难度设置菜单menu10.add(item6);menu10.add(item7);// menu2.add(item8);item5.setSelected(true);// 默认选项按钮// 傻⽠难度设置的⿏标点击事件item5.addMouseListener(new MouseListener() {@Overridepublic void mouseReleased(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mousePressed(MouseEvent e) {// TODO Auto-generated method stubIcon icon = new Icon() {@Overridepublic void paintIcon(Component c, Graphics g, int x, int y) {// TODO Auto-generated method stub}@Overridepublic int getIconWidth() {// TODO Auto-generated method stubreturn 0;}@Overridepublic int getIconHeight() {// TODO Auto-generated method stubreturn 0;}};Object[] options = { "保存并重新开始游戏", "不,谢谢" };int n = JOptionPane.showOptionDialog(null, "是否保存设置并重新开始", "⼈机博弈设置", 0, 1, icon, options, "保存并重新开始游戏"); if (n == 0) {panel.setGameDifficulty(0);panel.Start();item5.setSelected(true);}}@Overridepublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseEntered(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stub});// 简单难度设置模式item6.addMouseListener(new MouseListener() {@Overridepublic void mouseReleased(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mousePressed(MouseEvent e) {// TODO Auto-generated method stubIcon icon = new Icon() {@Overridepublic void paintIcon(Component c, Graphics g, int x, int y) {// TODO Auto-generated method stub}@Overridepublic int getIconWidth() {// TODO Auto-generated method stubreturn 0;}@Overridepublic int getIconHeight() {// TODO Auto-generated method stubreturn 0;}};Object[] options = { "保存并重新开始游戏", "不,谢谢" };int n = JOptionPane.showOptionDialog(null, "是否保存设置并重新开始", "难度设置", 0, 1, icon, options, "保存并重新开始游戏"); if (n == 0) {panel.setGameDifficulty(1);panel.Start();item6.setSelected(true);}}@Overridepublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseEntered(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stub}});// 普通难度设置item7.addMouseListener(new MouseListener() {@Overridepublic void mouseReleased(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mousePressed(MouseEvent e) {// TODO Auto-generated method stubIcon icon = new Icon() {@Overridepublic void paintIcon(Component c, Graphics g, int x, int y) {// TODO Auto-generated method stub}@Overridepublic int getIconWidth() {// TODO Auto-generated method stubreturn 0;}@Overridepublic int getIconHeight() {// TODO Auto-generated method stubreturn 0;}};Object[] options = { "保存并重新开始游戏", "不,谢谢" };int n = JOptionPane.showOptionDialog(null, "是否保存设置并重新开始", "⼈机博弈设置", 0, 1, icon, options, "保存并重新开始游戏"); if (n == 0) {panel.setGameDifficulty(2);panel.Start();item7.setSelected(true);}}@Overridepublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseEntered(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stub}});//游戏帮助提⽰信息menu6.addMouseListener(new MouseListener() {@Overridepublic void mouseReleased(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mousePressed(MouseEvent e) {// TODO Auto-generated method stubIcon icon = new Icon() {@Overridepublic void paintIcon(Component c, Graphics g, int x, int y) {// TODO Auto-generated method stub}@Overridepublic int getIconWidth() {// TODO Auto-generated method stubreturn 0;}@Overridepublic int getIconHeight() {// TODO Auto-generated method stubreturn 0;};JOptionPane.showMessageDialog(null, "制作⼈员:韩红剑");}@Overridepublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseEntered(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stub}});/** 窗⼝⾥⾯的容器设置*/Container con = this.getContentPane(); // 实例化⼀个容器⽗类con.add(panel); // 将容器添加到⽗类/** 窗⼝⾥⾯的容器设置完毕*/}}2.第⼆步,设置显⽰棋盘的容器,⽂件源代码为MyPanel.java package StartGame;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Image;import java.awt.Panel;import java.awt.Toolkit;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.awt.event.MouseMotionListener;import java.awt.image.*;import java.io.File;import .URL;import java.util.Arrays;import java.util.Random;import javax.swing.ImageIcon;import javax.swing.JOptionPane;import javax.swing.JPanel;//设置窗体⾥⾯的容器操作public class MyPanel extends JPanel implements MouseListener, Runnable { private static final Toolkit ResourceUtil = null;public Image boardImg; // 定义背景图⽚static int[][] allChess = new int[15][15]; // 棋盘数组static int[][] temporaryChess = new int[15][15];int x;// 保存棋⼦的横坐标int y;// 保存棋⼦的纵坐标Boolean canPlay = false; // 游戏是否继续,默认为继续Boolean isBlack = true;// 是否是⿊⼦,默认为⿊⼦Boolean isManAgainst = false; // 判断是否是⼈⼈对战String message = "⽤户下棋";Thread t = new Thread(this);int maxTime = 120;int blackTime = 120;int whiteTime = 120;String blackMessage = "⽆限制";String whiteMessage = "⽆限制";static int gameDifficulty = 0;// 设置游戏难度,0为傻⽠模式,1为简单,2为普通,3为困难 // 获取isBlack的值public boolean getIsBlack() {return this.isBlack;}// 设置isBlack的值public void setIsBlack(boolean isBlack) {this.isBlack = isBlack;}// 获取isManAgainst的值public boolean getIsManAgainst() {return this.isManAgainst;}// 获取isManAgainst的值public void setIsManAgainst(boolean isManAgainst) {this.isManAgainst = isManAgainst;}// 获取isManAgainst的值public int getGameDifficulty() {return this.gameDifficulty;}// 设置setGameDifficulty的值public void setGameDifficulty(int gameDifficulty) {this.gameDifficulty = gameDifficulty;}// 构造函数public MyPanel() {boardImg = Toolkit.getDefaultToolkit().getImage("./src/StartGame/fiveCHessBourd.jpg"); this.repaint();// 添加⿏标监视器addMouseListener((MouseListener) this);// addMouseMotionListener((MouseMotionListener) this);// this.requestFocus();t.start();t.suspend();// 线程挂起// t.resume();}// 数据初始化@Overridepublic void paint(Graphics g) {super.paint(g);int imgWidth = boardImg.getWidth(this); // 获取图⽚的宽度int imgHeight = boardImg.getHeight(this); // 获取图⽚的⾼度int FWidth = getWidth();int FHeight = getHeight();String message; // 标记谁下棋int x = (FWidth - imgWidth) / 2;int y = (FHeight - imgHeight) / 2;g.drawImage(boardImg, x, y, null); // 添加背景图⽚到容器⾥⾯g.setFont(new Font("宋体", 0, 14));g.drawString("⿊⽅时间:" + blackTime, 30, 470);g.drawString("⽩⽅时间:" + whiteTime, 260, 470);// 绘制棋盘for (int i = 0; i < 15; i++) {g.drawLine(30, 30 + 30 * i, 450, 30 + 30 * i);g.drawLine(30 + 30 * i, 30, 30 + 30 * i, 450);}// 绘制五个中⼼点g.fillRect(240 - 5, 240 - 5, 10, 10); // 绘制最中⼼的正⽅形g.fillRect(360 - 5, 360 - 5, 10, 10); // 绘制右下的正⽅形g.fillRect(360 - 5, 120 - 5, 10, 10); // 绘制右上的正⽅形g.fillRect(120 - 5, 360 - 5, 10, 10);// 绘制左下的正⽅形g.fillRect(120 - 5, 120 - 5, 10, 10);// 绘制左上的正⽅形// 定义棋盘数组for (int i = 0; i < 15; i++) {for (int j = 0; j < 15; j++) {// if (allChess[i][j] == 1) {// // ⿊⼦// int tempX = i * 30 + 30;// int tempY = j * 30 + 30;// g.fillOval(tempX - 7, tempY - 7, 14, 14);// }// if (allChess[i][j] == 2) {// // ⽩⼦// int tempX = i * 30 + 30;// int tempY = j * 30 + 30;// g.setColor(Color.WHITE);// g.fillOval(tempX - 7, tempY - 7, 14, 14);// g.setColor(Color.BLACK);// g.drawOval(tempX - 7, tempY - 7, 14, 14);// }draw(g, i, j); // 调⽤下棋⼦函数}}}// ⿏标点击时发⽣的函数@Overridepublic void mousePressed(MouseEvent e) {// x = e.getX();// 获取⿏标点击坐标的横坐标// y = e.getY();// 获取⿏标点击坐标的纵坐标// if (x >= 29 && x <= 451 && y >= 29 && y <= 451) { // ⿏标点击在棋⼦框⾥⾯才有效 //// }if (canPlay == true) {// 判断是否可以开始游戏x = e.getX(); // 获取⿏标的焦点y = e.getY();if (isManAgainst == true) {// 判断是否是⼈⼈对战manToManChess();} else { // 否则是⼈机对战,⼈机下棋manToMachine();}}}// 判断是否输赢的函数private boolean checkWin(int x, int y) {// TODO Auto-generated method stubboolean flag = false;// 保存共有多少相同颜⾊棋⼦相连int count = 1;// 判断横向特点:allChess[x][y]中y值相同int color = allChess[x][y];// 判断横向count = this.checkCount(x, y, 1, 0, color);if (count >= 5) {flag = true;} else {// 判断纵向count = this.checkCount(x, y, 0, 1, color);if (count >= 5) {flag = true;} else {// 判断右上左下count = this.checkCount(x, y, 1, -1, color);if (count >= 5) {flag = true;} else {// 判断左下右上count = this.checkCount(x, y, 1, 1, color);if (count >= 5) {flag = true;}}}}return flag;}// 判断相同棋⼦连接的个数private int checkCount(int x, int y, int xChange, int yChange, int color) {// TODO Auto-generated method stubint count = 1;int tempX = xChange;int tempY = yChange;while (x + xChange >= 0 && x + xChange <= 14 && y + yChange >= 0 && y + yChange <= 14 && color == allChess[x + xChange][y + yChange]) {count++;if (xChange != 0) {xChange++;}if (yChange != 0) {if (yChange > 0) {yChange++;} else {yChange--;}}}xChange = tempX;yChange = tempY;while (x - xChange >= 0 && x - xChange <= 14 && y - yChange >= 0 && y - yChange <= 14 && color == allChess[x - xChange][y - yChange]) {count++;if (xChange != 0) {xChange++;}if (yChange != 0) {if (yChange > 0) {yChange++;} else {yChange--;}}}return count;}// 机器⼈判断⿊棋相连的数量private int checkCountMachine(int x, int y, int xChange, int yChange, int color) {// TODO Auto-generated method stubint count = 0;int tempX = xChange;int tempY = yChange;while (x + xChange >= 0 && x + xChange <= 14 && y + yChange >= 0 && y + yChange <= 14 && color == allChess[x + xChange][y + yChange]) {count++;if (xChange != 0) {xChange++;}if (yChange != 0) {if (yChange > 0) {yChange++;} else {yChange--;}}}xChange = tempX;yChange = tempY;while (x - xChange >= 0 && x - xChange <= 14 && y - yChange >= 0 && y - yChange <= 14 && color == allChess[x - xChange][y - yChange]) {count++;if (xChange != 0) {xChange++;}if (yChange != 0) {if (yChange > 0) {yChange++;} else {yChange--;}}}return count;}public void paintConmponents(Graphics g) {super.paintComponents(g);}// 绘制⿊⽩棋⼦public void draw(Graphics g, int i, int j) {if (allChess[i][j] == 1) {g.setColor(Color.black);// ⿊⾊棋⼦g.fillOval(30 * i + 30 - 7, 30 * j + 30 - 7, 14, 14);g.drawString(message, 230, 20);}if (allChess[i][j] == 2) {g.setColor(Color.white);// ⽩⾊棋⼦g.fillOval(30 * i + 30 - 7, 30 * j + 30 - 7, 14, 14);g.drawString(message, 230, 20);}}@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseReleased(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseEntered(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void run() {// TODO Auto-generated method stub// 判断是否有时间限制if (maxTime > 0) {while (true) {// System.out.println(canPlay + "11");if (isManAgainst) {if (isBlack) {blackTime--;if (blackTime == 0) {JOptionPane.showMessageDialog(this, "⿊⽅超时,游戏结束!"); }} else {whiteTime--;if (whiteTime == 0) {JOptionPane.showMessageDialog(this, "⽩⽅超时,游戏结束!"); }}} else {// 监控⿊⼦下棋的时间,也就是⽤户下棋的时间blackTime--;if (blackTime == 0) {JOptionPane.showMessageDialog(this, "⽤户超时,游戏结束!");}// 不监控电脑⽩字下棋}blackMessage = blackTime / 3600 + ":" + (blackTime / 60 - blackTime / 3600 * 60) + ":" + (blackTime - blackTime / 60 * 60);whiteMessage = whiteTime / 3600 + ":" + (whiteTime / 60 - whiteTime / 3600 * 60) + ":" + (whiteTime - whiteTime / 60 * 60);this.repaint();try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}}// 点击开始游戏设置属性,游戏开始public void Start() {this.canPlay = true;for (int i = 0; i < 14; i++) {for (int j = 0; j < 14; j++) {allChess[i][j] = 0;}}if (canPlay == true) {t.resume();}this.repaint();JOptionPane.showMessageDialog(this, "游戏开始了,请开始下棋");if (isBlack == false && isManAgainst == false) {machineChess(gameDifficulty);}// 另⼀种⽅式 allChess=new int[19][19]// message = "⿊⽅先⾏";//// isBlack = true;// blackTime = maxTime;// whiteTime = maxTime;// if (maxTime > 0) {// blackMessage = maxTime / 3600 + ":" + (maxTime / 60 - maxTime / 3600// * 60) + ":"// + (maxTime - maxTime / 60 * 60);// whiteMessage = maxTime / 3600 + ":" + (maxTime / 60 - maxTime / 3600// * 60) + ":"// + (maxTime - maxTime / 60 * 60);// t.resume();// } else {// blackMessage = "⽆限制";// whiteMessage = "⽆限制";// }// this.repaint();// 如果不重新调⽤,则界⾯不会刷新}// ⼈⼈对战下棋函数public void manToManChess() {if (x >= 29 && x <= 451 && y >= 29 && y <= 451) {// System.out.println("在棋盘范围内:"+x+"--"+y);x = (x + 15) / 30 - 1; // 是为了取得交叉点的坐标y = (y + 15) / 30 - 1;if (allChess[x][y] == 0) {// 判断当前要下的是什么棋⼦if (isBlack == true) {allChess[x][y] = 1;isBlack = false;blackTime = 120;message = "轮到⽩⽅";} else {allChess[x][y] = 2;isBlack = true;whiteTime = 120;message = "轮到⿊⽅";}}// 判断这个棋⼦是否和其他棋⼦连成5个boolean winFlag = this.checkWin(x, y);this.repaint(); // 绘制棋⼦if (winFlag == true) {JOptionPane.showMessageDialog(this, "游戏结束," + (allChess[x][y] == 1 ? "⿊⽅" : "⽩⽅") + "获胜!"); canPlay = false;}} else {// JOptionPane.showMessageDialog(this,// "当前位⼦已经有棋⼦,请重新落⼦");}}// ⼈机对战下棋函数public void manToMachine() {if (x >= 29 && x <= 451 && y >= 29 && y <= 451) {// System.out.println("在棋盘范围内:"+x+"--"+y);x = (x + 15) / 30 - 1; // 是为了取得交叉点的坐标y = (y + 15) / 30 - 1;if (allChess[x][y] == 0) {// 判断当前要下的是什么棋⼦if (isBlack == true) {allChess[x][y] = 1;this.repaint(); // 绘制棋⼦machineChess(gameDifficulty);isBlack = true;blackTime = 120;message = "⽤户下棋";whiteTime = 120;boolean winFlag = this.checkWin(x, y);this.repaint(); // 绘制棋⼦if (winFlag == true) {JOptionPane.showMessageDialog(this, "游戏结束," + (allChess[x][y] == 1 ? "⿊⽅" : "⽩⽅") + "获胜!"); canPlay = false;}} else {allChess[x][y] = 1;// allChess[x][y] = 2;this.repaint();isBlack = false;whiteTime = 120;blackTime = 120;boolean winFlag = this.checkWin(x, y);this.repaint(); // 绘制棋⼦if (winFlag == true) {JOptionPane.showMessageDialog(this, "游戏结束," + (allChess[x][y] == 1 ? "⿊⽅" : "⽩⽅") + "获胜!"); canPlay = false;}machineChess(gameDifficulty);}}// 判断这个棋⼦是否和其他棋⼦连成5个// boolean winFlag = this.checkWin(x, y);// this.repaint(); // 绘制棋⼦//// if (winFlag == true) {// JOptionPane.showMessageDialog(this, "游戏结束," + (allChess[x][y] ==// 1 ? "⿊⽅" : "⽩⽅") + "获胜!");// canPlay = false;// }}}。
JAVA五子棋游戏(控制台程序)
JAVA五子棋游戏(控制台程序)//==================类1================================public class Chessboard{private String[][] init;static final int BOARD_SIZE = 22;public void initBoard(){// 初始化棋盘,开始新的游戏时,应该调用此方法init = new String[15][15];for (int i = 0; i < init.length; i++){for (int j = 0; j < init[i].length; j++){init[i][j] = "﹢";}}}public void printBoard(){// 在控制台输出棋盘,各方每一完一颗棋子后,由于棋盘上棋子的状态有改变,// 所以必须调用此方法重新输入棋盘for (String[] row : init){for (String string : row){System.out.print(string);}System.out.println();}}public void setBoard(int posX, int posY, String chessman){// posX与posY是新下棋子的x与y坐标,,chessman是新下棋子的类型(黑子与白子),// 每下完一颗棋子后,通过调用此方法把棋子设置到棋盘上。
if (chessman.equals(Chessman.WHITE.getChessman())){init[posX][posY] = chessman;}else{init[posX][posY] = Chessman.BLACK.getChessman();}}public String[][] getBoard(){// 返回棋盘,返回类型是保存棋盘的二维数组return init;}}//================类2========================public enum Chessman{BLACK("●"), WHITE("○");private String chessman;private Chessman(String chessman){this.chessman = chessman;}public String getChessman(){return this.chessman;}}//=============类3===============================import java.util.Random;import java.util.Scanner;public class GobangGame{public static final int WIN_COUNT = 5;private int posX = 0, posY = 0;private Chessboard chessboard;/** public GobangGame() {** }*/public GobangGame(Chessboard chessboard){this.chessboard = chessboard;}public boolean isVaild(String inputStr){// 此方法验证控制台的输入字符串是否合法,如果合法,返回true,// 如果不合法,则返回false,此方法抛出Exception异常int[] p = new int[2];String[] pointStrings = inputStr.split(",");try{for (int i = 0; i < pointStrings.length; i++){p[i] = Integer.parseInt(pointStrings[i]) - 1;}}catch (Exception e){// TODO Auto-generated catch blockSystem.out.println("输入格式不合法,请重新输入!");return false;}if ((p[0] >= 0 && p[0] < 15) && (p[1] >= 0 && p[1] < 15)) {if (!chessboard.getBoard()[p[1]][p[0]].equals("﹢")){System.out.println("位置不合法,请重新输入!");return false;}else{posX = p[1];posY = p[0];chessboard.setBoard(posX, posY, Chessman.BLACK.getChessman());chessboard.printBoard();return true;}}else{System.out.println("x与y的坐标只能是1~15的数字,请重新输入!");return false;}}public void start(){// 开始游戏// Chessboard chessboard=new Chessboard();chessboard.initBoard();System.out.println("初始化棋盘。
五子棋代码(JAVA)
package ui;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JLabel;import javax.swing.JOptionPane;public class Welcome extends JLabel implements ActionListener {/*** 欢迎界面*/private static final long serialVersionUID = 1L;private FIR father = null;private JButton btnTwoGame = null;// 游戏界面按钮private JButton btnHelp = null;// 游戏帮助按钮private JButton btnExit = null;// 游戏退出按钮/*** Launch the application** @param args*//*** Create the application*/public Welcome(FIR father) {this.father = father;this.setIcon(IconResourses.bgWelcome);initialize();}/*** Initialize the contents of the frame*/private void initialize() {this.setLayout(null);// 先设置布局,再添加组件/** 实例化btnHelp,btnTwoGame,btnExit并设置相关属性,注册监听器*/btnHelp = new JButton(IconResourses.btnHelp);btnHelp.addActionListener(this);btnHelp.setBounds(450, 290, 138, 43);this.add(btnHelp);btnTwoGame = new JButton(IconResourses.btnTwoGame);btnTwoGame.addActionListener(this);btnTwoGame.setBounds(450, 230, 138, 43);this.add(btnTwoGame);btnExit = new JButton(IconResourses.btnExit);btnExit.setBounds(450, 350, 138, 43);btnExit.addActionListener(this);this.add(btnExit);}public void actionPerformed(ActionEvent e) {if (e.getSource() == btnTwoGame) {// 游戏按钮响应方法father.show("game");// 显示游戏界面} else if (e.getSource() == btnHelp) {// 游戏帮助响应方法father.show("help");// 显示帮助界面} else if (e.getSource() == btnExit) {// 游戏退出响应方法// 点击"是"确定退出游戏if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this,"确定退出游戏吗?", "五子棋", JOptionPane.YES_NO_OPTION)) { System.exit(0);}}}}package ui;import javax.swing.JLabel;public class ChessGrid extends JLabel {/*** 棋格*/private static final long serialVersionUID = 1L;private JLabel rim= null;private int row = 0; // 标志当前棋格的行private int col = 0; // 标志当前棋格的列private int flag = 0;// 标志当前棋格的状态:0无子,1黑子,2白子/*** 棋格构造函数无棋子状态** @param row 指定行位置* @param col 指定列位置*/public ChessGrid(int row, int col) {this.row = row;this.col = col;this.init();// 设用类成员初始化方法}/*** 棋格构造函数同时指定棋子状态** @param row 指定行位置* @param col 指定列位置* @param flag:指定状态*/public ChessGrid(int row, int col, int flag) {this.row = row;this.col = col;this.flag = flag;this.init();// 设用类成员初始化方法}/*** 初始化类成员*/private void init() {// 实例化类成员rim = new JLabel(IconResourses.rim);// 设置类成员相关属性rim.setBounds(0, 0, 35, 35);rim.setVisible(false);// 先设置布局,后添加组件this.setLayout(null);this.add(rim);}// 设置选框是否可见public void setRim(boolean flag) {rim.setVisible(flag);}public int getRow() {return row;}public void setRow(int row) {this.row = row;}public int getCol() {return col;}public void setCol(int col) {this.col = col;}// 返回当前棋格的状态public int getFlag() {return flag;}// 设置当前棋格的状态public void setFlag(int flag) {this.flag = flag;if (flag == 0) {this.setIcon(null);} else if (flag == 1) {this.setIcon(IconResourses.lblBlack);} else if (flag == 2) {this.setIcon(IconResourses.lblWhite);}}package ui;import javax.swing.Icon;import javax.swing.ImageIcon;public class IconResourses {public static Icon lblWhite=new ImageIcon(IconResourses.class.getResource("bai.gif"));//白棋子public static Icon lblBlack=new ImageIcon(IconResourses.class.getResource("hei.gif"));//黑棋子public static Icon bq_yiban=new ImageIcon(IconResourses.class.getResource("yiban.gif"));//表情一般public static Icon bq_shikao=new ImageIcon(IconResourses.class.getResource("shikao.gif"));//表情思考public static Icon yiban=new ImageIcon(IconResourses.class.getResource("yiban.gif"));public static Icon lose=new ImageIcon(IconResourses.class.getResource("lose.gif"));//表情一般public static Icon victory=new ImageIcon(IconResourses.class.getResource("victory.gif"));//胜利表情public static Icon btn_pass_un=new ImageIcon(IconResourses.class.getResource("btn_pass_un.gif"));//通过public static Icon btn_pass_on=new ImageIcon(IconResourses.class.getResource("btn_pass_on.gif"));//通过public static Icon btn_reset_un=new ImageIcon(IconResourses.class.getResource("btn_reset_un.gif"));//重置public static Icon btn_reset_on=new ImageIcon(IconResourses.class.getResource("btn_reset_on.gif"));//重置public static Icon btn_send=new ImageIcon(IconResourses.class.getResource("send.jpg"));//发送按钮public static Icon btn_return_un=new ImageIcon(IconResourses.class.getResource("btn_return_un.gif"));//返回public static Icon btn_return_on=new ImageIcon(IconResourses.class.getResource("btn_return_on.gif"));//返回public static Icon btn_goon_on=new ImageIcon(IconResourses.class.getResource("btn_goon_on.gif"));public static Icon btn_goon_un=new ImageIcon(IconResourses.class.getResource("btn_goon_un.gif"));public static Icon btn_start_on=new ImageIcon(IconResourses.class.getResource("btn_start_on.gif"));//开始public static Icon btn_start_un=new ImageIcon(IconResourses.class.getResource("btn_start_on.gif"));//开始public static Icon btn_back_on=new ImageIcon(IconResourses.class.getResource("btn_back_on.gif"));//返回public static Icon btn_back_un=new ImageIcon(IconResourses.class.getResource("btn_back_on.gif"));//返回public static Icon btnHelp=new ImageIcon(IconResourses.class.getResource("help.gif"));//帮助按钮背景public static Icon btnExit=new ImageIcon(IconResourses.class.getResource("exit.gif")); //退出游戏按钮背景public static Icon btnTwoGame=new ImageIcon(IconResourses.class.getResource("twogame.gif"));//双人游戏按钮背景public static Icon btnReturn=new ImageIcon(IconResourses.class.getResource("return.jpg"));public static Icon bgWelcome=new ImageIcon(IconResourses.class.getResource("welcome.gif"));//欢迎界面背景public static Icon bgMain=new ImageIcon(IconResourses.class.getResource("main.gif"));//游戏主界面背景public static Icon bgHelp=new ImageIcon(IconResourses.class.getResource("bg_help.gif"));//帮助界面背景public static Icon rim=new ImageIcon(IconResourses.class.getResource("kuang.gif"));//棋子外框public static Icon sound=new ImageIcon(IconResourses.class.getResource("bg.mid"));//背景音乐}package ui;import java.applet.Applet;import java.applet.AudioClip;/*** 播放声音类* 支持格式: .au、.aiff、.Wav、.Midi、.rfm*/public class Sound{//音乐路径private String url="bg.mid";//音乐对象private AudioClip audio=null;//默认构造函数,播放背景音乐public Sound(){this.init();}//根据新路径播放音乐public Sound(String url){this.url=url;this.init();}//初始化类成员private void init(){if(!"".equals(url)){try {audio = Applet.newAudioClip(Sound.class.getResource(url));} catch (Exception e) {e.printStackTrace();}}}//单曲public void play(){if(audio!=null){audio.stop();audio.play();}}//停止播放public void stop(){if(audio!=null){audio.stop();}}//循环播放public void loop(){if(audio!=null){audio.loop();}}}package ui;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JLabel;/*** 游戏帮助界面* @author*/public class Help extends JLabel implements ActionListener {/*** 版本号*/private static final long serialVersionUID = 1L;private FIR father = null;//父容器引用,构造函数中传入private JButton btnReturn = null;//返回欢迎界面按钮/*** 游戏帮助界面构造函数* @param father父容器引用*/public Help(FIR father) {//父容器引用传入,赋值this.father = father;//调用类成员初始化方法this.init();//此类继函至JLabel,以此可设置游戏欢迎界面的背景this.setIcon(IconResourses.bgHelp);}/*** 初始化方法* 此方法主要目的是:1 实例化类成员2 布局*/private void init(){//实例化类成员btnReturn = new JButton(IconResourses.btnReturn);//设置类成员位置大小btnReturn.setBounds(310, 470, 50,23);//为类成员注册监听器btnReturn.addActionListener(this);//先设设置布局,再添加组件this.setLayout(null);//添加组件this.add(btnReturn);}public void actionPerformed(ActionEvent e) {if (e.getSource() == btnReturn) {//返回按钮响应方法//显示欢迎界面father.show("welcome");}}}package ui;import java.awt.Color;import java.awt.Graphics;import java.awt.Image;import java.awt.Toolkit;import javax.swing.*;public class Timer extends JPanel implements Runnable{/*** 时间设置以JLable作为载体*/private static final long serialVersionUID = 1L;private static Image image=Toolkit.getDefaultToolkit().createImage(Timer.class.getResource("number.gif"));private Game father;//调用父类private int secTemp;//从play开始到pause用了多少秒,每次play之后归0,secTemp记录从双方每一次落子到落子完成并暂停计时器时所消耗的时间private int seconds=1800;//比赛总时间private Thread time;//时间线程private boolean flag;//是否处于计时中/** 构造函数,默认比赛总时间为30分钟*/public Timer(Game father){this.father=father;this.init();}/** 构造函数,设置比赛总时间*/public Timer(Game father,int seconds){this.father=father;this.seconds=seconds;this.init();}/** 对私有属性seconds公开化*/public int getSeconds(){return this.seconds;}public void setSeconds(int seconds){this.seconds=seconds;this.repaint();//重置完时间后,刷新画板}/** 初始化相关成员*/private void init(){this.setBackground(Color.black);flag=false;time=new Thread(this);time.start();//启动线程,使其处于就绪状态}/** 重写JLalbe中的paint方法*/public void paint(Graphics g){super.paint(g);int temp=seconds/60;int i=0;//画分钟十位i=temp/10;g.drawImage(image, 0, 0, 9, 16, i*9, 0, (i+1)*9, 16, this);//画分钟个位i=temp%10;g.drawImage(image, 10, 0, 19, 16, i*9, 0, (i+1)*9, 16, this);//画中间线g.drawImage(image, 20, 0,29 ,16, 90, 0, 99, 16, this);//计算出秒数temp=seconds%60;//画秒钟个位i=temp/10;g.drawImage(image, 30, 0, 39, 16, i*9, 0, (i+1)*9, 16, this);//画秒钟个位i=temp%10;g.drawImage(image, 40, 0,49, 16, i*9, 0, (i+1)*9, 16, this); }/** 暂停时间*/public void pause(){this.flag=false;}/** 继续时间*/public void play(){this.flag=true;this.secTemp=0;}/** 实现线程的run接口*/public void run(){while(true){if(flag){if(seconds>0){seconds--;secTemp++;this.repaint();}else{father.timeOver();}}try{Thread.sleep(1000);}catch(Exception e){e.printStackTrace();}}}public int getSecTemp(){return this.secTemp;}}package ui;import java.awt.Cursor;import java.awt.Graphics;import java.awt.Image;import java.awt.Point;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.util.ArrayList;import javax.swing.JButton;import javax.swing.JLabel;import javax.swing.JOptionPane;public class Game extends JLabel implements MouseListener, ActionListener { /*** 游戏主界面*/private static final long serialVersionUID = 1L;private FIR father;private ChessGrid[][] crosses = new ChessGrid[15][15];// 实例化棋盘数组private ChessGrid temp = null;// 上一步棋格private int start = 0;// 游戏运行状态0未开始1进行中2暂停3回放private boolean flag = true;// 哪方行棋,true为黑方,false为白方private JButton btnStart = null;// 开始按钮private JButton btnReturn = null;// 返回按钮private JButton btnPass = null;// 暂停按钮private JButton btnBack = null;// 悔棋private Timer palTimeBai = null;// 白方剩余时间private Timer palTimeHei = null;// 黑方剩余时间private JLabel lblEmotionBai = null;// 白方表情private JLabel lblEmotionHei = null;// 黑方表情private ArrayList<ChessGrid> qb = null;// 棋步private Image image;// 鼠标图片/** 构造函数,转到FIR中去*/public Game(FIR father) {this.father = father;init();// 初始化类成员getImage("hei.gif");// 当转到该界面时,鼠标变成黑色的棋子this.setVisible(true);this.reSet();// 重置游戏参数}/** 初始化*/public void init() {this.setIcon(IconResourses.bgMain);// 棋盘背景界面this.setLayout(null);// 无布局// 循环棋盘格子,实例化,设置属性,同时添加监听器,并添加到游戏界面上int i = 0;// 行int j = 0;// 列for (i = 0; i < 15; i++) {for (j = 0; j < 15; j++) {crosses[i][j] = new ChessGrid(i, j);crosses[i][j].setBounds(163 + j * 35, 13 + i * 35, 35, 35);crosses[i][j].addMouseListener(this);this.add(crosses[i][j]);}}// 实例化保存棋步的容器qb = new ArrayList<ChessGrid>();// 实例化其它成员lblEmotionBai = new JLabel(IconResourses.bq_yiban);lblEmotionHei = new JLabel(IconResourses.bq_yiban);btnStart = new JButton(IconResourses.btn_start_on);btnBack = new JButton(IconResourses.btn_back_un);btnPass = new JButton(IconResourses.btn_pass_un);btnReturn = new JButton(IconResourses.btn_return_on);/** 黑白双方时间*/palTimeBai = new Timer(this);// palTimeBai.setSeconds(600);palTimeBai.setVisible(true);palTimeHei = new Timer(this);// palTimeHei.setSeconds(600);palTimeHei.setVisible(true);// 设置其它成员属性lblEmotionBai.setBounds(45, 65, 65, 65);lblEmotionHei.setBounds(45, 345, 65, 65);palTimeBai.setBounds(73, 206, 50, 16);palTimeHei.setBounds(73, 487, 50, 16);btnStart.setBounds(13, 250, 30, 60);btnBack.setBounds(78, 250, 30, 60);btnPass.setBounds(45, 250, 30, 60);btnReturn.setBounds(110, 250, 30, 60);// btnStart.setDisabledIcon(IconResourses.btn_start_un);// btnBack.setDisabledIcon(IconResourses.btn_back_un);// btnPass.setDisabledIcon(IconResourses.btn_pass_un);// btnReturn.setDisabledIcon(IconResourses.btn_return_un);btnStart.addActionListener(this);btnBack.addActionListener(this);btnPass.addActionListener(this);btnReturn.addActionListener(this);// 添加其它成员this.add(palTimeBai);this.add(palTimeHei);this.add(lblEmotionBai);this.add(lblEmotionHei);this.add(btnStart);this.add(btnBack);this.add(btnPass);this.add(btnReturn);}public void reSet() {// 重置棋盘for (int i = 0; i < 15; i++) {for (int j = 0; j < 15; j++) {crosses[i][j].setFlag(0);crosses[i][j].setRim(false);}}start = 0;// 游戏标志设置为0,未开始flag = true;// 重新开始游戏,黑方先行棋// 暂停时间,并重置为1800秒palTimeBai.pause();palTimeBai.setSeconds(1800);palTimeHei.pause();palTimeHei.setSeconds(1800);// 重置表情lblEmotionBai.setIcon(IconResourses.bq_yiban);lblEmotionHei.setIcon(IconResourses.bq_yiban);qb.clear();// 清空棋步数组// 重置按钮图标btnStart.setIcon(IconResourses.btn_start_on);btnPass.setIcon(IconResourses.btn_pass_on);// 锁定一些功能按钮btnBack.setEnabled(false);btnPass.setEnabled(false);}/** 实现四个按钮的动作监听*/public void actionPerformed(ActionEvent e) {if (e.getSource() == btnStart) {// 开始游戏或重置游戏if (start == 0) {// 游戏未开始,执行开始操作btnStart.setIcon(IconResourses.btn_reset_on);// 开始按钮变为重置按钮btnPass.setIcon(IconResourses.btn_pass_on);// 暂停按钮变为可用的按钮btnBack.setIcon(IconResourses.btn_back_un);// 悔棋按钮变为可用的按钮/** 初始化并将黑子居中*/crosses[7][7].setBounds(163 + 7 * 35, 13 + 7 * 35, 35, 35);crosses[7][7].setFlag(1);crosses[7][7].setRim(true);qb.add(crosses[7][7]);// palTimeHei.play();// palTimeBai.pause();getImage("bai.gif");// 鼠标变成白子的图片flag = false;// 下一步为白子// 黑方先走,开始计时if (flag == true) {palTimeHei.play();palTimeBai.pause();} else {palTimeBai.play();palTimeHei.pause();}lblEmotionBai.setIcon(IconResourses.bq_shikao);// 设置黑方表情btnPass.setEnabled(true);// 暂停按钮可用btnBack.setEnabled(false);// 悔棋按钮不可用start = 1;// 标志游戏是在进行中} else {// 否则执行游戏重置操作this.reSet();}} else if (e.getSource() == btnPass) {// 暂停或继续游戏if (start == 1) {// 游戏进行中,进行暂停操作// 暂停时间palTimeBai.pause();palTimeHei.pause();start = 2;// 标志游戏为暂停状态btnPass.setIcon(IconResourses.btn_goon_on);// 更改成继续图标/** 暂停中不可悔棋*/btnBack.setIcon(IconResourses.btn_back_un);btnBack.setEnabled(false);} else if (start == 2) {// 游戏暂停中,进行继续操作// 根据当前是哪方下子,play相应的时间if (flag == true) {// 黑方行棋,开始计时palTimeHei.play();} else {// 白方行棋,开始计时palTimeBai.play();}start = 1;// 标志游戏为进行状态btnPass.setIcon(IconResourses.btn_pass_on);// 更改成暂停图标/** 游戏进行中可悔棋*/btnBack.setIcon(IconResourses.btn_back_on);btnBack.setEnabled(true);}} else if (e.getSource() == btnBack) {// 悔棋// 有棋步记录,且获得对方的同意,才可以悔棋int answer = JOptionPane.showConfirmDialog(null, "对方请求悔棋,是不答应?","信息", JOptionPane.YES_NO_OPTION);if (qb.size() > 0) {// 清除掉可能后来选择的一些格子方框if (temp != null) {temp.setRim(false);}// 取得最后下的一步棋,同时将它从棋步数组中移除/** 只能在白方行了第二着棋之后才能悔棋*/if (answer == 0 && qb.size() >= 5) {// 如果用户点击“确定”所做的操作ChessGrid box = qb.remove(qb.size() - 1);// 置空最后一步棋box.setFlag(0);box.setRim(false);}else{btnBack.setEnabled(false);}// 下棋角色,时间,表情对换// int answer=1;if (flag) {// 当前为黑方下棋,说明是白方悔棋flag = false;lblEmotionBai.setIcon(IconResourses.bq_shikao);lblEmotionHei.setIcon(IconResourses.bq_yiban);// 把被白方浪费掉的时间,返还给黑方,同时被浪费掉的这部分时间视为白方的palTimeHei.pause();int timewasteHei = palTimeHei.getSecTemp();// 黑棋还未下这一步棋所用时间palTimeHei.setSeconds(palTimeHei.getSeconds()+ timewasteHei);// palTimeBai.setSeconds(palTimeBai.getSeconds()-timewasteHei);palTimeBai.play();getImage("bai.gif");}} else {// 当前为白方下棋,说明是黑方悔棋flag = true;lblEmotionBai.setIcon(IconResourses.bq_yiban);lblEmotionHei.setIcon(IconResourses.bq_shikao);// 把被黑方浪费掉的时间,返还给白方,同时被浪费掉的这部分时间视为黑方的palTimeBai.pause();int timewasteBai = palTimeBai.getSecTemp();// 白棋上一步棋所用时间palTimeBai.setSeconds(palTimeBai.getSeconds() + timewasteBai);// palTimeHei.setSeconds(palTimeHei.getSeconds()-timewasteBai);palTimeHei.play();getImage("hei.gif");}// 没有棋步记录时,悔棋不可用,否则取得当前棋步数组中的最后一个子,进行红框标注if (qb.size() == 0) {btnBack.setEnabled(false);} else {// get(index)和remove(index)都返回当前数组中的最后一个对象// 区别是,get仅返回不从数组中删除这个对象,而remove返回的同时从数组中移除这个对象qb.get(qb.size() - 1).setRim(true);btnBack.setIcon(IconResourses.btn_back_on);btnBack.setEnabled(true);}} else if (e.getSource() == btnReturn) {// 返回欢迎界面// 游戏中,提示是否返回if (start > 0) {if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this, "正在游戏中,返回将导至游戏信息丢失!", "五子棋",JOptionPane.YES_NO_OPTION)) {father.show("welcome");// 重置游戏this.reSet();}} else {father.show("welcome");}}}/** 当改白子行棋时鼠标上的图片变成白棋的图片,当改黑子行棋时鼠标上的图片变成黑棋的图片*/private void getImage(String image_url) {image = java.awt.Toolkit.getDefaultToolkit().createImage(FIR.class.getResource(image_url));Cursor transparentCursor = java.awt.Toolkit.getDefaultToolkit().createCustomCursor(image, new Point(0, 0), "invisiblecursor"); // invisiblecursor是任意取的this.setCursor(transparentCursor);}/** 下棋的事件操作方法*/public void mouseClicked(MouseEvent e) {}/** 实现落子功能*/public void mousePressed(MouseEvent e) {crosses[7][7].setRim(false);/* 去掉当前棋上一步棋的外框*/if (qb.size() != 0) {temp = qb.get(qb.size() - 1);temp.setRim(false);}if (qb.size() == 4) {btnBack.setEnabled(true);}ChessGrid lblChessGrid = (ChessGrid) e.getSource();// 按键触发的是棋格上的JLableif (start == 1 && e.getButton() == 1) {// 游戏是否在进行中,同时只有左键起效if (lblChessGrid.getFlag() == 0) {// 只有无子的情况下,才允许落子,有子的情况下,不允许落子if (flag == false) {// 白子行棋getImage("hei.gif");// 鼠标变成黑子palTimeBai.pause();palTimeHei.play();lblChessGrid.setFlag(2);lblChessGrid.setVisible(true);lblChessGrid.setRim(true);qb.add(lblChessGrid);lblEmotionBai.setIcon(IconResourses.bq_yiban);lblEmotionHei.setIcon(IconResourses.bq_shikao);if (checkWin(lblChessGrid.getRow(), lblChessGrid.getCol())) {// System.out.println("fdk;");lblEmotionBai.setIcon(IconResourses.victory);lblEmotionHei.setIcon(IconResourses.lose);palTimeHei.pause();JOptionPane.showMessageDialog(this, "白方赢了!");this.gameOver();}flag = true;} else {// 黑子行棋getImage("bai.gif");// 鼠标变成白子palTimeHei.pause();palTimeBai.play();lblChessGrid.setFlag(1);lblChessGrid.setVisible(true);lblChessGrid.setRim(true);qb.add(lblChessGrid);lblEmotionBai.setIcon(IconResourses.bq_shikao);lblEmotionHei.setIcon(IconResourses.bq_yiban);if (checkWin(lblChessGrid.getRow(), lblChessGrid.getCol())) {lblEmotionBai.setIcon(IconResourses.lose);lblEmotionHei.setIcon(IconResourses.victory);palTimeBai.pause();JOptionPane.showMessageDialog(this, "黑方赢了!");this.gameOver();}flag = false;}}}}public void mouseReleased(MouseEvent e) {}public void mouseEntered(MouseEvent e) {}public void mouseExited(MouseEvent e) {}@Overridepublic void printComponents(Graphics arg0) {// TODO Auto-generated method stubsuper.printComponents(arg0);}/** 判胜处理*/// 检查当前下子是否可以胜利private boolean checkWin(int row, int col) {if (checkNum(row, col, 1) >= 5 || checkNum(row, col, 2) >= 5|| checkNum(row, col, 3) >= 5 || checkNum(row, col, 4) >= 5) { return true;} else {return false;}}// 判断连子数,type:1纵向,2横向,3左斜,4右斜private int checkNum(int row, int col, int type) {int nextrow = 0;// 向上走int nextcol = 0;int count = 1;int num = 0;if (row >= 0 && row < 15 && col >= 0 && col < 15) {if (type == 1) {// 纵向nextrow = row;// 向上走nextcol = col - 1;while (crosses[row][col].getFlag() != 0 && nextcol >= 0) {if (crosses[nextrow][nextcol].getFlag() == crosses[row][col].getFlag()) {count++;nextcol--;} else {break;}}nextrow = row;// 向下走nextcol = col + 1;while (crosses[row][col].getFlag() != 0 && nextcol < 15) { if (crosses[nextrow][nextcol].getFlag() == crosses[row][col].getFlag()) {count++;nextcol++;} else {break;}}num = count;}if (type == 2) {// 横向nextrow = row - 1;// 向左走nextcol = col;while (crosses[row][col].getFlag() != 0 && nextcol >= 0) { if (crosses[nextrow][nextcol].getFlag() == crosses[row][col].getFlag()) {count++;nextrow--;} else {break;}}nextrow = row + 1;// 向右走nextcol = col;while (crosses[row][col].getFlag() != 0 && nextcol < 15) { if (crosses[nextrow][nextcol].getFlag() == crosses[row][col].getFlag()) {count++;nextrow++;} else {break;}}num = count;}if (type == 3) {// 左斜nextrow = row - 1;// 向左上走nextcol = col - 1;while (crosses[row][col].getFlag() != 0 && nextcol >= 0&& nextrow >= 0) {if (crosses[nextrow][nextcol].getFlag() == crosses[row][col].getFlag()) {count++;nextrow--;nextcol--;} else {break;}}nextrow = row + 1;// 向左下走nextcol = col + 1;while (crosses[row][col].getFlag() != 0 && nextcol < 15&& nextrow < 15) {if (crosses[nextrow][nextcol].getFlag() == crosses[row][col].getFlag()) {count++;nextrow++;nextcol++;} else {break;}}num = count;}if (type == 4) {// 右斜nextrow = row - 1;// 向右下走nextcol = col + 1;while (crosses[row][col].getFlag() != 0 && nextcol >= 0&& nextrow >= 0) {if (crosses[nextrow][nextcol].getFlag() == crosses[row][col].getFlag()) {count++;nextrow--;nextcol++;} else {break;}}nextrow = row + 1;// 向右上走nextcol = col - 1;while (crosses[row][col].getFlag() != 0 && nextcol < 15&& nextrow < 15) {if (crosses[nextrow][nextcol].getFlag() == crosses[row][col].getFlag()) {count++;nextrow++;nextcol--;} else {break;}}num = count;}}return num;}// 游戏结束后清空棋盘public void gameOver() {this.reSet();// 重置棋盘}// 游戏重新开始的处理方法public void reStart() {}/** 双方任何一方还未分胜负之前时间用完后的处理*/public void timeOver() {if (palTimeBai.getSeconds() == 0 && palTimeHei.getSeconds() != 0) { JOptionPane.showMessageDialog(this, "白方游戏时间到,黑方获胜");gameOver();}if (palTimeBai.getSeconds() != 0 && palTimeHei.getSeconds() == 0) { JOptionPane.showMessageDialog(this, "黑方游戏时间到,白方获胜");gameOver();}if (palTimeBai.getSeconds() == 0 && palTimeHei.getSeconds() == 0) { JOptionPane.showMessageDialog(this, "游戏时间到,不分胜负");gameOver();}}}package ui;import java.awt.CardLayout;import java.awt.Dimension;import java.awt.event.WindowEvent;import java.awt.event.WindowListener;import javax.swing.JFrame;import javax.swing.JOptionPane;import java.awt.Toolkit;public class FIR extends JFrame implements WindowListener{private static final long serialVersionUID = 1L;private CardLayout layout;//布局private Welcome welcome;//欢迎界面private Help help;//帮助界面private Sound bgSound;//游戏背景音乐private Game game;//游戏界面/*** Launch the application* @param args*/public static void main(String args[]) {try {FIR window = new FIR();window.setVisible(true);} catch (Exception e) {e.printStackTrace();}}/*** Create the application*/public FIR() {initialize();init();}/*** Initialize the attributes of the frame*/private void initialize() {this.setTitle("单机版五子棋(无禁手)");this.setSize(700, 575);Dimension screen=Toolkit.getDefaultToolkit().getScreenSize();this.setLocation((screen.width-700)/2, (screen.height-550)/2);this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);this.addWindowListener(this);//添加窗体监听器this.setResizable(false);}/*** 动态初始化该窗体*/public void init(){welcome=new Welcome(this);help=new Help(this);game=new Game(this);bgSound=new Sound();bgSound.loop();//循环播放背景音乐layout=new CardLayout();//将窗体设置为卡片布局this.setLayout(layout);this.add(welcome, "welcome");this.add(help,"help");this.add(game,"game");}/*** 显示相应名称的卡片* @param name 要显示的卡片的名称*/public void show(String name){layout.show(this.getContentPane(), name);}/***实现WindowListener接口中的抽象方法*/public void windowOpened(WindowEvent e){}/*** 在点游戏窗体关闭按钮时,提示是否退出游戏*/public void windowClosing(WindowEvent arg0) {//点击"是"确定退出游戏if(JOptionPane.YES_OPTION==JOptionPane.showConfirmDialog(this, "确定退出游戏吗?","五子棋",JOptionPane.YES_NO_OPTION)){System.exit(0);}}public void windowClosed(WindowEvent e){}public void windowIconified(WindowEvent e){}public void windowDeiconified(WindowEvent e){}public void windowActivated(WindowEvent e){}public void windowDeactivated(WindowEvent e){}}。
java五子棋小游戏实验报告(附源代码)
手机五子棋游戏得设计与实现专业:姓名:班级:学号:指导教师:摘要J2ME(Java 2 Micro Edition)就是近年来随着各种不同设备,尤其就是移动通信设备得飞速发展而诞生得一项开发技术。
它因其“writeonce,run anywhere"得Java特性而提高了开发得效率.随着手机性能得不断提高,手机休闲娱乐应用将成为PC休闲娱乐应用之后又一重要业务增长点。
棋类游戏规则单一,比较适合在手机等便携终端推广。
由于具有跨平台、易于移植、占用空间小得优势,J2ME成为移动应用开发平台得主流,并提供了很多用以支持移动应用软件得开发得API。
现将该技术用于这次得手机游戏开发,可以实现游戏得快速开发,不但便于查瞧游戏运行过程中内存得占用量与程序得每一部分代码消耗了多少处理器时间,而且可以不断地优化代码,使代码具有高度得复用性、可扩展性、可维护性。
游戏得开发以J2ME为平台,利用Java技术,结合J2ME得MIDP技术,并对于程序设计思想,重要类、方法等展开讨论。
在对弈部分,分析设计走棋算法,选择合适得方式组织成代码,实现基本得人工智能。
过程中使用了J2ME中得CLDC/MIDP软件体系,主要运用了MID Profile得特定类得支持,来完成游戏得开发。
关键词:J2ME;CLDC;MIDPAbstractJ2ME isa kind offast developing technology implemented on various devicesespecially mobile municationequipments、It improves the efficiency of the developmentprocess because of its ”write once,run anywhere” nature、Thedevelopment trendof the entertainment market based on thecell phone is very obviousbecause the handset performanceenhances unceasingly、The entertainment market basedon the cellphone willto be thenew important business growthpoint follow the PCentertainment market、As therules of asingle chess game,itis more suitable for mobile phones and other portable terminal extension、J2ME has been thepreferred platform for development because ofits platformindependentand patibility,and provides a lot of APIs to support the development of mobile applicationsoftware、Thetechnology for mobilegame development,can achieve the rapid development of thegame、It is not only easy too bserve the memory consumption andprocessor consumed timedu ring theoperation ofthe game, but also can optimize the cod e,sothatthecode has a highdegreeofreusability,scalability,maintainability、The game has designed by J2ME,the Java technology and the MIDP technology、Istudiedthe procedurethought,the imp ortantclass andthemethod、In the playing chess part,I have analyzed the algorithm,choosed theappropriateway to organize the code and realized the basic artificial intelligence、On the other hand,I learned software systemofCLDC/MIDPand the specific class oftheMID Propletethegame develo pment、Keywords: J2ME;CLDC;MIDP目录1 概述ﻩ错误!未定义书签。
Java实现五子棋游戏的完整代码
Java实现五⼦棋游戏的完整代码⽤Java编写简单的五⼦棋,供⼤家参考,具体内容如下前⾔这两天在空闲时间做了个五⼦棋项⽬,分享给⼤家看⼀下,界⾯是这样的:界⾯很丑我知道,本⼈虽有⼏年PS基础,但知识浅薄,审美观不尽⼈意,做到如此实属极限(其实我懒得做了),⼤家将就着看看吧。
下⾯放出代码,为⽅便⼤家参考,我⼏乎每条代码都标有注释。
测试类代码public class Test {public static void main(String[] args) {MyJFrame mj=new MyJFrame();mj.myJFrame();}}MyJFrame类代码import javax.imageio.ImageIO;import javax.swing.*;import java.awt.*;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;public class MyJFrame extends JFrame implements MouseListener {int qx = 20, qy = 40, qw = 490, qh = 490;//棋盘位置、宽⾼int bw = 150, bh = 50, bx = 570, by = 150;//按钮宽⾼、位置int x = 0, y = 0;//保存棋⼦坐标int[][] SaveGame = new int[15][15];//保存每个棋⼦int qc = 1;//记录⽩棋=2,⿊棋=1int qn = 0;//判断棋⼦是否重复boolean canplay = true;//判断游戏是否开始和结束String go = "⿊⼦先⾏";//游戏信息//---------------------------------------------------------------------------------------------------------------------//窗体public void myJFrame() {this.setTitle("五⼦棋"); //标题this.setSize(800, 550); //窗⼝⼤⼩this.setResizable(false); //窗⼝是否可以改变⼤⼩=否this.setDefaultCloseOperation(MyJFrame.EXIT_ON_CLOSE);//窗⼝关闭⽅式为关闭窗⼝同时结束程序 int width = Toolkit.getDefaultToolkit().getScreenSize().width;//获取屏幕宽度int height = Toolkit.getDefaultToolkit().getScreenSize().height;//获取屏幕⾼度// System.out.println("宽度:"+width);//测试// System.out.println("⾼度:"+height);//测试this.setLocation((width - 800) / 2, (height - 600) / 2); //设置窗⼝默认位置以屏幕居中this.addMouseListener(this);this.setVisible(true); //窗⼝是否显⽰=是}//---------------------------------------------------------------------------------------------------------------------//覆写paint⽅法,绘制界⾯public void paint(Graphics g) {//双缓冲技术防⽌屏幕闪烁BufferedImage bi = new BufferedImage(800, 550, BufferedImage.TYPE_INT_ARGB);Graphics g2 = bi.createGraphics();//获取图⽚路径BufferedImage image = null;try {image = ImageIO.read(new File("D:/#Java/五⼦棋/tp/wzqbj.jpg"));} catch (IOException e) {e.printStackTrace();}g2.drawImage(image, 10, 10, this);//显⽰图⽚g2.setColor(Color.BLACK);//设置画笔颜⾊g2.setFont(new Font("华⽂⾏楷", 10, 50));//设置字体g2.drawString("晓时五⼦棋", 525, 100);//绘制字符//棋盘g2.setColor(Color.getHSBColor(30, (float) 0.10, (float) 0.90));//设置画笔颜⾊g2.fillRect(qx, qy, qw, qh);//绘制棋盘背景矩形//开始按钮g2.setColor(Color.WHITE);//设置画笔颜⾊g2.fillRect(bx, by, bw, bh);//绘制开始按钮g2.setFont(new Font("华⽂⾏楷", 10, 30));//设置字体g2.setColor(Color.black);//设置画笔颜⾊g2.drawString("开始", 615, 185);//绘制字符//悔棋按钮g2.setColor(Color.LIGHT_GRAY);//设置画笔颜⾊g2.fillRect(bx, by + 60, bw, bh);//绘制悔棋按钮g2.setFont(new Font("华⽂⾏楷", 10, 30));//设置字体g2.setColor(Color.WHITE);//设置画笔颜⾊g2.drawString("悔棋", 615, 245);//绘制字符//认输按钮g2.setColor(Color.GRAY);//设置画笔颜⾊g2.fillRect(bx, by + 120, bw, bh);//绘制认输按钮g2.setFont(new Font("华⽂⾏楷", 10, 30));//设置字体g2.setColor(Color.WHITE);//设置画笔颜⾊g2.drawString("认输", 615, 305);//绘制字符//游戏信息栏g2.setColor(Color.getHSBColor(30, (float) 0.10, (float) 0.90));//设置画笔颜⾊g2.fillRect(550, 350, 200, 150);//绘制游戏状态区域g2.setColor(Color.black);//设置画笔颜⾊g2.setFont(new Font("⿊体", 10, 20));//设置字体g2.drawString("游戏信息", 610, 380);//绘制字符g2.drawString(go, 610, 410);//绘制字符g2.drawString("作者:晓时⾕⾬", 560, 440);//绘制字符g2.drawString("联系⽅式:", 560, 465);//绘制字符g2.drawString("qq 717535996", 560, 490);//绘制字符g2.setColor(Color.BLACK);//设置画笔颜⾊//绘制棋盘格线for (int x = 0; x <= qw; x += 35) {g2.drawLine(qx, x + qy, qw + qx, x + qy);//绘制⼀条横线g2.drawLine(x + qx, qy, x + qx, qh + qy);//绘制⼀条竖线}//绘制标注点for (int i = 3; i <= 11; i += 4) {for (int y = 3; y <= 11; y += 4) {g2.fillOval(35 * i + qx - 3, 35 * y + qy - 3, 6, 6);//绘制实⼼圆}}//绘制棋⼦for (int i = 0; i < 15; i++) {for (int j = 0; j < 15; j++) {if (SaveGame[i][j] == 1)//⿊⼦{int sx = i * 35 + qx;int sy = j * 35 + qy;g2.setColor(Color.BLACK);g2.fillOval(sx - 13, sy - 13, 26, 26);//绘制实⼼圆}if (SaveGame[i][j] == 2)//⽩⼦{int sx = i * 35 + qx;int sy = j * 35 + qy;g2.setColor(Color.WHITE);g2.fillOval(sx - 13, sy - 13, 26, 26);//绘制实⼼圆g2.setColor(Color.BLACK);g2.drawOval(sx - 13, sy - 13, 26, 26);//绘制空⼼圆}}}g.drawImage(bi, 0, 0, this);// g.drawRect(20, 20, 20, 20);//绘制空⼼矩形}//--------------------------------------------------------------------------------------------------------------------- //判断输赢private boolean WinLose() {boolean flag = false;//输赢int count = 1;//相连数int color = SaveGame[x][y];//记录棋⼦颜⾊//判断横向棋⼦是否相连int i = 1;//迭代数while (color == SaveGame[x + i][y]) {count++;i++;}i = 1;//迭代数while (color == SaveGame[x - i][y]) {count++;i++;}if (count >= 5) {flag = true;}//判断纵向棋⼦是否相连count = 1;i = 1;//迭代数while (color == SaveGame[x][y + i]) {count++;i++;}i = 1;//迭代数while (color == SaveGame[x][y - i]) {count++;i++;}if (count >= 5) {flag = true;}//判断斜向棋⼦是否相连(左上右下)count = 1;i = 1;//迭代数while (color == SaveGame[x - i][y - i]) {count++;i++;}i = 1;//迭代数while (color == SaveGame[x + i][y + i]) {count++;i++;}if (count >= 5) {flag = true;}//判断斜向棋⼦是否相连(左下右上)count = 1;i = 1;//迭代数while (color == SaveGame[x + i][y - i]) {count++;i++;}i = 1;//迭代数while (color == SaveGame[x - i][y + i]) {count++;i++;}if (count >= 5) {flag = true;}return flag;}//--------------------------------------------------------------------------------------------------------------------- //初始化游戏public void Initialize() {//遍历并初始化数组for (int i = 0; i < 15; i++) {for (int j = 0; j < 15; j++) {SaveGame[i][j] = 0;}}//⿊⼦先⾏qc = 1;go = "轮到⿊⼦";}//--------------------------------------------------------------------------------------------------------------------- @Override//⿏标点击public void mouseClicked(MouseEvent e) {}@Override//⿏标按下public void mousePressed(MouseEvent e) {//获取⿏标点击位置x = e.getX();y = e.getY();//判断是否已开始游戏if (canplay == true) {//判断点击是否为棋盘内if (x > qx && x < qx + qw && y > qy && y < qy + qh) {//计算点击位置最近的点if ((x - qx) % 35 > 17) {x = (x - qx) / 35 + 1;} else {x = (x - qx) / 35;}if ((y - qy) % 35 > 17) {y = (y - qy) / 35 + 1;} else {y = (y - qy) / 35;}//判断当前位置有没有棋⼦if (SaveGame[x][y] == 0) {SaveGame[x][y] = qc;qn = 0;} else {qn = 1;}//切换棋⼦if (qn == 0) {if (qc == 1) {qc = 2;go = "轮到⽩⼦";} else {qc = 1;go = "轮到⿊⼦";}}this.repaint();//重新执⾏⼀次paint⽅法//弹出胜利对话框boolean wl = this.WinLose();if (wl) {JOptionPane.showMessageDialog(this, "游戏结束," + (SaveGame[x][y] == 1 ? "⿊⽅赢了" : "⽩⽅赢了"));//弹出提⽰对话框 canplay = false;}// System.out.println(1);//测试} else {// System.out.println(0);//测试}}//实现开始按钮//判断是否点击开始按钮if (e.getX() > bx && e.getX() < bx + bw && e.getY() > by && e.getY() < by + bh) {//判断游戏是否开始if (canplay == false) {//如果游戏结束,则开始游戏canplay = true;JOptionPane.showMessageDialog(this, "游戏开始");//初始化游戏Initialize();this.repaint();//重新执⾏⼀次paint⽅法} else {//如果游戏进⾏中,则重新开始JOptionPane.showMessageDialog(this, "重新开始");//初始化游戏Initialize();this.repaint();//重新执⾏⼀次paint⽅法}}//实现悔棋按钮//判断是否点击悔棋按钮if (e.getX() > bx && e.getX() < bx + bw && e.getY() > by + 60 && e.getY() < by + 60 + bh) {//判断游戏是否开始if (canplay == true) {//遍历棋盘上是否有棋⼦int z = 0;for (int i = 0; i < 15; i++) {for (int j = 0; j < 15; j++) {if (SaveGame[i][j] != 0) {z++;}}}//判断是否有棋⼦if (z != 0) {JOptionPane.showMessageDialog(this, "下棋亦如⼈⽣,你⾛的每⼀步都没有回头路。
java五子棋程序
一个很经典的java 五子棋程序(源码)import java.awt.*;import java.awt.event.*;import java.applet.Applet;import java.awt.Color;publicclass enzit extends Applet implementsActionListener,MouseListener,MouseMotionListener,ItemListener { int color_Qizi=0;// 旗子的颜色标识0: 白子1: 黑子int intGame_Start=0;// 游戏开始标志0 未开始 1 游戏中int intGame_Body[][]=newint[16][16]; // 设置棋盘棋子状态0 无子 1 白子 2 黑子Button b1=new Button(" 游戏开始");Button b2=new Button(" 重置游戏");Label lblWin=new Label(" ");Checkbox ckbHB[]=new Checkbox[2];CheckboxGroup ckgHB=new CheckboxGroup(); public void init() { 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();}publicvoid itemStateChanged(ItemEvent e){if (ckbHB[0].getState()) // 选择黑子先还是白子先{color_Qizi=0;}else{color_Qizi=1;}}publicvoid actionPerformed(ActionEvent e){Graphics g=getGraphics();if (e.getSource()==b1){Game_start();}else{Game_re();}}publicvoid mousePressed(MouseEvent e){} publicvoid mouseClicked(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);}publicvoid mouseEntered(MouseEvent e){} publicvoid mouseExited(MouseEvent e){} publicvoid mouseReleased(MouseEvent e){} publicvoid mouseDragged(MouseEvent e){}public void mouseMoved(MouseEvent e){}publicvoid paint(Graphics g){ draw_qipan(g);}publicvoid set_Qizi(int x,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(int i=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 (int i=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(int x,int y) //{int x1,y1,t=1; x1=x;y1=y;for (int i=1;i<5 ;i++ ){if (x1>15){break;}if (intGame_Body[x1+i][y1]==intGame_Body[x][y]) { t+=1; }else{break;}}for (int i=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(int x,int y) // 判断输赢竖{int x1,y1,t=1;x1=x;y1=y;for (int i=1;i<5 ;i++ ){if (x1>15){if (intGame_Body[x1][y1+i]==intGame_Body[x][y]){t+=1;}else{break;} for (int i=1;i<5 ;i++ ) {if (x1<1){break;} if(intGame_Body[x1][y1-i]==intGame_Body[x][y]){t+=1;}else{break;}}return true;}else{return false;}}publicboolean Game_win_3(int x,int y) // 判断输赢左斜{int x1,y1,t=1;x1=x;y1=y;for (int i=1;i<5 ;i++ ){if (x1>15){break;}if (intGame_Body[x1+i][y1-i]==intGame_Body[x][y]) {t+=1;}else{for (int i=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){return true;}else{return false;}}publicboolean Game_win_4(int x,int y) // 判断输赢左斜{int x1,y1,t=1;x1=x;y1=y;for (int i=1;i<5 ;i++ ){if (x1>15){break;}if (intGame_Body[x1+i][y1+i]==intGame_Body[x][y]){t+=1;}else{break;}}for (int i=1;i<5 ;i++ ) {if (x1<1){if(intGame_Body[x1-i][y1-i]==intGame_Body[x][y]) {t+=1;}else{break;}}if (t>4){returntrue;}else{returnfalse;}}}。
java实现简单五子棋小游戏(1)
java实现简单五⼦棋⼩游戏(1)本⽂实例为⼤家分享了java实现简单五⼦棋⼩游戏的具体代码,供⼤家参考,具体内容如下讲解五⼦棋,实际上就是⽤⼀个数组来实现的。
没有其他很复杂的结构。
⾸先我们制作五⼦棋,先要有⼀个棋盘。
public void setGraphics(Graphics g){this.g=g;for(int i=0;i<11;i++){g.drawLine(100+Size*i, 100, 100+Size*i, 500);g.drawLine(100, 100+Size*i, 500, 100+Size*i);}for(int i=0;i<11;i++){for(int j=0;j<11;j++){chessboard[i][j]=0;}}}此时我们在画布上制作了⼀个棋盘,图⽰如下:接下来我们要实现的就是如何去放置棋⼦了。
放置棋⼦⼤体思路就是,当我们点击⼀个⽹格点的时候,可以出现⼀个⽩棋或者⿊棋,所以我们在这⾥需要学会如何画⼀个椭圆。
// 绘制⼀个椭圆g.drawOval(a-Size/4, b-Size/4, Size/2, Size/2);//修改左上⾓的坐标,使画好的圆恰好在以⽹格点所在的位置上// 填充⼀个椭圆g.setColor(Color.BLACK);g.fillOval(a-Size/4, b-Size/4, Size/2, Size/2);此时,点击某⼀个位置就会出现⼀个⿊棋⼦。
这⾥我们需要注意的是,我们不可能要求⽤户每⼀次的点击都⾮常准确,所以我们必须设定⼀个范围,只要这个范围内的点击,我们都默认点击到了这个⽹格上⾯。
因为⽹格⼤⼩为40,所以我们以⼀个⽹格点位中⼼,向上下左右移动20长度的范围都属于这个点。
⽩棋的设置也⼀样if(number==0){// 绘制⼀个椭圆g.drawOval(a-Size/4, b-Size/4, Size/2, Size/2);//修改左上⾓的坐标,使画好的圆恰好在以⽹格点所在的位置上// 填充⼀个椭圆g.setColor(Color.BLACK);g.fillOval(a-Size/4, b-Size/4, Size/2, Size/2);number++;}else{g.drawOval(a-Size/4, b-Size/4, Size/2, Size/2);// 填充⼀个椭圆g.setColor(Color.WHITE);g.fillOval(a-Size/4, b-Size/4, Size/2, Size/2);number--;}现在我们看⼀下我们的棋盘,⽩棋和⿊棋都可以放到棋盘上⾯了,但是依旧存在⼀个问题,当我们在同⼀位置点击两次后会发⽣覆盖现象。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
2 说明:表2.6 Scan方法名功能备注public void evaluate(int shape[][][]) 电脑用于估计玩家下步棋的走法三、运行结果:四、源代码:import java.awt.*;import java.awt.event.*;class ChessPad extends Panel implements MouseListener,ActionListener{ int array[][]=new int[19][19];Scan scanp=new Scan();Scan scanc=new Scan();AutoPlay autoPlay=new AutoPlay();Evaluate evaluatep=new Evaluate();Evaluate evaluatec=new Evaluate();Sort sort=new Sort();int i=0;int x=-1,y=-1,棋子颜色=1;Button button=new Button("重新开局");TextField text_1=new TextField("请黑棋下子"),text_2=new TextField(),text_3=new TextField();ChessPad(){setSize(440,440);setLayout(null);setBackground(Color.pink);addMouseListener(this);add(button);button.setBounds(10,5,60,26);button.addActionListener(this);add(text_1); text_1.setBounds(90,5,90,24);add(text_2); text_2.setBounds(290,5,90,24);add(text_3); text_3.setBounds(200,5,80,24);for(int i=0;i<19;i++)for(int j=0;j<19;j++){array[i][j]=0;}for(int i=0;i<19;i++)for(int j=0;j<19;j++)for(int h=0;h<5;h++){scanp.shape[i][j][h]=0;scanc.shape[i][j][h]=0;}text_1.setEditable(false);text_2.setEditable(false);}public void paint(Graphics g){for (int i=40;i<=400;i=i+20){g.drawLine(40,i,400,i);}for(int j=40;j<=400;j=j+20){g.drawLine(j,40,j,400);}g.fillOval(97,97,6,6);g.fillOval(337,97,6,6);g.fillOval(97,337,6,6);g.fillOval(337,337,6,6);g.fillOval(217,217,6,6);}public void mousePressed(MouseEvent e){int a=0,b=0;if(e.getModifiers()==InputEvent.BUTTON1_MASK){x=(int)e.getX();y=(int)e.getY();ChessPoint_black chesspoint_black=new ChessPoint_black(this);ChessPoint_white chesspoint_white=new ChessPoint_white(this);i++;text_3.setText("这是第"+i+"步");if((x+5)/20<2||(y+5)/20<2||(x-5)/20>19||(y-5)/20>19){}else { a=(x+10)/20;b=(y+10)/20;if(array[b-2][a-2]==0&&棋子颜色==1){this.add(chesspoint_black);chesspoint_black.setBounds(a*20-9,b*20-9,18,18);棋子颜色=棋子颜色*(-1);array[b-2][a-2]=1;if (Judge.judge(array,1)){text_1.setText("黑棋赢!");棋子颜色=2;removeMouseListener(this);}else{text_1.setText(""); }}}if(i>2&&棋子颜色==-1){scanp.scan(array,1);scanc.scan(array,-1);sort.sort(scanp.shape);sort.sort(scanc.shape);evaluatep.evaluate(scanp.shape);evaluatec.evaluate(scanc.shape);棋子颜色=棋子颜色*(-1);this.add(chesspoint_white);if(evaluatep.max>evaluatec.max){text_2.setText(evaluatep.max_x+" "+evaluatep.max_y+" "+evaluatep.max);chesspoint_white.setBounds((evaluatep.max_y+2)*20-9,(evaluatep.max_x+2)*20-9,18,1 8);array[evaluatep.max_x][evaluatep.max_y]=-1;text_1.setText("请黑棋下子");for(int i=0;i<19;i++)for(int j=0;j<19;j++)for(int h=0;h<5;h++){scanp.shape[i][j][h]=0;scanc.shape[i][j][h]=0;}}else{text_2.setText(evaluatec.max_x+" "+evaluatec.max_y+" "+evaluatec.max);chesspoint_white.setBounds((evaluatec.max_y+2)*20-9,(evaluatec.max_x+2)*20-9,18,1 8);array[evaluatec.max_x][evaluatec.max_y]=-1;if (Judge.judge(array,-1)){text_2.setText("白棋赢!");棋子颜色=2;removeMouseListener(this);}else{text_1.setText("请黑棋下子");for(int i=0;i<19;i++)for(int j=0;j<19;j++)for(int h=0;h<5;h++){scanp.shape[i][j][h]=0;scanc.shape[i][j][h]=0;}}}}if(i<=2&&棋子颜色==-1){autoPlay.autoPlay(array,b-2,a-2);this.add(chesspoint_white);棋子颜色=棋子颜色*(-1);chesspoint_white.setBounds((autoPlay.y+2)*20-9,(autoPlay.x+2)*20-9,18,18);array[autoPlay.x][autoPlay.y]=-1;if (Judge.judge(array,-1)){text_2.setText("白棋赢!");棋子颜色=2;removeMouseListener(this);}else{text_1.setText("请黑棋下子");text_2.setText(autoPlay.x+" "+autoPlay.y); }}}}public void mouseReleased(MouseEvent e){}public void mouseEntered(MouseEvent e){}public void mouseExited(MouseEvent e){}public void mouseClicked(MouseEvent e){}public void actionPerformed(ActionEvent e){this.removeAll();棋子颜色=1;add(button);button.setBounds(10,5,60,26);add(text_1);text_1.setBounds(90,5,90,24);text_2.setText("");text_1.setText("请黑棋下子");add(text_2);text_2.setBounds(290,5,90,24);add(text_3); text_3.setBounds(200,5,80,24);i=0;text_3.setText("这是第"+i+"步");for(int i=0;i<19;i++)for(int j=0;j<19;j++){array[i][j]=0;}for(int i=0;i<19;i++)for(int j=0;j<19;j++)for(int h=0;h<5;h++){scanp.shape[i][j][h]=0;scanc.shape[i][j][h]=0;}addMouseListener(this);}}class ChessPoint_black extends Canvas implements MouseListener{ ChessPad chesspad=null;ChessPoint_black(ChessPad p){setSize(20,20);addMouseListener(this);chesspad=p;}public void paint(Graphics g){g.setColor(Color.black);g.fillOval(0,0,18,18);}public void mousePressed(MouseEvent e){/*if(e.getModifiers()==InputEvent.BUTTON3_MASK){chesspad.remove(this);chesspad.棋子颜色=1;chesspad.text_2.setText("");chesspad.text_1.setText("请黑棋下子");}*/}public void mouseReleased(MouseEvent e){}public void mouseEntered(MouseEvent e){}public void mouseExited(MouseEvent e){}public void mouseClicked(MouseEvent e){}}class ChessPoint_white extends Canvas implements MouseListener{ ChessPad chesspad=null;ChessPoint_white(ChessPad p){setSize(20,20);addMouseListener(this);chesspad=p;}public void paint(Graphics g){g.setColor(Color.white);g.fillOval(0,0,18,18);}public void mousePressed(MouseEvent e){/*if(e.getModifiers()==InputEvent.BUTTON3_MASK){chesspad.remove(this);chesspad.棋子颜色=-1;chesspad.text_2.setText("请白棋下子");chesspad.text_1.setText("");}*/}public void mouseReleased(MouseEvent e){}public void mouseEntered(MouseEvent e){}public void mouseExited(MouseEvent e){}public void mouseClicked(MouseEvent e){}}public class Chess extends Frame{ChessPad chesspad=new ChessPad();Chess(){setVisible(true);setLayout(null);Label label=new Label("五子棋",Label.CENTER);add(label);label.setBounds(70,55,440,26);label.setBackground(Color.orange);add(chesspad);chesspad.setBounds(70,90,440,440);addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});pack();setSize(600,550);}public static void main(String args[]){Chess chess=new Chess();}}class AutoPlay{int x,y;void autoPlay(int chesspad[][],int a,int b){int randomNumber=(int)(Math.random()*8)+1;switch(randomNumber){case(1):if(chesspad[a-1][b-1]==0){x=a-1;y=b-1;}else if(chesspad[a-2][b-2]==0){x=a-2;y=b-2;}else {x=a-3;y=b-3;}break;case(2):if(chesspad[a-1][b]==0){x=a-1;y=b;}else if(chesspad[a-2][b]==0){x=a-2;y=b;}else {x=a-3;y=b;}break;case(3):if(chesspad[a-1][b+1]==0){x=a-1;y=b+1;}else if(chesspad[a-2][b+2]==0){x=a-2;y=b+2;}else {x=a-3;y=b+3;}break;case(4):if(chesspad[a][b+1]==0){x=a;y=b+1;}else if(chesspad[a][b+2]==0){x=a;y=b+2;}else {x=a;y=b+3;}break;case(5):if(chesspad[a+1][b+1]==0){x=a+1;y=b+1;}else if(chesspad[a+2][b+2]==0){x=a+2;y=b+2;}else {x=a+3;y=b+3;}break;case(6):if(chesspad[a+1][b]==0){x=a+1;y=b;}else if(chesspad[a+2][b]==0){x=a+2;y=b;}else {x=a+3;y=b;}break;case(7):if(chesspad[a+1][b-1]==0){x=a+1;y=b-1;}else if(chesspad[a+2][b-2]==0){x=a+2;y=b-2;}else {x=a+3;y=b-3;}break;case(8):if(chesspad[a][b-1]==0){x=a;y=b-1;}else if(chesspad[a][b-2]==0){x=a;y=b-2;}else{x=a;y=b+3;}break;}}}class Evaluate{int max_x,max_y,max;public void evaluate(int shape[][][]){int i=0,j=0;for(i=0;i<19;i++)for(j=0;j<19;j++){switch(shape[i][j][0]) {case 5:shape[i][j][4]=200;break;case 4:switch(shape[i][j][1]){case 4:shape[i][j][4]=150+shape[i][j][2]+shape[i][j][3];break;case 3:shape[i][j][4]=100+shape[i][j][2]+shape[i][j][3];break;default:shape[i][j][4]=50+shape[i][j][2]+shape[i][j][3];}break;case 3:switch(shape[i][j][1]){case 3:shape[i][j][4]=75+shape[i][j][2]+shape[i][j][3];break;default:shape[i][j][4]=20+shape[i][j][2]+shape[i][j][3];}break;case 2:shape[i][j][4]=10+shape[i][j][1]+shape[i][j][2]+shape[i][j][3];break;case 1:shape[i][j][4]=shape[i][j][0]+shape[i][j][1]+shape[i][j][2]+shape[i][j][3];default : shape[i][j][4]=0;}}int x=0,y=0;max=0;for(x=0;x<19;x++)for(y=0;y<19;y++)if(max<shape[x][y][4]){max=shape[x][y][4];max_x=x;max_y=y;}}}class Judge{static boolean judge(int a[][],int color){int i,j,flag;for(i=0;i<19;i++){flag=0;for(j=0;j<19;j++)if(a[i][j]==color){flag++;if (flag==5)return true;}else flag=0;}for(j=0;j<19;j++){flag=0;for(i=0;i<19;i++)if(a[i][j]==color){flag++;if(flag==5)return true;}else flag=0;}for(j=4;j<19;j++){flag=0; int m=j;for(i=0;i<=j;i++){if(a[i][m--]==color){flag++;if(flag==5)return true;}else flag=0;}}for(j=14;j>=0;j--){flag=0; int m=j;for(i=0;i<=18-j;i++){if(a[i][m++]==color){flag++;if(flag==5)return true;}else flag=0;}}for(i=14;i>=0;i--){flag=0; int n=i;for(j=0;j<19-i;j++){if(a[n++][j]==color){flag++;if(flag==5)return true;}else flag=0;}}for(j=14;j>=0;j--){flag=0; int m=j;for(i=18;i>=j;i--){if(a[i][m++]==color){flag++;if(flag==5)return true;}else flag=0;}}return false;}}class Scan{int shape[][][]=new int[19][19][5];void scan(int chesspad[][],int colour){int i,j;for(i=0;i<=18;i++)for(j=0;j<=18;j++)if(chesspad[i][j]==0){int m=i,n=j;while(n-1>=0&&chesspad[m][--n]==colour){shape[i][j][0]++;}n=j;while(n+1<=18&&chesspad[m][++n]==colour){shape[i][j][0]++;}n=j;while(m-1>=0&&chesspad[--m][n]==colour){shape[i][j][1]++;}m=i;while(m+1<=18&&chesspad[++m][n]==colour){shape[i][j][1]++;}m=i;while(m-1>=0&&n+1<=18&&chesspad[--m][++n]==colour){shape[i][j][2]++;}m=i;n=j;while(m+1<=18&&n-1>=0&&chesspad[++m][--n]==colour){shape[i][j][2]++;}m=i;n=j;while(m-1>=0&&n-1>=0&&chesspad[--m][--n]==colour){shape[i][j][3]++;}m=i;n=j;while(m+1<=18&&n+1<=18&&chesspad[++m][++n]==colour){shape[i][j][3]++;}}}}class Sort{public void sort(int shape[][][]){int temp;for(int i=0;i<19;i++)for(int j=0;j<19;j++){for(int h=1;h<=4;h++){for(int w=3;w>=h;w--){if(shape[i][j][w-1]<shape[i][j][w]){temp=shape[i][j][w-1];shape[i][j][w-1]=shape[i][j][w];shape[i][j][w]=temp;}}}}}}。