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

相关文章

SpringSecurity显示用户账号已被锁定的原因及解决方案

《SpringSecurity显示用户账号已被锁定的原因及解决方案》SpringSecurity中用户账号被锁定问题源于UserDetails接口方法返回值错误,解决方案是修正isAccountNon... 目录SpringSecurity显示用户账号已被锁定的解决方案1.问题出现前的工作2.问题出现原因各

Python的端到端测试框架SeleniumBase使用解读

《Python的端到端测试框架SeleniumBase使用解读》:本文主要介绍Python的端到端测试框架SeleniumBase使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全... 目录SeleniumBase详细介绍及用法指南什么是 SeleniumBase?SeleniumBase

Java继承映射的三种使用方法示例

《Java继承映射的三种使用方法示例》继承在Java中扮演着重要的角色,它允许我们创建一个类(子类),该类继承另一个类(父类)的所有属性和方法,:本文主要介绍Java继承映射的三种使用方法示例,需... 目录前言一、单表继承(Single Table Inheritance)1-1、原理1-2、使用方法1-

Spring @Scheduled注解及工作原理

《Spring@Scheduled注解及工作原理》Spring的@Scheduled注解用于标记定时任务,无需额外库,需配置@EnableScheduling,设置fixedRate、fixedDe... 目录1.@Scheduled注解定义2.配置 @Scheduled2.1 开启定时任务支持2.2 创建

SpringBoot中使用Flux实现流式返回的方法小结

《SpringBoot中使用Flux实现流式返回的方法小结》文章介绍流式返回(StreamingResponse)在SpringBoot中通过Flux实现,优势包括提升用户体验、降低内存消耗、支持长连... 目录背景流式返回的核心概念与优势1. 提升用户体验2. 降低内存消耗3. 支持长连接与实时通信在Sp

Spring Boot 实现 IP 限流的原理、实践与利弊解析

《SpringBoot实现IP限流的原理、实践与利弊解析》在SpringBoot中实现IP限流是一种简单而有效的方式来保障系统的稳定性和可用性,本文给大家介绍SpringBoot实现IP限... 目录一、引言二、IP 限流原理2.1 令牌桶算法2.2 漏桶算法三、使用场景3.1 防止恶意攻击3.2 控制资源

Mac系统下卸载JAVA和JDK的步骤

《Mac系统下卸载JAVA和JDK的步骤》JDK是Java语言的软件开发工具包,它提供了开发和运行Java应用程序所需的工具、库和资源,:本文主要介绍Mac系统下卸载JAVA和JDK的相关资料,需... 目录1. 卸载系统自带的 Java 版本检查当前 Java 版本通过命令卸载系统 Java2. 卸载自定

springboot下载接口限速功能实现

《springboot下载接口限速功能实现》通过Redis统计并发数动态调整每个用户带宽,核心逻辑为每秒读取并发送限定数据量,防止单用户占用过多资源,确保整体下载均衡且高效,本文给大家介绍spring... 目录 一、整体目标 二、涉及的主要类/方法✅ 三、核心流程图解(简化) 四、关键代码详解1️⃣ 设置

Java Spring ApplicationEvent 代码示例解析

《JavaSpringApplicationEvent代码示例解析》本文解析了Spring事件机制,涵盖核心概念(发布-订阅/观察者模式)、代码实现(事件定义、发布、监听)及高级应用(异步处理、... 目录一、Spring 事件机制核心概念1. 事件驱动架构模型2. 核心组件二、代码示例解析1. 事件定义

SpringMVC高效获取JavaBean对象指南

《SpringMVC高效获取JavaBean对象指南》SpringMVC通过数据绑定自动将请求参数映射到JavaBean,支持表单、URL及JSON数据,需用@ModelAttribute、@Requ... 目录Spring MVC 获取 JavaBean 对象指南核心机制:数据绑定实现步骤1. 定义 Ja