用java写的小游戏,翻棋子的小游戏。
使用MVC的设计思想。
package cn.zhx.game;
public interface function {
int getR();
int getC();
boolean isBack(int r, int c);
void change(int r, int c);
boolean isAll();
}
package cn.zhx.game;
public class Model implements function {
int r;
int c;
boolean[][] flag;
public Model(int r, int c) {
super();
this.r = r;
this.c = c;
this.flag = new boolean[r][c];
}
@Override
public int getR() {
// TODO Auto-generated method stub
return flag == null ? 0 : r;
}
@Override
public int getC() {
// TODO Auto-generated method stub
return flag == null ? 0 : c;
}
@Override
public boolean isBack(int r, int c) {
// TODO Auto-generated method stub
return flag[r][c];
}
@Override
public void change(int r, int c) {
// TODO Auto-generated method stub
if ((r >= 0 && r < this.r) && (c >= 0 && c < this.c)) {
if (flag[r][c]) {
flag[r][c] = false;
} else {
flag[r][c] = true;
}
}
}
@Override
public boolean isAll() {
// TODO Auto-generated method stub
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (!flag[i][j]) {
return false;
}
}
}
return true;
}
}
package cn.zhx.game;
import java.awt.GridLayout;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
public class ViewFrame extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
final static Icon backImage = new ImageIcon("./image/back.GIF");
final static Icon okImage = new ImageIcon("./image/ok.GIF");
int r;
int c;
GridLayout mainLayout;
JButton[][] buttons;
Model model;
public ViewFrame(int r, int c) throws HeadlessException {
super();
this.r = r;
this.c = c;
mainLayout = new GridLayout(r, c);
setLayout(mainLayout);
model = new Model(r, c);
initButtons();
setSize(580,460);
}
private void initButtons() {
buttons = new JButton[r][c];
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
buttons[i][j] = new JButton(backImage);
buttons[i][j].setActionCommand(i + "," + j);
buttons[i][j].addActionListener(this);
add(buttons[i][j]);
}
}
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String cmd = e.getActionCommand();
int br = Integer.parseInt(cmd.substring(0,cmd.indexOf(",")));
int bc = Integer.parseInt(cmd.substring(cmd.indexOf(",")+1));
model.change(br - 1, bc);
model.change(br + 1, bc);
model.change(br, bc - 1);
model.change(br, bc + 1);
changeView(br - 1, bc);
changeView(br + 1, bc);
changeView(br, bc - 1);
changeView(br, bc + 1);
if (model.isAll()) {
}
}
private void changeView(int br, int bc) {
if ((br >= 0 && br < this.r) && (bc >= 0 && bc < this.c)) {
if (model.isBack(br, bc)) {
buttons[br][bc].setIcon(okImage);
} else {
buttons[br][bc].setIcon(backImage);
}
}
}
}
运行的效果
java写的小游戏
最新推荐文章于 2024-07-30 20:48:56 发布