用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);
		}
	}
	
}


 

發佈了15 篇原創文章 · 獲贊 32 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章