日期:2014-05-20 浏览次数:20805 次
package com.gzsoft.wuziqi; import java.awt.Color; import java.awt.Dialog; import java.awt.Frame; import java.awt.Graphics; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.JPanel; /** * 一个棋盘窗口的类; * * @author lyp * */ public class QPFrame extends Frame { // 1棋盘类的引用 private Qipan qipan = null; // 2棋盘窗口,持有自己的应用 private QPFrame qpf = this; // 3是否开启! private Boolean start = false; public void launchFrame() { // 4窗口的布局设置 this.setTitle("五子棋(泥豆米版本!)"); this.setBounds(300, 100, 502, 530); //this.setBackground(Color.GREEN); this.setResizable(false); this.setVisible(true); this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { qpf.start = false; System.exit(0); } }); // 5设置棋盘 this.qipan = new Qipan(14); // 起一个新的线程 this.start = true; MyThread myThread = new MyThread(); myThread.start(); this.addMouseListener(new MouseMonitor()); } public static void main(String[] args) { QPFrame qp = new QPFrame(); qp.launchFrame(); } public void paint(Graphics g) { Toolkit tk = Toolkit.getDefaultToolkit(); // 画出棋盘 Image img = tk.getImage(QPFrame.class.getClassLoader().getResource( "棋盘.jpg")); g.drawImage(img, 2, 26, 500, 500, null); this.qipan.paint(g); } public void reset() { this.qipan=new Qipan(14); } // //////////////////////////////调用线程,每隔200毫秒重新画一次界面/////////////////////////////////// class MyThread extends Thread { public void run() { while (start) { qpf.repaint(); try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } } } // //////////////////////////////鼠标的监听类,控制鼠标点击键盘时候画出一个棋子//////////////// class MouseMonitor extends MouseAdapter { private Boolean whiteOrBlack = false; public void mousePressed(MouseEvent e) { int x = e.getX(); int y = e.getY(); System.out.println("x:" + x + " y:" + y); //处理边缘问题: int j = (x - 22) / 34; if ((x - 22) % 34 >= 17) { j++; } int i = (y - 28) / 34; if ((y - 28) % 34 > 17) { i++; } //System.out.println("i:" + i + " j:" + j); //判断是白方还是黑方下子,白方用1表示,黑方用2表示 int xiaqi = 0; if (!whiteOrBlack) { xiaqi = 1; } else { xiaqi = 2; } //判断鼠标点击的是不 是边界:如果越界,就下子失败, if (i > 0 && i < 14 && j > 0 && j < 14) { //下子到已经有子的地方,就下子失败,setQIZI的方法就返回结果0;成功则发回结果1 int jieguo = qpf.qipan.setQIZI(i, j, xiaqi); //如果下棋成功,轮到对方下子; if (jieguo == 1) { whiteOrBlack = !whiteOrBlack; } //判断此时的局势是不是有人胜出 Boolean win = TestWin.isWin(qipan, xiaqi); if (win) { if (xiaqi == 1) { System.out.println("白方赢了"); Dialog log = new Dialog(qpf, "白方赢了!"); log.setLocation(500, 500); log.setVisible(true); qpf.reset(); this.whiteOrBlack=false; } else { System.out.println("黑方赢了"); Dialog log = new Dialog(qpf, "黑方赢了!"); log.setLocation(500, 500); log.setVisible(true); } } } } } }