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

The most basic code for web pages

◆Add to favorites illustrate Click to add your we...

Vue.set() and this.$set() usage and difference

When we use Vue for development, we may encounter...

Analysis and solution of a MySQL slow log monitoring false alarm problem

Previously, for various reasons, some alarms were...

How to handle super large form examples with Vue+ElementUI

Recently, due to business adjustments in the comp...

How to implement a lucky wheel game in WeChat applet

I mainly introduce how to develop a lucky wheel g...

A brief discussion on HTML ordered lists, unordered lists and definition lists

Ordered List XML/HTML CodeCopy content to clipboa...

JavaScript Closures Explained

Table of contents 1. What is a closure? 2. The ro...

Introduction to Vue3 Composition API

Table of contents Overview Example Why is it need...

VMware and CentOS system installation method to reset the root password

Today's Tasks 1. Choice of Linux distribution...

Analysis of the method of setting up scheduled tasks in mysql

This article uses an example to describe how to s...

Record of the actual process of packaging and deployment of Vue project

Table of contents Preface 1. Preparation - Server...