java - setBackground 搞乱了 Thread.sleep

标签 java swing animation graphics

我尝试了不同的方法为这款贪吃蛇游戏制作了两种背景,一种黑色用于菜单,一种白色用于游戏台词。我为此找到的最佳解决方案是使用 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(...)在绘画方法中,这可能会触发重绘,这通常不会有太大问题......
  • 但是您的程序逻辑在您的绘画方法覆盖中被调用,这是一个主要问题。当您发现您无法完全或部分控制何时或什至是否调用绘画方法或多久调用一次,因此其中包含程序逻辑可能是致命的,并且可能导致您的程序完全故障由于 setBackground 调用。
  • 你也是while (true)循环和 Thread.sleep(...)调用您的 Swing 代码,如果 Swing 代码是在 Swing 事件线程上启动的(应该完成的),这些代码可能会完全卡住您的 GUI。
  • 您重写了 paint 方法,但在其中调用了 super paintComponent,这是一个不匹配的 super 方法,这将破坏 Swing 图形链,可能会导致严重的绘画不规则性。

建议:

  • 首先,也是最重要的,将所有程序逻辑置于所有绘画方法之外。
  • 删除所有Thread.sleep(...)电话和while (true)循环。
  • 使用 Swing Timer,并在 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/

相关文章:

java - Spinner 获取其项目值(而不是位置)

javascript - 如何创建 SVG 光标跟踪元素?

java - 带有 JCombobox 编辑器的 JTable : handle mouse clicks

java - 如何从应用程序服务器(EJB)通知(或发送消息) Swing 客户端?

java - 如何使密码在 Swing 文本字段中不可见?

java - Java Swing 应用程序中屏幕特定部分上的持续类似对话框的功能 - JDialog 功能是正确的选择吗?

java - Timer util 不会为 JLabel 添加新行

JavaFX PathTransition 动画未播放

firefox - Angular 2 动画/过渡仅适用于 chrome?

java - 将 XML 文件与其他 PDF 文件一起附加在 zip 文件中