java游戏之迷宫

import java.applet.Applet;
import java.awt.Button;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class Move extends Applet implements KeyListener,ActionListener {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	Button b_go=new Button("go");//一个代表人的按钮
	Rectangle rect1,rect2,rect3;
	int b_x=0,b_y=0;
	public void init()
	{
		b_go.addKeyListener(this);
		setLayout(null);
		rect1=new Rectangle(20,40,200,40);//画长方形,也就是设置轨道,大家可以尝试一下更复杂的轨道
		rect2=new Rectangle(200,40,40,200);
		rect3=new Rectangle(200,220,100,40);
		b_go.setBackground(Color.lightGray);//设置背景颜色
		add(b_go);                          //添加按钮到窗口中
		b_go.setBounds(22,45,20,20);
		b_x=b_go.getBounds().x;             //设置按钮每一步的移动为坐标
		b_y=b_go.getBounds().y;
		b_go.requestFocus();
	}
	public void paint(Graphics g)
	{
		g.setColor(Color.green);            //为轨道添加颜色,使其更显眼
		g.fillRect(20, 40, 200, 40);
		g.setColor(Color.YELLOW);
		g.fillRect(200,40,40,200);
		g.setColor(Color.CYAN);
		g.fillRect(200, 220, 100, 40);
		g.drawString("出口",310,260);
		g.setColor(Color.BLACK);
		
	}

	
	public void keyPressed(KeyEvent e) 
	{
		if((e.getKeyCode()==KeyEvent.VK_UP))        //设置键盘中上键所控制的动作
		{
			Rectangle rect=new Rectangle(b_x,b_y);  //创建一个和按钮一样大的矩形
			if(rect.intersects(rect1)||rect.intersects(rect2)||rect.intersects
					(rect3))                       //让按钮就只能在轨道中运动
			{                                      //以下都是同理
				b_y=b_y-2;
				b_go.setLocation(b_x,b_y);
			}
		}
		else if(e.getKeyCode()==KeyEvent.VK_DOWN)
		{
			Rectangle rect=new Rectangle(b_x,b_y,20,20);
			if(rect.intersects(rect1)||rect.intersects(rect2)||rect.intersects(rect3))
			{
				b_y=b_y+2;
				b_go.setLocation(b_x,b_y);
			}
		}
		else if(e.getKeyCode()==KeyEvent.VK_LEFT)
		{
			Rectangle rect=new Rectangle(b_x,b_y,20,20);
			if(rect.intersects(rect1)||rect.intersects(rect2)||rect.intersects(rect3))
			{
				b_x=b_x-2;
				b_go.setLocation(b_x, b_y);
			}
		}
		else if(e.getKeyCode()==KeyEvent.VK_RIGHT)
		{
			Rectangle rect=new Rectangle(b_x,b_y,20,20);
			if(rect.intersects(rect1)||rect.intersects(rect2)||rect.intersects(rect3))
			{
				b_x=b_x+2;
				b_go.setLocation(b_x, b_y);
			}
		}
	}

	
	public void keyReleased(KeyEvent arg0)
	{
	}
	public void keyTyped(KeyEvent arg0) 
	{
	}
	
	public void actionPerformed(ActionEvent e)
	{
		b_go.setBounds(22,45,20,20);
		b_x=b_go.getBounds().x;
		b_y=b_go.getBounds().y;
		b_go.requestFocus();
	}
}

这个还是比较简单   没有设置结束,重新开始等等这些机制,轨道也只是随便画了一下。

大家可以尝试更为复杂一点的程序^_^

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值