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

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

Java进阶13讲__第12讲_1/2

多线程、线程池 1.  线程概念 1.1  什么是线程 1.2  线程的好处 2.   创建线程的三种方式 注意事项 2.1  继承Thread类 2.1.1 认识  2.1.2  编码实现  package cn.hdc.oop10.Thread;import org.slf4j.Logger;import org.slf4j.LoggerFactory

JAVA智听未来一站式有声阅读平台听书系统小程序源码

智听未来,一站式有声阅读平台听书系统 🌟&nbsp;开篇:遇见未来,从“智听”开始 在这个快节奏的时代,你是否渴望在忙碌的间隙,找到一片属于自己的宁静角落?是否梦想着能随时随地,沉浸在知识的海洋,或是故事的奇幻世界里?今天,就让我带你一起探索“智听未来”——这一站式有声阅读平台听书系统,它正悄悄改变着我们的阅读方式,让未来触手可及! 📚&nbsp;第一站:海量资源,应有尽有 走进“智听

零基础学习Redis(10) -- zset类型命令使用

zset是有序集合,内部除了存储元素外,还会存储一个score,存储在zset中的元素会按照score的大小升序排列,不同元素的score可以重复,score相同的元素会按照元素的字典序排列。 1. zset常用命令 1.1 zadd  zadd key [NX | XX] [GT | LT]   [CH] [INCR] score member [score member ...]