import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
public class GUI extends JFrame implements ActionListener {
private JButton startButton = new JButton("Start");
private JLabel scoreLabel = new JLabel("Score: 0");
private JPanel boardPanel = new JPanel(new GridLayout(8,8));
private TheGame game = new TheGame();
public GUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setTitle("JSameGame");
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.add(startButton,BorderLayout.WEST);
topPanel.add(scoreLabel,BorderLayout.EAST);
startButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if ( game.data.started ) {
int value = JOptionPane.showConfirmDialog(null, "Are you sure?");
if ( value == JOptionPane.OK_OPTION ) {
scoreLabel.setText("Score: 0");
game.initializeGame();
updateBoard();
}
} else {
scoreLabel.setText("Score: 0");
game.initializeGame();
updateBoard();
}
}
});
getContentPane().setLayout(new BorderLayout());
getContentPane().add(topPanel,BorderLayout.NORTH);
getContentPane().add(boardPanel);
setLocationRelativeTo(null);
}
private void updateBoard() {
boardPanel.removeAll();
int cellNum = 0;
for ( int i = 0; i < 8; i++ ) {
for ( int j = 0; j < 8; j++ ) {
JButton cellButton = new JButton();
cellButton.setOpaque(true);
cellButton.setActionCommand(cellNum+"");
switch (game.data.board[i][j].color) {
case Square.EMPTY: cellButton.setBackground(Color.BLACK);break;
case Square.BLUE: cellButton.setBackground(Color.BLUE);break;
case Square.RED: cellButton.setBackground(Color.RED);break;
case Square.GREEN: cellButton.setBackground(Color.GREEN);break;
case Square.PINK: cellButton.setBackground(Color.PINK);break;
}
cellButton.addActionListener(this);
boardPanel.add(cellButton);
cellNum++;
}
}
boardPanel.updateUI();
}
@Override
public void actionPerformed(ActionEvent e) {
game.data.started = true;
int cell = Integer.parseInt(e.getActionCommand());
int x = cell / 8;
int y = cell % 8;
game.squareSelected(x, y);
updateBoard();
scoreLabel.setText("Score: "+game.data.score);
if ( game.isBoardEmpty() ) {
JOptionPane.showMessageDialog(this, "You WIN!\nYour Score is "+game.data.score+"\nPress OK to start a new Game");
game.data.started = false;
startButton.doClick();
}else{
if ( !game.isPairsAvailable() ) {
JOptionPane.showMessageDialog(this, "You LOSE!\nYour Score is "+game.data.score+"\nPress OK to start a new Game");
game.data.started = false;
startButton.doClick();
}
}
}
public static void main(String[] args) {
try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Exception e){}
new GUI().setVisible(true);
}
}
|