我尝试了多种方法为该蛇游戏制作两个背景,一个为菜单黑色,另一个为游戏线条白色。我为此找到的最佳解决方案是使用setBackground。但是当我运行游戏时,Thread.sleep陷入混乱,现在这条蛇走得非常快。为了解决这个问题,我将多个值放入Thread.sleep中,但是无论值如何,蛇都以相同的速度行进。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.Thread;
import java.util.Random;

public class Snake extends JPanel implements KeyListener, MouseListener{
    public  boolean right = false;
    public  boolean left = false;
    public  boolean up = false;
    public  boolean down = false;

    public int snakex[] = new int[10000000];
    public int snakey[] = new int[10000000];
    public int snakeLength = 0;

    public int applex;
    public int appley;

    public int buttonX = 150;
    public int buttonY = 125;

    public boolean appleEaten = true;

    public static boolean reset = false;
    public static boolean ingame = false;
    public static boolean menu = true;

    public static int speed = 200;

    public void forLogic(){
        for(int i = snakeLength; i > 1; i--){
            if(snakeLength > 4 &&  snakex[0] ==  snakex[i] && snakey[0] == snakey[i]){
                System.out.println("You Loose \n Your Score was: " + snakeLength);
                ingame = false;
            }
        }

        Movement();

        if(snakex[0] >= 30*20){
            snakex[0] = 0;
        }
        if(snakex[0] < 0){
            snakex[0] = 29*20;
        }
        if(snakey[0] >= 25*20){
            snakey[0] = 0;
        }
        if(snakey[0] < 0){
            snakey[0] = 24*20;
        }

        if(snakex[0] == applex*20 && snakey[0] == appley*20) {
            appleEaten = true;
            snakeLength++;
            //System.out.println(snakeLength);
        }

        if(appleEaten){
            appleLocation();
            appleEaten = false;
        }
    }

    public void appleLocation(){
        boolean goodToGo = false;
        Random rand = new Random();
        while(!goodToGo){
            applex = rand.nextInt(30);
            appley = rand.nextInt(25);
            boolean checker = false;
            for(int i = snakeLength; i > 0; i--) {
                if (applex == snakex[i]||appley == snakey[i]) {
                    checker = true;
                }
            }
            if(!checker){goodToGo = true;}
        }
    }

    public void Movement(){
        if(reset){
            left = false;
            right = false;
            up = false;
            down = false;

            snakex[0] = 0;
            snakey[0] = 0;
            snakeLength = 1;
            appleLocation();
            reset = false;
        }

        if(right){
            snakex[0] += 20;
        }
        if(left){
            snakex[0] -= 20;
        }
        if(up){
            snakey[0] -= 20;
        }
        if(down){
            snakey[0] += 20;
        }
    }

    public void mouseEntered(MouseEvent e){}

    public void mouseExited(MouseEvent e){}

    public void mousePressed(MouseEvent e){
        int mouseX = e.getX();
        int mouseY = e.getY();
        if(mouseX > buttonX && mouseX < buttonX + 300 && mouseY > buttonY && mouseY < buttonY + 75){
            ingame = true;
        }
    }

    public void mouseReleased(MouseEvent e){}

    public void mouseClicked(MouseEvent e){}

    public void keyTyped(KeyEvent e) {}

    public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode();
        if(key == 39 && !left) {
            right = true;
            up = false;
            down = false;
        }
        if(key == 37 && !right){
            left = true;
            up = false;
            down = false;
        }
        if(key == 38 && !down){
            up = true;
            left = false;
            right = false;
        }
        if(key == 40 && !up){
            down = true;
            left = false;
            right = false;
        }
        if(key == 82){
            reset = true;
        }
    }

    public void keyReleased(KeyEvent e) {}

    @SuppressWarnings("serial")
    public void paint(Graphics g) {
        super.paintComponent(g);
        if(menu){
            setBackground(Color.BLACK);
            g.setColor(Color.green);
            g.setFont(new Font("Courier New", Font.BOLD, 50));
            g.drawString("Snake Game", 150, 50);
            g.drawRect(buttonX, buttonY, 300, 75);
            g.setFont(new Font("Courier New", Font.BOLD, 40));
            g.drawString("PLAY", 250, 175);
        }
        if(ingame) {
            setBackground(Color.WHITE);
            int x = 0;
            int y = 0;
            for (x = 0; x < 30; x++) {
                for (y = 0; y < 25; y++) {
                    g.setColor(Color.black);
                    g.fillRect(x * 20, y * 20, 19, 19);
                }
            }

            g.setColor(Color.red);
            g.fillOval(applex * 20, appley * 20, 19, 19);

            forLogic();

            g.setColor(Color.green);
            for (int i = snakeLength; i > 0; i--) {
                snakex[i] = snakex[(i - 1)];
                snakey[i] = snakey[(i - 1)];
                g.fillRect(snakex[i], snakey[i], 19, 19);
            }
        }
    }
    public static void main(String[] args) throws InterruptedException {
        JFrame jframe = new JFrame("Snake Game");
        Snake snake = new Snake();
        jframe.add(snake);
        snake.addMouseListener(snake);
        snake.addKeyListener(snake);
        jframe.setSize(615, 540);
        jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jframe.setFocusable(true);
        jframe.setVisible(true);
        snake.requestFocusInWindow();
        jframe.setLocationRelativeTo(null);

        while(true) {
            if (!menu) {
                ingame = true;
            }
            if (menu == ingame) {
                ingame = false;
            }

            if (menu) {
                snake.repaint();
            }

            if (ingame) {
                while (true) {
                    Thread.sleep(200);
                    snake.repaint();
                }
            }
        }
    }
}

最佳答案

很抱歉,这个代码有太多问题,很难知道从哪里开始。



问题:


首先,您要在绘画方法中调用setBackground(...),这有可能触发重新绘画,通常这不是什么大问题。
但是您需要从绘画方法覆盖范围内调用程序逻辑,这是一个主要问题。当您发现您没有完全或部分地控制何时,甚至何时调用paint方法或调用频率,因此在其中包含程序逻辑可能会致命,并可能导致程序完全故障由于setBackground调用。
您还需要在您的Swing代码中进行while (true)循环和Thread.sleep(...)调用,如果在Swing事件线程上启动了Swing代码(如预期的那样),这些代码将完全冻结GUI。
您将覆盖paint方法,但在其中调用superpaintComponent(一种不匹配的super方法),这将破坏Swing图形链,从而可能导致严重的绘制不规则。




意见建议:


首先,要获得所有绘画方法之外的所有程序逻辑。
删除所有Thread.sleep(...)调用和while (true)循环。
使用Swing计时器,并在Timer的ActionListener中推进游戏“滴答”。
在此“刻度”中,更新程序中关键字段的状态
然后调用repaint();
仅覆盖paintComponent方法
在此替代中,调用相同的super方法。
在paintComponent中,使用修改后的字段可以更改绘制的内容和方式。
在类的构造函数中一次调用setBackground(...)
在绘画方法中具有游戏逻辑。这表明使用第一条原则进行重写将非常有益:在游戏循环中使用Swing计时器,在Swing代码中不使用其他延迟代码,重写paintComponent并在重写中调用相同的super方法,从而将绘画与逻辑分离。
阅读教程。您正在猜测哪个在这里不起作用(如您所知)。




更多


考虑创建一些非GUI逻辑类。
这可以包括GridPoint表示网格上每个点的x和y位置
Grid类是GridPoint的二维数组,GridPoint是保存蛇在其中移动的宇宙的逻辑网格。
SnakePoints可以包含ArrayList<GridPoint>,该保持点在蛇上的逻辑位置。
最后一课还可以提供添加点,移动蛇和吃苹果的方法。
一个告诉SnakePoints前进一格的计时器

关于java - setBackground搞砸了Thread.sleep,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33557943/

10-13 03:45