簡體   English   中英

Java游戲板陣列未更新

[英]Java game board array not updating

我目前正在嘗試復制游戲黑白棋(對於不熟悉的人,這里是一個示例: http : //www.mathsisfun.com/games/reversi.html )。 我目前遇到的問題與我嘗試更新游戲板有關。 我有一個稱為板的2D陣列,當用戶單擊特定的單元格時,該板將與該播放器一起更新。 但是事實並非如此。 到目前為止,這是我的代碼:

    /* Main.java
 *
 * this is a simple program that will implement the game of reversi, it will only deal with the game itself and a
 * simple scoreboard.
 */

/** includes **/
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Rectangle2D;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;

import javax.swing.JComponent;
import javax.swing.JFrame;

/** classes **/

public class Reverse extends JFrame {

    /** constructors **/
    public Reverse() {
        setSize(648, 670);
        setTitle("Reversi");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(true);
        setLocationRelativeTo(null);

        //Initialize Widget
        widget = new ReversiWidget();
        //Initialize Content Pane
        getContentPane().add(widget);
    }

    /** public functions **/
    public static void main(String[] args) {
        Reverse w = new Reverse();
        w.setVisible(true);
    }

    /** private fields **/
    ReversiWidget widget;   // where the game is being played
}

class ReversiWidget extends JComponent implements MouseListener {

    int width = getWidth();
    int height = getHeight();
    int column = 8;
    int row = 8;


    /** constructors **/
    public ReversiWidget() {
        black = this.black;
        cyan = this.cyan;
        white = this.white;

        //Initialize game state
        initialState();

        //add mouse listener
        addMouseListener(this);
    }

    /** public functions **/

    // method required by MouseListener. not used
    public void mouseClicked(MouseEvent event) {

    }

    // method required by MouseListener. not used
    public void mouseEntered(MouseEvent event) {

    }

    // method required by MouseListener. not used
    public void mouseExited(MouseEvent event) {

    }

    // will react to mouse press events on the widget
    public void mousePressed(MouseEvent event) {
        //get value of left button clicked
        if(event.getButton() == 3){


        }
    }

    // will react to mouse release events on the widget
    public void mouseReleased(MouseEvent event) {
        //determine value for newx and newy
        //get mouse pressed
        int x = event.getX();
        int y = event.getY();
        setX(x);
        setY(y);
        rowSelected = x / sqaure_size;
        colSelected = y / sqaure_size;
        current_player = 1;
        if (rowSelected >= 0 && rowSelected < row && colSelected >= 0 && colSelected < column){
            System.out.println("C Row && C Col: "+rowSelected+"  | "+colSelected);
            System.out.println(oldx+" | "+oldy);
            board[rowSelected][colSelected] = current_player;
            System.out.println("Board Test: "+board[0][0]+", "+board[0][1]+", "+board[0][2]+", "+board[0][3]+", ");
            attemptMove(rowSelected, colSelected, current_player);
        }

    }

    // repaints the widget when an update of any kind is made
    public void paintComponent(Graphics g) {
        //paint background
        //type cast graphics object

        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(Color.CYAN);
        g2d.fillRect(0,0,640, 640);
        //run draw grid method
        drawGrid(g2d);
        drawPieces(g2d);
    }


    /** private functions **/

    // will take in a position (x,y) a player and will attempt to make a move. if successful then it will place the
    // piece and update the game board.
    private void attemptMove(int x, int y, int player) {

        //repaint();

    }   

    // checks if there is a piece in a given position. returns 0 if empty, -1 if out of bounds, 1 for player 1, and
    // 2 for player 2
    private int checkPiece(int x, int y) {
        return -5;
    }

    // determines if a valid reverse chain can be made from the position (x, y) in the given direction (dx, dy) and a
    // given player
    private boolean determineChain(int x, int y, int dx, int dy, int player) {
        return false;
    }

    // determines if an end game state has been reached. this will happen if there are zero spaces on the board, if one
    // player has lost all of their pieces, or there are no valid moves left for either player
    private boolean determineEndGame() {
        return false;
    }

    // will draw the grid for the game. this assumes a 640 by 640 grid
    private void drawGrid(Graphics2D g2d) {
        //type cast graphics component
        //This is where it gets tricky

                //Here we're going to draw our grid
                int rowCount = width / row;
                int colCount  = height / column;
                int cell = 79;

                //Create Rows
                for(int a=0;a<row;a++){
                    g2d.setColor(Color.BLACK);
                    g2d.drawLine(0, colCount, 638, rowCount);
                    colCount = colCount + cell;
                    rowCount = rowCount + cell;
                }

                colCount = 79;
                rowCount = 79;
                //Create Columns
                for(int b=0;b<column;b++){
                    g2d.setColor(Color.BLACK);
                    //x1,y1  - x2,y2
                    System.out.println("ColCount: "+colCount);
                    g2d.drawLine(colCount, 0, rowCount, 675);
                    colCount = colCount + cell;
                    rowCount = rowCount + cell;

                }

                for (int rows = 0; rows < row; rows++) {
                 for (int col = 0; col < column; col++) {
                    board[row][column] = 0; // all cells empty
                    System.out.print(board[row][column]);
                 }
                 System.out.println();
              }

    }

    // will draw the pieces that are currently on the board. assumes a widget size of 640 square
    private void drawPieces(Graphics2D g2d) {

        int x = getX();
        int y = getY();
        System.out.println("drawPieces: "+x+" | "+y);
        //Traverse the entire board length to see if a move has been made

        //Black Initial Pieces
        g2d.setColor(Color.BLACK);
        g2d.fillOval(316, 237, 78,78);
        g2d.fillOval(238, 317, 78,78);

        //White Initial Pieces
        g2d.setColor(Color.WHITE);
        g2d.fillOval(238, 239, 78,78);
        g2d.fillOval(317, 317, 78,78);
        board[3][3] = 1;
        board[4][3] = 2;
        board[3][4] = 2;
        board[3][3] = 1;
        setBoard(3,3,1);
        setBoard(4,3,1);
        setBoard(3,4,1);
        //setBoard();

        //If move is made draw black piece

                        if(board[rowSelected][colSelected] == 2){
                           g2d.setColor(Color.BLACK);
                           g2d.fillOval(rowSelected, colSelected, 79, 79);
                        }


        //if move is made draw white pieces

                        if(board[rowSelected][colSelected] == 1){
                            g2d.setColor(Color.WHITE);
                            g2d.fillOval(rowSelected, colSelected, 79, 79);   
                        }





    }

    // will initialise the game board to the starting state
    private void initialState() {
        inPlay = true;
    }

    // given a position (x, y) and a player this will determine if there is a valid move to be made at the given
    // position by checking for the availability of a reverse chain in any direction
    private boolean reverseChainAvailable(int x, int y, int player) {
        return false;
    }   

    // given a position (x, y), direction (dx, dy) and a player this will reverse all opponents pieces in a given
    // direction. NOTE: this assumes that determineChain has been used first. method does not perform checks
    private void reversePieces(int x, int y, int dx, int dy, int player) {

    }

    // called at the end of a valid turn this will swap the current players
    private void swapPlayers() {

    }

    // updates the player scores after a piece has been placed
    private void updatePlayerScores() {

    }

    public void setX(int x){this.oldx = x;}
    public void setY(int y){this.oldy = y;}
    public void setBoard(int x, int y, int player){this.board[x][y] = board[x][y] = player;}

    /** private fields **/
    //initial board state
    public int board[][] = new int[9][9];
    int oldx;
    int oldy;   // denotes where the player clicked when he pressed the mouse button
    int current_player;                 // denotes who the current player is
    int player_1_score, player_2_score; // denotes the score each player has in the game thus far
    boolean inPlay;                     // indicates if the game is being played at the moment
    Color black, cyan, white;           // color objects that represent their named colours
    int sqaure_size = 79;
    int rowSelected = oldx / sqaure_size;
    int colSelected = oldy / sqaure_size;
}

特定的問題與此方法有關:

public void mouseReleased(MouseEvent event) {
        //determine value for newx and newy
        //get mouse pressed
        int x = event.getX();
        int y = event.getY();
        setX(x);
        setY(y);
        rowSelected = x / sqaure_size;
        colSelected = y / sqaure_size;
        current_player = 1;
        if (rowSelected >= 0 && rowSelected < row && colSelected >= 0 && colSelected < column){
            System.out.println("C Row && C Col: "+rowSelected+"  | "+colSelected);
            System.out.println(oldx+" | "+oldy);
            board[rowSelected][colSelected] = current_player;
            System.out.println("Board Test: "+board[0][0]+", "+board[0][1]+", "+board[0][2]+", "+board[0][3]+", ");
            attemptMove(rowSelected, colSelected, current_player);
        }

    }

編輯*,請原諒。

g2d.fillOval(rowSelected, colSelected, 79, 79)將會成為一個問題,因為rowSelectedcolSelected是您的木板陣列的索引,並且不反映視圖/虛擬木板的偏移量,需要對這些偏移量進行轉換以反映圖形網格...

嘗試改用g2d.fillOval(rowSelected * 79, colSelected * 79, 79, 79)

還應該避免使用“魔術”數字,並對這些值進行常量或查找,以便您可以更輕松地進行更改...

您需要取消注釋repaint請求才能完成此工作...

哦,您似乎也正在從繪畫方法中修改游戲的狀態,因此我建議您不要這樣做,因為繪畫可以隨時發生。

另外,在執行任何繪畫之前,請確保您正在調用super.paintComponent ,這將防止出現任何討厭的繪畫偽像,尤其是在處理從JComponent擴展的組件時

更新

Swing中的繪畫具有破壞性。 也就是說,每次發生繪制周期時,都希望您重新繪制組件的整個狀態。 繪制過程的一部分是“清理” Graphics上下文,這就是為什么調用super.paintXxx重要的super.paintXxx

您將需要遍歷您的電路板並重新繪制,例如...

for (int y = 0; y < row; y++) {
    for (int x = 0; x < col; x++) {
        if(board[y][x] == 2){
           g2d.setColor(Color.BLACK);
           g2d.fillOval(y * 79, x * 79, 79, 79);
        } else if(board[y][x] == 1){
            g2d.setColor(Color.WHITE);
           g2d.fillOval(y * 79, x * 79, 79, 79);
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM