js+html实现打字游戏v2

实现逻辑,看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="choosefile()" />
<body>
<script>

    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
相关推荐
jjw_zyfx几秒前
css 点击显示并移动元素,再次点击移回元素并消失
前端·javascript·css
英俊潇洒美少年10 分钟前
Vue2 高德地图地址选择器完整实战(组件抽离+高并发优化+@amap/amap-jsapi-loader最佳实践)
前端·javascript·vue.js
threelab24 分钟前
从工厂模式到简化封装:三维引擎架构演进之路 threejs设计
javascript·3d·架构·webgl
白日梦想家68143 分钟前
实战避坑+性能对比,for与each循环选型指南
开发语言·前端·javascript
帅帅哥的兜兜1 小时前
猪齿鱼:实现table分页勾选
前端·javascript·vue.js
wicb91wJ61 小时前
手写一个Promise,彻底掌握异步原理
开发语言·前端·javascript
zs宝来了1 小时前
Next.js SSR/SSG:路由与渲染模式深度解析
前端·javascript·框架
ZC跨境爬虫1 小时前
UI前端美化技能提升日志day5:从布局优化到CSS继承原理深度解析
前端·css·ui·html·状态模式
代码小书生1 小时前
游戏中文翻译教程,可将游戏画面中的其他外文语种,实时翻译转换成为简体中文!支持OCR实时文本识别、屏幕实时翻译!
游戏·翻译·汉化·中文翻译·实时翻译·电脑游戏·游戏翻译
沪漂阿龙1 小时前
深度强化学习入门:从倒立摆游戏看懂AI如何“自己学会走路”
人工智能·游戏