IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> Java JUI打字小游戏项目 -> 正文阅读

[Java知识库]Java JUI打字小游戏项目

JUI打字游戏

效果展示

游戏页面
在这里插入图片描述
在这里插入图片描述

暂停图
在这里插入图片描述

游戏结束页面
在这里插入图片描述

素材

链接: 单词素材
提取码: 95a8
链接:图片素材
提取码: 7s1u

代码实现

子弹类:
package www.git;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

/*
 *@author Liu
 *@Description 创建子弹类
 *@data 2021/12/8
 */
public class Bullet {
    private int x;
    private int y;
    private int speed;
    public static BufferedImage image;

    static {
        try {
            image = ImageIO.read(Bullet.class.getResourceAsStream("1bullet.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void step() {
        this.y -= this.speed;
    }


    public Bullet(int x) {
        this.x = x;
        this.y = Typer.HEIGHT;
        this.speed = 12;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public int getSpeed() {
        return speed;
    }

    public void setSpeed(int speed) {
        this.speed = speed;
    }

    public BufferedImage getImage() {
        return image;
    }

    public void setImage(BufferedImage image) {
        this.image = image;
    }

}
单词课程类
```java
package www.git;

import java.io.*;
import java.util.LinkedList;
import java.util.List;

/*
 *@author Liu
 *@Description
 *@data 2021/12/7
 */
public class Course {
    private String name;//第一行的内容
    private String content;//第二行的内容
    private List<Word> list;
    private int index;
    public Course(File file, int index) throws IOException {
        if (!file.exists()) {
            System.out.println("文件不存在!");
            return;
        }
        InputStreamReader isr = new InputStreamReader(new FileInputStream(file));
        BufferedReader br = new BufferedReader(isr);
       this.name=br.readLine().trim();
       this.content=br.readLine().trim();
       this.list=new LinkedList<>();
        String line=null;
        while ((line=br.readLine()) != null) {
            line=line.trim();
            if (line.length()!=0) {
                String[] s = line.trim().split("\\s+");
                Word word = new Word(s[1], s[0]);
                this.list.add(word);
            }
        }
        this.index=index;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public List<Word> getList() {
        return list;
    }

    public void setList(List<Word> list) {
        this.list = list;
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    @Override
    public String toString() {
        return index+"."+this.name;
    }
}

单词类

package www.git;

import java.util.Random;

/*
 *@author Liu
 *@Description
 *@data 2021/12/7
 */
public class Word {
    private int x;
    private int y;
    private int width;
    private int height;
    private int speed;
    private String chinese;
    private String english;
    private boolean match;

    public boolean isMatch() {
        return match;
    }

    public void setMatch(boolean match) {
        this.match = match;
    }

    public Word(String chinese, String english) {
        this.chinese = chinese;
        this.english = english;
        int max = Math.max(chinese.length() * 2, english.length());
        this.width = max * 16;//字号*两者的较大值
        this.height = 2 * 16 + 2;
        Random random = new Random();
        this.x = random.nextInt(800 - this.width);//窗口的宽度
        this.y = -this.height;
        this.speed = random.nextInt(3) + 1;
    }
    public void move(){
        this.y+=this.speed;
    }
    @Override
    public String toString() {
        return "Word{" +
                "x=" + x +
                ", y=" + y +
                ", width=" + width +
                ", height=" + height +
                ", speed=" + speed +
                ", chinese='" + chinese + '\'' +
                ", english='" + english + '\'' +
                '}';
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public int getWidth() {
        return width;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public int getSpeed() {
        return speed;
    }

    public void setSpeed(int speed) {
        this.speed = speed;
    }

    public String getChinese() {
        return chinese;
    }

    public void setChinese(String chinese) {
        this.chinese = chinese;
    }

    public String getEnglish() {
        return english;
    }

    public void setEnglish(String english) {
        this.english = english;
    }
}

功能类

package www.git;


import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.Timer;

/*
 *@author Liu
 *@Description
 *@data 2021/12/7
 */
public class Typer extends JPanel {
    public static final int WIDTH = 800;//宽
    public static final int HEIGHT = 534;//高
    public static final int FONT_SIZE = 16;//字号
    private static final int START = 1;//游戏状态
    private static final int PAUSE = 2;
    private static final int RUNNING = 3;
    private static final int GAMEOVER = 4;
    //表示游戏状态
    private int state = START;
    public static BufferedImage logo;
    public static BufferedImage background;
    public static BufferedImage pause;
    public static BufferedImage gameover;
    private List<Bullet> bullets;//创建子弹的对象

    private Course[] courses;
    private Course currentCourse;

    private List<Word> currentWord;
    private List<Word> words;//掉落的对象

    private StringBuffer buffer;//键盘键入的字符

    //logo图片
    static {
        try {
            logo = ImageIO.read(Typer.class.getResourceAsStream("1typer.png"));
            background = ImageIO.read(Typer.class.getResourceAsStream("1bg.png"));
            pause = ImageIO.read(Typer.class.getResourceAsStream("1pause.png"));
            gameover = ImageIO.read(Typer.class.getResourceAsStream("1gameover.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Typer() throws IOException {
        File file = new File("./dic");
        File[] files = file.listFiles();
        this.courses = new Course[files.length];
        for (int i = 0; i < files.length; i++) {
            this.courses[i] = new Course(files[i], i + 1);
        }
        this.currentCourse = this.courses[0];
        this.currentWord = this.currentCourse.getList();
        this.words = new LinkedList<>();
        this.buffer = new StringBuffer();
        this.bullets = new LinkedList<>();
    }

    public static void main(String[] args) {

        JFrame frame = new JFrame();
        frame.setSize(WIDTH, HEIGHT);
        frame.setTitle("打字游戏");
        frame.setIconImage(logo);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭窗口,关闭程序

        frame.setLocationRelativeTo(null);//设置窗口位置
        //创建画板对象
        Typer typer = null;
        try {
            typer = new Typer();
        } catch (IOException e) {
            e.printStackTrace();
        }
        frame.add(typer);
        frame.setVisible(true);//设置窗口可见,并调用paint方法
        typer.startAction();
        //添加键盘监听
        Typer.Key l = typer.new Key();
        frame.addKeyListener(l);
        typer.addKeyListener(l);

    }

    class Key extends KeyAdapter {
        @Override
        public void keyPressed(KeyEvent e) {
            char c = e.getKeyChar();
            System.out.println(c);
            int code = e.getKeyCode();
            if (code == KeyEvent.VK_F1 && state == RUNNING) {
                state = PAUSE;
            } else if (code == KeyEvent.VK_C && state == PAUSE) {
                state = RUNNING;
            } else if (code == KeyEvent.VK_ESCAPE) {
                state=GAMEOVER;
                System.out.println("游戏结束!");
                System.exit(0);
            } else {
                if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9') {
                    buffer.append(c);
                } else if (c == '.') {
                    buffer.append(c);
                } else if (code == KeyEvent.VK_BACK_SPACE) {
                    if (buffer.length() > 0) {
                        buffer.deleteCharAt(buffer.length() - 1);
                    }
                }
            }
        }
    }

    public void startAction() {
        this.currentCourse = (Course) JOptionPane.showInputDialog(this, "选择", "选择框",
                JOptionPane.PLAIN_MESSAGE, new ImageIcon(logo),
                this.courses,
                this.currentCourse
        );
        if (this.currentCourse == null) {
            System.exit(0);
        }
        state = RUNNING;
        //添加定时器
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                switch (state) {
                    case RUNNING:
                        enterAction();
                        moveAction();
                        //改变单词状态
                        changeState();
                        bulletMove();
                        remove();
                        gameOver();
                        break;

                }
                repaint();
            }
        }, 5, 25);
    }
    int count=0;
    public void gameOver(){
        for (Word word : words) {
            if (word.getY() >= HEIGHT) {
                count++;
                if (count >= 3) {
                    state=GAMEOVER;
                }
            }
        }
    }
    //碰撞
    public int score = 0;

    public void remove() {
        Iterator<Bullet> iterator = bullets.iterator();
        while (iterator.hasNext()) {
            Bullet next = iterator.next();
            boolean flag = wordAction(next);
            if (flag) {
                iterator.remove();
                score += 10;
            }
        }
    }

    private boolean wordAction(Bullet next) {
        Iterator<Word> it = words.iterator();
        while (it.hasNext()) {
            Word word = it.next();
            if (word.isMatch()) {
                if (word.getX() == next.getX() && word.getY() <= next.getY()
                        && word.getY() + word.getHeight() >= next.getY()) {
                    it.remove();
                    return true;
                }
            }
        }
        return false;
    }


    //计算分数
    public void bulletMove() {
        for (Bullet bullet : bullets) {
            bullet.step();
        }
    }

    int moveIndex = 0;

    //改变单词状态
    public void changeState() {
        for (Word word : words) {
            if (word.getEnglish().equals(buffer.toString())) {
                word.setMatch(true);
                buffer = new StringBuffer();
                bullets.add(new Bullet(word.getX()));
            }
        }
    }

    public void moveAction() {
        if (moveIndex++ % 2 == 0) {
            for (Word w : words) {
                w.move();
            }
        }
    }

    int enterIndex = 0;

    public void enterAction() {
        if (enterIndex++ % 20 == 0) {
            words.add(this.currentWord.remove(0));
        }
    }

    @Override
    public void paint(Graphics g) {
        //画背景图
        g.drawImage(background, 0, 0, null);
        switch (state) {
            case RUNNING:
                for (Word word1 : words) {
                    if (word1.isMatch()) {
                        g.setColor(Color.YELLOW);
                        g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, FONT_SIZE));
                        g.drawString(word1.getChinese(), word1.getX(), word1.getY());
                        g.drawString(word1.getEnglish(), word1.getX(), word1.getY() + FONT_SIZE);
                    } else {
                        g.setColor(Color.red);
                        g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, FONT_SIZE));
                        g.drawString(word1.getChinese(), word1.getX(), word1.getY());
                        g.drawString(word1.getEnglish(), word1.getX(), word1.getY() + FONT_SIZE);
                        if (word1.getEnglish().startsWith(buffer.toString())) {
                            g.setColor(Color.WHITE);
                            g.drawString(buffer.toString(), word1.getX(), word1.getY() + FONT_SIZE);
                        }
                    }
                }

//        g.drawString(str,270,475);
                g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 20));
                g.setColor(Color.BLUE);
                g.drawString(buffer.toString(), 270, 475);
                //给word添加状态,匹配过还是未匹配过
                for (Bullet bullet : bullets) {
                    g.drawImage(Bullet.image, bullet.getX(), bullet.getY(), null);
                }
                g.setFont((new Font(Font.DIALOG, Font.BOLD, 20)));
                g.setColor((Color.CYAN));
                g.drawString("score", 10, 25);
                g.drawString(String.valueOf(score), 80, 25);
                break;
            case PAUSE:
                g.drawImage(pause, 0, 0, null);
                break;
            case GAMEOVER:
                g.drawImage(gameover, 0, 0, null);
                g.setFont((new Font(Font.DIALOG, Font.BOLD, 40)));
                g.setColor((Color.BLUE));
                g.drawString("游戏结束",320,200);
                g.drawString("score", 340, 240);
                g.drawString(String.valueOf(score), 340, 280);
                break;
        }
    }
}
  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2021-12-09 11:31:13  更:2021-12-09 11:31:37 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 6:31:08-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码