简易打字游戏

257 阅读1分钟

我们以前刚接触电脑的菜鸟时期应该都有玩过一些打字游戏,一些字母往下掉然后我们按下相应字母键然后这个字母消失,一个很简单的打字小游戏,其中用了animate

body部分

<div class="box animate__animated ">  </div>

 <p>请在键盘上按下屏幕上显示的字母</p>

css部分

<style>

        * {

            margin: 0;

            padding: 0;

            list-style: none;

            text-decoration: none;

        }

        body {

            background-color: #2d2d2d;

           

        }

        .box {

            width: 300px;

            height: 300px;

            /* background-color: lightblue; */

            margin: 200px auto;

            font-size: 200px;

            text-align: center;

            color: #88df8e;

        }

        p {

            width: 250px;

            height: 20px;

            line-height: 20px;

            text-align: center;

            display: inline-block;

            background-color: coral;

            position: relative;

            bottom: 200px;

            left: calc(50% - 125px);

        }

    </style>
    

Js部分

var box = document.querySelector('.box');

        var p = document.querySelector('p');

        var right = 0;

        var wrong = 0;

        function letter() {

            return String.fromCharCode((Math.random() * 25) + 65);

        }

        box.innerHTML = letter();

        window.onkeydown = function (ev) {

            if (ev.keyCode == box.innerHTML.charCodeAt()) {

                box.innerHTML = letter();

                right++;

                box.classList.add('animate__zoomIn');

            } else {

                box.classList.add('animate__shakeX');

                wrong++

            }

        }


 

        window.onkeyup = function (ev) {

            box.classList.remove('animate__zoomIn');

            box.classList.remove('animate__shakeX');

            p.innerHTML = '总计' + (right + wrong) + '次,正确率 ' + ((right / (right + wrong)) * 100).toFixed(2) + '%';

        }