java毕业设计
java游戏毕业设计-源代码+论文+开题下载
一份基于java的五子棋游戏设计心急的人可以直接下载源码看了
下载源代码以及开题论文
一、先上图片
二、部分游戏设计的目录
基于Java的五子棋游戏的设计
摘 要
五子棋作为一个棋类竞技运动,在民间十分流行,为了熟悉五子棋规则及技巧,以及研究简单的人工智能,决定用Java开发五子棋游戏。主要完成了人机对战和玩家之间联网对战2个功能。网络连接部分为Socket编程应用,客户端和服务器端的交互用Class Message定义,有很好的可扩展性,客户端负责界面维护和收集用户输入的信息,及错误处理。服务器维护在线用户的基本信息和任意两个对战用户的棋盘信息,动态维护用户列表。在人机对弈中通过深度搜索和估值模块,来提高电脑棋手的智能。分析估值模块中的影响精准性的几个要素,以及提出若干提高精准性的办法,以及对它们搜索的节点数进行比较,在这些算法的基础上分析一些提高提高电脑AI方案,如递归算法、电脑学习等。算法的研究有助于理解程序结构,增强逻辑思维能力,在其他人工智能方面也有很大的参考作用。
关键词:深度搜索;估值;电脑AI;五子棋;算法
Gobang Java-based games design
Abstract
Gobang chess as a sport, is very popular in civil, in order to become familiar with gobang rules and techniques, and the study of simple artificial intelligence, decided to use the Java Development gobang games. Completed a major man-machine war and the war gamers interconnection between the two functions. Network Connection Socket Programming for some applications, client and server interaction with Class Message definition, a very good scalability, Client interface is responsible for the collection and maintenance of user input information, and error handling. Server users maintain online basic information and arbitrary two-time users of the chessboard of information, dynamic maintenance user list. The man-machine players through depth search and valuation module, the computer players to improve intelligence. Analysis Module valuation of the precise elements, as well as a number of increased precision, and on their search for nodes, In these algorithms on the basis of analysis to raise some computer AI programs, such as recursive algorithm, computer learning. Algorithm of procedures contribute to the understanding of the structure, logical thinking ability, In other areas of artificial intelligence have great references.
.
Key words: Search depth; Valuation; Computer AI; Gobang ; Algorithm
目 录
java游戏毕业设计
论文总页数:23页
1 引言 1
1.1 课题背景 1
1.2 本课题研究的意义 1
1.3 本课题的研究方法 2
2 课题相关基础 2
2.1 五子棋 2
2.1.1 棋盘和棋子 2
2.1.2 规则及解释 3
2.1.3 五子棋常用术语 4
2.1.4 五子棋攻防 7
3 Java 8
3.1 Java简介 8
3.2 Java开发环境 9
4 课题详细研究方法 10
4.1 程序结构说明 10
4.2 棋盘及棋子的类 11
4.2.1 棋盘 11
4.2.2 棋子 13
4.3 胜负判断条件 13
4.4 网络对战 15
4.5 电脑AI 17
结 论 21
参考文献 21
致 谢 22
声 明 23
1引言
1.1课题背景
五子棋是起源于中国古代的传统黑白棋种之一。现代五子棋日文称之为连珠,英译为Renju,英文称之为Gobang或FIR(Five in a Row 的缩写),亦有连五子、五子连、串珠、五目、五目碰、五格等多种称谓。
五子棋起源于古代中国,发展于日本,风靡于欧洲。对于它与围棋的关系有两种说法,一说早于围棋,早在 “ 尧造围棋 ” 之前,民间就已有五子棋游戏;一说源于围棋,是围棋发展的一个分支。在中国的文化里,倍受人们的青睐。本世纪初五子棋传入欧洲并迅速风靡全欧。通过一系列的变化,使五子棋这一简单的游戏复杂化、规范化,而最终成为今天的职业连珠五子棋,同时也成为一种国际比赛棋。
Java语言是当今最为流行的程序设计语言之一 作为一门非常优秀和极为健壮的编程语言,它同时具有的面向对象,与平台无关,分布式应用,安全,稳定和多线程等优良的特征,使用Java语言,不仅可以开发出功能强大的大型应用程序,而且Java语言本身突出的跨平台的特性也使得它特别适合于Internet上的应用开发,可以这样说,Java的出现使得所开发的应用程序“一次编写,处处可用”的实现成为了可能。
1.2本课题研究的意义
近来随着计算机的快速发展,各种各样的电脑游戏层出不穷,使得我们能有更多的娱乐项目,而棋类游戏能起到锻炼人的思维和修身养性的作用,而且棋类游戏水平颇高,大有与人脑分庭抗礼之势。其中战胜过国际象棋世界冠军-卡斯帕罗夫的“深蓝”便是最具说服力的代表;其它像围棋的“手淡”、象棋的“将族”等也以其优秀的人工智能深受棋迷喜爱。
java游戏毕业设计进入了人类的生活,人工智能的重要性如今显而易见。自己对人工智能比较感兴趣,而五子棋游戏程序的开发实现这个课题,正好提供给我这样一个研究的机会,通过对人工智能中博弈方面的研究(人机对弈),让我在简单的人机对弈全局设计,以及具体到相关算法上有了深入的了解。人工智能属于计算机科学的领域,它以计算机技术为基础,近几十年来,它的理论和技术已经日益成熟,应用领域也正在不断扩大,显示出强大的生命力。人工智能大致可以分成几个学科,它们每一个都是独特的,但是它们常常又互相结合起来完成设计任务,这时,这些学科之间的差别就变的很模糊。人工智能在专家系统,自然语言理解,自动定理证明,自动程序设计,人工智能在机器人学、模式识别、物景分析、数据库的智能检索、机器下棋(实质上是博弈论问题)和家用电器智能化等领域都有广泛的应用。而这个课题就是和人工智能中的博弈论领域紧密相关的。
java游戏毕业设计核心是人工智能和Socekt编程,。并且人工智能中的博弈部分,由于采用了大量的搜索算法,其中很多被利用到各方面。它的概念、方法和技术,正在各行各业广泛渗透。智能已经成为当今各种新产品、新装备的发展方向。所以,趁着这个机会,对人工智能中比较容易实现的人机博弈进行了解研究学习,也是很实用且很有必要的。
三、部分代码结构
ServOneClient.java 服务端对于单个用户的处理类
import java.io.*;
import java.net.*;
public class ServeOneClient extends Thread
{
private Socket socket;
private String player=null;
protected ObjectInputStream in;
protected ObjectOutputStream out;
public ServeOneClient(Socket s) throws IOException
{
socket = s;
//System.out.println("server socket begin ...");
in =new ObjectInputStream(
socket.getInputStream());
out = new ObjectOutputStream(
socket.getOutputStream());
//System.out.println("server socket in and out ...");
//如果所有的请求都抛出异常,请求者负责关闭套接字,否则线程会将其关闭
start();
}
public void run()
{
Message obj=new Message();
while (true)
{
try {
obj =(Message)in.readObject();
doMessage(obj);
}catch(ClassNotFoundException er){}
catch(IOException e){}
}
/*
System.out.println("closing...");
try {
socket.close();
}catch (IOException e) {}
*/
}
/**
* 处理消息
* msg
* 1= 成功的请求 2=套接字关闭
*/
public int doMessage(Message msg)
{
//System.out.println("doMessage begin...type="+msg.type);
switch(msg.type)
{
case 1:{//新的连接到服务端
sendNewPlayer(msg); //客户端必须返回类型type==10
addPlayer(msg); // msg.msg == 新玩家的名字
break;
}
case 2:{// 下棋子
putChessman(msg);
break;
}
case 3:{//请求其他人游戏
requestAnother(msg);
break;
}
case 4:{
denyRequest(msg);
break;
}
case 5:{
acceptRequest(msg);
break;
}
case 6:{//胜利请求
checkVictory(msg);
break;
}
case 7:{//断开请求
getdisconnect(msg);
break;
}
case 8:{//保存游戏
break;
}
case 12:{//信息设置
boolean flag=true;
setting(msg,flag);
break;
}
case 13:{
boolean flag=false;
setting(msg,flag);
break;
}
case 19:{
playerRefresh(msg);
break;
}
case 20:{
try{
this.out.writeObject(msg);
}catch(IOException e){
e.printStackTrace();
}
break;
}
default:{
}
}
return 0; // 完毕
}
/**
* 判断游戏,更新所有的客户端面板
* type = 7 发起者将要关闭游戏
*/
public void getdisconnect(Message msg)
{
Group gg = null;
Player pp = null;
String str=null;
//如果发起连接的人在一个组
for(int i=0;i<Server.groupList.size();i++)
{
gg = (Group)Server.groupList.get(i);
if(this.equals(gg.selfSocket)==true)
{
msg.type=6; // gg.player win
try{
gg.playerSocket.out.writeObject(msg);
}
catch(IOException e)
{
e.printStackTrace();
}
sendLeftMsg(gg.self);
//更新列表
Server.groupList.remove(gg);
return;
}
if(this.equals(gg.playerSocket)==true)
{
msg.type=6;
try{
gg.selfSocket.out.writeObject(msg);
}catch(IOException e)
{
e.printStackTrace();
}
sendLeftMsg(gg.player);
Server.groupList.remove(gg);
return;
}
}
// 发起断开连接请求的玩家是否在列表里
for(int i=0;i<Server.playerList.size();i++)
{
pp = (Player)Server.playerList.get(i);
if(this.equals(pp.selfSocket)==true)
{
break;
}
}
sendLeftMsg(pp.self);
Server.playerList.remove(pp); // 移去断开者
updateClient();
}
private void sendLeftMsg(String str)
{
char cc;
for(int i=0;i<50;i++)
{
cc=str.charAt(i);
if(cc!='\0')
System.out.print(cc);
else break;
}
System.out.print(" has left server ...\n");
}
/**
* 拒绝玩家请求
* type ==4 msg == 拒绝者的名字
*/
public void denyRequest(Message msg)
{
String denyName=null;
Player pp=null;
for(int i=0;i<Server.playerList.size();i++)
{
pp = (Player)Server.playerList.get(i);
if(this.equals(pp.selfSocket)==true)
{
denyName = new String(pp.self);
break;
}
}
for(int i=0;i<Server.playerList.size();i++)
{
pp = (Player)Server.playerList.get(i);
if(arrayMatchString(msg.msg,pp.self)==true)
{
Message ms = new Message();
ms.type=4;
strToCharArray(denyName,ms.msg);
try{// requestor 's socket send msg to it's client
pp.selfSocket.out.writeObject(ms);
}
catch(IOException er)
{
er.printStackTrace();
}
break;
}
}
}
/**
* B接受请求,A 服务端 更新列表
* type ==5 msg == A的名字
*/
public void acceptRequest(Message msg)
{
Player pps=null,ppd=null;//ppd = B pps = A
String acceptName=null;
for(int i=0;i<Server.playerList.size();i++)
{
ppd = (Player)Server.playerList.get(i);
if(this.equals(ppd.selfSocket)==true)
{
break;
}
}
for(int i=0;i<Server.playerList.size();i++)
{
pps = (Player)Server.playerList.get(i);
if(arrayMatchString(msg.msg,pps.self)==true)
{
break;
}
}
Message ss = new Message();
ss.type=14; // B玩家设置颜色
ss.color=msg.color;
try{
ppd.selfSocket.out.writeObject(ss);
}catch(IOException e)
{
e.printStackTrace();
}
ss.type=5; // B接受A的请求
strToCharArray(ppd.self,ss.msg);
try{
pps.selfSocket.out.writeObject(ss);
}catch(IOException e)
{
e.printStackTrace();
}
//上传列表并显示,服务端显示数组列表
Group p1 = new Group();
p1.self=new String(pps.self);
p1.selfSocket = pps.selfSocket;
p1.selfColor = pps.color;
p1.player = new String(ppd.self);
p1.playerSocket = ppd.selfSocket;
if(p1.selfColor==1)
{
p1.playerColor = 2;
}
else
{
p1.playerColor = 1;
}
p1.Setting = pps.setting;
Server.groupList.add(p1);
///System.out.println(p1.self+p1.selfColor+" player "+p1.player+p1.playerColor);
if(Server.playerList.size()==2)
{
msg.type=15;
try{
pps.selfSocket.out.writeObject(msg);
ppd.selfSocket.out.writeObject(msg);
}catch(IOException e){
e.printStackTrace();
}
}
Server.playerList.remove(pps);
Server.playerList.remove(ppd);
//System.out.println(" after create a group,playerlist size = "+Server.playerList.size());
updateClient();
}
/**
* 当新组创建或玩家离开时更新CLIENT端列表
*/
public void updateClient()
{
Message msg = new Message();
Player pp = null,ppm = null;
for(int i=0;i<Server.playerList.size();i++)
{
pp = (Player)Server.playerList.get(i);
msg.type=15; //更新客户端玩家列表
try{ //清空列表
// System.out.println("clear "+pp.self+"'s list box");
pp.selfSocket.out.writeObject(msg);
}catch(IOException e)
{
e.printStackTrace();
}
for(int j=0;j<Server.playerList.size();j++)
{
ppm=(Player)Server.playerList.get(j);
strToCharArray(ppm.self,msg.msg);
msg.type=9;
try{
//System.out.println("updating ..."+pp.self+" list box about"+ppm.self);
pp.selfSocket.out.writeObject(msg);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
//稍后,同一组玩家的列表将会更新
}
/**
* 判断arr[] 是否等于 str
*/
private boolean arrayMatchString(char []arr,String str)
{
for(int i=0; i<50 && str.charAt(i)!='\0';i++)
{
if(arr[i]!=str.charAt(i))
return false;
}
return true;
}
/**
* type ==3
*/
public void requestAnother(Message msg)
{
Player pp = null; // 接收者
Player spp = null; // 发送者
String senderName=null;
// 获得发起者的名字
for(int i=0;i<Server.playerList.size();i++)
{
spp = (Player)Server.playerList.get(i);
if(this.equals(spp.selfSocket)==true)
{
senderName = new String(spp.self);
//System.out.println("requestor 's name = "+senderName);
break;
}
}
for(int i=0;i<Server.playerList.size();i++)
{
pp = (Player)Server.playerList.get(i);
if(arrayMatchString(msg.msg,pp.self)==true)
{
Message ms = new Message();
strToCharArray(senderName,ms.msg);
ms.type=3;
if(spp.color==1)
{
ms.color = 2; //set another's color
}
else
{
ms.color = 1;
}
ms.setting=spp.setting;
try{// 玩家B的套接字发送 msg 到B的客户端
pp.selfSocket.out.writeObject(ms);
//System.out.println("type= "+ms.type+" "+pp.self+ " send msg to name = "+ms.msg[0]+"with B's color"+ms.color);
}catch(IOException er)
{
er.printStackTrace();
}
break;
}
}
}
// 以'\0'结束,把字符串转换成数组
public void strToCharArray(String str,char [] arr)
{
int i=0;
for(i=0;i<str.length()&&i<49;i++)
{
arr[i] = str.charAt(i);
}
arr[i]='\0';
}
/**
*设置信息标志
* msg
*/
public void setting(Message msg,boolean flag)
{
int i=0;
Player pp=null;
for(i=0;i<Server.playerList.size();i++)
{
pp =(Player) Server.playerList.get(i);
if(this.equals(pp.selfSocket)==true)
{
if(flag==true)
pp.setting=msg.setting;
else
pp.color=msg.color;
//System.out.println("setting "+pp.setting+"color = "+pp.color);
}
}
}
/**
* 在数组的结束端过滤黑棋所占的空间
*/
public String arrayToString(char [] arr)
{
int i=0,length=0;
while(arr[i]!='\0' && i<50)
{
i++;
}
length=i;
char [] ss = new char[length];
for(i=0;i<length;i++)
{
ss[i]=arr[i];
}
String str = new String(ss);
return str;
//System.out.println("arraytoString "+str+"length = "+length);
}
/**
* 添加新玩家到所有的CLIENT端玩家列表
* 读取服务端玩家列表并发送到每个CLIENT上
*/
public void sendNewPlayer(Message player)
{
Player pp=null;
player.type=9;
// System.out.println("send new Player ...");
for(int i=0;i<Server.playerList.size();i++)
{
pp=(Player)Server.playerList.get(i);
try{
if(pp.self!=null){//发送信息到其他人,除了自己
//System.out.println(pp.self+" add list "+player.msg[0]+"i = "+i);
pp.selfSocket.out.writeObject(player);
}
}catch(IOException e)
{
e.printStackTrace();
}
}
}
/**
* 玩家结束游戏并等待
*/
public void playerRefresh(Message player)
{
Player ppo = new Player();
Player pp = null;
ppo.color = player.color;
ppo.self = new String(player.msg);
ppo.selfSocket = this;
Server.playerList.add(ppo);
for(int i=0;i<Server.playerList.size();i++)
{
pp = (Player)Server.playerList.get(i);
if(this.equals(pp.selfSocket)==false)
{
Message msg = new Message();
strToCharArray(pp.self, msg.msg);
msg.type = 9;
msg.color = pp.color;
// System.out.println("refresh " + pp.self + "serverlist size " +
// Server.playerList.size());
try {
this.out.writeObject(msg);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Message ms = new Message();
strToCharArray(ppo.self, ms.msg);
ms.type=10;
try{
this.out.writeObject(ms);
}
catch(IOException e)
{
e.printStackTrace();
}
//Message ms = new Message();
player.type=10;
for(int i=0 ;i<Server.playerList.size();i++)
{
pp = (Player)Server.playerList.get(i);
if(this.equals(pp.selfSocket)!=true)
{
try{
pp.selfSocket.out.writeObject(player);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
}
/**
* 添加新玩家到服务端玩家列表
*/
public void addPlayer(Message player)
{
int i=0;
Player pp=null,tp=null;
for(i=0;i<Server.playerList.size();i++)
{
pp=(Player)Server.playerList.get(i);
if(this.equals(pp.selfSocket)==true)
{
//System.out.println("match socket ok and send to itself...");
pp.self = new String(player.msg);
try{
for (int j = 0; j < Server.playerList.size(); j++)
{
Message temp = new Message();
tp = (Player) Server.playerList.get(j);
if (tp.self != null)
{
strToCharArray(tp.self, temp.msg);
//temp.coordinateX=(byte)j;
temp.type = 10; //reply for type==1
//System.out.println("host "+pp.self+" add list to client name = "+temp.coordinateX+temp.msg[0]);
pp.selfSocket.out.writeObject(temp);
}
}
// out.writeObject(player);
}
catch(IOException e)
{
e.printStackTrace();
}
break;
}
}/*
System.out.print("welcome ");
int k=0;
while(true){
if(player.msg[k]!='\0')
System.out.print(player.msg[k++]);
else break;
}
System.out.println();*/
//System.out.println(" at "+pp.selfSocket.socket.toString());
}
public Socket getSocket()
{
return socket;
}
/**
* 检查MSG发送者是否获胜
* type=6 msg = 获胜者的名字
*/
public void checkVictory(Message msg)
{
}
/**
* type = 2 ,(msg.coordinateX,msg.coordinateY).msg.color
*/
public void putChessman(Message msg)
{
Group gg = new Group();
ServeOneClient soc=null;
String tName=null;
int color=0;
// 修改服务段面板
for(int i=0;i<Server.groupList.size();i++)
{
gg = (Group)Server.groupList.get(i);
if(this.equals(gg.selfSocket)==true)
{
soc = gg.playerSocket;
tName = new String(gg.player);
color = gg.selfColor;
break;
}
if(this.equals(gg.playerSocket)==true)
{
soc = gg.selfSocket;
tName = new String(gg.self);
color = gg.playerColor;
break;
}
}
gg.board[msg.coordinateX][msg.coordinateY]=color;
// 判断是否有人获胜
if(judge(gg,msg.coordinateX,msg.coordinateY)==true)
{//一方获胜
// 告诉双方并从列表中移开
try{
msg.type=6; // 胜利
this.out.writeObject(msg);
msg.type=17; // 失败
soc.out.writeObject(msg);
// System.out.println("send failed to "+tName);
}
catch(IOException e)
{
e.printStackTrace();
}
Server.groupList.remove(gg); //从列表中移开
return;
}
// 发送msg到其他玩家
try{
//System.out.println("server put chess man "+msg.coordinateX+","+msg.coordinateY);
soc.out.writeObject(msg);
}
catch(IOException e)
{
e.printStackTrace();
}
}
/**
* 判断是否有人获胜
*/
private boolean judge(Group gg,int x,int y)
{
int i = 0, j = 0, count = 0;
int color=gg.board[x][y];
// x 方向
for (i = 0, count = 0; x - i >= 0 && i < 5; i++)
{
if (color == gg.board[x - i][y])
{
count++;
}
else {
break;
}
// System.out.println("( "+x+" , "+y+" )"+"count = "+count);
if (count == 5)
return true;
}
for (i = 1; x + i < 15 && i < 5; i++)
{
if (color == gg.board[x + i][y])
{
count++;
}
else {
break;
}
if (count == 5)
return true;
}
// y 方向
for (i = 0, count = 0; y - i >= 0 && i < 5; i++)
{
if (color == gg.board[x][y - i])
{
count++;
}
else {
break;
}
// System.out.println("( "+x+" , "+y+" )"+"count = "+count);
if (count == 5)
return true;
}
for (i = 1; y + i < 15 && i < 5; i++)
{
if (color == gg.board[x][y + i])
{
count++;
}
else {
break;
}
// System.out.println("( "+x+" , "+y+" )"+"count = "+count);
if (count == 5)
return true;
}
// '\' 方向
for (i = 0, count = 0; x - i >= 0 && y - i >= 0 && i < 5; i++)
{
if (color == gg.board[x - i][y - i])
{
count++;
}
else {
break;
}
// System.out.println("( "+x+" , "+y+" )"+"count = "+count);
if (count == 5)
return true;
}
for (i = 1; x + i < 15 && y + i < 15 && i < 5; i++)
{
if (color == gg.board[x + i][y + i])
{
count++;
}
else {
break;
}
// System.out.println("( "+x+" , "+y+" )"+"count = "+count);
if (count == 5) {
return true;
}
}
// '/' 方向
for (i = 0, count = 0; x + i < 15 && y - i >= 0 && i < 5; i++)
{
if (color == gg.board[x + i][y - i])
{
count++;
}
else {
count = 0;
}
// System.out.println("( "+x+" , "+y+" )"+"count = "+count);
if (count == 5)
return true;
}
for (i = 1; x - i >= 0 && y + i < 15 && i < 5; i++)
{
if (color == gg.board[x - i][y + i])
{
count++;
}
else {
break;
}
// System.out.println("( "+x+" , "+y+" )"+"count = "+count);
if (count == 5)
{
return true;
}
}
return false;
}
}
电脑对战时处理 ChessWZQ.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.net.*;
import java.io.*;
public class ChessWZQ extends JFrame
{
JPanel contentPane;
BorderLayout borderLayout1 = new BorderLayout();
protected Image white = null;
protected Image black = null;
protected static int pColor; // 人的颜色
protected static int cColor; //电脑的颜色
static boolean ptocFlag=false;
boolean pFirst = false;
private int bestX=0; // 电脑找到最好的棋子位置的 X坐标
private int bestY=0; // 电脑找到最好的棋子位置的Y坐标
private int RectX1=0; // 根据坐标 (x,y)确定矩形范围
private int RectY1=0; // 长度为 9
private int RectX2=0; // 大小为 9*9
private int RectY2=0;
private int weightBoard[][];
static Socket socket;
private static int PORT;
static ObjectInputStream in;
static ObjectOutputStream out;
String name=null ;
String serverAddress=null;
static char send[];
public static Message message = new Message();
public static boolean beginFlag = false;
BoardPanel bpanel = new BoardPanel();
JPanel jpanel3 = new JPanel();
JLabel label1 = new JLabel("Player1");
JLabel label2 = new JLabel(" VS ");
JLabel label3 = new JLabel("Player2");
JLabel label4 = new JLabel("Player List ");
JLabel label5 = new JLabel("Message list... ");
static JLabel label6 = new JLabel("welcome");
JLabel label7 = new JLabel("Host");
JLabel label8 = new JLabel("Player");
JRadioButton jrbBlack = new JRadioButton("Black");
JRadioButton jrbWhite = new JRadioButton("White");
DefaultListModel lItems = new DefaultListModel();
JList list = new JList(lItems);
JMenuBar mb = new JMenuBar();
JMenu create = new JMenu("Create");
JMenu setting = new JMenu("Setting");
JMenu quit = new JMenu("Quit");
JMenu about = new JMenu("About");
JMenuItem cPtoP = new JMenuItem("Play With people");
JMenuItem cPtoC = new JMenuItem("Play With Computer");
JMenuItem load = new JMenuItem("Load game...");
JMenuItem save = new JMenuItem("Save ...");
// JMenuItem sLimited = new JMenuItem("禁止禁手");
// JMenuItem sNoLimited = new JMenuItem("允许禁手");
public ChessWZQ()
{
enableEvents(AWTEvent.WINDOW_EVENT_MASK);
getContentPane().setLayout(null);
weightBoard = new int [15][15]; // 保存每个位置的重要性
PORT = Server.PORT;//设置套接字端口
send = new char[60];
try {
jbInit();
}
catch(Exception e)
{
e.printStackTrace();
}
try {
getContentPane().setLayout(null);
jrbBlack.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
bpanel.setColor(1);
cColor=2;
jrbBlack.setEnabled(false);
jrbWhite.setEnabled(false);
drawChess(1);
jrbWhite.setSelected(true);
if(ptocFlag==true)
{
return;
}
Message ms = new Message();
ms.color=1;
ms.type=13;
try{
out.writeObject(ms);
}
catch(IOException error)
{
error.printStackTrace();
}
}
});
jrbWhite.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
bpanel.setColor(2);
cColor=1;
jrbWhite.setEnabled(false);
jrbBlack.setEnabled(false);
drawChess(2);
jrbBlack.setSelected(false);
if(ptocFlag==true)
{
return;
}
Message ms = new Message();
ms.color=2;
ms.type=13;
try{
out.writeObject(ms);
}
catch(IOException error)
{
error.printStackTrace();
}
}
});
about.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
JOptionPane.showMessageDialog(null,
"Author: Kahn \nCopyright (c) 2007-CUIT \nMail:[email protected]",
"五子棋1.0(beta)",JOptionPane.INFORMATION_MESSAGE);
}
});
quit.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
int flag=JOptionPane.showConfirmDialog(null,
"Quit the Program ?",
"Are you sure to quit ?",
JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
if(flag==0)
{ //确定
// 断开和服务端的连接
sendDisconnect();
System.exit(0);
}
}
});
setting.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
Object selection[] = {"Forbiden","Allow any"};
Object set = JOptionPane.showInputDialog(null,
"Setting...","would you allow any method?",
JOptionPane.QUESTION_MESSAGE,null,selection,selection[0]);
if(ptocFlag==true)
{
return;
}
Message ms = new Message();
if(set==null)
{
return;
}
if(set.toString().equals(selection[0]))
{
ms.setting=false;
}
else{
ms.setting=true;
}
//System.out.println("setting begin..."+msg.setting);
ms.type=12;
try{
out.writeObject(ms);
}
catch(IOException error)
{
error.printStackTrace();
}
}
});
cPtoP.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
ptocFlag=false;
JOptionPane.showMessageDialog(null,
"You can choose a player from the listBox on the right","Welcome...",
JOptionPane.INFORMATION_MESSAGE);
}
});
cPtoC.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(ptocFlag==true)
{
int flag=JOptionPane.showConfirmDialog(null,
"You give up... ?","Message",
JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
if(flag==0)
{
newGame();
return;
}
}
label3.setText("Computer");
Object selection[] = {"Computer First","You First"};
Object set = JOptionPane.showInputDialog(null,
"choose who first...","setting...",
JOptionPane.QUESTION_MESSAGE,null,
selection,selection[0]);
ptocFlag = true;
if(set.toString().equals(selection[1]))
{
pFirst = true;
}
else
{
pFirst = false;
}
pColor=bpanel.getColor();
if(pColor==1)
{
jrbBlack.setSelected(true);
jrbWhite.setSelected(false);
cColor=2;
}
else
{
jrbWhite.setSelected(true);
jrbBlack.setSelected(false);
cColor=1;
}
jrbBlack.setEnabled(false);
jrbWhite.setEnabled(false);
ptoComputer();
}
});
create.setBounds(5,5,40,20);
setting.setBounds(45,5,40,20);
quit.setBounds(85,5,40,20);
about.setBounds(125,5,40,20);
create.add(cPtoP);
create.add(cPtoC);
//create.add(load);
//create.add(save);
mb.add(create);
mb.add(setting);
mb.add(quit);
mb.add(about);
this.setJMenuBar(mb);
bpanel.setBounds(0,0,470,460);
bpanel.setBorder(BorderFactory.createMatteBorder(0,0,1,1,Color.ORANGE));
jpanel3.setLayout(null);
jpanel3.setBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.DARK_GRAY));
jpanel3.setBounds(470,0,180,460);
label7.setBounds(10,10,30,20);
label7.setBackground(Color.blue);
label7.setForeground(Color.yellow);
label8.setBounds(90,10,40,30);
label8.setBackground(Color.blue);
label8.setForeground(Color.yellow);
label1.setBounds(10,40,50,20);
label2.setForeground(Color.RED);
label2.setBounds(60,40,50,20);
label3.setBounds(90,40,70,20);
label4.setForeground(Color.BLUE);
label4.setBounds(10,78,70,20);
label5.setBackground(Color.magenta);
label5.setForeground(Color.RED);
label5.setBounds(15,395,160,20);
label6.setBounds(15,415,180,20);
//label6.setBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.yellow));
jrbBlack.setSelected(true);
jrbBlack.setBounds(10,380,80,15);
jrbWhite.setBounds(90,380,80,15);
list.setBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.black));
list.setBounds(10,100,150,265);
list.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
// 双击选择玩家
if(e.getClickCount()==2)
{
String str = list.getSelectedValue().toString();
if(str.equals(name)==true)
{
label6.setText("You can't choose yourself");
return;
}
label3.setText(str);
list.setEnabled(false);
Message ms = new Message();
ms.type=3; //请求和别人游戏
strToCharArray(str,ms.msg);
ms.color = bpanel.getColor();
//System.out.println("request for play with "+str);
try{
out.writeObject(ms);
}
catch(IOException er)
{
er.printStackTrace();
}
}
}
});
jpanel3.add(label1);
jpanel3.add(label2);
jpanel3.add(label3);
jpanel3.add(label4);
jpanel3.add(label5);
jpanel3.add(label6);
jpanel3.add(label7);
// jpanel3.add(label8);
jpanel3.add(jrbBlack);
jpanel3.add(jrbWhite);
jpanel3.add(list);
// getContentPane().add(jpanel1);
getContentPane().add(bpanel);
getContentPane().add(jpanel3);
// lItems.add(0,"Kahn1");
// lItems.add(0,"Kahn2");
}
catch(Exception e)
{
e.printStackTrace();
}
}
//组件初始化
private void jbInit() throws Exception
{
contentPane = (JPanel) this.getContentPane();
contentPane.setLayout(borderLayout1);
this.setSize(new Dimension(660, 530));
this.setTitle("五子棋客户端(beta)");
}
/**
*发送断开请求到服务端
* type = 7
*/
public void sendDisconnect()
{
Message ms = new Message();
ms.type=7;
try{
out.writeObject(ms);
}
catch(IOException e)
{
e.printStackTrace();
}
}
public void drawChess(int col)
{
Graphics g = jpanel3.getGraphics();
if(col==1) g.setColor(Color.black);
else g.setColor(Color.white);
g.fillOval(50,10,20,20);
}
/**
* 格式: java ChessWZQ < server address> <player name>
* args[0]=服务端地址 args[1]=玩家名字
*/
public static void main(String [] args)
{
ChessWZQ wzq = new ChessWZQ();
wzq.setResizable(false);
wzq.setVisible(true);
wzq.drawChess(1); //默认颜色为黑色
Message ms = new Message();
if(args[0]!=null)
wzq.serverAddress = new String(args[0]);
else
wzq.serverAddress = new String("localhost");
if(args[1]!=null)
wzq.name = new String(args[1]);
else
wzq.name = new String("Kahn");
wzq.strToCharArray(wzq.name,ms.msg);
try{
// 从命令行得到服务端名字
InetAddress addr = InetAddress.getByName(wzq.serverAddress);
//System.out.println("address "+ addr.toString()+" port: "+PORT);
socket = new Socket(addr, PORT);
//System.out.println("set socket successful...");
out = new ObjectOutputStream(
socket.getOutputStream());
in = new ObjectInputStream(
socket.getInputStream());
ms.type=1;
try{
out.writeObject(ms);
}
catch(IOException e)
{
e.printStackTrace();
}
while(true)
{
try {
ms = (Message) in.readObject();
//System.out.println("get message from server...type = "+ms.type);
wzq.doMessage(ms);
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
//System.out.println("ms.coordinateX + , + msg.coordinateY");
//System.out.println(ms.color);
//System.out.println("close ...");
//socket.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
/**
* 处理从服务端发来的信息
* msg
*/
protected int doMessage(Message msg)
{
String str=arrayToString(msg.msg);
//System.out.println("msg name = "+str+" msg.type = "+msg.type);
switch(msg.type)
{
case 2:{//响应放棋子
putChessman(msg);
break;
}
case 3:{//其他玩家的请求
requestAnother(msg);
break;
}
case 4:{ // B拒绝和A游戏
getDeny(msg);
break;}
case 5:{ // B 接收A的请求
acceptToPlay(msg);
break;}
case 6:{
getVictory(msg);
break;}
case 7:{
getDisconnection(msg);
break;}
case 9:{//回复添加新玩家到所有的客户端
///System.out.println("add new player to list type = 9 name = "+str+"msg[0]= "+msg.msg[0]);
lItems.add(0,str);
break;
}
case 10:{ //连接回复
//System.out.println("add him self type = 10 name = "+str+"msg[0]= "+msg.coordinateX+msg.msg[0]);
label1.setText(str);
label6.setText("welcome "+str);
lItems.add(0,str);
break;
}
case 14:{ //B接收和A游戏,设置MSG及设置游戏选项
break;
}
case 15:{
lItems.clear();
break;
}
case 17:{
getFailed(msg);
break;
}
case 20:{
ptocWin(msg);
break;
}
}
return 0; //结束
}
private void ptocWin(Message ms)
{
String str=this.arrayToString(ms.msg);
JOptionPane.showMessageDialog(null,str+" win the game!","Win the game",JOptionPane.INFORMATION_MESSAGE);
newGame();
}
/**
* 游戏失败并开始新的游戏
* type == 17
* msg
*/
public void getFailed(Message msg)
{
bpanel.drawChess(msg.coordinateX,msg.coordinateY);
JOptionPane.showMessageDialog(null,
"Sorry,You've failed the game",
"Try Again",
JOptionPane.INFORMATION_MESSAGE);
label3.setText("Player2");
// 继续新游戏
newGame();
}
/**
*另一个玩家发送断开请求
* type ==7
* msg
*/
public void getDisconnection(Message msg)
{
getVictory(msg);
}
/**
* 游戏胜利
* type ==6
* msg
*/
public void getVictory(Message msg)
{
JOptionPane.showMessageDialog(null,
"You Win The Game",
"Congratulations",
JOptionPane.INFORMATION_MESSAGE);
//继续新游戏
label3.setText("Player2");
newGame();
}
/**
* 当人获胜时 ,他能够开始新游戏
* msg
*/
public void newGame()
{
jrbBlack.setEnabled(true);
jrbWhite.setEnabled(true);
jrbBlack.setSelected(true);
jrbWhite.setSelected(false);
list.setEnabled(true);
setting.setEnabled(true);
bpanel.clearBoard();
drawChess(1);
pColor=1;cColor=2;
if(ptocFlag==false)
{
Message msg = new Message();
msg.type = 19;
strToCharArray(name, msg.msg);
try {
out.writeObject(msg);
}
catch (IOException e)
{
e.printStackTrace();
}
}
ptocFlag=false;
beginFlag=false;
}
public void putChessman(Message msg)
{
if(ptocFlag==false)
{
bpanel.updateBoard(msg.coordinateX,msg.coordinateY);
bpanel.drawChess(msg.coordinateX,msg.coordinateY);
beginFlag = true;
return;
}else{
//更新本地面板
// 搜索最优坐标并下棋
}
}
/**
* A从B收到确定消息并根据B来设置
* type= 5 B 接受和A游戏
* msg = B的名字
*/
public void acceptToPlay(Message msg)
{
String str=arrayToString(msg.msg);
String ss=null;
if(msg.color==1)
{
ss = new String("white");
bpanel.setColor(2);
}
else{
ss = new String("black");
bpanel.setColor(1);
}
JOptionPane.showMessageDialog(null,
"OK. "+str+" have accepted your requestion\nYour color is"+ss,
"Game will to begin...",JOptionPane.ERROR_MESSAGE);
list.setEnabled(false);
jrbBlack.setEnabled(false);
jrbWhite.setEnabled(false);
setting.setEnabled(false);
beginFlag=true;
}
/**
* A收到B的拒绝信息
* type ==4 拒绝游戏
* msg
*/
public void getDeny(Message msg)
{
String str=arrayToString(msg.msg);
JOptionPane.showMessageDialog(null,
"I'm sorry\n"+str+" denied your requestion",
"Sorry...",JOptionPane.ERROR_MESSAGE);
list.setEnabled(true);
label3.setText("Player2");
}
/**
* A请求和B游戏,B的动作如下
* msg = 请求者的名字
*/
public void requestAnother(Message msg)
{
String str=arrayToString(msg.msg);
// System.out.print("client requestAnother begin ...");
int flag =JOptionPane.showConfirmDialog(null,
"Player "+str+" want to play with you\nAre you OK?",
"Play request...",JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
if(flag==0)
{// 确定
msg.type=5; //同意请求
if(msg.color==1)
{ // msg.color为B的颜色
drawChess(msg.color);
jrbBlack.setSelected(true);
jrbWhite.setSelected(false);
bpanel.setColor(1);
}
else{
drawChess(msg.color);
jrbWhite.setSelected(true);
jrbBlack.setSelected(false);
bpanel.setColor(2);
}
// System.out.println("B's color is"+msg.color);
list.setEnabled(false);
label3.setText(str);
setting.setEnabled(false);
jrbBlack.setEnabled(false);
jrbWhite.setEnabled(false);
beginFlag=true;
}
if(flag==1)
{//拒绝请求
msg.type=4;
}
try{
out.writeObject(msg);
}
catch(IOException e)
{
e.printStackTrace();
}
}
public void paint(Graphics g)
{
super.paint(g);
drawChess(bpanel.getColor());
}
/**
* 当WINDOWS关闭时能退出
*/
protected void processWindowEvent(WindowEvent e)
{
super.processWindowEvent(e);
if (e.getID() == WindowEvent.WINDOW_CLOSING)
{
System.exit(0);
}
}
//把字符串转换成数组并以'\0'结束
public void strToCharArray(String str,char [] arr)
{
int i;
for(i=0;i<str.length()&&i<49;i++)
{
arr[i] = str.charAt(i);
}
arr[i]='\0';
}
/**
* 在数组的末端过滤黑棋的位置
* arr
* str
*/
public String arrayToString(char [] arr)
{
int i=0,length=0;
while(arr[i]!='\0' && i<50)
{
i++;
}
length=i;
char [] ss = new char[length];
for(i=0;i<length;i++)
{
ss[i]=arr[i];
}
String str = new String(ss);
return str;
//System.out.println("arraytoString "+str+"length = "+length);
}
/**
* 人和电脑对战
*/
public void ptoComputer()
{
int x=0,y=0;
int position;
if(pFirst==false)
{
x=7;
y=7;
bpanel.updateBoard(x,y);
bpanel.drawChess(x,y);
beginFlag=true;
}else{
beginFlag=true;
}
}
/**
* 选择最优的位置下棋
*/
private void cPutChess(int x,int y)
{
setRect(x,y);
setWeight(x,y,pColor);
getBetter(3);
}
/**
* 9*9矩形
*/
private void setRect(int x,int y)
{
if(x-4>0) RectX1=x-4;
else RectX1=0;
if(x+4>14) RectX2=14;
else RectX2=x+4;
if(y-4>0) RectY1=y-4;
else RectY1=0;
if(y+4>14) RectY2=14;
else RectY2=y+4;
if(RectX1>RectY1) RectX1 = x-(y-RectY1);
else RectY1 = y-(x-RectX1);
if(RectX2>RectY2) RectY2 = y+(RectX2-x);
else RectX2 = x+(RectY2-y);
}
/**
* 在范围内设定黑棋重要性
*/
private void setWeight(int x,int y,int tcolor)
{
int i=RectX1,j=RectY1,value=0,k=0,n=0,flag=0;
// '--' 方向
for(i=RectX1,j=y;i<=RectX2;i++)
{
if(BoardPanel.board[i][j]!=0)
{
continue;
}
value=0;flag=0;
for(k=1;i-k>=RectX1 && k<5;k++)
{
if(BoardPanel.board[i-k][j]==tcolor)
{
value++;
continue;
}
if(BoardPanel.board[i-k][j]==0)
{//black space
flag++;
break;
}
}
for(k=1;i+k<RectX2 && k<5;k++)
{
if(BoardPanel.board[i+k][j]==tcolor)
{
value++;
}
if(BoardPanel.board[i+k][j]==0)
{
flag++;
break;
}
}
n=weight(value,flag);
if(weightBoard[i][j]<n)
{
weightBoard[i][j]=n;
}
}
// '|' 方向
for(i=x,j=RectY1;j<=RectY2;j++)
{
if(BoardPanel.board[i][j]!=0)
{
continue;
}
value=0;flag=0;
for(k=1;j-k>=RectY1 && k<5;k++)
{
if(BoardPanel.board[i][j-k]==tcolor)
{
value++;
continue;
}
if(BoardPanel.board[i][j-k]==0)
{
flag++;
break;
}
}
for(k=1;j+k<RectY2 && k<5;k++)
{
if(BoardPanel.board[i][j+k]==tcolor)
{
value++;
}
if(BoardPanel.board[i][j+k]==0)
{
flag++;
break;
}
}
n=weight(value,flag);
if(weightBoard[i][j]<n)
{
weightBoard[i][j]=n;
}
}
// '\' 方向
for(i=RectX1,j=RectY1;i<=RectX2;i++,j++)
{
if(BoardPanel.board[i][j]!=0)
{
continue;
}
value=0;flag=0;
for(k=1;i-k>=RectX1 && k<5 ;k++)
{
if(BoardPanel.board[i-k][j-k]==tcolor)
{
value++;
continue;
}
if(BoardPanel.board[i-k][j-k]==0)
{
flag++;
break;
}
}
for(k=1;i+k<RectX2 && k<5;k++)
{
if(BoardPanel.board[i+k][j+k]==tcolor)
{
value++;
}
if(BoardPanel.board[i+k][j+k]==0)
{
flag++;
break;
}
}
n=weight(value,flag);
if(weightBoard[i][j]<n)
{
weightBoard[i][j]=n;
}
}
// '/' 方向
for(i=RectX2,j=RectY1;i>=RectX1;i--,j++)
{
if(BoardPanel.board[i][j]!=0)
{
continue;
}
value=0;flag=0;
for(k=1;i+k<=RectX2 && k<5;k++)
{
if(BoardPanel.board[i+k][j-k]==tcolor)
{
value++;
continue;
}
if(BoardPanel.board[i+k][j-k]==0)
{
flag++;
break;
}
}
for(k=1;i-k>=RectX1 && k<5;k++)
{
if(BoardPanel.board[i-k][j+k]==tcolor)
{
value++;
}
if(BoardPanel.board[i-k][j+k]==0)
{
flag++;
break;
}
}
n=weight(value,flag);
if(weightBoard[i][j]<n)
{
weightBoard[i][j]=n;
}
}
}
/**
* 返回重量值
*count
*flag
*/
private int weight(int count, int flag)
{
int weight=0;
switch(count)
{
case 0:{
if(flag>0) weight=200;
else weight=0;
break;
}
case 1:{
if(flag>0) weight=1000;
else weight=0;
break;
}
case 2:{
if(flag>0) weight=5000;
else weight=0;
break;
}
case 3:{
if(flag>0) weight=8000;
else weight=0;
break;
}
case 4:{
if(flag>0) weight=10000;
else weight=0;
break;
}
}
return weight;
}
/**
* 搜索整个面板找到更好的计数位置,默认值为3
*/
private void getBetter(int count)
{
int [][] better = new int [count][2];
int [][] tempArray = new int [15][15];
for(int i=0;i<15;i++)
{
for(int j=0;j<15;j++)
{
tempArray[i][j]=weightBoard[i][j];
}
}
for(int i=0;i<count;i++)
{
getBiggest(tempArray,better[i][0],better[i][1]);
}
bestX=better[0][0];bestY=better[0][1];
}
/**
* arr
* x
* y
*/
private void getBiggest(int [][] arr,int x,int y)
{
int [] temp=new int[2];
int swt=arr[0][0],tmp=0;
for(int i=0;i<15;i++)
{
for(int j=0;j<15;j++)
{
if(arr[i][j]>swt)
{
temp[0]=i;temp[1]=j;
swt=arr[i][j];
}
}
}
x=temp[0];
y=temp[1];
arr[x][y]=0;
}
}
下载地址
相关阅读
JavaScript之childNodes 和 children 区别
1、先让我们来看看childNodes的用法,以及是如何计算节点数量: 为什么输出是7而不是3呢?原来Internet Explorer 会忽略节点之间生
Java经典编程300例 PDF扫描版[78MB]http://pan.baidu.com/s/1gdGirZ1面向对象软件工程:使用UML、模式与 Java(第3版)完整版PDF[59MB]
public class Triangle { public boolean isTriangle(int a,int b,int c){ boolean flag = false; if (a+b>c&&a+c>b&&b+c>a
摘要 ThreadLocal是Java中的一个类,在Java 1.2版本加入,它的作者是Josh Bloch和Doug Lea。这篇文章会详细深入的分析ThreadLocal(基
springboot 2.0 使用Hikari连接池(号称java平台最快的,
1.springboot 2.0 默认连接池就是Hikari了,所以引用parents后不用专门加依赖 2.贴我自己的配置(时间单位都是毫秒) # jdbc_config