机智的我的gravatar头像
机智的我2015-06-18 13:02:38

自己按照教程写的java swing五子棋小游戏

自己按照教程写的java swing五子棋小游戏

实现了左手下右手下棋及判定胜负 但是时间设置有点问题 加入菜单栏和系统托盘

package wuziqi;
	
	import java.awt.AWTException;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
	


import java.net.URL;

	import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.WindowConstants;
	
	public class MyChess extends JFrame implements MouseListener, Runnable {
		int x = 0;
		int y = 0;// 保存棋子的 x y坐标
		int[][] allChess = new int[15][15];// 保存之前下过的全部棋子的坐标
		// 其中数据内容 0: 表示这个点并没有棋子, 1: 表示这个点是黑子, 2:表示这个点是白子
		boolean isBlack = true;
		boolean canplay = true;
		String message = "黑方先下";
		int maxTime = 0;// 保存最多拥有时间(秒)
		Thread t = new Thread(this);// 做倒计时线程类
		int blacktime = 0;
		int whitetime = 0;
		String blackMessage = "无限制";
		String whiteMessage = "无限制";
		BufferedImage bg = null;
		BufferedImage black = null;
		BufferedImage white = null;
	
		public MyChess() {
	
			this.setTitle("我的五子棋");// 设
			this.setSize(500, 600);// 设置窗口大小 500*600
			this.setResizable(false);// 设置窗口大小不可被改变
			this.setLocationRelativeTo(null);// 设置窗口初始在屏幕正中间
		    this.setLocationRelativeTo(null);  //
		    this.setTray();  //
			this.setIconImage(Toolkit.getDefaultToolkit().createImage(
					"logo5.png"));// 给窗体添加一个图标
			this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 设置退出
			this.addMouseListener(this);// 加入鼠标监听器
			
		JLayeredPane layeredPane = getLayeredPane();
			URL url=getClass().getResource("bg4.jpg");
			Icon icon =new ImageIcon(url);
			JLabel bg=new JLabel(icon);
		    bg.setSize(500,600);
			layeredPane.add(bg,new Integer(Integer.MIN_VALUE));
			JPanel contenJPanel=(JPanel)getContentPane();
			contenJPanel.setOpaque(false);
			this.repaint();
			t.start();// 启动线程
			t.suspend();// 挂起线程
			this.repaint();
			this.setVisible(true); // 设置窗口显示
			//实现菜单↓
			 JMenuBar menubar;
			
			 JMenu menu;
			 JMenuItem item1, item2, item3;
		
			 menubar = new JMenuBar();
			 menu = new JMenu("菜单");
			 item1 = new JMenuItem("重新开始");
			 item2 = new JMenuItem("退出");
			 item3 = new JMenuItem("关于");
			 item1.setAccelerator(KeyStroke.getKeyStroke("1"));
			 item1.addActionListener(new ActionListener() {
			 @Override
			 public void actionPerformed(ActionEvent e) {
			 String str = "是否要重新开始游戏?";
			
			 if (JOptionPane.showConfirmDialog(null, str, "重新开始",
			 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
				 for (int i = 0; i < 15; i++) {
						for (int j = 0; j < 15; j++) {
							allChess[i][j] = 0;// 棋盘清空
							message = "黑方先行";
							isBlack = true;
							blacktime = maxTime;
							whitetime = maxTime;
						
						}}
			
	
			 
			 }
			 }
			 });	this.repaint();
			 item2.addActionListener(new ActionListener() {
			 @Override
			 public void actionPerformed(ActionEvent e) {
			 String str = "是否要退出游戏?";
			
			 if (JOptionPane.showConfirmDialog(null, str, "退出游戏",
			 JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
			 System.exit(0); // 退出
			 }
			 }
			 });
			 item3.addActionListener(new ActionListener() {
			 @Override
			 public void actionPerformed(ActionEvent e) {
			 String str = "关于";
			 JOptionPane.showMessageDialog(null, "吼吼吼吼");
			 }
			
			 });
			
			 item2.setAccelerator(KeyStroke.getKeyStroke('2'));
			 item3.setAccelerator(KeyStroke.getKeyStroke('3'));
			 menu.add(item1);
			 menu.addSeparator();
			 menu.add(item2);
			 menu.addSeparator();
			 menu.add(item3);
			 menubar.add(menu);
			 setJMenuBar(menubar);
			 validate();
			setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
			this.setVisible(true); 
//	
		}
		
//		
	
		// clear棋盘方法↓
		// protected void clearMap() {
		// for (int i = 0; i < 15; i++) {
		// for (int j = 0; j < 15; j++) {
		// allChess[i][j] = '+';
		// }
		// }
		//
		// }	
		public void setTray(){
		   if(SystemTray.isSupported()){//判断当前平台是否支持托盘功能  
	            //创建托盘实例  
	            SystemTray tray = SystemTray.getSystemTray();  
	            //创建托盘图标:1.显示图标Image 2.停留提示text 3.弹出菜单popupMenu 4.创建托盘图标实例  
	            //1.创建Image图像  
	            Image image=null;
				try {
					image = ImageIO.read(getClass().getResource("logo2.png"));
				} catch (IOException e2) {
					// TODO 自动生成的 catch 块
					e2.printStackTrace();
				} 
	            //2.停留提示text  
	            String text = "五子棋";  
	            //3.弹出菜单popupMenu  
	            PopupMenu popMenu = new PopupMenu();  
	            MenuItem itmOpen = new MenuItem("Start");  
	            itmOpen.addActionListener(new ActionListener(){  
	                public void actionPerformed(ActionEvent e) {  
	                    Show();  
	                }                 
	            });  
	            MenuItem itmHide = new MenuItem("Hidde");  
	            itmHide.addActionListener(new ActionListener(){  
	                public void actionPerformed(ActionEvent e) {  
	                    UnVisible();  
	                }  
	            });  
	            MenuItem itmExit = new MenuItem("Exit");  
	            itmExit.addActionListener(new ActionListener(){  
	                public void actionPerformed(ActionEvent e) {  
	                    Exit();  
	                }  
	            });  
	            popMenu.add(itmOpen);  
	            popMenu.add(itmHide);  
	            popMenu.add(itmExit);  
	              
	            //创建托盘图标  
	            TrayIcon trayIcon = new TrayIcon(image,text,popMenu);  
	            //将托盘图标加到托盘上  
	            try {  
	                tray.add(trayIcon);  
	            } catch (AWTException e1) {  
	                e1.printStackTrace();  
	            }  
	        }  
	    }  
	      
	    //内部类中不能直接调用外部类(this不能指向)  
	    public void UnVisible() {  
	        this.setVisible(false);  
	    }  
	    public void Show() {  
	        this.setVisible(true);  
	    }  
	    public void Exit() {  
	        System.exit(0);  
	    }  
	    public static void main(String[] args) {  
	        new MyChess();  
	    }  

	
		@Override
		public void paint(Graphics g) {
			try {
				bg = ImageIO.read(getClass().getResource("bg4.jpg"));// 导入图片
				black = ImageIO.read(getClass().getResource("black.png"));
				white	= ImageIO.read(getClass().getResource("white.png"));
				
			} catch (IOException e) {
				e.printStackTrace();
			}
	
			BufferedImage bgBufferedImage = new BufferedImage(500, 600,
					BufferedImage.TYPE_INT_ARGB);
			Graphics g2 = bg.createGraphics();
	
			g2.setFont(new Font("黑体", Font.BOLD, 20));
			g2.drawString("游戏信息:" + message, 155, 520);
			
			g2.setColor(Color.BLACK);
			g2.setFont(new Font("黑体",Font.BOLD,25));
			g2.drawString("开始游戏" , 20, 560);
			g2.drawString("游戏设置" , 150, 560);
			g2.drawString("认输" , 280, 560);
			g2.drawString("关于" , 355, 560);
			g2.drawString("退出" , 430, 560);
			g2.setFont(new Font("宋体", 0, 14));
			g2.drawString("黑方时间:" + blackMessage, 43, 490);
			g2.drawString("白方时间:" + whiteMessage, 355, 490);
			g2.setColor(Color.WHITE);
			
	
			for (int i = 0; i < 15; i++) {
				g2.drawLine(40, 40 + i * 30, 460, 40 + i * 30);
				g2.drawLine(40 + i * 30, 40, 40 + i * 30, 460);// 绘制棋盘上的线
				
			}
	
		
		
		
	
			// 绘制全部棋子 ↓
			for (int i = 0; i < 15; i++) {
				for (int j = 0; j < 15; j++) {
	
					if (allChess[i][j] == 1) {
						int tempx = 40 + 30 * i;
						int tempy = 38 + 30 * j;
						g2.drawImage(black, tempx - 12, tempy - 12, null);// 绘制黑子
					
					}
					if (allChess[i][j] == 2) {
						int tempx = 40 + 30 * i;
						int tempy = 38 + 30 * j;
	
						g2.drawImage(white, tempx - 12, tempy - 12, null);// 绘制白子
						
	
					}
				}
			}
			g.drawImage(bg, 0, 0, this);
		
		}
	
		@Override
		public void mouseClicked(MouseEvent e) {
			// TODO 自动生成的方法存根
			x = e.getX();
			y = e.getY();
			System.out.println("当前鼠标坐标:" + x + ',' + y);
			if (x > 30 && x < 470 && y > 40 && y < 480) {
				x = (x - 40) / 30;
				y = (y - 38) / 30;
				if (allChess[x][y] == 0) {
					// 判断棋子颜色↓
					if (isBlack == true) {
						allChess[x][y] = 1;
						isBlack = false;
						message = "轮到白方";
						this.repaint();
	
//						JOptionPane.showMessageDialog(rootPane, "轮到白方");
	
					} else {
						allChess[x][y] = 2;
						isBlack = true;
						message = "轮到黑方";
						this.repaint();
//						JOptionPane.showMessageDialog(rootPane, "轮到黑方");
					}
					// 判断游戏胜负↓
					boolean winFlag = this.checkWin();
					if (winFlag == true) {
						JOptionPane.showMessageDialog(this, "游戏结束,"
								+ (allChess[x][y] == 1 ? "黑方" : "白方") + "获胜!");
						canplay = false;
	
						}
					} else {
						JOptionPane.showMessageDialog(this, "当前位置已经有棋子,请重新落子!");
					}
	
					this.repaint();
	
				}
	
				if (e.getX() >= 15 && e.getX() <= 130 && e.getY() >= 540
						&& e.getY() <= 590) {
					int result = JOptionPane.showConfirmDialog(this, "是否重新开始游戏?");
					if (result == 0) {// 表示重新开始游戏
						// 重新开始所要做的操作,1棋盘清空,(allchess这个数组数据归零)2 将游戏信息的显示改回到开始位置
						// 3isblack改回到true 黑方先下
						for (int i = 0; i < 15; i++) {
							for (int j = 0; j < 15; j++) {
								allChess[i][j] = 0;// 棋盘清空
								message = "黑方先行";
								isBlack = true;
								blacktime = maxTime;
								whitetime = maxTime;
								this.repaint();
	
							}
	
						}
					}
				}
				if (e.getX() >= 150 && e.getX() <= 260 && e.getY() >= 540
						&& e.getY() <= 590) {
					String input = JOptionPane
							.showInputDialog("请输入游戏的最大时间(分钟)不能为0:");
					try {
						maxTime = Integer.parseInt(input) * 60;// 将String类型强制转换为int类型
						if (maxTime <= 0) {
							JOptionPane.showMessageDialog(this, "请输入正确时间,不能为负数和0");
	
						}
						if (maxTime > 0) {
							JOptionPane.showConfirmDialog(this, "设置完成!请开始游戏");
							for (int i = 0; i < 15; i++) {
								for (int j = 0; j < 15; j++) {
									allChess[i][j] = 0;// 棋盘清空
									message = "黑方先行";
									isBlack = true;
	
									if (maxTime > 0) {
										blackMessage = maxTime
												/ 3600
												+ ":"
												+ (maxTime / 60 - maxTime / 3600 * 60)
												+ ":"
												+ (maxTime - maxTime / 60 * 60);
										whiteMessage = maxTime
												/ 3600
												+ ":"
												+ (maxTime / 60 - maxTime / 3600 * 60)
												+ ":"
												+ (maxTime - maxTime / 60 * 60);
										t.resume();
									} else {
										blackMessage = "无限制";
										whiteMessage = "无限制";
									}
									this.repaint();
	
								}
							}
						}
					} catch (NumberFormatException e1) {
	
						e1.printStackTrace();
					}
					JOptionPane.showMessageDialog(this, "请输入正确!");
	
				}
				if (e.getX() >= 360 && e.getX() <= 400 && e.getY() >= 540
						&& e.getY() <= 590) {
					JOptionPane.showMessageDialog(this, "这是一个由Java开发的五子棋游戏程序--by蓝桥班雄鹰队胡靖 ");// 关于
	
				}
				if (e.getX() >= 420 && e.getX() <= 480 && e.getY() >= 540
						&& e.getY() <= 600) {
					JOptionPane.showMessageDialog(this, "游戏结束!");// 游戏结束
					System.exit(0);
				}
			
			// 认输↓
			if (e.getX() >= 270 && e.getX() <= 330 && e.getY() >= 540
					&& e.getY() <= 590) {
				int result = JOptionPane.showConfirmDialog(this, "是否确认认输");
	
				if (result == 0) {
					if (isBlack) {
						JOptionPane.showConfirmDialog(this, "黑方已经认输! 游戏结束");
					} else {
						JOptionPane.showConfirmDialog(this, "白方已经认输! 游戏结束");
					}
					canplay = false;
				}
			}
		}
	
		private boolean checkWin() {
			boolean flag = false;
			int count = 1;
			int color = allChess[x][y];
			count = this.checkCount(1, 0, color);
			if (count >= 5) {
				flag = true;
			} else {
				// 判断纵向
				count = this.checkCount(0, 1, color);
				if (count >= 5) {
					flag = true;
				} else {
					// 判断右上、左下
					count = this.checkCount(1, -1, color);
					if (count >= 5) {
						flag = true;
					} else {
						// 判断右下、左上
						count = this.checkCount(1, 1, color);
						if (count >= 5) {
							flag = true;
						}
					}
				}
			}
	
			return flag;
		}
	
		// 判断棋子相连↓
		private int checkCount(int xChange, int yChange, int color) {
			int count = 1;
			int tempX = xChange;
			int tempY = yChange;
			while (x + xChange >= 0 && x + xChange <= 18 && y + yChange >= 0
					&& y + yChange <= 18
					&& color == allChess[x + xChange][y + yChange]) {
				count++;
				if (xChange != 0)
					xChange++;
				if (yChange != 0) {
					if (yChange > 0)
						yChange++;
					else {
						yChange--;
					}
				}
			}
			xChange = tempX;
			yChange = tempY;
			while (x - xChange >= 0 && x - xChange <= 18 && y - yChange >= 0
					&& y - yChange <= 18
					&& color == allChess[x - xChange][y - yChange]) {
				count++;
				if (xChange != 0)
					xChange++;
				if (yChange != 0) {
					if (yChange > 0)
						yChange++;
					else {
						yChange--;
					}
				}
			}
			return count;
		}
	
		@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 自动生成的方法存根
	
		}
	
		
	
		@Override
		public void run() {
			if (maxTime > 0) {
				while (true) {
					if (isBlack) {
						blacktime--;
	
					} else {
	
						whitetime = maxTime--;
	
					}
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO 自动生成的 catch 块
						e.printStackTrace();
					}
					blackMessage = blacktime / 3600 + ":"
							+ (blacktime / 60 - blacktime / 3600 * 60) + ":"
							+ (blacktime - blacktime / 60 * 60);
					whiteMessage = whitetime / 3600 + ":"
							+ (whitetime / 60 - whitetime / 3600 * 60) + ":"
							+ (whitetime - whitetime / 60 * 60);
					this.repaint();
					System.out.println(blacktime + "--" + whitetime);
				}
	
			}
	
		}
	
	}

打赏

文件名:wzq11111.rar,文件大小:182.062K下载
  • /
      • /wzq11111
        • /wzq11111/.classpath
        • /wzq11111/.fatjar
        • /wzq11111/.project
          • /wzq11111/.settings
            • /wzq11111/.settings/org.eclipse.core.resources.prefs
            • /wzq11111/.settings/org.eclipse.jdt.core.prefs
          • /wzq11111/bin
              • /wzq11111/bin/wuziqi
                • /wzq11111/bin/wuziqi/MyChess$1.class
                • /wzq11111/bin/wuziqi/bg4.jpg
                • /wzq11111/bin/wuziqi/black.png
                • /wzq11111/bin/wuziqi/logo2.png
                • /wzq11111/bin/wuziqi/logo5.png
顶部客服微信二维码底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友