使用java制作五子棋

使用java制作五子棋

package bao;

import java.awt.AWTEvent;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.AWTEventListener;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
public class MyFreme extends JFrame {

static Graphics g; //新建画笔
static int [][] isArray = new int[16][16];  //储存棋子的二维数组
public static void main(String[] args) {
//isArray[5][5] = 1;                        测试数据
	MyFreme myfreme = new MyFreme();     //创建游戏窗口变量
	myfreme.start();                     //加载游戏窗口
	
	
}
public void start() {
	MyFreme mf = new MyFreme();
	mf.setSize(800, 800);
	//mf.setLocation(200, 200);
	mf.setVisible(true);
	mf.setDefaultCloseOperation(3);
	mf.setLocationRelativeTo(null);
	mf.setBackground(Color.GRAY);
	// 添加对鼠标点击的自定义监听
	MyLisiten ml = new MyLisiten();  
	ml.setG(mf);                        //将当前游戏窗口导入监听类中
	mf.addMouseListener(ml);            // 为当前窗口添加监听
	
}
@Override
public void paint(Graphics g) {
	// TODO 自动生成的方法存根
	super.paint(g);
	for (int i = 0; i <=15; i++) {  //画行
		g.drawLine(40, 40*i+40, 640, 40*i+40); 
		g.drawString(""+i, 40*i+20, 660);
		
	}
	for (int j = 0; j <=15; j++) {  //画列
		g.drawLine(40*j+40, 40, 40*j+40, 640);  
		g.drawString(""+j,20, 40*j+20);
	}
	//画棋子
	for (int i = 0; i < 15; i++) {
		
		for (int j = 0; j < 15; j++) {
			//黑子为1
			if (isArray[i][j]==1 ) {
				int countX = 40*i+20;
				int countY = 40*j+20;
				g.setColor(Color.black);
				g.fillOval(countX, countY, 40, 40);
			}
			//白子为2
			if (isArray[i][j]==2 ) {
				int countX = 40*i+20;
				int countY = 40*j+20;
				g.setColor(Color.white);
				g.fillOval(countX, countY, 40, 40);
			}
		}
	}
}

}

package bao;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class MyLisiten implements MouseListener{
public MyFreme mf;
int turn = 1; // 1表示该黑子下棋了 2表示白子下棋
int end = 0; //游戏结束判定 end=【5】时游戏结束
public void setG(MyFreme mf) {
this.mf = mf;
}
/*public int gameCompleteUP(int arrX,int arrY) {
//判断游戏是否结束
if(arrY<=15 && end<=5) {
if(mf.isArray[arrX][arrY] == 1) {
end++;
}

		int up = gameCompleteUP(arrX,arrY+1);
		int down = gameCompleteUP(arrX,arrY-1);
		end = up+down;	
	}
	return end;
		
}*/
@Override
public void mouseClicked(MouseEvent e) {
	// TODO 自动生成的方法存根
	int x = e.getX();               //获取鼠标点击的坐标
	int y = e.getY();
	int arrX,arrY;                 // 记录鼠标坐标相对应的数组位置
	
	// 进行位置范围的判定  与点击位置相近的为下棋的位置
	if(x%40<=20 && y%40<=20) {
		arrX = x/40-1;
		arrY = y/40-1;
	}else if (x%40>20 && y%40<=20) {
		arrX = x/40;
		arrY = y/40-1;
	}else if (x%40<20 && y%40>20) {
		arrX = x/40-1;
		arrY = y/40;
	}else {
		arrX = x/40;
		arrY = y/40;
	}
	if(mf.isArray[arrX][arrY]!= 0) {
		System.out.println("这个位置已经有棋子了,请换个位置!");
	}else {
		Graphics g = mf.getGraphics();
		System.out.println(arrX + "  " +arrY); // 初步测试是否实现鼠标监听的功能
		
		if(turn == 1) {    //黑子下棋
			int countX = 40*arrX+20;
			int countY = 40*arrY+20;
			g.setColor(Color.black);
			g.fillOval(countX, countY, 40, 40);
			mf.isArray[arrX][arrY] = 1;
			//gameCompleteUP(arrX, arrY);
			if(end>=5) {
				System.out.println("黑子获胜!");
				return;
			}
			
			turn++;
		}else {           //白子下棋
			int countX = 40*arrX+20;
			int countY = 40*arrY+20;
			g.setColor(Color.white);
			g.fillOval(countX, countY, 40, 40);
			mf.isArray[arrX][arrY] = 2;
			turn--;
		}
	}
	
}

@Override
public void mousePressed(MouseEvent e) {
	// TODO 自动生成的方法存根
	
}

@Override
public void mouseReleased(MouseEvent e) {
	// TODO 自动生成的方法存根
	
}

@Override
public void mouseEntered(MouseEvent e) {
	// TODO 自动生成的方法存根
	
}

@Override
public void mouseExited(MouseEvent e) {
	// TODO 自动生成的方法存根
	
}

}

简单 五子棋的客户端部分程序 //chessClient.java:客户端主程序。 //userPad.java:客户端的界面。 //chessPad.java:棋盘的绘制。 //chessServer.java:服务器端。 //可同时容纳50个人同时在线下棋,聊天。 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(userNumber>0 && !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无法关闭"); } 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=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(); } }
下面是一个简单的 Java 五子棋游戏示例,供参考: ```java import java.util.Scanner; public class Gomoku { private static final int ROWS = 15; private static final int COLS = 15; private static final int EMPTY = 0; private static final int BLACK = 1; private static final int WHITE = 2; private int[][] board = new int[ROWS][COLS]; private int player = BLACK; public void start() { Scanner scanner = new Scanner(System.in); while (true) { // 打印棋盘 printBoard(); // 获取玩家输入的坐标 System.out.print("请玩家 " + player + " 输入坐标,格式为 行 列:"); int row = scanner.nextInt(); int col = scanner.nextInt(); // 判断是否落子成功 if (placePiece(row, col)) { // 判断是否获胜 if (checkWin(row, col)) { System.out.println("玩家 " + player + " 获胜!"); printBoard(); break; } // 切换玩家 player = (player == BLACK) ? WHITE : BLACK; } else { System.out.println("该位置已经有子,请重新输入!"); } } } // 打印棋盘 private void printBoard() { for (int i = 0; i < ROWS; i++) { for (int j = 0; j < COLS; j++) { System.out.print(board[i][j] + " "); } System.out.println(); } } // 落子 private boolean placePiece(int row, int col) { if (board[row][col] == EMPTY) { board[row][col] = player; return true; } else { return false; } } // 判断是否获胜 private boolean checkWin(int row, int col) { int count = 1; // 横向 for (int i = col - 1; i >= 0; i--) { if (board[row][i] == player) { count++; } else { break; } } for (int i = col + 1; i < COLS; i++) { if (board[row][i] == player) { count++; } else { break; } } if (count >= 5) { return true; } // 纵向 count = 1; for (int i = row - 1; i >= 0; i--) { if (board[i][col] == player) { count++; } else { break; } } for (int i = row + 1; i < ROWS; i++) { if (board[i][col] == player) { count++; } else { break; } } if (count >= 5) { return true; } // 左上右下斜线 count = 1; for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) { if (board[i][j] == player) { count++; } else { break; } } for (int i = row + 1, j = col + 1; i < ROWS && j < COLS; i++, j++) { if (board[i][j] == player) { count++; } else { break; } } if (count >= 5) { return true; } // 右上左下斜线 count = 1; for (int i = row - 1, j = col + 1; i >= 0 && j < COLS; i--, j++) { if (board[i][j] == player) { count++; } else { break; } } for (int i = row + 1, j = col - 1; i < ROWS && j >= 0; i++, j--) { if (board[i][j] == player) { count++; } else { break; } } if (count >= 5) { return true; } // 没有获胜 return false; } public static void main(String[] args) { Gomoku game = new Gomoku(); game.start(); } } ``` 这个示例使用了一个二维数组来表示棋盘,玩家输入坐标后,通过 `placePiece` 方法把棋子放到相应的位置上,然后判断是否获胜,如果获胜就结束游戏,否则切换玩家。`checkWin` 方法实现了判断是否获胜的逻辑,通过遍历棋盘上的位置,计算横向、纵向和斜线方向上是否有连续的五个相同颜色的棋子。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值