当前位置: 首页 > 知识库问答 >
问题:

放置正确的光盘 连接四个java游戏与绘图面板

赵渊
2023-03-14

我正在尝试使用用户输入和绘图面板在Java中制作一个Connect Four Game。两个人轮流输入他们想要加入的栏目。我在制作它时遇到了问题,所以已经放好的光盘在下一个回合仍然留在板上(因为每次更新板时都会弹出一个新的绘图面板)(我们尝试使用GUI,但失败了)。我也很难每次关闭开关和改变颜色。非常感谢,这是我目前所拥有的。

import java.util.*;
import java.awt.*;

public class ConnectFour{
   public static void main(String[] args){
      Scanner console = new Scanner(System.in);
      char [][] board = new char [7][6];
      for (int i = 0; i< 7; i++){
         for (int j= 0; j< 6; j++){
            board[i][j] = ' '; 
         }
      }
      boolean isBlack = true ; //black discs turn
      boolean isRed = false ;   //red discs turn
      boolean playersTurn = true ;
      while (playersTurn){
         if (isBlack == true ){
            System.out.println("Black's Turn");
         }
         else {
            System.out.println("Red's Turn");
         }
         System.out.print("Choose a column to place your disk (1-7): ");

         int column = console.nextInt()-1;
         if (column < 0 || column > 7) { //while loop?
            System.out.print( "Column needs to be within 1-7"); //try catch?
         }

         drawBoard(column, board, isBlack, isRed);
         // connectedFour(board);
         // playersTurn = !playersTurn;
      }
      // isBlack = !isBlack; INVERT WHOSE TURN IT IS!!! unreachable statement??
   }

   public static void drawBoard(int column, char [][] board, boolean isBlack, boolean isRed) {
      DrawingPanel panel = new DrawingPanel(550,550);
      int rowAvailable;
      Graphics g = panel.getGraphics();
      g.drawLine(0,0,0,500);
      g.drawLine(0,0,500,0);
      g.drawLine(500,0,500,427);
      g.drawLine(0,427,500,427);

      for (int i = 0; i< 6; i++){
         for (int j= 0; j<= 6; j++){
            g.setColor(Color.YELLOW);
            g.fillRect(j*71,i*71,71,71);
            g.setColor(Color.WHITE);
            g.fillOval(j*71,i*71,71,71);
         }
      }

      int x = 0;
      int row = 5;

      while (board[column][row-x] != ' '){
         x++;
      }

      row = 5-x;

      if (isBlack == true) {
         g.setColor(Color.BLACK);  
         board[column][row-x] = 'b';                                                
      }                                                   
      else {
         g.setColor(Color.RED);
         board[column][row-x] = 'r';
      }
        // I KNOW THIS FOR LOOP DOES NOT WORK SUCCESSFULLY    
      for (int i = 0; i< 6; i++){                               
         for (int j= 0; j<= 6; j++){
            if(board[i][j] != 'b'){
               g.fillOval((i * 71),j*71, 71,71);
            }
         }
      }



         //       g.fillOval((column * 71),row*71, 71,71); //number 142 is just a test
                     //board[i][j] = WHOSE TURN IT IS (to update array)
          //  if(isBlack){
          //     board[column][row] = 'b';
         //   }
         //   else{
         //      board[column][row] = 'r';
          //  }
   }

   //get whose turn it is as parameter?? a color string? boolean?
   public static boolean  connectedFour( char[][] board){
      int verticalCount = 0;
      for (int i = 0; i< 6; i++){ //goes down each column //EXCEPTION HERE BECAUSE 0
         for( int j=0; j<=6; j++){
            if (board[i][j]== board[i-1][j]){
               verticalCount ++;
            }
         }
      }

      int horizontalCount = 0;
      for (int i =0; i<=6; i++){
         for (int j =0; j<6; j++){
            if (board[i][j-1] == board[i][j]){
               horizontalCount++;
            }
         }
      }

      int diagonalCount = 0;
      //get diagonal here
      if (verticalCount >= 4 || horizontalCount >= 4|| diagonalCount >=4){
         return true ; //return who the winner is. String?
      //
      }
      else {
         return false ;
      }
   }
}

共有1个答案

申屠宗清
2023-03-14
  • 不要将基于控制台的输入与 GUI 输出混合使用,这是两种不同的用户范例,需要不同的工作流程和管理方法
  • 不要使用获取图形,这不是绘画的工作方式。Swing 有一个定义的绘制过程,您应该使用它来确保在需要执行更新时收到通知。有关更多详细信息,请参阅AWT中的绘画和摇摆和执行自定义绘画。

以下是一个非常基本的示例,说明您如何使用API,而不是针对它。

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.awt.geom.RoundRectangle2D;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class ConnectFour {

    public static void main(String[] args) {
        new ConnectFour();
    }

    public ConnectFour() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new GamePane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public enum Player {

        RED, BLUE, NONE;
    }

    public class GamePane extends JPanel {

        private BoardPane boardPane;
        private JLabel label;
        private Player player = null;

        public GamePane() {
            setLayout(new BorderLayout());
            boardPane = new BoardPane();
            add(boardPane);

            label = new JLabel("...");
            label.setHorizontalAlignment(JLabel.CENTER);
            label.setForeground(Color.WHITE);
            label.setOpaque(true);
            label.setBorder(new EmptyBorder(10, 10, 10, 10));

            add(label, BorderLayout.NORTH);

            updatePlayer();

            boardPane.addChangeListener(new ChangeListener() {
                @Override
                public void stateChanged(ChangeEvent e) {
                    updatePlayer();
                }
            });
        }

        protected void updatePlayer() {
            String text = "...";
            Color color = null;
            if (player == null || player.equals(Player.BLUE)) {
                player = Player.RED;
                text = "Red";
                color = Color.RED;
            } else if (player.equals(Player.RED)) {
                player = Player.BLUE;
                text = "Blue";
                color = Color.BLUE;
            }

            label.setText(text);
            label.setBackground(color);
            boardPane.setPlayer(player);
        }

    }

    public class BoardPane extends JPanel {

        private Player[][] board;
        private Player player;

        private int hoverColumn = -1;

        public BoardPane() {
            board = new Player[8][8];
            for (int row = 0; row < board.length; row++) {
                for (int col = 0; col < board[row].length; col++) {
                    board[row][col] = Player.NONE;
                }
            }

            MouseAdapter mouseHandler = new MouseAdapter() {

                @Override
                public void mouseMoved(MouseEvent e) {
                    hoverColumn = getColumnAt(e.getPoint());
                    repaint();
                }

                @Override
                public void mouseExited(MouseEvent e) {
                    hoverColumn = -1;
                    repaint();
                }

                @Override
                public void mouseClicked(MouseEvent e) {
                    if (hoverColumn > -1) {
                        addPieceTo(hoverColumn);
                        repaint();
                    }
                }

            };

            addMouseMotionListener(mouseHandler);
            addMouseListener(mouseHandler);
        }

        public void addChangeListener(ChangeListener listener) {
            listenerList.add(ChangeListener.class, listener);
        }

        public void removeChangeListener(ChangeListener listener) {
            listenerList.add(ChangeListener.class, listener);
        }

        public void setPlayer(Player player) {
            this.player = player;
        }

        protected void addPieceTo(int col) {
            boolean added = false;
            if (col >= 0 && col < board[0].length) {
                for (int row = 0; row < board.length; row++) {
                    if (board[row][col] != Player.NONE) {
                        if (row >= 0) {
                            board[row - 1][col] = player;
                            added = true;
                        }
                        break;
                    }
                }
            }
            if (!added) {
                if (board[0][col] == Player.NONE) {
                    board[board.length - 1][col] = player;
                    added = true;
                }
            }
            if (added) {
                fireStateChanged();
            }
            repaint();
        }

        protected void fireStateChanged() {
            ChangeListener[] listeners = listenerList.getListeners(ChangeListener.class);
            if (listeners != null && listeners.length > 0) {
                ChangeEvent evt = new ChangeEvent(this);
                for (ChangeListener listener : listeners) {
                    listener.stateChanged(evt);
                }
            }
        }

        protected int getColumnAt(Point p) {

            int size = Math.min(getWidth() - 1, getHeight() - 1);

            int xOffset = (getWidth() - size) / 2;
            int yOffset = (getHeight() - size) / 2;

            int padding = getBoardPadding();

            int diameter = (size - (padding * 2)) / 8;

            int xPos = p.x - xOffset;
            int column = xPos / diameter;

            return Math.min(Math.max(0, column), board[0].length - 1);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        protected int getBoardPadding() {
            return 10;
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
            g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);

            int size = Math.min(getWidth() - 1, getHeight() - 1);

            int xOffset = (getWidth() - size) / 2;
            int yOffset = (getHeight() - size) / 2;

            g2d.fill(new RoundRectangle2D.Double(xOffset, yOffset, size, size, 20, 20));

            int padding = getBoardPadding();

            int diameter = (size - (padding * 2)) / 8;

            for (int row = 0; row < board.length; row++) {
                int yPos = (yOffset + padding) + (diameter * row);
                for (int col = 0; col < board[row].length; col++) {
                    int xPos = (xOffset + padding) + (diameter * col);
                    switch (board[row][col]) {
                        case RED:
                            g2d.setColor(Color.RED);
                            break;
                        case BLUE:
                            g2d.setColor(Color.BLUE);
                            break;
                        default:
                            g2d.setColor(getBackground());
                            break;
                    }
                    g2d.fill(new Ellipse2D.Double(xPos, yPos, diameter, diameter));
                }
            }

            if (hoverColumn > -1) {
                int yPos = (yOffset + padding) + (diameter * 0);
                int xPos = (xOffset + padding) + (diameter * hoverColumn);
                if (player != null) {
                    switch (player) {
                        case RED:
                            g2d.setColor(Color.RED);
                            break;
                        case BLUE:
                            g2d.setColor(Color.BLUE);
                            break;
                        default:
                            g2d.setColor(getBackground());
                            break;
                    }
                    g2d.fill(new Ellipse2D.Double(xPos, yPos, diameter, diameter));
                }

            }

            g2d.dispose();
        }

    }

}
 类似资料:
  • 我在java中创建了一个2D游戏,并试图将其分辨率提高到60 fps,分辨率为1920x1080像素。我的游戏逻辑在不到1毫秒的时间内表现良好。但是绘图需要超过10毫秒。在我相当强大的台式机(英特尔i5-4670K@3.40Ghz)上这可能就足够了,但是在我的笔记本电脑(英特尔i5-6300HQ@2.30Ghz)上,游戏已经慢了很多。绘图分为两个主要步骤: > 将游戏的每个部分绘制到Buffere

  • 我正在实验室工作,这是一个连接四的游戏。我在基本概念方面遇到了麻烦,例如类如何相互通信,如何使用私有实例变量,如何使用ArrayList,如何比较JLabels或将它们设置为可比较的东西...... 为了给出一个简单的分类,我有四个类:GUI、游戏、玩家、名称 我可以通过使用两个四循环来创建GUI,游戏是一个7列6块的网格。这些作品是图像, 例如,表示空白点。 图形用户界面是基于一个JFrame,

  • 问题内容: 我正在用Java编写游戏,现在是Swing + JOGL-一个带有GLCanvas的JFrame。 我使用etc.事件()处理输入,但似乎无法正常工作: 当我同时按下3个以上的键时,它们无法正确注册 -显然这是键盘的错误,我必须找到替代的控制方案。 窗口丢失后,重新获得焦点,输入完全停止工作… 我究竟做错了什么? 有没有更好的方法来处理Java中的键盘输入? (除非我别无选择,否则我不

  • 我已经编写了以下代码 它运行并设置动画,但是它的设置动画的方式与我引用的Javascript代码不同,可以在这里找到Javascript代码http://codepen.io/anon/pen/ZYQoQZ 任何有助于理解原因的帮助都是非常感谢的

  • 简单说一下自己的情况:   我是一个已经在职两年多的系统策划一直都有负责研发项目,有一个上线项目,不是什么大流水的项目,但工作内容也是比较了解了,也996过也不加班过,但是说实话的话进步最大的那段时间还是加班的那段时间,这个看个人吧,因为我如果过得太舒服的话,就会比较懒散。   最近因为一些互联网寒潮的缘故被裁员了所以说找了一个多月的工作非常的不容易,基本上就是面试连轴转,真的太累了。 坐标:成都

  • When building your games, you'll place lots of different objects in your game world. 当你建立了游戏,你就要放置许多不同的对象到你的游戏世界中。 Focusing 聚焦 It can be useful to focus the Scene View Camera on an object before manip