让我的椭圆堆叠在每一列上

时间:2011-05-19 01:27:00

标签: java swing

  

可能重复:
  issue with my main method in my connect4 game

您好, 在我的connect4游戏中,每当我点击任何正方形时,它将椭圆放在特定的正方形上,我如何得到它以便将椭圆放在该列的最低正方形上以便它可以叠加?

package Game;

import java.util.ArrayList;

public class ConnectFourBoard {

    // This constant is used to indicate the width and height, in cells,
    // of the board.  Since we want an 8x8 board, we'll set it to 8.
    private static final int WIDTH = 8;
    private static final int HEIGHT = 8;
    private ConnectFourCell[][] currentPlayer;

    // The current state the Othello board is defined with these two
    // fields: a two-dimensional array holding the state of each cell,
    // and a boolean value indicating whether it's the black player's
    // turn (true) or the white player's turn (false).
    private ConnectFourCell[][] cells;
    private boolean isBlueTurn;

    // Since the board is a model and it needs to notify views of changes,
    // it will employ the standard "listener" mechanism of tracking a list
    // of listeners and firing "events" (by calling methods on those
    // listeners) when things change.
    private ArrayList<ConnectFourListener> listeners;

    public ConnectFourBoard()
    {
        // Arrays, in Java, are objects, which means that variables of
        // array types (like cells, which has type OthelloCell[][]) are
        // really references that say where an array lives.  By default,
        // references point to null.  So we'll need to create an actual
        // two-dimensional array for "cells" to point to.
        cells = new ConnectFourCell[WIDTH][HEIGHT];
        listeners = new ArrayList<ConnectFourListener>();
        reset();
        isBlueTurn = true; 

    }

    public void reset(){
        for (int i = 0; i<WIDTH ; i++){
            for (int j = 0; j<HEIGHT; j++){

                cells[i][j] = ConnectFourCell.NONE; 
            }
        }

        isBlueTurn = true; 
    }

    public void addConnectFourListener(ConnectFourListener listener)
    {
        listeners.add(listener);
    }


    public void removeConnectFourListener(ConnectFourListener listener)
    {
        if (listeners.contains(listener))
        {
            listeners.remove(listener);
        }
    }


    // These are fairly standard "fire event" methods that we've been building
    // all quarter, one corresponding to each method in the listener interface.

    private void fireBoardChanged()
    {
        for (ConnectFourListener listener : listeners)
        {
            listener.boardChanged();
        }
    }


    private void fireGameOver()
    {
        for (ConnectFourListener listener : listeners)
        {
            listener.gameOver();
        }
    }


    // isBlackTurn() returns true if it's the black player's turn, and false
    // if it's the white player's turn.
    public boolean isBlueTurn()
    {
        return isBlueTurn;
    }

    public int getWidth()
    {
        return WIDTH;


    }

    public int getHeight(){

        return HEIGHT; 
    }
    // getBlackScore() calculates the score for the black player.
    public int getBlackScore()
    {
        return getScore(ConnectFourCell.BLUE);
    }


    // getWhiteScore() calculates the score for the white player.
    public int getWhiteScore()
    {
        return getScore(ConnectFourCell.RED);
    }

    // getScore() runs through all the cells on the board and counts the
    // number of cells that have a particular value (e.g., BLACK or WHITE).
    // This method uses the naive approach of counting them each time
    // it's called; it might be better to keep track of this score as we
    // go, updating it as tiles are added and flipped.
    private int getScore(ConnectFourCell cellValue)
    {
        int score = 0;

        for (int i = 0; i < WIDTH; i++)
        {
            for (int j = 0; j < HEIGHT; j++)
            {
                if (cells[i][j] == cellValue)
                {
                    score++;
                }
            }
        }

        return score;
    }




    // getWhiteScore() calculates the score for the white player.
    public int getRedScore()
    {
        return getScore(ConnectFourCell.RED);
    }

    public int getBlueScore() {
        // TODO Auto-generated method stub
        return getScore(ConnectFourCell.BLUE);
    }


    public ConnectFourCell getCell(int x, int y)
    {
        if (!isValidCell(x, y))
        {
            throw new IllegalArgumentException(
                "(" + x + ", " + y + ") is not a valid cell");
        }

        return cells[x][y];
    }
    /**
    * The drop method.
    *
    * Drop a checker into the specified HEIGHT,
    * and return the WIDTH that the checker lands on.
    */
    int drop(int HEIGHT) {
    if (hasWon()) {
    return -1;
    }

    for ( ; WIDTH<6 && HEIGHT != 0; WIDTH++) { };

    if (WIDTH==6) {
    // if the WIDTH is 6, it went through all 6 WIDTHs
    // of the cells, and couldn't find an empty one.
    // Therefore, return false to indicate that this
    // drop operation failed.
    return -1;
    }
    // fill the WIDTH of that HEIGHT with a checker.
    cells[HEIGHT][WIDTH] = currentPlayer[HEIGHT][WIDTH];
    // alternate the players
    //currentPlayer = (currentPlayer%2)+1;
    return WIDTH;
    }
    /**
    * The toString method
    *
    * Returns a String representation of this
    * Connect Four (TM) game.
    */
    public String toString() {
    String returnString = "";
    for (int WIDTH=5; WIDTH>=0; WIDTH--) {
    for (int HEIGHT=0; HEIGHT<7; HEIGHT++) {
    returnString = returnString + cells[HEIGHT][WIDTH];
    }
    returnString = returnString + "\n";
    }
    return returnString;
    }
    /**
    * The hasWon method.
    *
    * This method returns true if one of the
    * players has won the game.
    */
    public boolean hasWon()

    {
            // First, we'll establish who the current player and the opponent is.
        //ConnectFourCell



        ConnectFourCell myColor =
                isBlueTurn() ? ConnectFourCell.BLUE : ConnectFourCell.RED;

        ConnectFourCell otherColor =
                isBlueTurn() ? ConnectFourCell.RED : ConnectFourCell.BLUE;


    return true;

    }

    public void validMove( ){

    }
    public void makeAMove(int x, int y){

        //System.out.println(x+" "+y);
    //  cells[x][y] = ConnectFourCell.BLUE;

        //Check who's turn it is.  Set to that color.
        ConnectFourCell myColor = null;
        if ( isBlueTurn == true){
            myColor = myColor.BLUE; 

        }
        else {
            myColor = myColor.RED; 
        }

        cells[x][y]  = myColor; 


        //Check if it's a valid move.  If there is a piece there. can't
        // Look at the column.  play piece in the highest available slot



        //Check if there are 4 in a row.
        for (int WIDTH=0; WIDTH<6; WIDTH++) {
            for (int HEIGHT=0; HEIGHT<4; HEIGHT++) {
            if (!(cells[HEIGHT][WIDTH] == ConnectFourCell.NONE)  &&
            cells[HEIGHT][WIDTH] == cells[HEIGHT+1][WIDTH] &&
            cells[HEIGHT][WIDTH] == cells[HEIGHT+2][WIDTH] &&
            cells[HEIGHT][WIDTH] == cells[HEIGHT+3][WIDTH]) {

            }
            }
            }
            // check for a vertical win
            for (int WIDTH=0; WIDTH<3; WIDTH++) {
            for (int HEIGHT=0; HEIGHT<7; HEIGHT++) {
            if (!(cells[HEIGHT][WIDTH] == ConnectFourCell.NONE)  &&
            cells[HEIGHT][WIDTH] == cells[HEIGHT][WIDTH+1] &&
            cells[HEIGHT][WIDTH] == cells[HEIGHT][WIDTH+2] &&
            cells[HEIGHT][WIDTH] == cells[HEIGHT][WIDTH+3]) {

            }
            }
            }
            // check for a diagonal win (positive slope)
            for (int WIDTH=0; WIDTH<3; WIDTH++) {
            for (int HEIGHT=0; HEIGHT<4; HEIGHT++) {
                if (!(cells[HEIGHT][WIDTH] == ConnectFourCell.NONE) &&
            cells[HEIGHT][WIDTH] == cells[HEIGHT+1][WIDTH+1] &&
            cells[HEIGHT][WIDTH] == cells[HEIGHT+2][WIDTH+2] &&
            cells[HEIGHT][WIDTH] == cells[HEIGHT+3][WIDTH+3]) {

            }
            }
            }
            // check for a diagonal win (negative slope)
            for (int WIDTH=3; WIDTH<6; WIDTH++) {
            for (int HEIGHT=0; HEIGHT<4; HEIGHT++) {
                if (!(cells[HEIGHT][WIDTH] == ConnectFourCell.NONE)  &&
            cells[HEIGHT][WIDTH] == cells[HEIGHT+1][WIDTH-1] &&
            cells[HEIGHT][WIDTH] == cells[HEIGHT+2][WIDTH-2] &&
            cells[HEIGHT][WIDTH] == cells[HEIGHT+3][WIDTH-3]) {

            }
            }
            }


        fireBoardChanged();
        isBlueTurn = !isBlueTurn;

    }

    private boolean isValidCell(int x, int y)
    {
        return x >= 0 && x < WIDTH
              && x>= 0 && x<HEIGHT
              && y >= 0 && y < WIDTH
              && y>= 0 && y<HEIGHT;
    }
}


package UI;



import java.awt.*; 


import javax.swing.*;

import UI.ConnectFourBoardPanel;

import Game.ConnectFourBoard;
import Game.ConnectFourListener;

public class ConnectFourFrame extends JFrame implements ConnectFourListener {

    // Variables

    private ConnectFourBoard board;

    private JLabel scoreLabel;
    private ConnectFourBoardPanel boardPanel;
    private JLabel statusLabel;


    public ConnectFourFrame()
    {
        // The frame builds its own model.
         board = new ConnectFourBoard(); 

        // We want the frame to receive notifications from the board as its
        // state changes.
        System.out.println(this);
        board.addConnectFourListener(this);

        setTitle("Informatics 45 Spring 2011: ConnectFour Game");
        setSize(700, 700);
        setResizable(true);
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        getContentPane().setBackground(Color.BLACK);

        buildUI();
        refreshUI();
    }


    private void buildUI()
    {
        GridBagLayout layout = new GridBagLayout();
        getContentPane().setLayout(layout);

        Font labelFont = new Font("SansSerif", Font.BOLD, 18); 

        scoreLabel = new JLabel();
        scoreLabel.setForeground(Color.WHITE);
        scoreLabel.setFont(labelFont);
        layout.setConstraints(
            scoreLabel,
            new GridBagConstraints(
                0, 0, 1, 1, 1.0, 0.0,
                GridBagConstraints.CENTER,
                GridBagConstraints.NONE,
                new Insets(10, 10, 10, 10), 0, 0));
        getContentPane().add(scoreLabel);

        boardPanel = new ConnectFourBoardPanel(board);
        layout.setConstraints(
            boardPanel,
            new GridBagConstraints(
                0, 1, 1, 1, 1.0, 1.0,
                GridBagConstraints.CENTER,
                GridBagConstraints.BOTH,
                new Insets(10, 10, 10, 10), 0, 0));
        getContentPane().add(boardPanel);

        statusLabel = new JLabel();
        statusLabel.setForeground(Color.WHITE);
        statusLabel.setFont(labelFont);
        layout.setConstraints(
            statusLabel,
            new GridBagConstraints(
                0, 2, 1, 1, 1.0, 0.0,
                GridBagConstraints.CENTER,
                GridBagConstraints.NONE,
                new Insets(10, 10, 10, 10), 0, 0));
        getContentPane().add(statusLabel);
    }

    private void refreshUI()
    {
        // Refreshing the UI means to change the text in each of the
        // two labels (the score and the status) and also to ask the
        // board to repaint itself.

        scoreLabel.setText(
            "Blue: " + board.getBlueScore() +
            "          Red: " + board.getRedScore());



                if ( board.isBlueTurn() == false){
                    statusLabel.setText("Blue's Turn: ");
                }
                if ( board.isBlueTurn() == true){
                    statusLabel.setText("Red's Turn: ");
                }


        boardPanel.repaint();
    }

    // These are the ConnectFourBoardListener event-handling methods.

    public void boardChanged()
    {
        // When the board changes, we'll refresh the entire UI.  (There
        // are times when this approach is too inefficient, but it will
        // work fine for our relatively simple UI.)

        refreshUI();
    }


    public void gameOver()
    {
        // When the game is over, we'll pop up a message box showing the final
        // score, then, after the user dismisses the message box, dispose of
        // this window and end the program.

        JOptionPane.showMessageDialog(
            this,
            "Game over!\nFinal score: " + scoreLabel.getText(),
            "Game Over",
            JOptionPane.INFORMATION_MESSAGE);

        dispose();
    }

}

1 个答案:

答案 0 :(得分:0)

欢迎使用StackOverflow。你的问题很好 - 但总的来说,粘贴整个程序是一个坏主意。您应该描述您的程序,并在其中包含用于计算椭圆填充方式的片段。

话虽如此,这里有一个答案:    - 您想要查看当前选定的图块,如果其下方的图块被占用,请填写该单元格。如果未占用,请将当前图块设置为下方图块,然后重复。你想要这样做,直到你到达底行。

上面的答案并不包括检查所选瓷砖是否已被占用,但我相信你可以轻易搞清楚。