Java 屏幕蛇碰撞问题

Java 屏幕蛇碰撞问题,java,swing,double,screen,Java,Swing,Double,Screen,我是一个自学成才的程序员,我编写屏幕蛇是为了好玩。我使用的不是整数来存储蛇或苹果的位置,而是双精度。当蛇穿过苹果时,我有一个问题。当发生碰撞时,代码不会记录它发生了碰撞。我假设这是因为它们的X和Y值可能是.1。我已经试着修复这个问题两周了,但一直没有成功。对不起,如果我的代码有点乱。我不知道你们到底需要从代码中得到什么,所以我发布了所有的代码。我也非常感谢你的帮助!谢谢 主要类别: Random random = new Random(); Dimension screenSize = Tool

我是一个自学成才的程序员,我编写屏幕蛇是为了好玩。我使用的不是整数来存储蛇或苹果的位置,而是双精度。当蛇穿过苹果时,我有一个问题。当发生碰撞时,代码不会记录它发生了碰撞。我假设这是因为它们的X和Y值可能是.1。我已经试着修复这个问题两周了,但一直没有成功。对不起,如果我的代码有点乱。我不知道你们到底需要从代码中得到什么,所以我发布了所有的代码。我也非常感谢你的帮助!谢谢

主要类别:

Random random = new Random();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double ScreenW = screenSize.getWidth();
double ScreenH = screenSize.getHeight();

int ScreenX = (int)Math.round(ScreenW);
int ScreenY = (int)Math.round(ScreenH);

JFrame frame = new JFrame();

double x = 1, y = 1;
int size = 5;
int ticks;

private int columnCount = 25;
private int rowCount = 15;

double a = (ScreenW / columnCount) - 1;
double b = (ScreenH / rowCount) - 1;

private Key key;
private List<Rectangle2D> cells;
private Point selectedCell;


boolean up = false;
boolean down = false;
boolean right = true;
boolean left = false;
boolean running = true;
private Thread thread;

private BodyP p;
private ArrayList<BodyP> snake;

private Apple apple;
private ArrayList<Apple> apples;

double width = screenSize.width;
double height = screenSize.height;
double cellWidth = width / columnCount;
double cellHeight = height / rowCount;

double xOffset = (width - (columnCount * cellWidth)) / 2;
double yOffset = (height - (rowCount * cellHeight)) / 2;

public Max_SnakeGame() throws IOException {

    System.out.println(screenSize);
    System.out.println(a + "," + b);
    System.out.println(ScreenH + b);
    System.out.println(ScreenW + a);

    frame.getContentPane().add(new Screen());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setUndecorated(true);
    frame.setBackground(new Color(0, 0, 0, 0));
    frame.setLocationRelativeTo(null);
    frame.setMaximumSize(screenSize);
    frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
    frame.setVisible(true);
    Image img = Toolkit
            .getDefaultToolkit()
            .getImage(
                    "C:/Users/Max/My Documents/High School/Sophomore year/Graphic Disign/People art/The Mods Who Tell Pointless Stories.jpg");
    frame.setIconImage(img);

}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            try {
                new Max_SnakeGame();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });
}

public class Screen extends JPanel implements Runnable {

    private static final long serialVersionUID = 1L;

    public Screen() {
        key = new Key();
        addKeyListener(key);
        setMaximumSize(screenSize);
        setOpaque(false);
        setBackground(new Color(0, 0, 0, 0));
        setFocusable(true);
        snake = new ArrayList<BodyP>();
        apples = new ArrayList<>();
        start();
    }

    public void start() {
        running = true;
        thread = new Thread(this);
        thread.start();
    }

    public void run() {
        while (running) {
            MoveUpdate();
            repaint();

        }
    }

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        repaint();
        Graphics2D g2d = (Graphics2D) g.create();
        cells = new ArrayList<>(columnCount * rowCount);

        if (cells.isEmpty()) {
            for (int row = 0; row < rowCount; row++) {
                for (int col = 0; col < columnCount; col++) {
                    Rectangle2D cell = new Rectangle2D.Double(xOffset
                            + (col * cellWidth), yOffset
                            + (row * cellHeight), cellWidth, cellHeight);
                    cells.add(cell);
                }
            }
        }

        g2d.setColor(Color.GRAY);
        for (Rectangle2D cell : cells) {
            g2d.draw(cell);
        }

        for (int i = 0; i < snake.size(); i++) {
            snake.get(i).draw(g);
        }
        for (int i = 0; i < apples.size(); i++) {
            apples.get(i).draw(g);
        }

    }

}

private class Key implements KeyListener {
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();

        if (keyCode == KeyEvent.VK_RIGHT && !left) {
            up = false;
            down = false;
            right = true;
        }

        if (keyCode == KeyEvent.VK_LEFT && !right) {
            up = false;
            down = false;
            left = true;
        }

        if (keyCode == KeyEvent.VK_UP && !down) {
            left = false;
            right = false;
            up = true;
        }

        if (keyCode == KeyEvent.VK_DOWN && !up) {
            left = false;
            right = false;
            down = true;
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void keyReleased(KeyEvent e) {
        // TODO Auto-generated method stub

    }
}

public void MoveUpdate() {
    if (snake.size() == 0) {
        p = new BodyP(x, y, a, b);
        snake.add(p);
    }

    if (apples.size() == 0){
        double x1 = random.nextInt(25);
        double Ax = ((x1*a+x1+1)*10)/10;
        double y1 = random.nextInt(15);
        double Ay = ((y1*b+y1+1)*10)/10;
        double Afx = Math.round(Ax);
        double Afy = Math.round(Ay);


        System.out.println("Ax:"+Afx);
        System.out.println("Ay:"+Afy);


        apple = new Apple(Ax, Ay, a, b);
        apples.add(apple);

        }

    for(int i = 0; i < apples.size(); i++) {
        if(Math.round(x)-1 == apples.get(i).getx() || Math.round(x) == apples.get(i).getx() && Math.round(y)== apples.get(i).gety() || Math.round(y)-1 == apples.get(i).gety()) {
            size++;
            apples.remove(i);
            i--;
        }
    }

    ticks++;
    if (ticks > 2500000) {
        if (up == true) {
            if (y <= 2) {
                y = ScreenH - b;
                System.out.println("Y:" + y);

            } else {
                y -= b + 1;
                System.out.println("Y:" + y);
            }
        }

        // down loop
        else if (down == true) {
            if (y >= ScreenH - b) {
                y = 1;
                System.out.println("Y:" + y);

            }

            else {
                y += b + 1;
                System.out.println("Y:" + y);
            }
        }

        // left loop
        else if (left == true) {
            if (x <= 1) {
                x = ScreenW - a;
                System.out.println("X:" + x);
            }

            else {
                x -= a + 1;
                System.out.println("X:" + x);

            }
        }

        // right loop
        else if (right == true) {
            if (x >= ScreenW - a) {
                x = 1;
                System.out.println("X:" + x);
            }

            else {
                x += a + 1;
                System.out.println("X:" + x);
            }
        }
        ticks = 0;

        p = new BodyP(x, y, a, b);
        snake.add(p);
        // rect.setFrame(x, y, a, b);
        if (snake.size() > size) {
            snake.remove(0);
        }
    }
}

}
苹果类:

public class Apple {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double ScreenW = screenSize.getWidth();
double ScreenH = screenSize.getHeight();

double x = 1, y = 1;

private int columnCount = 25;
private int rowCount = 15;

double a = (ScreenW / columnCount) - 1;
double b = (ScreenH / rowCount) - 1;

public Apple(double x, double y, double a, double b) {
    this.x = x;
    this.y = y;
    this.a = a;
    this.b = b;
}
public void MoveUpdate(){

}
 public void draw(Graphics g) {
 Graphics2D g2 = (Graphics2D) g;
 Rectangle2D rect = new Rectangle2D.Double(x, y, a, b);
 g.setColor(Color.RED);
 g2.fill(rect); 
 }

public double getx() {
    return x;
}

public void setx(double x) {
    this.x = x;
}

public double gety() {
    return y;
}

public void sety(double y) {
    this.y = y;
}

}

如果您认为这是由于舍入误差造成的,请使用欧几里德距离并与所需公差进行比较:

final double tolerance = 1.0; // or whatsoever

double dx = snake.x - apple.x;
double dy = snake.y - apple.y;
if ( dx*dx + dy*dy < tolearance * tolerance )  ...
最终双公差=1.0;//或者别的什么
双dx=snake.x-apple.x;
双dy=snake.y-apple.y;
如果(dx*dx+dy*dy

我建议实现类似于
Point.distanceTo(Point)
的方法,以方便使用。

我回家后会尝试!我现在在学校(历史课…booorring!)。我会让你知道这是否管用。只要把它放进去,它就管用了!:D非常感谢!我从来没有想过这一点,当我开始为蛇撞到它的身体添加碰撞检测时,我肯定会注意到这个功能。我真的很感谢你的帮助!
final double tolerance = 1.0; // or whatsoever

double dx = snake.x - apple.x;
double dy = snake.y - apple.y;
if ( dx*dx + dy*dy < tolearance * tolerance )  ...