LinuxQuestions.org
Visit Jeremy's Blog.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 04-29-2016, 10:05 AM   #1
baronobeefdip
Senior Member
 
Registered: Jul 2009
Distribution: Debian Squeeze
Posts: 1,267

Rep: Reputation: 32
Programming Connect Four grid in Java


I have been trying to get this conection four GUI working, but for some reason, the grid and the size of the array don't seem to sync up very well. I have been playing around with the code but it doesn't seem to be working very well. The array works in displaying the contents in a grid way in the terminal, but not so well when inside of the jframe. Here is the code for each file. the Frame file contains the code for the GUI, the grid file contains the code for the grid which hold the values in the connect four grid. I don't know what logic is for, and the ConnectFour file contains the main function. These are it's contents

ConnectFour.java
Code:
package frame;
import java.util.Scanner;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author baronobeefdip
 */
public class ConnectFour {
    
    
    
    public static void main(String[] args)
    {
       Frame frame = new Frame();
       int slot;
       Scanner input = new Scanner(System.in);
       int state = 1;
       while(state == 1)
       {
           System.out.print("Where in the x coordinates do you want to insert: ");
           slot = input.nextInt();
           frame.my_grid.set_matrix(slot, 0, 1);
           frame.updateBoard();
           frame.display();
       }
    }
}

Frame.java
Code:
package frame;

import frame.Grid;
import frame.logic;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;

public class Frame {
    //declaration of gui objects

    private JFrame frame;
    private JLabel[][] slots;
    private JButton[] buttons;
    //variables used in grid
    public int xsize = 7;
    public int ysize = 6;
    private int currentPlayer = 1;
    //game variables to communicate with top program
    private boolean hasWon = false;
    private boolean hasDraw = false;
    private boolean quit = false;
    private boolean newGame = false;
    //making of grid and logic
    Grid my_grid = new Grid();
    logic my_logic = new logic(my_grid); //create game logic
    
    
    public Frame()
    {
        frame = new JFrame("connect four");
        buttons = new JButton[xsize];
        JPanel panel = (JPanel) frame.getContentPane();
        panel.setLayout(new GridLayout(xsize, ysize));
/*
        for (int i = 0; i < xsize; i++) {
            buttons[i] = new JButton("" + (i + 1));
            buttons[i].setActionCommand("" + i);
            buttons[i].addActionListener(
                    new ActionListener() {

                        public void actionPerformed(ActionEvent e) {
                            int a = Integer.parseInt(e.getActionCommand());
                            int y = my_grid.find_y(a);//check for space in collumn
                            if (y != -1) {
                                //sets a place to current player
                                if (my_logic.set_and_check(a, y, currentPlayer)) {
                                    hasWon = true;
                                } else if (my_logic.draw_game()) {//checks for drawgame
                                    hasDraw = true;
                                } else {
                                    //change player
                                    currentPlayer = my_grid.changeplayer(currentPlayer, 2);
                                    frame.setTitle("connect four - player " + currentPlayer + "'s turn");
                                }
                            } else {
                                JOptionPane.showMessageDialog(null, "choose another one", "column is filled", JOptionPane.INFORMATION_MESSAGE);
                            }
                        }
                    });
            panel.add(buttons[i]);
        }*/
        
        slots = new JLabel[xsize][ysize];
        for (int column = 0; column < ysize; column++) {
            for (int row = 0; row < xsize; row++) {
                slots[row][column] = new JLabel();
                slots[row][column].setHorizontalAlignment(SwingConstants.CENTER);
                slots[row][column].setBorder(new LineBorder(Color.black));
                panel.add(slots[row][column]);
            }
        }

        //jframe stuff
        frame.setContentPane(panel);
        frame.setSize(
                700, 600);
        frame.setVisible(
                true);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
    }
    
    
    public void updateBoard() {//keeps the gui in sync with the logggggtjiic and grid
        for (int row = 0; row < xsize; row++) {
            for (int column = 0; column < ysize; column++) {
                if (my_grid.matrix_equals(row, column, 1)) {
                    slots[row][column].setOpaque(true);
                    slots[row][column].setBackground(Color.red);
                }
                if (my_grid.matrix_equals(row, column, 2)) {
                    slots[row][column].setOpaque(true);
                    slots[row][column].setBackground(Color.blue);
                }
            }
        }
    }
    

    
    public void display()
    {
        for (int count = 0; count < ysize; count++)
        {
            for (int count2 = 0; count2 < xsize; count2++)
            {
                System.out.print(my_grid.matrix[count2][count]+" ");
            }
            System.out.print("\n");
        }
    }
}
Grid.java
Code:
package frame;

public class Grid {

    public int xsize;
    public int ysize;
    public int[][] matrix;

    public Grid() {
        xsize = 6;
        ysize = 7;

        matrix = new int[xsize][ysize];
        
        /*for (int i = 0; i < xsize; i++) {
            for (int j = 0; j < ysize; j++) {
                matrix[i][j] = 0;
                //cells_left++;
            }
        }*/
        
        for (int count = 0; count < ysize; count++)
        {
            for (int count2 = 0; count2 < xsize; count2++)
            {
                matrix[count2][count] = 0;
            }
        }
    }
    
    public void display()
    {
        for (int count = 0; count < ysize; count++)
        {
            for (int count2 = 0; count2 < xsize; count2++)
            {
                System.out.print(matrix[count2][count]+" ");
            }
            System.out.print("\n");
        }
    }
    //methods to gain access to internal private data

    /*public int get_cells_left() {
        //return cells_left;
    }
    */
    public int[][] get_matrix() {
        return matrix;
    }

    public boolean matrix_equals(int a, int b, int c) {
        return matrix [a][b] == c;
    }

    public void set_matrix(int a, int b, int temp_player) {
        matrix[a][b] = temp_player;
    }

    public int get_xsize() {//returns the xsize
        return xsize;
    }

    public int get_ysize() {//returns the xsize
        return ysize;
    }

    public int find_y(int x) {//checks for room in collumn and returns free spot.
        int y = -1;
        for (int i = 0; i < ysize; i++) {
            if (matrix[x][i] == 0) {
                y = i;
            }
        }
        return y;
    }

    public int changeplayer(int player, int max_players) {
        player++;
        if (player > max_players) {
            return 1;
        }
        return player;
    }
}
logic.java
Code:
package frame;

public class logic {

    private int cells_left = 0;
    private int max;
    private int xsize;
    private int ysize;
    Grid my_grid;

    public logic(Grid tempGrid) {
        max = 4;//connect 4 or n
        my_grid = tempGrid;
       // cells_left = my_grid.get_cells_left();
        xsize = my_grid.get_xsize();
        ysize = my_grid.get_ysize();
    }

    public boolean set_and_check(int x, int y, int player) {//sets the found coordinate to current player
        my_grid.set_matrix(x, y, player);
        cells_left--;
        return check_one(x, y, 0, 1, player) //syd
                || check_one(x, y, -1, 1, player) //sydvest
                || check_one(x, y, -1, 0, player) //vest
                || check_one(x, y, 1, 1, player);//sydøst
    }

    public boolean draw_game() {//checks for draw game
        return cells_left == 0;
    }

    private boolean check_one(int x, int y, int dx, int dy, int player) {
        int count = 0;
        int tempx = x;
        int tempy = y;

        while (count < max && valid(tempx, tempy)) {
            if (!my_grid.matrix_equals(tempx, tempy, player)) {
                break;

            }
            tempx += dx;
            tempy += dy;
            count++;
        }
        tempx = x - dx;
        tempy = y - dy;
        while (count < max && valid(tempx, tempy)) {
            if (!my_grid.matrix_equals(tempx, tempy, player)) {
                break;
            }
            tempx -= dx;
            tempy -= dy;
            count++;
        }
        return count == max;
    }

    private boolean valid(int x, int y) {
        //if the bounds are set to be >0 only then first row and collumn 
        //doesnt work
        return x >= 0 && x < xsize && y >= 0 && y < ysize;
    }
}
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
[SOLVED] How to connect a java client to a BSD server using socket programming sanju.lnt Programming 2 08-06-2011 02:57 PM
Java Programming: Java Runtime Environment not found when trying to compile murbz Linux - Software 2 03-26-2009 03:04 AM
LXer: Developing Grid apps with Perl, Java and Python LXer Syndicated Linux News 0 11-20-2007 03:20 AM
Programming a Connect Four UI (Java) lambada Programming 5 11-10-2003 09:58 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 08:19 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration