js+html实现打字游戏v2

news/2024/7/15 21:03:24 标签: javascript, html, 游戏

实现逻辑,看js+html实现打字游戏v1,在此基础之上增加了从文件读取到的单词,随机选取10个单词。
效果演示
在这里插入图片描述
上代码:

html"><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        span{
            font-size: larger;
            margin: 20px;
        }

        #score{
            background-color: red;
            color: white;
            position: absolute;
            left:90%;
            top: 90%;
        }
    </style>
</head>
<span id="score">
0
</span>
<input type="file" name="file" multiple="multiple" id="files" onchange="html" title=javascript>javascript language-html" title=javascript>javascript">choosefile()" />
<body>
<script>html" title=javascript>javascript">

    var content = "";
    var score = 0;
    //这里可以使用固定单词
    var words= ["apple","horizontal","vertical","vector","ghost","evil","banana","polo","curve","deploy"];
    var fileWords = [];
    var str = '';
    var count = 0;
    //单词生成速度,可以根据当前得分来设置,得分越高速度越快,比如当得分大于200时速度设为2,大于300百是速度设为3
    var speed = 1;


    function randWords(){
        if(fileWords.length>0){
            for (var i = 0; i <words.length ; i++) {
                var rand = Math.floor(Math.random()*fileWords.length);
                words[i] = fileWords[rand];
            }
        }
    }

    setInterval(()=>{
        if(count%(6-speed)===0){
            //从文件读取到的单词,随机选取10个单词
            this.randWords();
            let divElement = document.createElement('div');
            for (var i = 0; i <words.length ; i++) {
                var rand = Math.floor(Math.random()*words.length);
                var span = document.createElement('span');
                span.innerText = words[rand];
                divElement.appendChild(span);
                document.body.appendChild(divElement);
            }
        }
        count++;
    },1000)

    document.addEventListener("keydown",function (event) {
        str+=event.key;
        console.log(str);
        var spans = document.getElementsByTagName('span');
        var matchCnt = 0;
        for (var i = 0; i <spans.length ; i++) {
            if(str.includes(spans[i].innerText)){
                spans[i].style.color = 'red'
                score++;
                matchCnt++;
            }
        }
        if(matchCnt>0){
            str = '';
        }
        document.getElementById('score').innerText = score;

        //清除全部打出的一行
        var divs = document.getElementsByTagName('div');
        for (var i = 0; i <divs.length ; i++) {
            var children = divs[i].children;
            var redCnt = 0;
            for (var j = 0; j <children.length ; j++) {
                if(children[j].style.color === 'red'){
                    redCnt++;
                }
            }
            if(redCnt===children.length){
                document.body.removeChild(divs[i]);
            }
        }
    });

    function choosefile () {
        var fileList = document.getElementById('files').files;
        var nameStr = '';
        for (var i = 0; i < fileList.length; i++) {
            nameStr += `${i === 0 ? '' : ', '}${fileList[i].name}`;
            var reader = new FileReader();
            reader.readAsText(fileList[i], "UTF-8");
            reader.onload = function (e) {
                content = e.target.result;
                fileWords = content.split('\r\n');
            }
        }
    }

</script>
</body>
</html>

附录:englishg words.txt

understand
community
continent
recognize
something
although
movement
negative
acquire
content
respond
appeal
aspect
damage
monkey
select
though
wealth
within
asset
goods
stick
fair
fine
good
into
plan
week
ban
dam
fly
she
web
agreement
condition
purchase
ability
attract
combine
explain
natural
setting
several
almost
around
assure
danger
decade
ensure
parent
reduce
reject
alter
equal
exist
solar
speed
waste
cell
deny
fill
thus
consequence
demonstrate
influential
department
management
production
regulation
available
direction
formation
potential
campaign
contrast
preserve
attempt
element
factory
imagine
prepare
promote
weather
depend
desire
device
employ
expose
launch
manner
supply
arise
basic
down
duty
gift
down
duty
war
competition
specialist
conscious
emphasize
essential
privilege
represent
structure
conflict
explore
nuclear
obvious
present
enable
lesson
manage
member
phrase
safety
signal
suffer
slave
stage
earn
join
shop
infrastructure
productivity
investment
excessive
anything
medicine
positive
because
comment
confuse
freedom
genetic
journey
justify
arrive
couple
impose
refuse
reveal
screen
settle
agent
agree
crime
final
house
match
money
never
radio
royal
whole
area
cent
ever
food
kill
leak
mark
meet
pace
real
art
fit
net
conservation
performance
atmosphere
commercial
illustrate
population
associate
criticism
disappear
historian
congress
instance
internet
physical
railroad
separate
achieve
advance
already
capital
citizen
respect
agency
beyond
define
emerge
engage
expand
formal
gamble
period
record
return
second
senior
spread
admit
clean
ocean
piece
press
truth
baby
code
diet
fear
hand
sign
lot
it
administration
increasingly
publication
attractive
inevitable
journalist
optimistic
phenomenon
existence
guarantee
interpret
necessary
necessity
audience
database
exchange
familiar
humanity
perceive
religion
address
amateur
conduct
emotion
measure
mistake
outside
pursuit
receive
recover
advice
beauty
casual
dollar
either
except
former
middle
oppose
poetry
reader
severe
strong
switch
volume
apply
basis
board
robot
shock
third
total
boom
else
goal
make
poor
lay
consideration
conservation
constitution
institution
responsible
collection
commission
industrial
profitable
sufficient
classical
physician
recommend
religious
sensitive
tolerance
conclude
constant
dominant
dominate
enormous
epidemic
friendly
hospital
priority
restrict
strategy
airline
connect
deliver
deserve
discuss
educate
leisure
network
opinion
perhaps
station
sustain
commit
credit
divide
friend
invite
notion
prefer
region
remove
series
simply
adapt
break
enjoy
extra
bill
date
film
jump
link
next
odds
vay
odd
explanation
conclusion
eventually
everything
reputation
strengthen
widespread
celebrity
immediate
analysis
chemical
discover
domestic
province
security
chanel
correct
crucial
current
expense
observe
promise
recruit
regular
routine
typical
usually
variety
afford
assess
charge
church
differ
escape
factor
father
forest
hardly
height
indeed
orient
please
source
stable
along
award
aware
below
cross
crude
grade
happy
light
month
occur
quick
rapid
tough
wrong
cook
pick
rich
soon
upon
wage
low
consumption
description
convention
historical
successful
breakdown
conductor
exception
highlight
interview
judgement
ownership
procedure
voluntary
accident
announce
contract
contrary
creative
decrease
distance
internal
minister
opposite
ordinary
relation
somewhat
strength
compete
divorce
examine
largely
license
obscure
outcome
possess
propose
scholar
suicide
various
willing
annual
answer
before
belong
budget
gather
handle
ignore
inform
invest
margin
motion
option
origin
pursue
puzzle
random
really
secret
threat
urgent
verbal
alone
count
delay
draft
error
humor
laugh
novel
panel
plant
rural
trust
body
cite
city
cure
four
hurt
near
rear
suit
tool
type
fix
mix
owe
sex
conversation
corporation
independent
interesting
temperature
compromise
concession
disappoint
enterprise
cripple


http://www.niftyadmin.cn/n/4999864.html

相关文章

使用gradio创建一个提取pdf、excel中表格数据的demo

使用Gradio创建一个提取pdf、excel中表格数据的demo 最近需要对pdf、excel文件中的表格进行提取&#xff0c;用于一些分析&#xff0c;所以使用python完成了一个小工具&#xff0c;可以处理上传的pdf、excel文件&#xff0c;将其中所有表格提取出后存入数组输出&#xff1a; …

搭建单机版FastDFS分布式文件存储系统

一、准备工作 1、下载FastDFS安装包和依赖包 https://codeload.github.com/happyfish100/libfastcommon/tar.gz/V1.0.43 https://codeload.github.com/happyfish100/fastdfs/tar.gz/V6.06 https://codeload.github.com/happyfish100/fastdfs-nginx-module/tar.gz/V1.22 注&…

Logback日志记录只在控制台输出sql,未写入日志文件【解决】

原因&#xff1a;持久层框架对于Log接口实现方式不一样&#xff0c;日记记录的位置及展示方式也也不一样 mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # sql只会打印到控制台不会输出到日志文件种mybatis-plus:configuration:log-impl…

Sumo中Traci.trafficlight详解(上)

Sumo中Traci.trafficlight详解&#xff08;上&#xff09; 记录慢慢学习traci的每一天&#xff0c;希望也能帮到你 文章目录 Sumo中Traci.trafficlight详解&#xff08;上&#xff09;Traci.trafficlight信号灯参数讲解1.getAllProgramLogics(self,tlsID)2.getBlockingVehicle…

threejs得WebGLRenderer+CSS3DRenderer结合使用

文章目录 概要1&#xff1a;CSS3DRendererWebGLRenderer出现鬼畜bug2&#xff1a;解决思路3&#xff1a;代码示例小结 概要 在使用threejs显示label发现&#xff0c;人家自带了CSS3DRenderer/CSS2DRenderer. 1&#xff1a;CSS3DRendererWebGLRenderer出现鬼畜bug 第一种&…

Android列表片段

下面创建第二个片段WorkoutFragment&#xff0c;它包含不同训练项目构成的一个列表&#xff0c;用户可以从这个列表中选择训练项目。 列表视图是只包含一个列表的片段 列表片段是一种专门处理列表的片段&#xff0c;它会自动绑定到一个列表视图&#xff0c;所以不需要另外创建…

Kruise Rollout:基于 Lua 脚本的可扩展流量调度方案

作者&#xff1a;潘梦源 前言 Kruise Rollout [ 1] 是 OpenKruise 社区开源的渐进式交付框架。Kruise Rollout 支持配合流量和实例灰度的金丝雀发布、蓝绿发布、A/B Testing 发布&#xff0c;以及发布过程能够基于 Prometheus Metrics 指标自动化分批与暂停&#xff0c;并提供…

Hive的静态分区与动态分区

在 Hive 中,分区是一种组织数据的方式,允许你将表数据划分成更小的子集,以便更有效地管理和查询大型数据集。分区可以分为静态分区和动态分区,它们有不同的特点和用途。 1. 静态分区(Static Partitioning): 静态分区是在创建表时显式定义的分区方式。在静态分区中,你…