以下是現(xiàn)寫的 實現(xiàn)了兩人對戰(zhàn) 自己復(fù)制后運行把 沒什么難度 類名 Games
創(chuàng)新互聯(lián)公司主要從事網(wǎng)頁設(shè)計、PC網(wǎng)站建設(shè)(電腦版網(wǎng)站建設(shè))、wap網(wǎng)站建設(shè)(手機版網(wǎng)站建設(shè))、成都響應(yīng)式網(wǎng)站建設(shè)公司、程序開發(fā)、網(wǎng)站優(yōu)化、微網(wǎng)站、小程序設(shè)計等,憑借多年來在互聯(lián)網(wǎng)的打拼,我們在互聯(lián)網(wǎng)網(wǎng)站建設(shè)行業(yè)積累了豐富的網(wǎng)站制作、成都網(wǎng)站建設(shè)、網(wǎng)站設(shè)計、網(wǎng)絡(luò)營銷經(jīng)驗,集策劃、開發(fā)、設(shè)計、營銷、管理等多方位專業(yè)化運作于一體。
import java.util.Scanner;
public class Games {
private String board[][];
private static int SIZE = 17;
private static String roles = "A玩家";
//初始化數(shù)組
public void initBoard() {
board = new String[SIZE][SIZE];
for (int i = 0; i SIZE; i++) {
for (int j = 0; j SIZE; j++) {
// if(i==0){
// String str = "";
// str += j+" ";
// board[i][j]= str;
// }else if(i!=0j==0){
// String str = "";
// str += i+" ";
// board[i][j]= str;
// }else{
board[i][j] = "╋";
// }
}
}
}
//輸出棋盤
public void printBoard() {
for (int i = 0; i SIZE; i++) {
for (int j = 0; j SIZE; j++) {
System.out.print(board[i][j]);
}
System.out.println();
}
}
//判斷所下棋子位置是否合理
public boolean isOk(int x, int y) {
boolean isRight = true;
if (x = 16 || x 1 || y = 16 | y 1) {
//System.out.println("輸入錯誤,請從新輸入");
isRight = false;
}
if (board[x][y].equals("●") || board[x][y].equals("○")) {
isRight = false;
}
return isRight;
}
//判斷誰贏了
public void whoWin(Games wz) {
// 從數(shù)組挨個查找找到某個類型的棋子就從該棋子位置向右,向下,斜向右下 各查找5連續(xù)的位置看是否為5個相同的
int xlabel;// 記錄第一次找到某個棋子的x坐標
int ylabel;// 記錄第一次找到某個棋子的y坐標
// ●○╋
// 判斷人是否贏了
for (int i = 0; i SIZE; i++) {
for (int j = 0; j SIZE; j++) {
if (board[i][j].equals("○")) {
xlabel = i;
ylabel = j;
// 橫向找 x坐標不變 y坐標以此加1連成字符串
String heng = "";
if (i + 5 SIZE j + 5 SIZE) {
for (int k = j; k j + 5; k++) {
heng += board[i][k];
}
if (heng.equals("○○○○○")) {
System.out.println(roles+"贏了!您輸了!");
System.exit(0);
}
// 向下判斷y不變 x逐增5 連成字符串
String xia = "";
for (int l = j; l i + 5; l++) {
xia += board[l][j];
// System.out.println(xia);
}
if (xia.equals("○○○○○")) {
System.out.println(roles+"贏了!您輸了!");
System.exit(0);
}
// 斜向右下判斷
String youxia = "";
for (int a = 1; a = 5; a++) {
youxia += board[xlabel++][ylabel++];
}
if (youxia.equals("○○○○○")) {
System.out.println(roles+"贏了!您輸了!");
System.exit(0);
}
}
}
}
}
// 判斷電腦是否贏了
for (int i = 0; i SIZE; i++) {
for (int j = 0; j SIZE; j++) {
if (board[i][j].equals("●")) {
xlabel = i;
ylabel = j;
// 橫向找 x坐標不變 y坐標以此加1連成字符串
String heng = "";
if (j + 5 SIZE i + 5 SIZE) {
for (int k = j; k j + 5; k++) {
heng += board[i][k];
}
if (heng.equals("●●●●●")) {
System.out.println(roles+"贏輸了!您輸了!");
System.exit(0);
}
// 向下判斷y不變 x逐增5 連成字符串
String xia = "";
for (int l = i; l i + 5; l++) {
xia += board[l][ylabel];
// System.out.println(xia);
}
if (xia.equals("●●●●●")) {
System.out.println(roles+"贏了!您輸了!");
System.exit(0);
}
// 斜向右下判斷
String youxia = "";
for (int a = 1; a = 5; a++) {
youxia += board[xlabel++][ylabel++];
}
if (youxia.equals("●●●●●")) {
System.out.println(roles+"贏了!您輸了!");
System.exit(0);
}
}
}
}
}
}
public static void main(String[] args) {
Games wz = new Games();
Scanner sc = new Scanner(System.in);
wz.initBoard();
wz.printBoard();
while (true) {
System.out.print("請"+roles+"輸入X,Y坐標,必須在0-15范圍內(nèi),xy以空格隔開,輸入16 16結(jié)束程序");
int x = sc.nextInt();
int y = sc.nextInt();
if (x == SIZE y == SIZE) {
System.out.println("程序結(jié)束");
System.exit(0);
}
if (x SIZE || x 0 || y SIZE | y 0) {
System.out.println("輸入錯誤,請從新輸入");
continue;
}
//如果roles是A玩家 就讓A玩家下棋,否則就讓B玩家下棋。
if (wz.board[x][y].equals("╋")roles.equals("A玩家")) {
wz.board[x][y] = "○";
wz.printBoard();
//判斷輸贏
wz.whoWin(wz);
}else if(wz.board[x][y].equals("╋")roles.equals("B玩家")){
wz.board[x][y] = "●";
wz.printBoard();
//判斷輸贏
wz.whoWin(wz);
} else {
System.out.println("此處已經(jīng)有棋子,從新輸入");
continue;
}
if(roles.equals("A玩家")){
roles = "B玩家";
}else if(roles.equals("B玩家")){
roles = "A玩家";
}
}
}
}
java網(wǎng)絡(luò)五子棋
下面的源代碼分為4個文件;
chessClient.java:客戶端主程序。
chessInterface.java:客戶端的界面。
chessPad.java:棋盤的繪制。
chessServer.java:服務(wù)器端。
可同時容納50個人同時在線下棋,聊天。
沒有加上詳細注釋,不過絕對可以運行,j2sdk1.4下通過。
/*********************************************************************************************
1.chessClient.java
**********************************************************************************************/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
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;
chessclient.userpad.userList.removeAll();
chessclient.inputpad.userChoice.removeAll();
chessclient.inputpad.userChoice.addItem("所有人");
while(userToken.hasMoreTokens())
{
String user=(String)userToken.nextToken(" ");
if(userNumber0 !user.startsWith("[inchess]"))
{
chessclient.userpad.userList.add(user);
chessclient.inputpad.userChoice.addItem(user);
}
userNumber++;
}
chessclient.inputpad.userChoice.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.chessSocket.close無法關(guān)閉");
}
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("創(chuàng)建游戲成功,等待別人加入...");
}
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("連接成功,請創(chuàng)建游戲或加入游戲");
}
}
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=userpad.userList.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 "+userpad.userList.getSelectedItem()+" "+chessClientName);
}
}
else
{
isOnChess=true;
isClient=true;
controlpad.creatGameButton.setEnabled(false);
controlpad.joinGameButton.setEnabled(false);
controlpad.cancelGameButton.setEnabled(true);
chesspad.chessthread.sendMessage("/joingame "+userpad.userList.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(inputpad.userChoice.getSelectedItem().equals("所有人"))
{
try
{
out.writeUTF(inputWords.getText());
inputWords.setText("");
}
catch(Exception ea)
{
chatpad.chatLineArea.setText("chessClient:KeyPressed無法連接,建議重新連接 \n");
userpad.userList.removeAll();
inputpad.userChoice.removeAll();
inputWords.setText("");
controlpad.connectButton.setEnabled(true);
}
}
else
{
try
{
out.writeUTF("/"+inputpad.userChoice.getSelectedItem()+" "+inputWords.getText());
inputWords.setText("");
}
catch(Exception ea)
{
chatpad.chatLineArea.setText("chessClient:KeyPressed無法連接,建議重新連接 \n");
userpad.userList.removeAll();
inputpad.userChoice.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 java.net.*;
class userPad extends Panel
{
List userList=new List(10);
userPad()
{
setLayout(new BorderLayout());
for(int i=0;i50;i++)
{
userList.add(i+"."+"沒有用戶");
}
add(userList,BorderLayout.CENTER);
}
}
class chatPad extends Panel
{
TextArea chatLineArea=new TextArea("",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("關(guān)閉程序");
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;i50;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 java.net.*;
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++;
}
chesspad.netChessPaint(Integer.parseInt(chessOpt[0]),Integer.parseInt(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 implements MouseListener,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("請先連接服務(wù)器");
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++;
else
break;
}
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++;
else
break;
}
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++;
else
break;
}
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++;
else
break;
}
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++;
else
break;
}
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++;
else
break;
}
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++;
else
break;
}
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);
}
}
package org.crazyit.gobang;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* 五子棋游戲類
*
* @author yangenxiong yangenxiong2009@gmail.com
* @author Kelvin Mak kelvin.mak125@gmail.com
* @version 1.0
* br/網(wǎng)站: a href=""瘋狂Java聯(lián)盟/a
* brCopyright (C), 2009-2010, yangenxiong
* brThis program is protected by copyright laws.
*/
public class GobangGame {
// 定義達到贏條件的棋子數(shù)目
private final int WIN_COUNT = 5;
// 定義用戶輸入的X坐標
private int posX = 0;
// 定義用戶輸入的X坐標
private int posY = 0;
// 定義棋盤
private Chessboard chessboard;
/**
* 空構(gòu)造器
*/
public GobangGame() {
}
/**
* 構(gòu)造器,初始化棋盤和棋子屬性
*
* @param chessboard
* 棋盤類
*/
public GobangGame(Chessboard chessboard) {
this.chessboard = chessboard;
}
/**
* 檢查輸入是否合法。
*
* @param inputStr
* 由控制臺輸入的字符串。
* @return 字符串合法返回true,反則返回false。
*/
public boolean isValid(String inputStr) {
// 將用戶輸入的字符串以逗號(,)作為分隔,分隔成兩個字符串
String[] posStrArr = inputStr.split(",");
try {
posX = Integer.parseInt(posStrArr[0]) - 1;
posY = Integer.parseInt(posStrArr[1]) - 1;
} catch (NumberFormatException e) {
chessboard.printBoard();
System.out.println("請以(數(shù)字,數(shù)字)的格式輸入:");
return false;
}
// 檢查輸入數(shù)值是否在范圍之內(nèi)
if (posX 0 || posX = Chessboard.BOARD_SIZE || posY 0
|| posY = Chessboard.BOARD_SIZE) {
chessboard.printBoard();
System.out.println("X與Y坐標只能大于等于1,與小于等于" + Chessboard.BOARD_SIZE
+ ",請重新輸入:");
return false;
}
// 檢查輸入的位置是否已經(jīng)有棋子
String[][] board = chessboard.getBoard();
if (board[posX][posY] != "十") {
chessboard.printBoard();
System.out.println("此位置已經(jīng)有棋子,請重新輸入:");
return false;
}
return true;
}
/**
* 開始下棋
*/
public void start() throws Exception {
// true為游戲結(jié)束
boolean isOver = false;
chessboard.initBoard();
chessboard.printBoard();
// 獲取鍵盤的輸入
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String inputStr = null;
// br.readLine:每當(dāng)鍵盤輸入一行內(nèi)容按回車鍵,則輸入的內(nèi)容被br讀取到
while ((inputStr = br.readLine()) != null) {
isOver = false;
if (!isValid(inputStr)) {
// 如果不合法,要求重新輸入,再繼續(xù)
continue;
}
// 把對應(yīng)的數(shù)組元素賦為"●"
String chessman = Chessman.BLACK.getChessman();
chessboard.setBoard(posX, posY, chessman);
// 判斷用戶是否贏了
if (isWon(posX, posY, chessman)) {
isOver = true;
} else {
// 計算機隨機選擇位置坐標
int[] computerPosArr = computerDo();
chessman = Chessman.WHITE.getChessman();
chessboard.setBoard(computerPosArr[0], computerPosArr[1],
chessman);
// 判斷計算機是否贏了
if (isWon(computerPosArr[0], computerPosArr[1], chessman)) {
isOver = true;
}
}
// 如果產(chǎn)生勝者,詢問用戶是否繼續(xù)游戲
if (isOver) {
// 如果繼續(xù),重新初始化棋盤,繼續(xù)游戲
if (isReplay(chessman)) {
chessboard.initBoard();
chessboard.printBoard();
continue;
}
// 如果不繼續(xù),退出程序
break;
}
chessboard.printBoard();
System.out.println("請輸入您下棋的坐標,應(yīng)以x,y的格式輸入:");
}
}
/**
* 是否重新開始下棋。
*
* @param chessman
* "●"為用戶,"○"為計算機。
* @return 開始返回true,反則返回false。
*/
public boolean isReplay(String chessman) throws Exception {
chessboard.printBoard();
String message = chessman.equals(Chessman.BLACK.getChessman()) ? "恭喜您,您贏了,"
: "很遺憾,您輸了,";
System.out.println(message + "再下一局?(y/n)");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
if (br.readLine().equals("y")) {
// 開始新一局
return true;
}
return false;
}
/**
* 計算機隨機下棋
*/
public int[] computerDo() {
int posX = (int) (Math.random() * (Chessboard.BOARD_SIZE - 1));
int posY = (int) (Math.random() * (Chessboard.BOARD_SIZE - 1));
String[][] board = chessboard.getBoard();
while (board[posX][posY] != "十") {
posX = (int) (Math.random() * (Chessboard.BOARD_SIZE - 1));
posY = (int) (Math.random() * (Chessboard.BOARD_SIZE - 1));
}
int[] result = { posX, posY };
return result;
}
/**
* 判斷輸贏
*
* @param posX
* 棋子的X坐標。
* @param posY
* 棋子的Y坐標
* @param ico
* 棋子類型
* @return 如果有五顆相鄰棋子連成一條直接,返回真,否則相反。
*/
public boolean isWon(int posX, int posY, String ico) {
// 直線起點的X坐標
int startX = 0;
// 直線起點Y坐標
int startY = 0;
// 直線結(jié)束X坐標
int endX = Chessboard.BOARD_SIZE - 1;
// 直線結(jié)束Y坐標
int endY = endX;
// 同條直線上相鄰棋子累積數(shù)
int sameCount = 0;
int temp = 0;
// 計算起點的最小X坐標與Y坐標
temp = posX - WIN_COUNT + 1;
startX = temp 0 ? 0 : temp;
temp = posY - WIN_COUNT + 1;
startY = temp 0 ? 0 : temp;
// 計算終點的最大X坐標與Y坐標
temp = posX + WIN_COUNT - 1;
endX = temp Chessboard.BOARD_SIZE - 1 ? Chessboard.BOARD_SIZE - 1
: temp;
temp = posY + WIN_COUNT - 1;
endY = temp Chessboard.BOARD_SIZE - 1 ? Chessboard.BOARD_SIZE - 1
: temp;
// 從左到右方向計算相同相鄰棋子的數(shù)目
String[][] board = chessboard.getBoard();
for (int i = startY; i endY; i++) {
if (board[posX][i] == ico board[posX][i + 1] == ico) {
sameCount++;
} else if (sameCount != WIN_COUNT - 1) {
sameCount = 0;
}
}
if (sameCount == 0) {
// 從上到下計算相同相鄰棋子的數(shù)目
for (int i = startX; i endX; i++) {
if (board[i][posY] == ico board[i + 1][posY] == ico) {
sameCount++;
} else if (sameCount != WIN_COUNT - 1) {
sameCount = 0;
}
}
}
if (sameCount == 0) {
// 從左上到右下計算相同相鄰棋子的數(shù)目
int j = startY;
for (int i = startX; i endX; i++) {
if (j endY) {
if (board[i][j] == ico board[i + 1][j + 1] == ico) {
sameCount++;
} else if (sameCount != WIN_COUNT - 1) {
sameCount = 0;
}
j++;
}
}
}
return sameCount == WIN_COUNT - 1 ? true : false;
}
public static void main(String[] args) throws Exception {
GobangGame gb = new GobangGame(new Chessboard());
gb.start();
}
}
package com.test;
import java.util.Scanner;
public class? TestMain{
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
char[] name = { '空', '黑', '白' };
int count = 0;// 計數(shù)器,用來計算該誰下棋了
char[][] qi = new char[16][16];// 把棋盤情況放進二維數(shù)組中
while (true) {
int row = 0;// 初始化從控制臺接收到的row和col 的index為0
int col = 0;
if (count == 0) {
print(qi, name[count], row, col);
count++;
}
if (count == 1) {
System.out.println("請黑(@)下棋(i j):");
row = console.nextInt(16)%16;// 從控制臺接收到的row的index
col = console.nextInt(16)%16;// 從控制臺接收到的col的index
String condition = print(qi, name[count], row, col);
if (condition.length() == 1) {// 下棋正確
count++;
}
if (condition.length() == 2) {// 下棋出現(xiàn)錯誤,要下的位置已經(jīng)下過棋子
System.out.println("此位置已經(jīng)有棋子,黑棋重新再下");
}
if (condition.length() == 3) {// 黑棋子贏
System.out.println("黑棋很給力,白棋是浮云,黑棋贏了");
break;
}
if (condition.length() == 4) {
System.out.println("白棋子贏");
break;
}
}
if (count == 2) {
System.out.println("請白(*)下棋(i j):");
row = console.nextInt(16);
col = console.nextInt(16);
String condition = print(qi, name[count], row, col);
if (condition.length() == 1) {// 打印棋盤
count--;
}
if (condition.length() == 2) {// 下棋出現(xiàn)錯誤,要下的位置已經(jīng)下過棋子
System.out.println("此位置已經(jīng)有棋子,白棋重新再下");
}
if (condition.length() == 3) {
System.out.println("黑棋子贏");
break;
}
if (condition.length() == 4) {
System.out.println("白棋很給力,黑棋是浮云,白棋贏了");
break;
}
}
}
}
/**
* @param qi是裝棋盤情況
* @param name輪到誰下棋了
*? ? ? ? ? ? row 行號 col 列號 return true-下棋正確,false-下棋錯誤,重新下
*/
public static String print(char[][] qi, char name, int row, int col) {
String b = "無";// 初始化下棋是正確的
String str = "0123456789111111";
// 打印下第一行
System.out.print(" ");
for (int i = 0; i str.length(); i++) {
System.out.print(str.charAt(i));
}
System.out.println();
for (int i = 0; i qi.length; i++) {
System.out.print(str.charAt(i));
for (int j = 0; j qi[i].length; j++) {
if (name == '空') { // 還沒開始下棋時,棋盤默認顯示是'.'
qi[i][j] = '.';
}
if ((name == '黑') (i == row) (j == col)) {
if (qi[i][j] != '.') {// 下的位置已經(jīng)有棋子了,返回false
b = "有棋";
} else {
qi[i][j] = '@';// 黑方下棋后的位置顯示是'@'
if (win(qi, '@', row, col)) {
b = "黑棋子";
}
}
}
if ((name == '白') (i == row) (j == col)) {
if (qi[i][j] != '.') {
b = "有棋";
} else {
qi[i][j] = '*';// 黑方下棋后的位置顯示是'*'
if (win(qi, '*', row, col)) {
b = "白棋子贏";
}
}
}
System.out.print(qi[i][j]);
}
System.out.println();
}
return b;
}
public static boolean win(char[][] qi, char ch, int row, int col) {
boolean b = false;
boolean ns = n2s(qi, ch, row, col);
boolean we = w2e(qi, ch, row, col);
boolean wnes = wn2es(qi, ch, row, col);
boolean enws = en2ws(qi, ch, row, col);
b = ns || we || wnes || enws;
return b;
}
/* 從北到南方向 */
public static boolean n2s(char[][] qi, char ch, int row, int col) {
boolean win = false;
int north = 0;// begin
int south = 0;// end
while (qi[row][col] == ch) {
row--;
if (row 0) {
break;
}
}
row++;// row此時要++,不然等到下面的while(..)中的qi[row][col]永不會==ch
north = row;
while (qi[row][col] == ch) {
row++;
if (row 15) {
break;
}
}
south = row;
if ((south - north) = 5) {
win = true;
}
return win;
}
/* 從西到東方向 */
public static boolean w2e(char[][] qi, char ch, int row, int col) {
boolean win = false;
int west = 0;// begin
int east = 0;// end
while (qi[row][col] == ch) {
col--;
if (col 0) {
break;
}
}
col++;// col此時要++,不然等到下面的while(..)中的qi[row][col]永不會==ch
west = col;
while (qi[row][col] == ch) {
col++;
if (col 15) {
break;
}
}
east = col;
if ((east - west) = 5) {
win = true;
}
return win;
}
/* 從西北到東南方向 */
public static boolean wn2es(char[][] qi, char ch, int row, int col) {
boolean win = false;
int wn = 0;// begin
int es = 0;// end
while (qi[row][col] == ch) {
row--;
col--;
if (row 0 || col 0) {
break;
}
}
row++;// row和col此時要++,不然等到下面的while(..)中的qi[row][col]永不會==ch
col++;
wn = row;
while (qi[row][col] == ch) {
row++;
col++;
if (row 15 || col 15) {
break;
}
}
es = row;
if ((es - wn) = 5) {
win = true;
}
return win;
}
/* 從東北到西南方向 */
public static boolean en2ws(char[][] qi, char ch, int row, int col) {
boolean win = false;
int en = 0;// begin
int ws = 0;// end
while (qi[row][col] == ch) {
row--;
col--;
if (row 0 || col 0) {
break;
}
}
row++;// row和col此時要++,不然等到下面的while(..)中的qi[row][col]永不會==ch
col++;
en = row;
while (qi[row][col] == ch) {
row++;
col++;
if (row 15 || col 15) {
break;
}
}
ws = row;
if ((ws - en) = 5) {
win = true;
}
return win;
}
}