五子棋游戏源码

这是五子棋的最终效果图,棋盘以及棋子均是程序作图。下边奉献个人的源代码。

GoBangGUI.java 这个源文件主要是界面的实现

package game.gobang;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class GoBangGUI extends JFrame{
	private JPanel mainframe;
	private GoBangBoard board;
	private JPanel control;
	private GridLayout grid;
	private BorderLayout border;
	private JButton start;
	private JButton end;
	private JLabel label;
	private int row;
	private int column;
	private Gobang gobang;
	private MouseAdapter mouselistener;
	private boolean flag;
	private boolean ok;
	private ActionListener actionlistener;

	public GoBangGUI(){
		this("GoBang Game", 10, 10);
	}
	public GoBangGUI(String title, int row, int column){
		super(title);
//		this.setUndecorated(true);
		this.row = row;
		this.column = column;
		this.flag = false;
		this.ok = false;
		initial();
		setSize(600, 600);
		this.setResizable(false);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setLocationByPlatform(true);
		this.setVisible(true);
		this.requestFocus();
	}

	private void initial() {
		createComponent();
		layOut();
		listener();
	}
	private void createComponent() {
		mainframe = new JPanel();
		control = new JPanel();
		border = new BorderLayout();
		grid = new GridLayout();
		start = new JButton("Start");
		label = new JLabel();
		gobang = new Gobang(row, column);
		board = new GoBangBoard(gobang, row, column);
		end = new JButton("Exit");
//		gobang.getData()[0][0] = GobangColor.WHITE;
	}
	private void layOut() {
		this.getContentPane().add(mainframe);
//		setBackpicture();
//		mainframe.setBackground(Color.yellow);
		mainframe.setLayout(border);
		mainframe.add(board, BorderLayout.CENTER);
//		board.setBounds(0, 0, 500, 500);
		mainframe.add(control, BorderLayout.EAST);
		Box ve = Box.createVerticalBox();
		ve.add(start);
		ve.add(Box.createVerticalStrut(50));
		end.setSize(start.getWidth(), start.getHeight());
		ve.add(end);
		control.add(ve);
	}
	private void setBackpicture() {
		ImageIcon a = new ImageIcon("/home/qcq/1.jpg");
		JLabel p = new JLabel(a);
		p.setBounds(0, 0, a.getIconWidth(), a.getIconHeight());
		this.getLayeredPane().add(p, Integer.MIN_VALUE);
	}
	/*
	 * 判断鼠标落入棋盘窗格的位置索引 (x, y)为当前鼠标的坐标。
	 */
	private Place judgePlace(int indexx, int indexy, int x, int y, int squre){
		for (int i = 0; i < row; i++){
			for (int j = 0; j < column; j++){
				if (x >= indexx + j * squre && x <= indexx + (j + 1) * squre
						&&y >= indexy + i * squre && y <= indexy + (i + 1) * squre){
					return new Place(i, j);
				}
			}
		}
		return null;
	}
	private void listener() {
		mouselistener = new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				int x = e.getX();
				int y = e.getY();
				/*
				 * (25, 10) is a special coordinate. the board draw begins here,
				 * when the board added to the this JFrame the begin change to
				 * (25, 10 + 25), However, I do not know why. just keep it;
				 * */
				if (ok){
					Place temp = judgePlace(25, 10, x, y, board.getSqure());
					System.out.println(temp);
					if (flag){
						if (!gobang.check(temp.getX(), temp.getY())){
							JOptionPane.showMessageDialog(mainframe, "Change another place");
						} else {
							gobang.setChess(temp.getX(), temp.getY(), GobangColor.WHITE);
							repaint();
							if (gobang.isSuccess(new Place(0, 0), new Place(row - 1, column - 1), GobangColor.WHITE)){
	//							JOptionPane.showMessageDialog(mainframe, "The white player is win");
								int choice = JOptionPane.showConfirmDialog(mainframe, "The white player is win", "DO you want try again",
										JOptionPane.YES_NO_OPTION);
								if (choice == JOptionPane.YES_OPTION){
									gobang.initial();
									ok = false;
									repaint();
								}
							}
							flag = false;
						}

					} else {
						if (!gobang.check(temp.getX(), temp.getY())){
							JOptionPane.showMessageDialog(mainframe, "Change another place");
						} else {
							gobang.setChess(temp.getX(), temp.getY(), GobangColor.BLACK);
							repaint();
							if (gobang.isSuccess(new Place(0, 0), new Place(row - 1, column - 1), GobangColor.BLACK)){
	//							JOptionPane.showMessageDialog(mainframe, "The black player is win");
								int choice = JOptionPane.showConfirmDialog(mainframe, "The black player is win", "DO you want try again",
										JOptionPane.YES_NO_OPTION);
								if (choice == JOptionPane.YES_OPTION){
									gobang.initial();
									ok = false;
									repaint();
								}
							}
							flag = true;
						}
					}
				} else {
					JOptionPane.showMessageDialog(mainframe, "please start the game");
				}
			}
		};
		actionlistener = new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if (((JButton)(e.getSource())).getText().equals("Start")){
					ok = true;
				} else if (((JButton)(e.getSource())).getText().equals("Exit")){
					System.exit(0);
				}
			}
		};
		board.addMouseListener(mouselistener);
		start.addActionListener(actionlistener);
		end.addActionListener(actionlistener);
	}

	public static void main(String[] args) {
		GoBangGUI game = new GoBangGUI(null, 20, 20);
	}

}

GoBangBoard.java本文件是棋盘的绘图

package game.gobang;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.LayoutManager;

import javax.swing.JPanel;

public class GoBangBoard extends JPanel {
	private Gobang gobang;
	private int row;
	private int column;
	private int squre;

	public GoBangBoard() {
		//this.setBounds(x, y, width, height);
	}
	public GoBangBoard(Gobang gobang, int row, int column){
		this.gobang = gobang;
		this.column = column;
		this.row = row;
	}

	public int getSqure(){
		return squre;
	}

	public void paint(Graphics g){
		Graphics2D gg = (Graphics2D)g;
		squre = (this.getWidth() - 50) / Math.max(row, column);
		/**
		 * from the point (25, 10) draw the game's background.
		 * */
		/*
		 * below draw the background gird.
		 * */
		int x = 25;
		int y = 10;
		gg.setStroke(new BasicStroke(0.5f, BasicStroke.CAP_ROUND,
				BasicStroke.JOIN_ROUND, 1.0f,new float[]{5f, 5f},0f));
		gg.setColor(Color.blue);
		for (int i = 0; i < row; i++){
			for (int j = 0; j < column; j++){
				gg.drawRect(x + j * squre, y + i * squre, squre, squre);
			}
		}
		for (int i = 0; i < gobang.getData().length; i++){
			for (int j = 0; j < gobang.getData()[i].length; j++){
				if (GobangColor.WHITE == gobang.getData()[i][j]){
					gg.setColor(Color.blue);
					gg.fillOval(x + j * squre, y + i * squre, squre, squre);
				} else if (GobangColor.BLACK == gobang.getData()[i][j]){
					gg.setColor(Color.BLACK);
					gg.fillOval(x + j * squre, y + i * squre, squre, squre);
				}
			}
		}

		gg.setStroke(new BasicStroke(5f));
		gg.setColor(Color.blue);
		gg.drawRect(x - 1, y - 1, squre * column + 2, squre * row + 2);
		gg.dispose();

	}
}

GobangColor.java 本文件是棋子颜色的枚举定义。

package game.gobang;

public enum GobangColor {
	BLACK,
	WHITE,
	NULL
}

Placejava 本文件是关于棋子位置的定义

package game.gobang;

/**
 * here lays the snake's body coordinate information.
 * */
public class Place {
	private int x;
	private int y;
	public Place(){
		this(0, 0);
	}
	public Place(int x, int y) {
		this.x = x;
		this.y = y;
	}
	public int getX() {
		return x;
	}
	public void setX(int x) {
		this.x = x;
	}
	public int getY() {
		return y;
	}
	@Override
	public String toString() {
		return "Place [x=" + x + ", y=" + y + "]";
	}
	public void setY(int y) {
		this.y = y;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + x;
		result = prime * result + y;
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Place other = (Place) obj;
		if (x != other.x)
			return false;
		if (y != other.y)
			return false;
		return true;
	}
}

Gobang.java本文件是五子棋实现的核心逻辑代码

package game.gobang;

import java.util.Scanner;

/**
 * Question 19、利用二维数组实现五子棋下棋功能
 * */
public class Gobang {

	private GobangColor[][] data;
	private int row = 10;
	private int column = 10;

	public Gobang() {
		/*
		 * The default checkerboard is 10 * 10 boxes;
		 * */
		this(10, 10);
		initial();
	}
	/*
	 * Initial the Game
	 * */
	public void initial(){
		for (int i = 0; i < row; i++){
			for (int j = 0; j < column; j++){
				data[i][j] = GobangColor.NULL;
			}
		}
	}

	/*
	 * The piece move
	 * */
	public void setChess(int row, int column,GobangColor color){
		data[row][column] = color;
	}

	public Gobang(int row, int column){
		/*
		 * set the Chess squre to row * line
		 * */
		this.row = row;
		this.column = column;
		data = new GobangColor[row][];
		for (int i = 0; i < row; i++){
			data[i] = new GobangColor[column];
		}
		initial();
	}
	public GobangColor[][] getData() {
		return data;
	}
	public void setData(GobangColor[][] data) {
		this.data = data;
	}
	public int getRow() {
		return row;
	}
	public void setRow(int row) {
		this.row = row;
	}
	public int getColumn() {
		return column;
	}
	public void setColumn(int column) {
		this.column = column;
	}
	/*
	 * print out the current checkerboard
	 * */
	public void printCheckerBoard(){
		/*
		 * print out the chessboard layout
		 * */
		for (GobangColor[] i: data){
			for (GobangColor j : i){
				System.out.print(j.toString() + " ");
			}
			System.out.println();
		}
	}
	/*
	 * verify the input data to insure the piece is in the range
	 * and not put this piece in the history place
	 * 验证棋子在合适的位置上
	 * */
	public boolean check(int x, int y){
		if (x < 0 || x >= row || y < 0 || y >= column){
			System.out.println("The input is error");
			System.out.println("The input should from(0, 0) to (" + (x - 1) + "," + (y - 1) + ")");
			return false;
		}
		if (GobangColor.NULL != data[x][y]){
			System.out.println("This place already has one piece!");
			return false;
		}
		return true;
	}

	/*
	 * judge if successed, The parameter x and y
	 * is the range which need to be scanning.
	 * The Scanning range can zoom in a range which is a circle(a square)
	 * center in current move, radius is 5.
	 * 扫描棋盘看是不是有棋子获胜,可以优化扫描方案,将扫描的范围局限于一个以落子处为中心
	 * 5为半径的棋盘(isSucess的重载方法实现这一个思想)。
	 */
	public boolean isSuccess(Place x, Place y, GobangColor color){
		boolean flag = false;
		int counter = 0;
		label:
		for (int i = (int) x.getX(); i <= (int)y.getX(); i++){
			for (int j = (int)x.getY(); j <= (int)y.getY(); j++){
				/*
				 * scanning the [x,y] range in 4 directions.
				 * */

				// check the horizontal
				counter = 0;
				if (j + 4 <= (int)y.getY()){
					for (int index = j; index <= j + 4; index++){
						if (color == data[i][index]){
							counter++;
						}
					}
				}
				if (5 == counter){
					flag = true;
					break label;
				}
				// check the vertical
				counter = 0;
				if (i + 4 <= (int)y.getX()){
					for (int index = i; index <= i + 4; index++){
						if (color == data[index][j]){
							counter++;
						}
					}
				}
				if (5 == counter){
					flag = true;
					break label;

				}
				//check the dig line
				counter = 0;
				if ((i + 4 <= (int)y.getX()) && (j + 4 <= (int)y.getY())){
					for (int indexX = i, indexY = j; indexX <= i + 4 ;indexX++, indexY++){
						if (color == data[indexX][indexY]){
							counter++;
						}
					}
				}
				if (5 == counter){
					flag = true;
					break label;
				}
				//check the reverse dig line
				counter = 0;
				if ((i + 4 <= (int)y.getX()) && (j - 4 >= (int)x.getY())){
					for (int indexX = i, indexY = j; indexX <= i + 4;indexX++, indexY--){
						if (color == data[indexX][indexY]){
							counter++;
						}
					}
				}
				if (5 == counter){
					flag = true;
					break label;
				}
			}
		}

		return flag;

	}
	/*
	 * 这是一个重载的方法,与上一个方法不同的是没有使用扫描来实现判定
	 * 而是基于落子的地方,来基于四个方向进行计数判断。
	 * */
	public boolean isSuccess(Place x, GobangColor color){
		boolean flag = false;
		/*
		 * horizontal direction
		 * */
		int counter = 0;
		for (int i = x.getY(); i >= Math.min(x.getY() - 4, row); i--){
			if (color == data[x.getX()][i]){
				counter++;
			}else{
				break;
			}
		}
		for (int i = x.getY() + 1; i <= Math.min(x.getY() + 4, column - 1); i++){
			if (color == data[x.getX()][i]){
				counter++;
			}else{
				break;
			}
		}
		if (5 == counter){
			flag = true;
		}
		/*
		 * vertical direction
		 * */
		counter = 0;
		for (int i = x.getX(); i >= Math.min(x.getX() - 4, row); i--){
			if (color == data[i][x.getY()]){
				counter++;
			}else{
				break;
			}
		}
		for (int i = x.getY() + 1; i <= Math.min(x.getY() + 4, column - 1); i++){
			if (color == data[i][x.getY()]){
				counter++;
			}else{
				break;
			}
		}
		if (5 == counter){
			flag = true;
		}
		/*
		 * diagonal direction
		 * */
		counter = 0;
		for (int i = x.getX(), j = x.getY(); i >= Math.min(x.getX() - 4, row)
				&& j >= Math.min(x.getY() - 4, row); i--, j--){
			if (color == data[i][j]){
				counter++;
			}else{
				break;
			}
		}
		for (int i = x.getX() + 1, j = x.getY() + 1; i <= Math.min(x.getX() + 4, column - 1)
				&& j <= Math.min(x.getY() + 4, column - 1); i++, j++){
			if (color == data[i][j]){
				counter++;
			}else{
				break;
			}
		}
		if (5 == counter){
			flag = true;
		}
		/*
		 * reverse diagonal direction
		 * */
		counter = 0;
		for (int i = x.getX(), j = x.getY(); i <= Math.min(x.getX() + 4, column - 1)
				&& j >= Math.min(x.getY() - 4, row); i++, j--){
			if (color == data[i][j]){
				counter++;
			}else{
				break;
			}
		}
		for (int i = x.getX() + 1, j = x.getY() + 1; i >= Math.min(x.getX() - 4, row)
				&& j <= Math.min(x.getY() + 4, column - 1); i--, j++){
			if (color == data[i][j]){
				counter++;
			}else{
				break;
			}
		}
		if (5 == counter){
			flag = true;
		}
		return flag;
	}
	/*
	 * The actual game start here, where black first, white second,
	 * we can optimize the game which  do not call
	 * the method isSuccess in the first segment. such as 8 moves.
	 * and we can narrow the scanning the range to a square just talk above.
	 * */
	public void playChess(){
		Scanner in = new Scanner(System.in);
		Place x = new Place(0, 0);
		Place y = new Place(row - 1, column - 1);
		label:
		while (true){
			//The input should like 1,2
			while (in.hasNext()){

				String[] str = in.next().split(",");
				int indexX = Integer.valueOf(str[0]);
				int indexY = Integer.valueOf(str[1]);
				if (!check(indexX, indexY)){
					System.out.println("please input again");
					continue;
				}else{
					setChess(indexX, indexY, GobangColor.BLACK);
					printCheckerBoard();
//					if (isSuccess(x, y, GobangColor.BLACK)){
					if (isSuccess(new Place(indexX, indexY), GobangColor.BLACK)){
						System.out.println("The Black is win");
						break label;
					}
					break;
				}
			}
			while (in.hasNext()){
				String[] str = in.next().split(",");
				int indexX = Integer.valueOf(str[0]);
				int indexY = Integer.valueOf(str[1]);
				if (!check(indexX, indexY)){
					System.out.println("please input again");
					continue;
				}else{
					setChess(indexX, indexY, GobangColor.WHITE);
					printCheckerBoard();
//					if (isSuccess(x, y, GobangColor.WHITE)){
					if (isSuccess(new Place(indexX, indexY), GobangColor.WHITE)){
						System.out.println("The White is win");

						break label;
					}
					break;
				}
			}
		}
		in.close();
	}

	public static void main(String[] args) {
		Gobang chess = new Gobang();
		chess.playChess();
	}

}
时间: 2024-10-23 16:49:09

五子棋游戏源码的相关文章

Win8五子棋游戏源码

技术特点:在web版的silverlight的五子棋的基础上,进行了简单的改动,就OK了, 体现了微软的技术真的强大. 功能介绍:能够进行人与人的对战,与人机对战 实现五子棋基本功能,可以选择对战模式 人与人 .人与电脑.双击棋盘下棋.开发环境为:Visual Studio 2012 <ignore_js_op> <ignore_js_op> 详细说明:http://wp.662p.com/thread-8139-1-1.html Win8五子棋游戏源码

android五子棋游戏源码

这个游戏案例是android五子棋游戏源码,也是自己最近做的android五子棋游戏,现在拿出来给大家看看一下.因为初学,所以只做了魅族屏幕的,不过这个没有影响大家的学习和运行,喜欢的朋友可以在这个的基础上进行升级或更新吧. 项目源码下载:http://code.662p.com/view/6853.html <ignore_js_op> <ignore_js_op> 详细说明:http://android.662p.com/thread-5294-1-1.html

【141030】VC++贪吃蛇游戏源码(Win32+API)

不错的贪吃蛇游戏,运用了Win32的API.完整源代码,在VS2005下编译通过.内附有编程要点,很好的学习范例. 游戏源码下载地址:点击下载

11款手机微信小游戏源码特效

html5微信吃苹果游戏源码下载 html5手机淘宝万能时装屋小游戏源码下载 html5 3d拳王游戏制作3D拳击游戏源码下载 html5 3d拼图游戏制作3D魔方游戏源码下载 htm5 3d游戏制作3D熊出没游戏源码下载 html5微信小游戏超级染色游戏源码下载 html5读心术小游戏源码下载_读心术微信小游戏源码下载 找你歌微信html5游戏源码下载_找你歌微信游戏源码下载 方言等级考试游戏源码下载_方言等级测试微信游戏源码下载 中秋节吃月饼游戏html5微信游戏源码下载 9款html5微信

【史上最全】微信朋友圈游戏源码下载

源码介绍:  所有源码都是html5开发,可以跨平台,无论谷歌安卓还是苹果ios都可以流畅运行,游戏可以根据自己的情况添加链接,可以分享到微信圈后跳转的你的游戏平台页.个别游戏可以设置指定次数提示添加微信账号回复指定内容获得答案.保证游戏可运行性,不像某些不良卖家价格很高买来的根本没几个能用或者很多凑数游戏. 一个简单的营利模式: 通过手机作为入口,分享某某游戏的得分到朋友圈,朋友圈内的病毒式传播速度超过你想象.然后你可以自己加入关注微信代码.百度移动广告代码.淘客代码.等等吧,可以发挥的空间非

21款网页版html5小游戏源码

html5魅族创意的贪食蛇游戏源码下载 html5网页版打砖块小游戏源码下载 html5 3D立体魔方小游戏源码下载 html5网页版飞机躲避游戏源码下载 html5三国人物连连看游戏源码下载 js html5 2048数字游戏源码_2048网页版源码下载 html5盲打高手打飞字游戏下载_网页版英文打飞字游戏源码下载 jQuery flappy bird电脑版小游戏源码下载 网页版html5 3d俄罗斯方块游戏源码下载 jQuery html5迷宫游戏源码下载 html5网页游戏仿flappy

横版格斗游戏 cocos2d-x游戏源码

请大家赏个脸,如果感兴趣的看一下,含金量非常高的横版格斗游戏源码,  我的淘宝网址: Beat 'Em Up Game 名将.恐龙.拳皇.三国战纪.战国传承,一个个响当当的名字,承载了80后多少儿时的梦想.横版格斗过关游戏,曾经是最受大众欢迎的一种类型,拳拳到肉的打击感,轻风飘逸的一招一式,还有怒涛般的连击技,令无数玩家如痴如醉.这种游戏也一度是游戏性最强的游戏,但在卡牌横行,快餐文化泛滥的今天,这种游戏已经失去了往日的光彩,但这不是游戏本身的错,而主要在于游戏厂商的急功近利.这种游戏不同于纯界

安卓版猜拳游戏源码

安卓版猜拳游戏源码,该文件中带有安装测试包的,这个游戏源码比较简单的,现在有两个代码,一个自定义VIEW的,一个就是普通的imageView图片,游戏非常适合一些新手的使用和学习. <ignore_js_op> <ignore_js_op> <ignore_js_op>  详细说明:http://android.662p.com/thread-4914-1-1.html 安卓版猜拳游戏源码,布布扣,bubuko.com

多人在线扑克游戏源码带服务端完整版

多人在线扑克游戏源码带服务端完整版,本项目源码是一套网络版的扑克牌项目源码,带服务器端源码,服务器端也是用java做的,打开游戏以后需要配置IP服务器端的IP和端口,服务端默认监听9999端口,客户端ip填写10.0.2.2,端口信息不用管直接点连接就可以连接到电脑上的服务端.项目源码注释比较丰富,可以研究一下里面的算法之类的.搭建这个服务端环境废了我半天劲,不知道是不是我运行的方法不对,打开前两个游戏客户端没有问题,打开第三个就开始直接强制退出.游戏没玩成所以没有截那部分的图.<ignore_