1

Hello Together 最近我了解了 keyListeners,所以我尝试用它编写一个小游戏。现在它已经完成了,但我想实现一些额外的功能。我想到了一个计时器左右。所以你只能玩 1 分钟左右.. 之后它会计算你的分数并将其添加到 higescores 但我不知道我怎么能做到这一点。如果有人可以帮助我,我会很高兴。谢谢。

现在我所有的代码都在一个类中。这就是我得到的:

import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;

public class Main extends JPanel implements KeyListener {
    private static final long serialVersionUID = 1L;

    private static int x = 350;
    private static int y = 350;
    private static int punkte = 0;
    private static boolean isThere = true;
    private static int apx = 250;
    private static int apy = 350;

    public Main() {
        addKeyListener(this);
    }

    public void keyPressed(KeyEvent evt) {
        int keyCode = evt.getKeyCode();
        int d = 0;

        if (evt.isShiftDown())
            d = 5;
        else
            d = 1;

        if (keyCode == KeyEvent.VK_LEFT) {
            x -= d;
        } else if (keyCode == KeyEvent.VK_RIGHT) {
            x += d;
        } else if (keyCode == KeyEvent.VK_UP) {

            y -= d;
        } else if (keyCode == KeyEvent.VK_DOWN) {
            y += d;
        }
    }

    public void keyReleased(KeyEvent evt) {
    }

    public void keyTyped(KeyEvent evt) {
    }

    public boolean isFocusTraversable() {
        return true;
    }

    public void paint(Graphics g) {

        int c1 = (int) (Math.floor(Math.random() * 254) + 1);
        int c2 = (int) (Math.floor(Math.random() * 254) + 1);
        int c3 = (int) (Math.floor(Math.random() * 254) + 1);

        int cx1 = (int) (Math.floor(Math.random() * 254) + 1);
        int cx2 = (int) (Math.floor(Math.random() * 254) + 1);
        int cx3 = (int) (Math.floor(Math.random() * 254) + 1);

        int x1 = (int) (Math.floor(Math.random() * 680) + 1);
        int y1 = (int) (Math.floor(Math.random() * 600) + 1);

        String punkteStr = String.valueOf(punkte);

        g.setColor(new Color(c1, c2, c3));

        g.fillRect(x, y, 50, 50);
        g.setFont(new Font("Arial", Font.BOLD, 50));
        g.drawString(punkteStr, 10, 40);
        g.setColor(new Color(cx1, cx2, cx3));
        if (isThere) {

            g.fillOval(apx, apy, 50, 50);
        }
        if (x == apx && y == apy) {
            punkte++;
            apx = (int) (Math.floor(Math.random() * 680) + 1);
            apy = (int) (Math.floor(Math.random() * 600) + 1);
        }
        repaint();
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setTitle("Lightning Catcher v1 by Jonas");
        frame.setSize(700, 650);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBackground(Color.BLACK);

        Container contentPane = frame.getContentPane();
        contentPane.add(new Main());
        frame.setVisible(true);
    }
}
4

0 回答 0