用java做的一个小游戏—黑白反斗棋(适合菜鸟)

用Java做的一个小游戏,黑白反斗棋,我玩过了5*5和10*10的。是学习之后做的,不是自己原始开发的。

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class MainFrame extends JFrame implements ActionListener{
	JButton[][] bus=new JButton[10][10];
	//构造方法,方法名必须和类名一致,作用就是创建对象
	public MainFrame(){
		
		//网格布局
		
		String path=MainFrame.class.getClassLoader().getResource("haha.jpg").getPath();
		ImageIcon icon=new ImageIcon(path);
		setIconImage(icon.getImage());
		GridLayout g=new GridLayout(10,10);
		getContentPane().setLayout(g);
		setTitle("黑白翻斗棋");
		for (int i = 0; i < 10; i++) {
			for (int j = 0; j < 10; j++) {
				JButton bu=new JButton();
				//给按钮注册上点击事件
				bu.addActionListener(this);
				bu.setActionCommand(i+","+j);
				bu.setSize(50, 50);
				bu.setBackground(Color.WHITE);
				bus[i][j]=bu;
				add(bu);
			}
		}
		//得到显示器的宽和高
		int x=(int)Toolkit.getDefaultToolkit().getScreenSize().getWidth();
		int y=(int)Toolkit.getDefaultToolkit().getScreenSize().getHeight();
		setLocation((x-500)/2,(y-500)/2);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
	
	}

	
	public static void main(String[] args) {
		MainFrame m=new MainFrame();
		m.setSize(500, 500);
		m.setVisible(true);
	}


	@Override
	public void actionPerformed(ActionEvent e) {
		JButton bu=(JButton)e.getSource();
		//System.out.println(bu.getActionCommand());
		ChengebgColor(bu);
		String actioncommand=bu.getActionCommand();
		String[] command=actioncommand.split(",");
//		for (int i = 0; i < command.length; i++) {
//			System.out.println(command[i]);
//		}
		
		int x=Integer.parseInt(command[0]);
		int y=Integer.parseInt(command[1]);
		if(x-1>=0){
			ChengebgColor(bus[x-1][y]);
		}
		if(x+1<10){
			ChengebgColor(bus[x+1][y]);
		}
		if(y-1>=0){
			ChengebgColor(bus[x][y-1]);
		}
		if(y+1<10){
			ChengebgColor(bus[x][y+1]);
		}
		
		
	}
	
	public void ChengebgColor(JButton bu){
		if(bu.getBackground()==Color.WHITE){
			bu.setBackground(Color.BLACK);
		}else{
			bu.setBackground(Color.WHITE);
		}
	}
	
}


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值