Java打字游戏

贴吧上看到有人做Java打字游戏,但是问题多多,我把他的程序拿来大改一番,算是半个原创吧。键盘按出对应字母,则该字母消失并随机产生新字母。

如果加些贴图润色一下可以更美观,学习计划紧,暂时不美化了。

Java打字游戏_第1张图片

代码如下:

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class LetterGame extends JFrame {
    public static final int WIDTH = 300;
    public static final int HEIGHT = 400;

    public LetterGame(String gameName){
        super(gameName);
        MyJPanel mp = new MyJPanel();
        Thread t = new Thread(mp);
        t.start();
        add(mp);
        addKeyListener(mp);
        setVisible(true);
        setSize(WIDTH, HEIGHT);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new LetterGame("LetterGame");
    }
}
class MyJPanel extends JPanel implements Runnable,KeyListener {
    int[] x = new int[10];
    int[] y = new int[10];
    char[] c = new char[10];
    public MyJPanel(){
        arrayRandom();     
    }

    private void arrayRandom(){
        for(int i=0;i<10;i++){
            arraySingleRandom(i);
        }
    }

    private void arraySingleRandom(int i){
        x[i] = (int)(Math.random()*LetterGame.WIDTH);
        y[i] = (int)(Math.random()*LetterGame.HEIGHT*0.7);
        c[i] = (char)(Math.random()*26+97);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setFont(new Font("微软雅黑", Font.BOLD, 20));
        for(int i=0;i<10;i++) g.drawString(new Character(c[i]).toString(), x[i], y[i]);
    }

    @Override
    public void run() {
        while(true){
            for(int i = 0;i<10;i++) y[i]++;
            repaint();
            try {
                Thread.sleep(600);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {}

    @Override
    public void keyPressed(KeyEvent e) {
        char keyc = e.getKeyChar();
        for(int i = 0; i < c.length; i++){
            if (c[i] == keyc){
                arraySingleRandom(i);
                return;
            }
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {}

}


版权声明:本文为博主原创文章,未经博主允许不得转载。

转载于:https://www.cnblogs.com/kinglearnjava/p/4883309.html

你可能感兴趣的:(Java打字游戏)