0基础java初学者都能做的打字通小游戏? 内含源码解读和细致讲解!!

本文主要是介绍0基础java初学者都能做的打字通小游戏? 内含源码解读和细致讲解!!,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

打字通游戏实现

打字通游戏简介:主要应用了流与文件的知识,结合oop,对菜单功能,逐行比对功能,读取输入行功能,结果输出功能等进行了详细的实现,由于本游戏需要基于一定故事文本作为数据,建议先行下载资源后在控制台创建相对路径,便于游戏的实现。由于本案例只是作为知识巩固用,所以本文作者仅仅在控制台进行了源码的实现,并没有进行网页或者其他的设计。
代码:Java
工具:Idea编辑器(2019),notepad++

**本文关于故事文本的资源如下:
提取码:6666

结果展示

在这里插入图片描述
在这里插入图片描述
(数据测试的时候是复制粘贴所以数据异常 但是打字结果的呈现功能是没有问题的)

Story类

//由于读取每一个故事要按行读取,要通过继承Iterator接口规范迭代器行为
public class Story implements Iterator<String>{//注意:该类中的方法参数都是File Storyprivate List<String> list;//此处将集合命名为属性的原因见下图private Iterator<String> itLine;//将迭代器封装为类属性,仅供story类中按行读取的迭代操作使用(迭代器封装为属性常见于一次性操作)private String name;/*** 将文件名转化为故事名,初始化属性(即.log前面的部分,并且应该全部转化为大写,实例:happy_day.log -> Happy Day)* @param story 文件引用* @return*/private String parseName(File story){final StringBuilder sb = new StringBuilder();for (String s : story.getName().split("\\.")[0].split("_")) {if(sb.length()>0) {sb.append(" ");}sb.append(s.substring(0, 1).toUpperCase());sb.append(s.substring(1));}return sb.toString();}public Story(File story){name = parseName(story);list = new ArrayList<>();BufferedReader reader = null;try {reader = new BufferedReader(new FileReader(story),256);//FileReader的方法参数可以是文件或者是地址String line;while(null != (line = reader.readLine())){list.add(line);//迭代器按行读取到的line添加到集合属性中,从而完成数据读取}} catch (Exception e) {e.printStackTrace();}finally{if(null != reader){try {reader.close();} catch (IOException e) {e.printStackTrace();}}}}public String getName() {return name;}//重置迭代器:读取完一行之后迭代器回到行首public void reset(){itLine = list.iterator();}@Overridepublic boolean hasNext() {return itLine.hasNext();}@Overridepublic String next() {return itLine.next();}
}

图1.1

图1.1解释:最基础的数据存储方式就是按行的磁盘存储,但有一种常见的方式是通过集合存储之后再读取到文件之中,而优化则是直接将集合定义为该文件的属性,并且直接写到集合之中。而在代码中,story的数据类型即为File,用一个List来存储数据。

工具类

public class IO {// 输入工具private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));// 获取输入行public static String inputLine() throws IOException{return br.readLine();}// 输入指定范围内整数public static int inputIntIn(String title,int min,int max) throws IOException{String str;System.out.printf("请输入%s:",title);do{str = br.readLine();int value;if(str.matches("\\d+") && (value = Integer.parseInt(str))>=min && value<=max){return value;}System.out.printf("%s输入非法,必须是%d~%d之间的整数,请重新输入!",title,min,max);}while(true);}
}

输入分析类:根据行得到单词集合迭代器,利用迭代器进行结果统计和输出。

public class InputAnalysis {public static final String CHAR_COUNT = "CHAR_COUNT";public static final String WORD_COUNT = "WORD_COUNT";public static final String CORRECT_CHAR_COUNT = "CORRECT_CHAR_COUNT";public static final String CORRECT_WORD_COUNT = "CORRECT_WORD_COUNT";/*** 传入行,提取空格和标点符号分隔出来的单词,并获得单词集合的迭代器* @param line 每行内容* @return*/public static Iterator<String> lineToIterator(String line){//见下图List<String> words = new ArrayList<>();int fromIx = 0,toIx = 0;final char[] chars = line.toCharArray();while(toIx<chars.length){if(!Character.isLetterOrDigit(chars[toIx])){// 标点或者空格words.add(line.substring(fromIx,toIx));//如果是空格,则不需要读取空格if(Character.isSpaceChar(chars[toIx])){fromIx = toIx+1;}else {//如果是标点,则需要读取到标点fromIx = toIx;words.add(line.substring(fromIx,fromIx+1));fromIx++;}//fromIx需要移动到标点或者空格的下一位}toIx++;}return words.iterator();}/*** 利用上述方法分别获取故事行和输入行的迭代器,并进行比较* @param storyLine* @param inputLine* @return*/public Map<String,Integer> compare(String storyLine, String inputLine){Map<String,Integer> map = new HashMap<>(4);final Iterator<String> itStory = lineToIterator(storyLine);final Iterator<String> itInput = lineToIterator(inputLine);int charCount = 0, wordCount = 0,correctCharCount = 0,correctWordCount = 0;// wordCount和charCount应该是在遍历storyWord的过程中需要遍历的,而correctCharCount/correctWordCount即需要在遍历的过程中对inputWord中的进行计数。while(itStory.hasNext()){final String storyWord = itStory.next();wordCount += 1;charCount += storyWord.length();if(itInput.hasNext()){final String inputWord = itInput.next();if(inputWord.equals(storyWord)){correctWordCount+=1;correctCharCount+=inputWord.length();}}}map.put(CHAR_COUNT,charCount);map.put(WORD_COUNT,wordCount);map.put(CORRECT_CHAR_COUNT,correctCharCount);map.put(CORRECT_WORD_COUNT,correctWordCount);return map;}}

请添加图片描述

主类

public class YBPrinter {private List<Story> stories;//便于根据下标获取storypublic YBPrinter(String directory) {//创建文件内对象final File dir = new File(directory);//判定目录是否存在if(!dir.exists()){System.err.printf("故事目录%s不存在",directory);System.exit(0);}//获取目录下的内容列表final File[] files = dir.listFiles(f -> f.getName().matches("[a-z0-9]+(_[a-z0-9]+)*\\.log"));stories = new ArrayList<>(files.length);//遍历内容列表,构造出story,传入数组for (File file : files) {stories.add(new Story(file));}}//构建菜单private int chooseStory() throws IOException {System.out.println("======= 打字通小游戏 =======");System.out.println("\n可选文章如下:");int count = 0;final Iterator<Story> it = stories.iterator();//利用迭代器输出菜单while(it.hasNext()){System.out.printf("%d、%s\n",++count,it.next().getName());}//输入选择编号final int choice = IO.inputIntIn("请输入选项编号(输入0退出)", 0, stories.size());return choice;}public void start(){InputAnalysis analysis = new InputAnalysis();while(true){try{final int choice = chooseStory();if(choice==0){return;}final Story story = stories.get(choice-1);story.reset();//每获取一个story,都要重置迭代器int charCount = 0, wordCount = 0,correctCharCount = 0,correctWordCount = 0;long startTime = System.currentTimeMillis();// 获取输入行与故事行的分析结果while(story.hasNext()){final String storyLine = story.next();if(storyLine.equals("")){continue;}System.out.println(storyLine);final String inputLine = IO.inputLine();final Map<String, Integer> rst = analysis.compare(storyLine, inputLine);charCount += rst.get(InputAnalysis.CHAR_COUNT);wordCount += rst.get(InputAnalysis.WORD_COUNT);correctCharCount += rst.get(InputAnalysis.CORRECT_CHAR_COUNT);correctWordCount += rst.get(InputAnalysis.CORRECT_WORD_COUNT);}// 数据处理long stopTime = System.currentTimeMillis();// 将毫秒转化为分钟float timeConsumption = (stopTime-startTime)/60000.0f;float correctRate = correctWordCount*1.0f/wordCount;int charPerMinute = (int)Math.floor(correctCharCount/timeConsumption);System.out.printf("%s 本次打字结果如下:\n",story.getName());System.out.printf("总时间消耗:%.2f分钟\n",timeConsumption);System.out.printf("单词数:%d\n",wordCount);System.out.printf("字符数:%d\n",charCount);System.out.println(String.format("正确率:%.2f",correctRate*100)+"%");System.out.printf("总速度:%d 字母/分钟\n",charPerMinute);}catch(Exception e){e.printStackTrace();}}}
}

启动类

public class Start {public static void main(String[] args) {new YBPrinter("file/story").start();//此处为Directory中的story文件夹的相对路径,story文件夹则存放着各个故事}
}

分析

请添加图片描述

请添加图片描述

这篇关于0基础java初学者都能做的打字通小游戏? 内含源码解读和细致讲解!!的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/225238

相关文章

springboot集成easypoi导出word换行处理过程

《springboot集成easypoi导出word换行处理过程》SpringBoot集成Easypoi导出Word时,换行符n失效显示为空格,解决方法包括生成段落或替换模板中n为回车,同时需确... 目录项目场景问题描述解决方案第一种:生成段落的方式第二种:替换模板的情况,换行符替换成回车总结项目场景s

SpringBoot集成redisson实现延时队列教程

《SpringBoot集成redisson实现延时队列教程》文章介绍了使用Redisson实现延迟队列的完整步骤,包括依赖导入、Redis配置、工具类封装、业务枚举定义、执行器实现、Bean创建、消费... 目录1、先给项目导入Redisson依赖2、配置redis3、创建 RedissonConfig 配

SpringBoot中@Value注入静态变量方式

《SpringBoot中@Value注入静态变量方式》SpringBoot中静态变量无法直接用@Value注入,需通过setter方法,@Value(${})从属性文件获取值,@Value(#{})用... 目录项目场景解决方案注解说明1、@Value("${}")使用示例2、@Value("#{}"php

SpringBoot分段处理List集合多线程批量插入数据方式

《SpringBoot分段处理List集合多线程批量插入数据方式》文章介绍如何处理大数据量List批量插入数据库的优化方案:通过拆分List并分配独立线程处理,结合Spring线程池与异步方法提升效率... 目录项目场景解决方案1.实体类2.Mapper3.spring容器注入线程池bejsan对象4.创建

线上Java OOM问题定位与解决方案超详细解析

《线上JavaOOM问题定位与解决方案超详细解析》OOM是JVM抛出的错误,表示内存分配失败,:本文主要介绍线上JavaOOM问题定位与解决方案的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一、OOM问题核心认知1.1 OOM定义与技术定位1.2 OOM常见类型及技术特征二、OOM问题定位工具

基于 Cursor 开发 Spring Boot 项目详细攻略

《基于Cursor开发SpringBoot项目详细攻略》Cursor是集成GPT4、Claude3.5等LLM的VSCode类AI编程工具,支持SpringBoot项目开发全流程,涵盖环境配... 目录cursor是什么?基于 Cursor 开发 Spring Boot 项目完整指南1. 环境准备2. 创建

Spring Security简介、使用与最佳实践

《SpringSecurity简介、使用与最佳实践》SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架,本文给大家介绍SpringSec... 目录一、如何理解 Spring Security?—— 核心思想二、如何在 Java 项目中使用?——

SpringBoot+RustFS 实现文件切片极速上传的实例代码

《SpringBoot+RustFS实现文件切片极速上传的实例代码》本文介绍利用SpringBoot和RustFS构建高性能文件切片上传系统,实现大文件秒传、断点续传和分片上传等功能,具有一定的参考... 目录一、为什么选择 RustFS + SpringBoot?二、环境准备与部署2.1 安装 RustF

springboot中使用okhttp3的小结

《springboot中使用okhttp3的小结》OkHttp3是一个JavaHTTP客户端,可以处理各种请求类型,比如GET、POST、PUT等,并且支持高效的HTTP连接池、请求和响应缓存、以及异... 在 Spring Boot 项目中使用 OkHttp3 进行 HTTP 请求是一个高效且流行的方式。

java.sql.SQLTransientConnectionException连接超时异常原因及解决方案

《java.sql.SQLTransientConnectionException连接超时异常原因及解决方案》:本文主要介绍java.sql.SQLTransientConnectionExcep... 目录一、引言二、异常信息分析三、可能的原因3.1 连接池配置不合理3.2 数据库负载过高3.3 连接泄漏