// UserInterface.java
// Description: User interface for TicTacToe game
// Author: Chris Wilcox
// Date: 4/9/2015

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;

public class UserInterface extends JFrame implements ActionListener {

    private static final long serialVersionUID = 1L;

    // User interface
    private JPanel topPanel; // Points area
    private JPanel bottomPanel; // Game area
    private Image iconB, iconX, iconO;
    private JLabel message;
    private JButton buttons[][] = new JButton[3][3];
    private Font font;

    // Student object
    TicTacToe tictactoe;
    
    public UserInterface() {

        // Look and feel
        try {
            UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Setup message
        font = new Font("Arial", Font.PLAIN, 24);
        message = new JLabel("You are 'X', computer is 'O'");
        message.setFont(font);
        message.setForeground(new Color(0xFFFFFF));
        
        // Top panel for message
        topPanel = new JPanel();
        topPanel.add(message);
        topPanel.setBackground(new Color(0x0076A3));

        // Bottom panel for board
        bottomPanel = new JPanel();
        bottomPanel.setLayout(new GridLayout(3, 3, 0, 0));
        add(Box.createRigidArea(new Dimension(0, 5)), BorderLayout.NORTH);
        add(bottomPanel, BorderLayout.CENTER);

        // Split panel
        JSplitPane sp = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
        sp.setEnabled(false);
        sp.setDividerSize(0);
        sp.add(topPanel);
        sp.add(bottomPanel);
        add(sp, BorderLayout.CENTER);

        // Load images
        ImageIcon icon0 = new ImageIcon("images/B.png");
        Image image0 = icon0.getImage();
        iconB = image0.getScaledInstance(128, 128, Image.SCALE_DEFAULT);
        ImageIcon icon1 = new ImageIcon("images/X.png");
        Image image1 = icon1.getImage();
        iconX = image1.getScaledInstance(128, 128, Image.SCALE_DEFAULT);
        ImageIcon icon2 = new ImageIcon("images/O.png");
        Image image2 = icon2.getImage();
        iconO = image2.getScaledInstance(128, 128, Image.SCALE_DEFAULT);

        // Build panel of buttons
        for (int row = 0; row < 3; row++) {
            for (int col = 0; col < 3; col++) {

                // Initialize and add button
                JButton button = new JButton();
                buttons[row][col] = button;
                Border border = new LineBorder(Color.black, 1);
                button.addActionListener(this);
                button.setOpaque(true);
                button.setBackground(Color.white);
                button.setBorder(border);
                button.setIcon(new ImageIcon(iconB));
                bottomPanel.add(button);
            }
        }

        // Window setup
        setSize(530, 530);
        setTitle("TicTacToe Game");
        setResizable(false);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setAlwaysOnTop(true);
    }

    public void redrawBoard() {

        // Wait for awhile
        try {
            Thread.sleep(500);
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }

        // Get data from student
        char board[][] = tictactoe.data();

        // Redraw board
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                char tile = board[i][j];
                switch (tile) {
                case '-':
                    buttons[i][j].setIcon(new ImageIcon(iconB));
                    break;
                case 'X':
                    buttons[i][j].setIcon(new ImageIcon(iconX));
                    break;
                case 'O':
                    buttons[i][j].setIcon(new ImageIcon(iconO));
                    break;
                }
            }
        }
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {

                // Instantiate user interface
                UserInterface ui = new UserInterface();
                ui.tictactoe = new TicTacToe();
                ui.setVisible(true);
                ui.redrawBoard();
            }
        });
    }

    public void actionPerformed(ActionEvent e) {
        
        JButton button = (JButton) e.getSource();
        Dimension size = button.getSize();
        int buttonX = button.getX();
        int buttonY = button.getY();
        int col = buttonX / size.width;
        int row = buttonY / size.height;
        System.out.println("Player moved at row " + row + ", col " + col);
        if (tictactoe.status() == TicTacToe.eStatus.IN_PROGRESS)
            tictactoe.player(row, col);
        if (tictactoe.status() == TicTacToe.eStatus.IN_PROGRESS) 
            tictactoe.computer();

        redrawBoard();

        // Game over?
        if (tictactoe.status() == TicTacToe.eStatus.TIE_GAME)
            message.setText("Tie game, kind of boring!");
        else if (tictactoe.status() == TicTacToe.eStatus.PLAYER_WINS)
            message.setText("Player won, congratulations!");
        else if (tictactoe.status() == TicTacToe.eStatus.COMPUTER_WINS)
            message.setText("Computer won, that's lame!");
    }
}

© 2015 CS160 Colorado State University. All Rights Reserved.