Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 8 of 8
  1. #1
    New Coder
    Join Date
    Oct 2010
    Posts
    22
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Java Connect4 -newbie

    Ok, first off, this code is very messy and uncommented sooo if you know a decent amount on Java you should be able to navigate it for the most part.

    I am making a connect4 game, and I am still very new to Java.

    My issues right now revolve around three things.
    1. Whenever I choose an odd number for the board size, it only displays an even amount of holes for the columns (if you test it you will see what I mean).
    2. As you can see in my code, I am trying to somehow link up my JButtons to an actionlistener...basically be entitled buttons[0] to buttons[(board size)]. However, it only seems to loop and actually assign a listener to half of the buttons, not sure why it is doing that.
    3. Once I do get the buttons working, how will I be able to get the JLabel images updated for a player's piece and at the same time only go down to the next available spot, rather than overlapping.

    Those are my current issues right now and this code is ultra messy, so sorry about that.
    (I've attached the images as well)

    Also, I use Eclipse.
    Code's in the spoiler

    Code:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Graphics2D;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    
    import javax.swing.BorderFactory;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JRadioButton;
    import javax.swing.JTextField;
    
    public class GameEngine {
    
    	static JFrame frameMenu = new JFrame("Welcome to Connect 4!");
    
    	static JFrame frameBoard = new JFrame("Connect 4");
    
    	static JPanel panel_main = new JPanel();
    
    	static JPanel panel_main_top = new JPanel();
    
    	static JPanel panel_main_bottom = new JPanel();
    
    	static JPanel userSelection = new JPanel();
    
    	static JPanel boardSizeSelection = new JPanel();
    
    	static JPanel connectsSelection = new JPanel();
    
    	static JPanel usersBackground = new JPanel();
    
    	static JPanel connectsBackground = new JPanel();
    
    	static JPanel playersPresentPanel = new JPanel();
    
    	static JPanel boardBottom = new JPanel();
    
    	static JPanel boardPlane = new JPanel();
    
    	static JPanel boardButtons = new JPanel();
    
    	static JPanel boardMenu = new JPanel();
    
    	static JPanel bottomCombo = new JPanel();
    
    	static JPanel boardMiddle = new JPanel();
    
    	static JPanel buttonPlane = new JPanel();
    
    	static JPanel boardGame = new JPanel();
    
    	static JPanel buttonCombo = new JPanel();
    
    	static JPanel buttonCombo1 = new JPanel();
    
    	static JPanel buttonCombo2 = new JPanel();
    
    	static JLabel playersPresent = new JLabel();
    
    	static JLabel numberOfUsersMessage = new JLabel();
    
    	static JLabel boardSizeMessage = new JLabel();
    
    	static JLabel filler = new JLabel("");
    
    	static JLabel label;
    
    	static JPanel buttonRow = new JPanel();
    
    	static JLabel moveLocation = new JLabel();
    
    	static JLabel moveLocation1 = new JLabel();
    
    	static JLabel connectsMessage = new JLabel();
    
    	static JLabel onePlayerMessage = new JLabel();
    
    	static JLabel twoPlayerMessage = new JLabel();
    
    	static JLabel threePlayerMessage = new JLabel();
    
    	static JLabel fourPlayerMessage = new JLabel();
    
    	static JLabel fourWinsMessage = new JLabel();
    
    	static JLabel fiveWinsMessage = new JLabel();
    
    	static JLabel sixWinsMessage = new JLabel();
    
    	static JLabel sevenWinsMessage = new JLabel();
    
    	static JLabel eightWinsMessage = new JLabel();
    
    	static JLabel scoreBoardMessage = new JLabel();
    
    	static JLabel playerTurnMessage = new JLabel();
    
    	static JRadioButton twoUserSelection = new JRadioButton("", false);
    
    	static JRadioButton threeUserSelection = new JRadioButton("", false);
    
    	static JRadioButton fourUserSelection = new JRadioButton("", false);
    
    	static JRadioButton fourConnectsSelection = new JRadioButton("", false);
    
    	static JRadioButton fiveConnectsSelection = new JRadioButton("", false);
    
    	static JRadioButton sixConnectsSelection = new JRadioButton("", false);
    
    	static JRadioButton sevenConnectsSelection = new JRadioButton("", false);
    
    	static JRadioButton eightConnectsSelection = new JRadioButton("", false);
    
    	static Graphics2D ga = null;
    
    	int smallcounter = 0;
    
    	int counter = 0;
    
    	JButton[] buttons = new JButton[15];
    
    	static JTextField names = new JTextField(1);
    
    	static JTextField move = new JTextField(2);
    
    	static JTextField move1 = new JTextField(2);
    
    	static int player1_wins = 0;
    
    	static int player2_wins = 0;
    
    	static int player3_wins = 0;
    
    	static int player4_wins = 0;
    
    	static int turnTracker = 1;
    
    	static JButton buttonStart, buttonExit, buttonReset, buttonUndo;
    
    	static String Player_1 = "Player 1";
    
    	static String Player_2 = "Player 2";
    
    	static String Player_3 = "Player 3";
    
    	static String Player_4 = "Player 4";
    
    	static String boardType = "10x10";
    
    	static String boardRowsString = "10";
    
    	static String boardColsString = "10";
    
    	static int boardRows = 10;
    
    	static int boardCols = 10;
    
    	static JLabel[][] boardArray;
    
    	static int userStatus = 2;
    
    	static int connects = 4;
    
    	static boolean match = false;
    
    	static boolean winner = false;
    
    	static String[] boards = { "10x10", "11x11", "12x12", "13x13", "14x14",
    			"15x15" };
    
    	static JComboBox boardGroups = new JComboBox(boards);
    
    	static String board[][];
    
    	Dimension menuSize = new Dimension(500, 200);
    
    	Dimension backgroundBoard;
    
    	ImageIcon emptySpace = new ImageIcon(
    			"C:/Users/Austin/Desktop/Storage/Developer/Java_Items/shape/emptySpace.png");
    
    	ImageIcon player1Space = new ImageIcon(
    			"C:/Users/Austin/Desktop/Storage/Developer/Java_Items/shape/player1Space.png");
    
    	ImageIcon player2Space = new ImageIcon(
    			"C:/Users/Austin/Desktop/Storage/Developer/Java_Items/shape/player2Space.png");
    
    	ImageIcon player3Space = new ImageIcon(
    			"C:/Users/Austin/Desktop/Storage/Developer/Java_Items/shape/player3Space.png");
    
    	ImageIcon player4Space = new ImageIcon(
    			"C:/Users/Austin/Desktop/Storage/Developer/Java_Items/shape/player4Space.png");
    
    	static ImageIcon arrow = new ImageIcon(
    			"C:/Users/Austin/Desktop/Storage/Developer/Java_Items/shape/arrow.png");
    
    	static JButton button = new JButton(arrow);
    
    	MyMouseListener m = new MyMouseListener();
    
    	public static void main(String arg[]) {
    		GameEngine t = new GameEngine();
    		t.ProjectGUI();
    
    	}
    
    	public void ProjectGUI() {
    
    		WelcomeGUI();
    
    	}
    
    	class MyMouseListener extends MouseAdapter {
    
    		public MyMouseListener() {
    			super();
    		}
    
    		public void mouseClicked(MouseEvent evt) {
    			if (evt.getSource() == emptySpace) {
    				turnTracker++;
    				Messages();
    			}
    
    		}
    	}
    
    	private void WelcomeGUI() {
    
    		twoUserSelection.setSelected(true);
    		fourConnectsSelection.setSelected(true);
    
    		boardGroups.setSelectedIndex(0);
    		boardGroups.addActionListener(new e());
    		boardGroups.setBackground(Color.white);
    		userSelection.setLayout(new GridLayout(1, 1));
    
    		usersBackground.setLayout(new GridLayout(1, 1));
    
    		connectsBackground.setLayout(new GridLayout(1, 1));
    
    		twoPlayerMessage.setText("2");
    		twoUserSelection.addActionListener(new e());
    		userSelection.add(twoPlayerMessage);
    		userSelection.add(twoUserSelection);
    
    		threePlayerMessage.setText("3");
    		threeUserSelection.addActionListener(new e());
    		userSelection.add(threePlayerMessage);
    		userSelection.add(threeUserSelection);
    
    		fourPlayerMessage.setText("4");
    		fourUserSelection.addActionListener(new e());
    		userSelection.add(fourPlayerMessage);
    		userSelection.add(fourUserSelection);
    
    		fourWinsMessage.setText("4 ");
    		fourConnectsSelection.addActionListener(new e());
    		connectsSelection.add(fourWinsMessage);
    		connectsSelection.add(fourConnectsSelection);
    
    		fiveWinsMessage.setText("5 ");
    		fiveConnectsSelection.addActionListener(new e());
    		connectsSelection.add(fiveWinsMessage);
    		connectsSelection.add(fiveConnectsSelection);
    
    		sixWinsMessage.setText("6 ");
    		sixConnectsSelection.addActionListener(new e());
    		connectsSelection.add(sixWinsMessage);
    		connectsSelection.add(sixConnectsSelection);
    
    		sevenWinsMessage.setText("7 ");
    		sevenConnectsSelection.addActionListener(new e());
    		connectsSelection.add(sevenWinsMessage);
    		connectsSelection.add(sevenConnectsSelection);
    
    		eightWinsMessage.setText("8 ");
    		eightConnectsSelection.addActionListener(new e());
    		connectsSelection.add(eightWinsMessage);
    		connectsSelection.add(eightConnectsSelection);
    
    		boardSizeSelection.setBackground(Color.white);
    		boardSizeSelection.setLayout(new GridLayout(1, 1));
    		boardSizeSelection.add(boardGroups);
    
    		numberOfUsersMessage.setText("Mark the number of players: ");
    		boardSizeMessage.setText("Select a board size.");
    		connectsMessage.setText("Number of connects required for win: ");
    
    		usersBackground.add(numberOfUsersMessage);
    		connectsBackground.add(connectsMessage);
    
    		panel_main_top.setBackground(Color.white);
    		panel_main_top.setLayout(new GridLayout(3, 2));
    		panel_main_top.add(usersBackground);
    		panel_main_top.add(userSelection);
    		panel_main_top.add(boardSizeMessage);
    		panel_main_top.add(boardSizeSelection);
    		panel_main_top.add(connectsBackground);
    		panel_main_top.add(connectsSelection);
    
    		panel_main_bottom.setBackground(Color.white);
    		panel_main_bottom.setLayout(new GridLayout(1, 2));
    
    		buttonStart = new JButton("Start Game");
    		buttonStart.addActionListener(new e());
    		panel_main_bottom.add(buttonStart);
    
    		buttonExit = new JButton("Exit");
    		buttonExit.addActionListener(new e());
    		panel_main_bottom.add(buttonExit);
    
    		panel_main.setLayout(new GridLayout(2, 1));
    		panel_main.setBackground(Color.white);
    		panel_main.setBorder(BorderFactory.createLineBorder(Color.black, 2));
    		panel_main.add(panel_main_top);
    		panel_main.add(panel_main_bottom);
    
    		frameMenu.setResizable(false);
    		frameMenu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frameMenu.getContentPane().add(panel_main);
    		frameMenu.pack();
    		frameMenu.setSize(menuSize);
    		frameMenu.setVisible(true);
    
    	}
    
    	private void Messages() {
    
    		if (userStatus == 2) {
    			scoreBoardMessage.setText("Leader board: " + Player_1 + ": "
    					+ player1_wins + "     |     " + Player_2 + ": "
    					+ player2_wins);
    		}
    
    		if (userStatus == 3) {
    			scoreBoardMessage.setText("Leader board: " + Player_1 + ": "
    					+ player1_wins + "     |     " + Player_2 + ": "
    					+ player2_wins + "     |     " + Player_3 + ": "
    					+ player3_wins);
    		}
    		if (userStatus == 4) {
    			scoreBoardMessage.setText("Leader board: " + Player_1 + ": "
    					+ player1_wins + "     |     " + Player_2 + ": "
    					+ player2_wins + "     |     " + Player_3 + ": "
    					+ player3_wins + "     |     " + Player_4 + ": "
    					+ player4_wins);
    		}
    
    		if (turnTracker > userStatus) {
    			turnTracker = 1;
    		}
    		if (turnTracker == 1) {
    			playerTurnMessage.setText("It is " + Player_1 + "'s turn.");
    		} else {
    			if (turnTracker == 2) {
    				playerTurnMessage.setText("It is " + Player_2 + "'s turn.");
    			} else {
    				if (turnTracker == 3 && userStatus >= 3) {
    					playerTurnMessage.setText("It is " + Player_3 + "'s turn.");
    				} else {
    					if (turnTracker == 4 && userStatus == 4) {
    						playerTurnMessage.setText("It is " + Player_4
    								+ "'s turn.");
    					}
    				}
    
    			}
    		}
    
    		if (userStatus == 2) {
    			playersPresent.setText("Current Players:  " + Player_1 + " | "
    					+ Player_2);
    		}
    
    		if (userStatus == 3) {
    			playersPresent.setText("Current Players:  " + Player_1 + " | "
    					+ Player_2 + " | " + Player_3);
    		}
    		if (userStatus == 4) {
    			playersPresent.setText("Current Players:  " + Player_1 + " | "
    					+ Player_2 + " | " + Player_3 + " | " + Player_4);
    		}
    	}
    
    	private void BoardGUI() {
    
    		boardMenu.setLayout(new GridLayout(2, 1));
    		boardMenu.setBackground(Color.white);
    		boardMenu.add(scoreBoardMessage);
    		boardMenu.add(playerTurnMessage);
    
    		buttonUndo = new JButton("Undo");
    		buttonUndo.addActionListener(new e());
    		boardButtons.add(buttonUndo);
    
    		buttonReset = new JButton("Reset");
    		buttonReset.addActionListener(new e());
    		boardButtons.add(buttonReset);
    
    		buttonExit = new JButton("Exit");
    		buttonExit.addActionListener(new e());
    		boardButtons.add(buttonExit);
    
    		boardMiddle.setLayout(new BorderLayout());
    		boardMiddle.add(buttonRow, BorderLayout.NORTH);
    		boardMiddle.add(boardPlane, BorderLayout.CENTER);
    
    		boardGame.setLayout(new BorderLayout());
    
    		boardGame.add(boardMenu, BorderLayout.NORTH);
    		boardGame.add(boardMiddle, BorderLayout.CENTER);
    		boardGame.add(boardButtons, BorderLayout.SOUTH);
    
    		boardGame.setBackground(Color.white);
    		boardGame.setBorder(BorderFactory.createLineBorder(Color.black, 2));
    
    	}
    
    	public void buttonBuilder() {
    		int h = 0;
    		buttonRow.setLayout(new GridLayout(1, 15));
    		for (h = 0; h < (boardRows/2); h++) {
    
    			buttons[h] = new JButton(arrow);
    			buttons[h].addActionListener(new e());
    			buttons[h].setHorizontalAlignment(JLabel.CENTER);
    			buttonRow.add(buttons[h]);
    			System.out.println("hcount: " + h);
    
    			if (h == boardRows - 1) {
    				break;
    			}
    		}
    	}
    
    	public class e implements ActionListener {
    
    		public void actionPerformed(ActionEvent e) {
    			Object source = e.getSource();
    
    			if (source == buttonStart) {
    				boardSetup();
    				getNames();
    				startGame();
    
    			}
    
    			if (source == twoUserSelection) {
    				threeUserSelection.setSelected(false);
    				fourUserSelection.setSelected(false);
    				userStatus = 2;
    			}
    
    			if (source == threeUserSelection) {
    				twoUserSelection.setSelected(false);
    				fourUserSelection.setSelected(false);
    				userStatus = 3;
    			}
    
    			if (source == fourUserSelection) {
    				twoUserSelection.setSelected(false);
    				threeUserSelection.setSelected(false);
    				userStatus = 4;
    			}
    
    			if (source == fourConnectsSelection) {
    				fiveConnectsSelection.setSelected(false);
    				sixConnectsSelection.setSelected(false);
    				sevenConnectsSelection.setSelected(false);
    				eightConnectsSelection.setSelected(false);
    				connects = 4;
    			}
    
    			if (source == fiveConnectsSelection) {
    				fourConnectsSelection.setSelected(false);
    				sixConnectsSelection.setSelected(false);
    				sevenConnectsSelection.setSelected(false);
    				eightConnectsSelection.setSelected(false);
    				connects = 5;
    			}
    
    			if (source == sixConnectsSelection) {
    				fourConnectsSelection.setSelected(false);
    				fiveConnectsSelection.setSelected(false);
    				sevenConnectsSelection.setSelected(false);
    				eightConnectsSelection.setSelected(false);
    				connects = 6;
    			}
    
    			if (source == sevenConnectsSelection) {
    				fourConnectsSelection.setSelected(false);
    				fiveConnectsSelection.setSelected(false);
    				sixConnectsSelection.setSelected(false);
    				eightConnectsSelection.setSelected(false);
    				connects = 7;
    			}
    
    			if (source == eightConnectsSelection) {
    				fourConnectsSelection.setSelected(false);
    				fiveConnectsSelection.setSelected(false);
    				sixConnectsSelection.setSelected(false);
    				sevenConnectsSelection.setSelected(false);
    				connects = 8;
    			}
    
    			if (source == boardGroups) {
    
    			}
    
    			if (source == buttons[1]) {
    				System.out.println("1");
    				Update();
    				if (userStatus == 1) {
    
    				}
    			}
    
    			if (source == buttons[2]) {
    				System.out.println("2");
    				Update();
    			}
    
    			if (source == buttons[3]) {
    				System.out.println("3");
    				Update();
    			}
    
    			if (source == buttons[4]) {
    				System.out.println("4");
    				Update();
    			}
    
    			if (source == buttons[5]) {
    				System.out.println("5");
    				Update();
    			}
    
    			if (source == buttons[6]) {
    				System.out.println("6");
    				Update();
    			}
    
    			if (source == buttons[7]) {
    				System.out.println("7");
    				Update();
    			}
    
    			if (source == buttonExit) {
    				System.exit(1);
    			}
    
    			if (source == buttonUndo) {
    
    				turnTracker--;
    				smallcounter--;
    				if (turnTracker <= 0 && counter > 0) {
    					turnTracker = 4;
    					counter--;
    				} else {
    					playerTurnMessage.setText("You cannot undo any further.");
    					playerTurnMessage.setForeground(Color.red);
    
    				}
    				Messages();
    
    			}
    		}
    
    		private void Update() {
    			playerTurnMessage.setForeground(Color.black);
    			smallcounter++;
    			if (smallcounter == 4) {
    				smallcounter = 0;
    				counter++;
    			}
    			turnTracker++;
    			if (turnTracker == 5) {
    				turnTracker = 1;
    			}
    			Messages();
    		}
    
    		private void getNames() {
    			if (userStatus == 2) {
    				Player_1 = JOptionPane.showInputDialog(null,
    						"Please enter player 1's name");
    
    				Player_2 = JOptionPane.showInputDialog(null,
    						"Please enter player 2's name");
    
    			}
    			if (userStatus == 3) {
    				Player_1 = JOptionPane.showInputDialog(null,
    						"Please enter player 1's name");
    
    				Player_2 = JOptionPane.showInputDialog(null,
    						"Please enter player 2's name");
    				Player_3 = JOptionPane.showInputDialog(null,
    						"Please enter player 3's name");
    			}
    			if (userStatus == 4) {
    				Player_1 = JOptionPane.showInputDialog(null,
    						"Please enter player 1's name");
    				Player_2 = JOptionPane.showInputDialog(null,
    						"Please enter player 2's name");
    				Player_3 = JOptionPane.showInputDialog(null,
    						"Please enter player 3's name");
    				Player_4 = JOptionPane.showInputDialog(null,
    						"Please enter player 4's name");
    			}
    
    		}
    
    		private void startGame() {
    			boardSetup();
    			BoardGUI();
    		}
    
    		private void packageBoard() {
    			frameBoard.setResizable(false);
    			frameBoard.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    			frameBoard.getContentPane().add(boardGame);
    			frameBoard.pack();
    			frameBoard.setSize(backgroundBoard);
    			frameMenu.setVisible(false);
    			frameBoard.setVisible(true);
    
    		}
    
    		private void boardSetup() {
    			boardType = boardGroups.getSelectedItem().toString();
    			boardRowsString = boardType.substring(0, 2);
    			boardColsString = boardRowsString;
    			boardRows = Integer.parseInt(boardRowsString);
    			boardCols = Integer.parseInt(boardColsString);
    			backgroundBoard = new Dimension((boardRows * 45), (boardCols * 40));
    
    			panelMaker();
    			Messages();
    			packageBoard();
    			buttonBuilder();
    
    		}
    
    		public void horizontalCheck() {
    			String playerMark = null;
    			int size = boardRows;
    			for (int row = 0; row < size; row++) {
    				for (int col = 0; col < size - connects; col++) {
    					match = true;
    					for (int i = 0; i < connects; i++) {
    
    						if (board[row][col + i] != playerMark) {
    							match = false;
    
    						}
    					}
    					if (match = true) {
    						winner = true;
    					}
    
    				}
    			}
    
    		}
    
    		public void verticallCheck() {
    		}
    
    		public void diagonal1Check() {
    		}
    
    		public void diagonal2Check() {
    		}
    
    		private void panelMaker() {
    			JLabel[][] boardnew = new JLabel[boardRows][boardCols];
    			boardPlane.setLayout(new GridLayout(boardRows, (boardCols / 2)));
    			boardPlane
    					.setBorder(BorderFactory.createLineBorder(Color.black, 2));
    			boardPlane.setBackground(Color.yellow);
    			int i = 0;
    			int j = 0;
    			int k = 0;
    
    			for (i = 0; i < boardRows; i++) {
    
    				for (j = 0; j < (boardCols / 2); j++) {
    
    					boardnew[i][j] = new JLabel(emptySpace);
    					boardnew[i][j].setHorizontalAlignment(JLabel.CENTER);
    					boardPlane.add(boardnew[i][j]);
    
    				}
    			}
    
    		}
    
    	}
    
    }
    Thank you guys so much!
    -Austin

  • #2
    New Coder
    Join Date
    Oct 2010
    Posts
    22
    Thanks
    1
    Thanked 0 Times in 0 Posts
    The images are here:


    <-- don't forgot the lil arrow.



  • #3
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    1's issue appears to be calling the buttonBuilder in more than one location, and relying on a division of the maximum size to overwrite. This is not desireable; I removed the boardSetup call from the e.actionPerformed. I haven't yet determined if this will be a problem. I modified the buttonBuilder to this:
    PHP Code:
        public void buttonBuilder() {
            
    int h 0;
            
    buttonRow.setLayout(new GridLayout(1boardRows));
            for (
    0< (boardRows); h++) {

                
    buttons[h] = new JButton(arrow);
                
    buttons[h].addActionListener(new e());
                
    buttons[h].setHorizontalAlignment(JLabel.CENTER);
                
    buttonRow.add(buttons[h]);
                
    System.out.println("hcount: " h);
            }
        } 
    2. It appears to have no problem with the button listener; the problem is the actionPerformed itself. Its only checking for buttons 1 - 7 inclusive, so you will never get around that one with that current code. You can add all additional buttons if desired.

    3. Sorry I don't quite understand what you're asking on the last. I don't have the images (I don't follow external links when I'm at work), but if you post the actual images in an attachment I can take a look and see what you mean. It sounds like either the image isn't updating properly, or that the stack isn't seeing anything below it, both of which shouldn't be a problem to correct.

    Now, as for cleaning up - yes definitely
    Don't forget you can do a lot to simplify this by using multiple action listeners for different tasks. You may also use anonymous inner classes to do what you need to do if it makes it easier (I generally just make a nested class, but it really doesn't make a difference if which is done). The real flaw for what you have here seems to all fall against the 'e' class that you have created. To me it seems to be doing a lot more work than it should be doing.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 
    Been gone for a few months, and haven't programmed in that long of a time. Meh, I'll wing it ;)

  • Users who have thanked Fou-Lu for this post:

    aanders5 (02-03-2011)

  • #4
    New Coder
    Join Date
    Oct 2010
    Posts
    22
    Thanks
    1
    Thanked 0 Times in 0 Posts
    I posted the image tags, so they should be showing up on the second post I made. But I will upload them right now into this post as well.

    I will test out the new button code right now.

    What I meant by Q 2, was how do I get the button (once pressed) to update the board to show the players piece within the game board.

    Finally, I am not sure how to do multiple actionListeners, is it basically the same thing as the "e", but instead I would use like a "z" and make a new class for it? If that is the scenario, what is the pro's and con's of just using 1 actionListener class for this program.

    Also, I tend to just write all my codes in 1 page, rather than in multiple pages. Not sure I do this, but I think for my next project (A banking application) I will use multiple pages.


    Thank you so far mate!
    -Austin

    P.S. The max upload for images was 4, so instead of showing you the four player pieces I only uploaded the empty space, player 1, 2, and the arrow button.


    P.S.S. OHHHH! Were you able to figure out why when I make the board size an odd number, it only creates columns 1 less than the size selected? I.E. If I pick 13x13 it will give me a board size of 13x12. No clue how it is doing that...

    Thanks again
    Attached Images Attached Images     
    Last edited by aanders5; 02-03-2011 at 10:01 PM.

  • #5
    New Coder
    Join Date
    Oct 2010
    Posts
    22
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Did you actually test the game out? Or just looked at it via the code? Cause your button setup makes 2x as many buttons. o.O


    Also boardsetup basically does this.
    When you check your board size, it pulls the string in (from the menu of your board choice) then turns it into an Int then assigns them to boardRows and boardCols. So without that function I bet the game would give you some sort of parsing error.


    Please actually RUN the game. It's easier for me to follow that way.
    Thank you though so far!

  • #6
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    Please re-read my previous post; I have indicated why you are creating two sets of buttons.

    All separate classes should be their own class file. You can embed as many inner and anonymous classes you desire as they are directly linked to the class itself, and are more often than not usable in other classes. If you have an interface that uses a custom action listener (or anything really), you would then create a separate action listener object to deal with it. Pros of separate classes are reusability, cons are useless if tightly bound to specific objects (which is why you are doing inner classes instead).

    Is this a school project you are doing and are bound to specific things / lessons, or your own? If its your own, modifications could be made to make this substantially easier. Looking at the board itself, its a multidimensional JLabel which is fine. But the question is how do you easily tell which one a particular player owns so that you can determine whether they have won? Its more work as now you need to essentially check the background specified by the JLabel itself. This is where more classes would help, if you have a Player class, you can create a underlying datastorage of a Player matrix or multidimensional player array. Each of these represents the pieces on the board, null would be a space and a particular player instance would be inserted when they have placed a piece. The GUI would then represent this by replacing the player with a particular color.

    This would make the button handling easy as well, just flip the logic instead of looking at it as rows x cols in the multidimensional array, look at it as cols x rows. This allows super easy lookups. Almost backwards of the traditional rows asc and cols asc, this would become cols asc and rows desc (visually, your GUI would work the stack in the cols from the bottom to the top).
    PHP Code:
    private class BoardListenerHandler implements ActionListener()
    {
        private 
    int iIndex;
        private 
    GameEngine geBoard;

        public 
    BoadListenerHandler(GameEngine geBoardint iIndex)
        {
            
    this.geBoard geBoard;
            
    this.iIndex iIndex;
        }
        public 
    void actionPerformed(ActionEvent e)
        {
            
    // We don't care what e is.
            
    this.geBoard.consumeSpace(iIndex);
        }

    Simple as that. Linking it to a button would be a simple matter of running a loop and dropping in the gameEngine object itself (this), and the index the column is. In a loop like you have its a simple matter of buttons[h].addActionListener(new BoardListenerHandler(this, h));
    Then you write a method consumeSpace(iIndex) in the game itself:
    PHP Code:
    public void consumeSpace(int iIndex)
    {
        
    boolean bAdded false;
        
    // You have to track your players somewhere, and I'm not sure if / how you plan on doing it,
        // so I'll just call mine under this.currentPlayer
        
    for (int i 0bPlayerMatrix[iIndex].length && !bAdded; ++i)
        {
            if (
    bPlayerMatrix[iIndex][i] == null)
            {
                
    bPlayerMatrix[iIndex][i] = this.currentPlayer;
                
    bAdded true;
                
    // Flag the next player to play
            
    }
        }
        if (!
    bAdded)
        {
            
    System.err.println("That column is full"); // Better even would be to write a method to check if its already full.
        
    }

        
    // run some determinations

    Have it determine if the player has won, if all the spaces have been filled without a winner, or if the column is full (you can also disable the button in that case as well), or to proceed to the next player (create that as a queue of players rotating them on and off the queue [don't use an array if you can avoid it, use a linked list]).

    Its complicated yes, very much so. But I think that looking at converting particularly for the Player class would be a huge benefit. Also, try to put as little work as you can inside of a listener when interacting with data, and instead give the listener access to a particular class or block of information to work with. You will find that its much easier to manage your classes if you have them completely centralized. There are always exceptions of course, if you have a massive abstract aggregate or composite model, then you may want to do some extra work within the common class. I'd still try to avoid this as much as possible, as anything listed as a ActionListener can be used by any class or method accepting an ActionListener. That won't work so well if it wasn't designed to work with a particular set of data.

    Edit:
    Oh btw, don't throw an exception from the consumeSpace. The actionListener will likely choke if you do manage to get it to toss (I don't think it will even accept it during compile time if you tried to create it as a checked exception).
    Last edited by Fou-Lu; 02-03-2011 at 11:18 PM.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 
    Been gone for a few months, and haven't programmed in that long of a time. Meh, I'll wing it ;)

  • #7
    New Coder
    Join Date
    Oct 2010
    Posts
    22
    Thanks
    1
    Thanked 0 Times in 0 Posts
    eh, im so lost. :/ I'll try to figure it out.
    I also get lost on using this and other functions of JAVA. I do work really hard with coding, and I love it a lot, but sometimes I just get overwhelmed when an aspect of it doesn't click for me.

    -Austin

  • #8
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    Start simple, and work to complex.
    It took me awhile to switch to OOP languages (I started with perl and PHP (procedural at the time only), neither of which is actually ideal for a starting language), so changing the logical paradigm to OO was a little tricky.

    Always take a step back, and look at the overall use and goal of the code - completely ignore things like the gui until you are ready to implement it (gui is simply a visual representation of your data). To a lesser degree, same with the listeners (they are useful either on cli or gui, but make sure its solid first). Look at what is interacting and how you can represent it as an object. There are literally unlimited approaches to the exact same result depending on the level of complexity, reusability and maintenance you want to shift around (finding your ideal balance).
    I look at this, and I see a Board (with a collection of Token - a name I used for the piece), Player with ownership of Token, and of course Token, representing the spaces taken. Note that Player is arbitrary, it can be extended to a CPU player as well if desired. On top of all these are listeners and the gui, which is the very last thing I write; all code I make is fully functional in a cli environment before sliding a gui on top of it. Each class can be handled with listeners of their own to determine things like winning, trying to stuff a column too full, passing to the next player, and so forth.

    If you are looking to rewrite (and not bound by particular methods, interfaces, etc provided by an assignment), I would start by determining how a Player interacts with a Board. A previous suggestion I made was to use a 2d array of Player itself, and simply toggle the ownership of the board for the players. This is a simple approach. Slide in between the Board and the Player a Token (or Piece or something to represent the game pieces themselves) which links a Token to the board, and a Player to a token, still giving you the same benefits of player ownership, but now when it comes to adding a gui you can control the token itself to change the colour or look to represent a particular player. The token would be a composite of the Player as well to ensure its owned when created.

    Don't think too hard on this stuff for the time being. You didn't mention if this is an assignment, but something strikes me as so - make sure you get it done first before trying to perform tasks like altering it to better manage it. Nothing is worse than having 2 half done projects when the time could have been used to make 1 complete project.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 
    Been gone for a few months, and haven't programmed in that long of a time. Meh, I'll wing it ;)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •