华容道(传统智力游戏)

package ytu.com;
import java.awt.*;
import javax.swing.*;

import java.awt.event.*;
public class Hua_Rong_Road extends JFrame 
implements MouseListener,KeyListener,ActionListener{
	Person person[]=new Person[10];
	JButton left,right,above,below;
	JButton restart=new JButton("重新开始");
	public Hua_Rong_Road(){
		init();
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100,100,320,500);
		setVisible(true);
		validate();
	}
	public void init(){
		setLayout(null);
		add(restart);
		restart.setBounds(100, 320,120,35);
		restart.addActionListener(this);
		String name[]={"嬷嬷","关羽","张","刘","周",
				"黄","兵","兵","兵","兵"};
		for(int k=0;kh/2)
			go1(man,below);
		if(yw/2)
			go1(man,right);
		
	}
	public void go1(Person man,JButton direction){
		boolean move=true;
		Rectangle manRect=man.getBounds();
		int x=man.getBounds().x;
		int y=man.getBounds().y;
		if(direction==below)
			y=y+50;
		else if(direction==above)
			y=y-50;
		else if(direction==left)
			x=x-50;
		else if(direction==right)
			x=x+50;
		manRect.setLocation(x, y);
		Rectangle directionRect=direction.getBounds();
		for(int k=0;k<10;k++){
			Rectangle personRect=person[k].getBounds();
			if((manRect.intersects(personRect))&&(man.number!=k))
				move=false;
		}
		if(manRect.intersects(directionRect))
			move=false;
		if(move==true)
			man.setLocation(x,y);
		
	}
	public void actionPerformed(ActionEvent e){
		dispose();
		new Hua_Rong_Road();
	}
	@Override
	public void mouseReleased(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void keyPressed(KeyEvent e) {
		// TODO Auto-generated method stub
		Person man=(Person)e.getSource();
		if(e.getKeyCode()==KeyEvent.VK_DOWN)
			go1(man,below);
		if(e.getKeyCode()==KeyEvent.VK_UP)
			go1(man,above);
		if(e.getKeyCode()==KeyEvent.VK_LEFT)
			go1(man,left);
		if(e.getKeyCode()==KeyEvent.VK_RIGHT)
			go1(man,right);	
	}
	 
	@Override
	public void keyReleased(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void keyTyped(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}
	

	
	
    	
}
package ytu.com;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Person extends JButton implements FocusListener{
	int number;
	Color c=new Color(255,245,170);
	Font font=new Font("宋体",Font.BOLD,12);
	Person(int number,String s){
		super(s);
		setBackground(c);
		setFont(font);
		this.number=number;
		c=getBackground();
		addFocusListener(this);
		
	}
	@Override
	public void focusGained(FocusEvent e) {
		// TODO Auto-generated method stub
		setBackground(Color.gray);
	}
	@Override
	public void focusLost(FocusEvent e) {
		// TODO Auto-generated method stub
		setBackground(c);
		
	}

}
package ytu.com;

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new Hua_Rong_Road();

	}

}

 

你可能感兴趣的:(Java)