反斗棋小游戏

在这里插入代码片package Shixi3;

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JButton;
import javax.swing.JFrame;



public class fdq extends JFrame{
	JButton[][] jbts=new JButton[10][10];//10*10的二维数组
	public fdq(){
		setBounds(450,100,500,500);
		setTitle("反斗棋");
		setLayout(new GridLayout(10,10));//网状布局
		for(int i=0;i<jbts.length;i++){//jbts.length一共多少行
			for(int j=0;j<jbts[i].length;j++){//jbts[i].length第i行有多少个
				JButton jbt =new JButton();
				jbt.setActionCommand(i+"-"+j);
				jbt.setBackground(Color.black);
				jbt.addMouseListener(new MyMouseListener());
				jbts[i][j]=jbt;
				add(jbt);
			}
		}
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
	}
	class MyMouseListener extends MouseAdapter{
		@Override//一定加
		public void mouseClicked(MouseEvent e){
			JButton jbt=(JButton)e.getSource();
			String str=jbt.getActionCommand();
			//System.out.println(str);
			String[] strs=str.split("-");
			int y=Integer.parseInt(strs[0]);
			int x=Integer.parseInt(strs[1]);
			updateColor(y,x);
			if(y-1>=0){
				int yy=y-1;
				updateColor(yy,x);
			}
			if(y-1<=9){
				int yy=y+1;
				updateColor(yy,x);
			}
			if(x-1>=0){
				int xx=x-1;
				updateColor(y,xx);
			}
			if(x-1<=9){
				int xx=x+1;
				updateColor(y,xx);
			}		
		}
		private void updateColor(int y, int x){//变色方法
			if(jbts[y][x].getBackground()==Color.black){
				jbts[y][x].setBackground(Color.white);
			}
			else{
				jbts[y][x].setBackground(Color.black);
			}
		}
	}
    public static void main(String[] args){//主方法
    	new fdq();
    }
}

反斗棋实现代码如上

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值