HTML5+JavaScript单词游戏

news2024/7/2 4:03:15

HTML5 +JavaScript单词游戏

数据字典格式:每行一个 单词 ,单词和解释用空格分隔,如

a art.一(个);每一(个)

ability n.能力;能耐,本领

able a.有能力的;出色的

baby n.婴儿;孩子气的人

back ad.在后;回原处;回

background n.背景,后景,经历

cable n.缆,索;电缆;电报

cafe n.咖啡馆;小餐厅

good a.好的;有本事的

需要注意的是,JavaScript 在浏览器环境中不能像python那样直接读取本地文本文件,这是出于安全考虑,可以将数据字典内容作为 JavaScript 数据直接嵌入到脚本中。

游戏规则:

每次随机从文本中选取一个英语单词,在界面上从左到右移动,随机选出三个单词的解释,和英语单词正确解释,随机放到四个按钮中,这四个按钮放到界面下方。

用户单击带有解释的按钮,界面上英语单词消失,再随机从文本中选取一个新英语单词,进入下一个猜单词过程;若英语单词移动出界面,用户未能单击有正确解释的按钮,表示失败,也将随机从文本中选取一个新英语单词,进入下一个猜单词过程。

有失败和成功计数。

使用HTML5来实现这个单词游戏, 运行界面:

使用面向过程方式实现,游戏源码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>单词游戏</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 20px;
        }
        #gameCanvas {
            border: 1px solid black;
        }
        #score {
            align-self: flex-end;
            margin-bottom: 10px;
        }
        #buttons {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            margin-top: 20px;
        }
        button {
            width: 180px;
            height: 40px;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <div id="score">成功: 0 失败: 0</div>
    <canvas id="gameCanvas" width="400" height="200"></canvas>
    <div id="buttons"></div>

    <script>
 // 字典数据
        const dictionaryData = `
a art.一(个);每一(个)
ability n.能力;能耐,本领
able a.有能力的;出色的
baby n.婴儿;孩子气的人
back ad.在后;回原处;回
background n.背景,后景,经历
cable n.缆,索;电缆;电报
cafe n.咖啡馆;小餐厅
good a.好的;有本事的
        `;

        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        const scoreElement = document.getElementById('score');
        const buttonsContainer = document.getElementById('buttons');

        let dictionary = {};
        let currentWord = "";
        let currentDefinition = "";
        let options = [];
        let successCount = 0;
        let failCount = 0;
        let wordX = -100;
        let moveSpeed = 1; // 新增:移动速度控制
        let lastTime = 0;  // 新增:用于控制动画帧率

	function loadDictionary() {
            const lines = dictionaryData.trim().split('\n');
            lines.forEach(line => {
                const [word, definition] = line.trim().split(' ', 2);
                dictionary[word] = definition;
            });
        }

        function chooseNewWord() {
            const words = Object.keys(dictionary);
            currentWord = words[Math.floor(Math.random() * words.length)];
            currentDefinition = dictionary[currentWord];
            options = [currentDefinition];
            while (options.length < 4) {
                const randomDef = dictionary[words[Math.floor(Math.random() * words.length)]];
                if (!options.includes(randomDef)) {
                    options.push(randomDef);
                }
            }
            options.sort(() => Math.random() - 0.5);
            updateButtons();
            wordX = -100;
        }

        function updateButtons() {
            buttonsContainer.innerHTML = '';
            options.forEach((option, index) => {
                const button = document.createElement('button');
                button.textContent = option.substring(0, 20) + "...";
                button.onclick = () => checkAnswer(index);
                buttonsContainer.appendChild(button);
            });
        }

        function moveWord(currentTime) {
            // 控制帧率,每16ms(约60fps)更新一次
            if (currentTime - lastTime < 16) {
                requestAnimationFrame(moveWord);
                return;
            }
            lastTime = currentTime;

            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.font = '24px Arial';
            ctx.fillText(currentWord, wordX, 100);

            if (wordX > canvas.width) {
                failCount++;
                updateScore();
                chooseNewWord();
            } else {
                wordX += moveSpeed; // 使用moveSpeed控制移动速度
            }

            requestAnimationFrame(moveWord);
        }

        function checkAnswer(index) {
            if (options[index] === currentDefinition) {
                successCount++;
            } else {
                failCount++;
            }
            updateScore();
            chooseNewWord();
        }

        function updateScore() {
            scoreElement.textContent = `成功: ${successCount} 失败: ${failCount}`;
        }

        function init() {
            loadDictionary();
            chooseNewWord();
            requestAnimationFrame(moveWord);
        }

        init();
    </script>
</body>
</html>

你可以通过调整 moveSpeed 的值来改变单词移动的速度。例如:

moveSpeed = 0.5; 会使单词移动得更慢

moveSpeed = 2; 会使单词移动得更快

上面的JavaScript代码是面向过程的,下面使用面向对象方式实现。

使用面向对象方式实现,游戏源码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>单词游戏</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 20px;
        }
        #gameCanvas {
            border: 1px solid black;
        }
        #score {
            align-self: flex-end;
            margin-bottom: 10px;
        }
        #buttons {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            margin-top: 20px;
        }
        button {
            width: 180px;
            height: 40px;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <div id="score">成功: 0 失败: 0</div>
    <canvas id="gameCanvas" width="400" height="200"></canvas>
    <div id="buttons"></div>

    <script>

 // 字典数据
        const dictionaryData = `
a art.一(个);每一(个)
ability n.能力;能耐,本领
able a.有能力的;出色的
baby n.婴儿;孩子气的人
back ad.在后;回原处;回
background n.背景,后景,经历
cable n.缆,索;电缆;电报
cafe n.咖啡馆;小餐厅
good a.好的;有本事的
        `;

        class WordGame {
            constructor() {
                this.canvas = document.getElementById('gameCanvas');
                this.ctx = this.canvas.getContext('2d');
                this.scoreElement = document.getElementById('score');
                this.buttonsContainer = document.getElementById('buttons');

                this.dictionary = {};
                this.currentWord = "";
                this.currentDefinition = "";
                this.options = [];
                this.successCount = 0;
                this.failCount = 0;
                this.wordX = -100;
                this.moveSpeed = 1;
                this.lastTime = 0;

                this.loadDictionary();
                this.chooseNewWord();
                this.updateButtons();
                requestAnimationFrame(this.moveWord.bind(this));
            }


	    loadDictionary() {
                const lines = dictionaryData.trim().split('\n');
                lines.forEach(line => {
                    const [word, definition] = line.trim().split(' ', 2);
                    this.dictionary[word] = definition;
                });
            }

            chooseNewWord() {
                const words = Object.keys(this.dictionary);
                this.currentWord = words[Math.floor(Math.random() * words.length)];
                this.currentDefinition = this.dictionary[this.currentWord];
                this.options = [this.currentDefinition];
                while (this.options.length < 4) {
                    const randomDef = this.dictionary[words[Math.floor(Math.random() * words.length)]];
                    if (!this.options.includes(randomDef)) {
                        this.options.push(randomDef);
                    }
                }
                this.options.sort(() => Math.random() - 0.5);
                this.wordX = -100;
            }

            updateButtons() {
                this.buttonsContainer.innerHTML = '';
                this.options.forEach((option, index) => {
                    const button = document.createElement('button');
                    button.textContent = option.substring(0, 20) + "...";
                    button.onclick = () => this.checkAnswer(index);
                    this.buttonsContainer.appendChild(button);
                });
            }

            moveWord(currentTime) {
                if (currentTime - this.lastTime < 16) {
                    requestAnimationFrame(this.moveWord.bind(this));
                    return;
                }
                this.lastTime = currentTime;

                this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
                this.ctx.font = '24px Arial';
                this.ctx.fillText(this.currentWord, this.wordX, 100);

                if (this.wordX > this.canvas.width) {
                    this.failCount++;
                    this.updateScore();
                    this.chooseNewWord();
                    this.updateButtons();
                } else {
                    this.wordX += this.moveSpeed;
                }

                requestAnimationFrame(this.moveWord.bind(this));
            }

            checkAnswer(index) {
                if (this.options[index] === this.currentDefinition) {
                    this.successCount++;
                } else {
                    this.failCount++;
                }
                this.updateScore();
                this.chooseNewWord();
                this.updateButtons();
            }

            updateScore() {
                this.scoreElement.textContent = `成功: ${this.successCount} 失败: ${this.failCount}`;
            }
        }

        // 初始化游戏
        new WordGame();
    </script>
</body>
</html>

这个面向对象的实现有以下几个主要特点:

所有游戏逻辑都封装在 WordGame 类中。

类的构造函数 constructor 初始化所有必要的属性和状态,并开始游戏循环。

每个功能都变成了类的方法,如 loadDictionary, chooseNewWord, updateButtons 等。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1877517.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

深入浅出:npm 常用命令详解与实践

在现代的前端开发流程中&#xff0c;npm&#xff08;Node Package Manager&#xff09;已经成为了不可或缺的一部分。它不仅帮助我们有效地管理项目中的依赖包&#xff0c;还提供了一系列强大的命令来优化开发体验。在这篇博客中&#xff0c;我们将深入探讨 npm 的常用命令&…

Navicat上新啦

前言 Navicat&#xff0c;在数据库界&#xff0c;几乎是一个神奇的存在&#xff0c;似乎统治了数据库开发工具的“一片天”。且看下图&#xff1a; 红的蓝的绿的橙的…&#xff0c;可以说&#xff0c;留给它的color不多了。 那么商业BI到服务监控、从云托管到云协作&#xff…

Qt事件传递顺序是怎样的?

1、事件传递顺序规则 在Qt中&#xff0c;事件传递的顺序事件首先传递到目标对象的事件过滤器&#xff0c;然后传递到事件处理函数&#xff0c;最后传递到父对象的事件过滤器和事件处理函数。 为了更好地理解这一过程&#xff0c;下面将通过一个示例来展示事件在父窗口和子窗口…

盘点全球Top10大云计算平台最热门技能证书

小李哥花了一年半时间终于考下全球10大云的77张认证&#xff0c;今天盘点下各个云的热门证书&#xff0c;希望能帮到非CS专业转IT和刚刚入行云计算的小伙伴。 排名取自23年Yahoo云计算市场份额排名报告&#xff0c;我会从云平台、证书价格、证书热门程度做推荐。 1️⃣亚马逊云…

微机原理 复习

第一章导论 1.3 冯诺依曼体系结构 &#xff08;1&#xff09;以二进制形式表示指令和数据 &#xff08;2&#xff09;程序和数据事先放在存储器中&#xff08;预存储&#xff09; &#xff08;3&#xff09;由运算器、控制器、输入设备和输出设备五大部件组成 字长、主频…

《昇思25天学习打卡营第6天|onereal》

Vision Transformer&#xff08;ViT&#xff09;简介 近些年&#xff0c;随着基于自注意&#xff08;Self-Attention&#xff09;结构的模型的发展&#xff0c;特别是Transformer模型的提出&#xff0c;极大地促进了自然语言处理模型的发展。由于Transformers的计算效率和可扩…

深度解析:机器学习如何助力GPT-5实现语言理解的飞跃

文章目录 文章前言机器学习在GPT-5中的具体应用模型训练与优化机器翻译与跨语言交流&#xff1a;情感分析与问答系统&#xff1a;集成机器学习功能&#xff1a;文本生成语言理解任务适应 机器学习对GPT-5性能的影响存在的挑战及解决方案技术细节与示例 文章前言 GPT-5是OpenAI公…

昇思25天学习打卡营第11天|SSD目标检测

1. 学习内容复盘 模型简介 SSD&#xff0c;全称Single Shot MultiBox Detector&#xff0c;是Wei Liu在ECCV 2016上提出的一种目标检测算法。使用Nvidia Titan X在VOC 2007测试集上&#xff0c;SSD对于输入尺寸300x300的网络&#xff0c;达到74.3%mAP(mean Average Precision)…

任意密码重置漏洞

文章目录 1. 任意密码重置漏洞原理2. 任意密码重置漏洞产生原因3. 任意密码重置漏洞场景3.1 验证码爆破3.2 验证凭证回传3.3 验证凭证未绑是用户3.4 跳过验证步骤3.5 凭证可预测3.6 同时向多个账户发送凭证 4. 任意密码重置经典案例4.1 中国人寿某重要系统任意账户密码重置4.2 …

Go Error 处理

&#x1f49d;&#x1f49d;&#x1f49d;欢迎莅临我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&#xff0c;也可以畅所欲言、分享您的想法和见解。 推荐:「stormsha的主页」…

ModuleNotFoundError: No module named ‘_sysconfigdata_x86_64_conda_linux_gnu‘

ModuleNotFoundError: No module named _sysconfigdata_x86_64_conda_linux_gnu 1.软件环境⚙️2.问题描述&#x1f50d;3.解决方法&#x1f421;4.结果预览&#x1f914; 1.软件环境⚙️ Ubuntu 20.04 Python 3.7.0 2.问题描述&#x1f50d; 今天发现更新conda之后&#xff0…

【数据库】Oracle安装报错(win10安装oracle提示环境不满足最低要求)

目录 一、问题场景&#xff1a; 二、问题描述 三、原因分析&#xff1a; 四、解决方案&#xff1a; 一、问题场景&#xff1a; 安装Oracle数据库 二、问题描述 安装之前提示&#xff08; [INS-13001]环境不满足最低要求。 是否确实要继续? &#xff09; 如图所示&…

1-爬虫基础知识(6节课学会爬虫)

1-爬虫基础知识&#xff08;6节课学会爬虫&#xff09; 1.什么是爬虫2.爬取的数据去哪了3.需要的软件和环境4.浏览器的请求&#xff08;1&#xff09;Url&#xff08;2&#xff09;浏览器请求url地址&#xff08;3&#xff09;url地址对应的响应 5.认识HTTP/HTTPS5.1 http协议之…

43.三倍游戏

上海市计算机学会竞赛平台 | YACSYACS 是由上海市计算机学会于2019年发起的活动,旨在激发青少年对学习人工智能与算法设计的热情与兴趣,提升青少年科学素养,引导青少年投身创新发现和科研实践活动。https://www.iai.sh.cn/problem/390 题目描述 三倍游戏是一种单人游戏。玩…

2.优化算法之滑动窗口1

1.长度最小的子数组 . - 力扣&#xff08;LeetCode&#xff09; &#xff08;1&#xff09;题目描述 给定一个含有 n 个正整数的数组和一个正整数 target 。 找出该数组中满足其总和大于等于 target 的长度最小的 子数组 [numsl, numsl1, ..., numsr-1, numsr] &#xff0c;…

全网唯一免费无水印AI视频工具!

最近Morph Studio开始免费公测&#xff01;支持高清画质&#xff0c;可以上传语音&#xff0c;同步口型&#xff0c;最重要的是生成的视频没有水印&#xff01; Morph Studio国内就可以访问&#xff0c;可以使用国内邮箱注册&#xff08;我用的163邮箱&#xff09;&#xff0c;…

Java代码高风险弱点与修复之——弱密码哈希漏洞-Very weak password hashing (WEAK_PASSWORD_HASH)

弱密码哈希漏洞 弱密码哈希漏洞指的是在密码存储和验证过程中,由于使用了不安全的哈希算法或哈希函数的错误使用,导致攻击者能够更容易地破解或绕过密码验证机制。这种漏洞使得存储在系统或应用中的用户密码容易受到威胁,增加了账户被非法访问和数据泄露的风险。 常见的弱…

前端工程化08-新的包管理工具pnpm

1、历史原因解读 pnpm这个东西发布的时间是比较早的&#xff0c;但是在最近一两年的时候才开始流行&#xff0c;甚至是可以说非常的盛行&#xff0c;那么这个包到底是个什么东西的&#xff0c;那么我们先说下&#xff0c;原来的包管理工具到底有那些问题&#xff1f;比如说我们…

面向对象和面向过程编程的区别

引言 小伙伴们&#xff0c;当你们看到这章的时候&#xff0c;显然你们已经跨过了来自指针给你们带来的麻烦&#xff0c;唔~真棒呢&#xff0c;但是我们只学会一些基础的C语法并不能帮我们解决问题&#xff0c;甚至是稍微难一些的题目我们都没办法解决&#xff0c;那怎么办呢&am…

Linux基础 - BIND加密传输缓存服务器

目录 零. 简介 一. 安装 二. 安全的加密传输 三. 部署缓存服务器 四. 总结 零. 简介 BIND&#xff08;Berkeley Internet Name Domain&#xff09;是一款广泛使用的开源 DNS&#xff08;域名系统&#xff09;服务器软件。 域名系统的主要作用是将易于人类理解的域名&…