JAVA程序设计(12.3)---- 监听器初级应用:五子棋

1.制作五子棋游戏软件

因为老师已经基本做完了,重做的时候快了很多……但是还是感觉思维很混乱…… 哪边先哪边后,哪个方法在哪边好之类的问题 太纠结了……

先是窗口 内部类:鼠标适配器  窗口的构造器  绘图

package com.lovo.homework2;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 * 类 : 我的五子棋窗口
 * 
 * @author Abe
 */
public class MyFrameRenju extends JFrame {
	private MyboardRenju board = new MyboardRenju();
	private boolean isBlack = true;
	private Image offImage = new BufferedImage(800, 800,
			BufferedImage.TYPE_INT_RGB);// 双缓冲
	private boolean isGameOver = false;
	
	/**
	 * 内部类:鼠标适配器
	 * 
	 * @author Abe
	 */
	public class MyMouseAdapter extends MouseAdapter {
		@Override
		public void mousePressed(MouseEvent e) { // 重写点击鼠标的方法
			if (!isGameOver) {
				int x = e.getX();
				int y = e.getY();
				if (x > 25 && x < 775 && y > 25 && y < 775) {
					int i = (x - 25) / 50;
					int j = (y - 25) / 50;
					if (board.move(i, j, isBlack)) {
						repaint();
						if (board.win(i, j, isBlack)) {
							JOptionPane.showMessageDialog(null,
									isBlack ? "黑方胜!" : "白方胜");
							isGameOver = true;
						}
						isBlack = !isBlack;
					}
				}
			}
		}
	}

	/**
	 * 构造器
	 */
	public MyFrameRenju() {
		this.setTitle("五子棋");
		this.setSize(800, 800);
		this.setResizable(false);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setLocationRelativeTo(null);
		this.setLayout(null);
		this.getContentPane().setBackground(new Color(180, 125, 12));

		MyMouseAdapter l = new MyMouseAdapter();
		this.addMouseListener(l);

	}

	/**
	 * 重写方法画出所有 newG均为双缓冲 去掉闪屏需要
	 */
	@Override
	public void paint(Graphics g) {
		Graphics newG = offImage.getGraphics();
		super.paint(newG);
		board.draw(newG);
		g.drawImage(offImage, 0, 0, 800, 800, null);
	}

	public static void main(String[] args) {
		new MyFrameRenju().setVisible(true);
	}
}


然后是位置面板,绘制棋子,走棋,判断胜负

package com.lovo.homework2;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.Stroke;

import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;

/**
 * 类 : 五子棋棋盘
 * 
 * @author Abe
 *
 */
public class MyboardRenju {
	private int[][] p = new int[15][15]; // 给每个交点赋值

	public void draw(Graphics g) {
		g.setColor(Color.BLACK);
		Graphics2D g2d = (Graphics2D) g; // 强转g为2D型 赋值给g2d
		g2d.setStroke(new BasicStroke(5));
		g.drawRect(50, 50, 700, 700);
		g2d.setStroke(new BasicStroke(1));
		g.fillOval(392, 392, 16, 16); // 画天元 星
		g.fillOval(195, 195, 10, 10);
		g.fillOval(195, 595, 10, 10);
		g.fillOval(595, 195, 10, 10);
		g.fillOval(595, 595, 10, 10);

		for (int i = 0; i < 750; i += 50) { // 画横纵坐标线
			g.drawLine(50, 100 + i, 750, 100 + i);
			g.drawLine(100 + i, 50, 100 + i, 750);
		}
		for (int i = 0; i < p.length; i++) { // 画出棋盘上的棋子
			for (int j = 0; j < p.length; j++) {
				if (p[i][j] != 0) {
					g.setColor(p[i][j] == 1 ? Color.black : Color.WHITE);
					g.fillOval(25 + i * 50, 25 + j * 50, 50, 50);
				}
			}
		}
	}

	/**
	 * 走棋
	 */
	public boolean move(int i, int j, boolean isBlack) {
		if (p[i][j] == 0) {
			p[i][j] = isBlack ? 1 : 2;
			return true;
		}
		return false;
	}

	/**
	 * 方法:判断胜负
	 */
	public boolean win(int i, int j, boolean isBlack) {
		int currentColor = isBlack ? 1 : 2;
		if (countH(i, j, currentColor) >= 5 || countV(i, j, currentColor) >= 5
				|| countX1(i, j, currentColor) >= 5
				|| countX2(i, j, currentColor) >= 5) {
			return true;
		}
		return false;
	}

	private int countH(int i, int j, int currentColor) {
		int counter = 1;
		int tempi = i;
		while (--tempi >= 0 && p[tempi][j] == currentColor) {
			counter++;
		}
		tempi = i;
		while (++tempi <= p.length && p[tempi][j] == currentColor) {
			counter++;
		}
		return counter;
	}

	private int countV(int i, int j, int currentColor) {
		int counter = 1;
		int tempj = j;
		while (--tempj >= 0 && p[i][tempj] == currentColor) {
			counter++;
		}
		tempj = j;
		while (++tempj <= p.length && p[i][tempj] == currentColor) {
			counter++;
		}
		return counter;
	}

	private int countX1(int i, int j, int currentColor) {
		int counter = 1;
		int tempi = i;
		int tempj = j;
		while (--tempj >= 0 && --tempi >= 0 && p[tempi][tempj] == currentColor) {
			counter++;
		}
		tempi = i;
		tempj = j;
		while (++tempj <= p.length && ++tempi <= p.length
				&& p[tempi][tempj] == currentColor) {
			counter++;
		}
		return counter;
	}

	private int countX2(int i, int j, int currentColor) {
		int counter = 1;
		int tempi = i;
		int tempj = j;
		while (--tempj >= 0 && ++tempi >= 0 && p[tempi][tempj] == currentColor) {
			counter++;
		}
		tempi = i;
		tempj = j;
		while (++tempj <= p.length && --tempi <= p.length
				&& p[tempi][tempj] == currentColor) {
			counter++;
		}
		return counter;
	}
}



简单 五子棋的客户端部分程序 //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(); } }
开发步骤和思路 1、 编写主框架类JFiveFrame, 设置大小,标题,关闭窗口的行为, 在main中创建并显示。 2、 编写DrawPanel extends JPanel,定义构造函数,来设置背景颜色。 然后在主框架类中创建DrawPanel对象,并添加到主框架中。 3、 DrawPanel中覆盖paintComponent方法来进行绘制。 绘制15*15网格的棋盘, 绘制前先定义边距、行数、列数、网格宽度等常量 4、 定义Chess类,包括x,y索引, 颜色。 定义构造函数和相应的get方法。 5、 在DrawPanel中创建Chess[], 然后在paintComponent方法中绘制棋子数组(注意将索引转换成坐标)。 6、 为DrawPanel实现监听器MouseListener, 覆盖相应抽象方法。在构造方法中增加监听器(addMouseListener...)。 7、 编写mousePressed方法的内容,预先定义isBlack表示下的是黑棋还是白棋, chessCount表示当前棋子的个数 8、 在mousePressed中获得下的坐标,转换成索引, 再创建Chess对象,添加到chessList中。再重新绘制。 9、 添加相应的判断: 不能画到棋盘外, 下过的地方不能再下(需要辅助方法findChess...) 10、 再添加胜利的判断isWin, 添加标记变量gameOver. 在mousePressed方法的最前面调用加入gameOver的判断, 在mousePressed方法的最后调用isWin, 返回true则给出消息提示,gameOver设置为true。 11、isWin方法具体的编写。在当前下棋的横向,纵向,两个斜向上分别判断是否有连续的同色五子。 继续改进: 加入菜单:重新开始; 退出; 悔棋; 加入工具栏,三个按纽。 为最后下的棋子做出标记(画红色的矩形边界)。 改变鼠标形状, 在可以下的地方变手形;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值