Native JS object-oriented typing game

Native JS object-oriented typing game

This article shares the specific code of JS object-oriented typing game for your reference. The specific content is as follows

Demo Introduction

Click the number displayed by the falling ball through the keyboard, and the ball will refresh and fall again at any position. In addition, after every five balls, the dropping speed will increase, the position and size of the balls will be refreshed, and the colors will be random. The demo source code can be used directly by implementing the object-oriented class method. Assign it to the HTML file and then open it to use it. It can be used as a school course design

Source code

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    .title{
        width: 1200px;
        height: 80px;
        margin:400px auto;
        color: darkblue;
        text-shadow: 3px 3px 3px black;
        font-size: 80px;
        font-weight: bold;
        text-align: center;
        font-family: "楷体";

    }
    .name{
        width: 1000px;
        height: 40px;
        margin:0 auto;
        color: skyblue;
        text-shadow: 3px 3px 3px black;
        font-size: 40px;
        font-weight: bold;
        text-align: center;
        font-family: "楷体";
    }
</style>

<body>
    <div style="font-size: 40px;">Current score<div class="score" >0</div></div>
    <div class="title">Native js small Demo: typing practice game</div>
    <div class="name">Author: lz</div>
</body>
<script>
    class TypingGame {
        constructor() {
            this.oSpan
            this.speed = 2;
            this.timer = "";
            this.word;
            this.colors = ["red", "orange", "purple", "black", "pink", "blue", "skyblue", "yellowgreen", "brown", "tomato", "indianred", "orchid", "peru", "aqua", "slateblue", "gray", "grey", "crimson","green"]//Color collection this.createWord(this.speed);
            document.onkeydown = e => {
                var e = e || window.event;
                var keycode = e.keyCode || e.which;
                // TypingGame.oSpan = this.$$("span");
                var keyword = String.fromCharCode(keycode).
                    toLowerCase()
                if (this.word === keyword) {
                    // Knock one down - score // Get the original score var score = this.$('.score', false).innerText - 0
                    // Let the score +1
                    score++
                    // Put the score after adding 1 into the div document.querySelector('.score').innerText = score
                    if (score === 5) {
                        this.speed += 2 // Every five letters, the falling speed increases}
                    this.oSpan.parentElement.removeChild(this.oSpan)
                    this.createWord(this.speed)
                }
            }


        }
        createWord(speed) {
            let wh=this.getRandom(30,80);//Random size this.oSpan = this.creEle('span');
            // console.log(this.oSpan)
            this.setStyle(this.oSpan, {
                width: wh+"px",
                height: wh+"px",
                position: 'absolute',
                top: 0,
                left: this.getRandom(document.documentElement.clientWidth - 30) + "px",
                borderRadius: "50%",
                lineHeight: '30px',
                textAlign: 'center',
                backgroundColor: this.colors[this.getRandom(18)],
                color: "white",
                fontWeight: "bold",
                textAlign:"center",
                lineHeight:wh+"px"
            })

            document.body.appendChild(this.oSpan)
            // Random characters: 97~122
            var randomNum = this.getRandom(97, 123)
            this.word = String.fromCharCode(randomNum);

            this.oSpan.innerText = this.word
            // This label should move slowly downward this.elementsMove(this.speed);
        }
        elementsMove() {
            // console.log(this.oSpan)
            // Timer clearInterval(this.timer)
            this.timer = setInterval(() => {
                // Get height var t = this.oSpan.offsetTop;
                // Increase the height t += this.speed;
                console.log(this.speed)
                // If this tag reaches the bottom of the browser, GAME OVER
                if (t >= document.documentElement.clientHeight - 30) {
                    clearInterval(this.timer)
                    if (confirm("GAME OVER, Do you want to play again?")) {
                        location.reload(); //Refresh and play again}
                }
                // Set the top of the label after enlarging
                this.oSpan.style.top = t + "px"
            }, 50)
        }
        setStyle(ele, styleObj) {
            for (var attr in styleObj) {
                ele.style[attr] = styleObj[attr]
            }
        }
        $(tag, all = false) {
            return all ? document.querySelectorAll(tag) : document.querySelector(tag);
        }
        creEle(tag) {
            return document.createElement(tag)
        }
        getRandom(a, b = 0) {
            var max = Math.max(a, b);
            var min = Math.min(a, b)
            return Math.floor(Math.random() * (max - min)) + min
        }
    }
    new TypingGame;
</script>

</html>

Demo screenshots

Areas for improvement

You can rewrite it yourself, add error prompts, and refresh the height randomly. Some speed optimizations could be done. Changing the animation to requestAnimationFrame() will make the effect more realistic.

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • JS realizes typing game
  • js to realize typing games
  • JavaScript to achieve a simple typing game
  • Native js to realize typing animation game
  • JavaScript game development: "Romance of the Three Kingdoms: The Legend of Cao Cao" component development (Part 3) Typewriter-like text output in scenario dialogue
  • JavaScript typing game code
  • JavaScript typing game implementation code
  • JavaScript balloon typing game

<<:  Ubuntu 20.04 Chinese input method installation steps

>>:  Vertical and horizontal splitting of MySQL tables

Recommend

MySQL high availability cluster deployment and failover implementation

Table of contents 1. MHA 1. Concept 2. Compositio...

Sample code for partitioning and formatting a disk larger than 20TB on centos6

1. Server environment configuration: 1. Check dis...

How to use geoip to restrict regions in nginx

This blog is a work note environment: nginx versi...

CSS to achieve fast and cool shaking animation effect

1. Introduction to Animate.css Animate.css is a r...

MySQL query optimization using custom variables

Table of contents Optimizing sorting queries Avoi...

Vue component library ElementUI implements table loading tree data tutorial

ElementUI implements a table tree list loading tu...

HTTP return code list (Chinese and English explanation)

http return code list (below is an overview) for ...

A brief talk about JavaScript Sandbox

Preface: Speaking of sandboxes, our minds may ref...

MySQL encryption and decryption examples

MySQL encryption and decryption examples Data enc...

How to use vue-video-player to achieve live broadcast

Table of contents 1. Install vue-video-player 2. ...

How to Dockerize a Python Django Application

Docker is an open source project that provides an...

How to implement remote connection for Redis under Linux

After installing Redis on Linux, use Java to conn...

Vue implements multi-tab component

To see the effect directly, a right-click menu ha...

Why should you be careful with Nginx's add_header directive?

Preface As we all know, the nginx configuration f...