您的位置:首页 > 其它

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

2011-12-28 22:06 375 查看
用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);
}
}

}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息