I have been working on TicTacToe for some time now. I just now got it to work but it's not working properly. When somebody gets three in a row a label is suppose to show that a player has won but it does'nt. So I cant figure out why it's having trouble deciding if somebody has won or not. The code in which I think there is a problem is in Bold. Here is the code:
Code:import java.awt.*; import javax.swing.*; import java.awt.event.*; public class ButtonArray extends JFrame implements ActionListener { JButton btn[][]; String player; JLabel lbl; public ButtonArray() { JPanel jp = new JPanel(); Container pane = getContentPane(); setSize(155,155); setTitle("Tic Tac Toe"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); btn = new JButton[3][3]; player = "X"; for (int x=0; x<3; x++) { for (int y=0; y<3; y++) { btn[x][y] = new JButton(" "); btn[x][y].addActionListener(this); jp.add(btn[x][y]); } } JPanel jp2 = new JPanel(); lbl = new JLabel("Status: player X to go next"); jp2.add(lbl); pane.setLayout(new BorderLayout()); pane.add(jp, BorderLayout.CENTER); pane.add(jp2,BorderLayout.SOUTH); setContentPane(pane); setResizable(false); setVisible(true); } public void actionPerformed(ActionEvent e) { for (int x=0; x<3; x++) { for (int y=0; y<3; y++) { if (e.getSource() == btn[x][y]) { processEvent(x,y); } } } } private boolean hasWon(int x, int y) { boolean won; won = true; for (int num=0; num<3; num++) { won = false; if (btn[x][num].getText().equals(player)) { won = true; } } if (!won) { won = false; for (int col=3; col<3; col++) { if (btn[col][y].getText().equals(player)) { won = true; } } } if (!won) { won = false; for (int num=0; num<3; num++) { if (btn[num][num].getText().equals(player)) { won = true; } } } if (!won) { won = false; for (int num=0; num<3; num++) { if (btn[2-num][num].getText().equals(player)) { won = true; } } } return won; } public void processEvent(int x, int y) { if (btn[x][y].getText().equals("X") || btn[x][y].getText().equals("O")) { System.out.println("Cell is already taken"); } else { btn[x][y].setText(player); } if (hasWon(x,y) == true) { lbl.setText("Game Won"); } if (player.equals("X")) { player = "O"; } else { player = "X"; } lbl.setText("Status: player " + player + " to go next"); } public static void main(String[] args) { ButtonArray ba = new ButtonArray(); } }




Reply With Quote