Table of Contents
回复内容:
Home Web Front-end H5 Tutorial JS猜数字游戏如何判断一个数字是否被猜过?

JS猜数字游戏如何判断一个数字是否被猜过?

Jun 07, 2016 am 08:43 AM

写一个竞猜游戏,用户必须猜一个秘密的数字,在每次猜完后程序会告诉用户他猜的数是太大了还是太小了,直到猜测正确,最后打印出猜测的次数。如果用户连续猜测同一个数字则只算一次。

我就是不知道怎么实现“如果用户连续猜测同一个数字则只算一次。”

没有思路,下面附上我写的代码,就是不知道实现最后一句。

如果有大神看到的话帮忙回答下,真的是想不出来。

回复内容:

涉及到javascript中的一个很有用的点:把object当hash来用

/**
 *
 * 用object当做hash来记录猜过的数字
 * 假设把所有猜过的数字存在一个array中, 其中有重复的数字
 * [1, 2, 5, 6, 3, 5, 1, 6, 2, 6]
 *
 */

var guesses = [1, 2, 5, 6, 3, 5, 1, 6, 2, 6];
var guessesHash = {};
var guessesCount = 0; // total guess count exclude duplicated guesses

for (var i = 0; i < guesses.length; i++) {
    if (!guessesHash[guesses[i]]) {
        guessesHash[guesses[i]] = true;
        guessesCount++;
    }
}

console.log(guessesCount); // should be 5

/**
 *
 * 当for loop中的i = 4时,guessesHash为:
 * {
 *     ‘1’: true,
 *     '2': true,
 *     '3': true,
 *     '5': true,
 *     '6': true,
 * }
 * 当for loop中的i = 5时,因为guessesHash[guesses[i]]是true,
 * 所以guessesCount++不会执行。
 * 换句话说,for loop中一旦遇到重复的数字guessesCount++就不会执行
 * 
 * 
 * 
 */
Copy after login
用数组或者object把输入过的数存起来即可。
<span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
    <span class="kd">var</span> <span class="nx">history</span><span class="o">=</span><span class="p">{},</span>
        <span class="nx">secret</span><span class="o">=</span><span class="mi">4</span><span class="p">;</span> <span class="c1">// https://www.xkcd.com/221/</span>
    
    <span class="k">do</span> <span class="p">{</span>
        <span class="kd">var</span> <span class="nx">input</span><span class="o">=</span><span class="nb">parseInt</span><span class="p">(</span><span class="nx">prompt</span><span class="p">(</span><span class="s1">'输入数字: '</span><span class="p">));</span>
        <span class="nx">history</span><span class="p">[</span><span class="nx">input</span><span class="p">]</span><span class="o">=</span><span class="kc">true</span><span class="p">;</span>
        <span class="k">if</span><span class="p">(</span><span class="nx">input</span><span class="o">></span><span class="nx">secret</span><span class="p">)</span>
            <span class="nx">alert</span><span class="p">(</span><span class="s1">'比这个小'</span><span class="p">);</span>
        <span class="k">else</span> <span class="k">if</span><span class="p">(</span><span class="nx">input</span><span class="o"><</span><span class="nx">secret</span><span class="p">)</span>
            <span class="nx">alert</span><span class="p">(</span><span class="s1">'比这个大'</span><span class="p">);</span>
    <span class="p">}</span> <span class="k">while</span><span class="p">(</span><span class="nx">input</span><span class="o">!==</span><span class="nx">secret</span><span class="p">);</span>
    
    <span class="kd">var</span> <span class="nx">count</span><span class="o">=</span><span class="mi">0</span><span class="p">;</span>
    <span class="k">for</span><span class="p">(</span><span class="kd">var</span> <span class="nx">_</span> <span class="k">in</span> <span class="nx">history</span><span class="p">)</span>
        <span class="nx">count</span><span class="o">++</span><span class="p">;</span>
    <span class="nx">alert</span><span class="p">(</span><span class="s1">'你猜了 '</span><span class="o">+</span><span class="nx">count</span><span class="o">+</span><span class="s1">' 次'</span><span class="p">);</span>
<span class="p">})();</span>
Copy after login
定义个全局变量,记录用户每次输入的值,一样的值不做重复记录,不一样的记录。最后看看这个变量的数。。。。 第一种方法:建个数组,用户输入时检查数组最后一个数是否和输入相等,不相等就push进去。最后输出数组的长度就好了。
第二种方法:不管用户输入是否有连续重复的数字,都push到一个数组里,最后把连续的数字剔除掉之后的长度就好了。这样问题就变成了:实现一个函数,用户输入:[1,2,2,2,3,3,4,4,4,5,5],要求输出为5 (即[1,2,3,4,5]的长度)
<span class="kd">var</span> <span class="nx">arr</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">,</span><span class="mi">4</span><span class="p">,</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">5</span><span class="p">];</span>

<span class="kd">function</span> <span class="nx">getLength</span><span class="p">(</span><span class="nx">arr</span><span class="p">)</span> <span class="p">{</span>
  <span class="k">return</span> <span class="nx">arr</span><span class="p">.</span><span class="nx">filter</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">v</span><span class="p">,</span><span class="nx">i</span><span class="p">,</span><span class="nx">arr</span><span class="p">){</span>
    <span class="k">return</span> <span class="nx">v</span><span class="o">!==</span><span class="nx">arr</span><span class="p">[</span><span class="nx">i</span><span class="o">-</span><span class="mi">1</span><span class="p">];</span>
  <span class="p">}).</span><span class="nx">length</span><span class="p">;</span>
<span class="p">}</span>

<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">getLength</span><span class="p">(</span><span class="nx">arr</span><span class="p">));</span> <span class="c1">// 5</span>
Copy after login
var n=0;
var lastAnswer=null;
//var 答案数组=[];//题主的问题里没有要求记录用户输入的答案,如果有需求的话,就加上这个。
function 用户输入之后的处理函数(int 用户输入的值){
if(lastAnswer!=用户输入的值){
n++;
lastAnswer=用户输入的值;
//答案数组.push(用户输入的值);//题主的问题里没有要求记录用户输入的答案,如果有需求的话,就加上这个。
//和正确答案比较。
}
else{
//连续猜测同一个数字;
}
} 不知道间隔猜测同样的数字算不算你说的连续输入相同的数字 ?不过原理是一样的 :
声明一个数组 ,里面放之前猜测过的数字,每次输入新数字时到数组中查找是否已存在,已经存在的,则跳过。 参考数组去重,很简单实现 把每次数字存入数组,对比数字和数组最后一个数是否相等。 hash虽说不太懂大概意思就是再弄一个数组 专门放这个数字猜没猜过? 这不是很简单么,两个变量的事,一个答案,一个是上次的值
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What exactly does H5 page production mean? What exactly does H5 page production mean? Apr 06, 2025 am 07:18 AM

H5 page production refers to the creation of cross-platform compatible web pages using technologies such as HTML5, CSS3 and JavaScript. Its core lies in the browser's parsing code, rendering structure, style and interactive functions. Common technologies include animation effects, responsive design, and data interaction. To avoid errors, developers should be debugged; performance optimization and best practices include image format optimization, request reduction and code specifications, etc. to improve loading speed and code quality.

How to run the h5 project How to run the h5 project Apr 06, 2025 pm 12:21 PM

Running the H5 project requires the following steps: installing necessary tools such as web server, Node.js, development tools, etc. Build a development environment, create project folders, initialize projects, and write code. Start the development server and run the command using the command line. Preview the project in your browser and enter the development server URL. Publish projects, optimize code, deploy projects, and set up web server configuration.

How to make h5 click icon How to make h5 click icon Apr 06, 2025 pm 12:15 PM

The steps to create an H5 click icon include: preparing a square source image in the image editing software. Add interactivity in the H5 editor and set the click event. Create a hotspot that covers the entire icon. Set the action of click events, such as jumping to the page or triggering animation. Export H5 documents as HTML, CSS, and JavaScript files. Deploy the exported files to a website or other platform.

What Does H5 Refer To? Exploring the Context What Does H5 Refer To? Exploring the Context Apr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

What is the H5 programming language? What is the H5 programming language? Apr 03, 2025 am 12:16 AM

H5 is not a standalone programming language, but a collection of HTML5, CSS3 and JavaScript for building modern web applications. 1. HTML5 defines the web page structure and content, and provides new tags and APIs. 2. CSS3 controls style and layout, and introduces new features such as animation. 3. JavaScript implements dynamic interaction and enhances functions through DOM operations and asynchronous requests.

What application scenarios are suitable for H5 page production What application scenarios are suitable for H5 page production Apr 05, 2025 pm 11:36 PM

H5 (HTML5) is suitable for lightweight applications, such as marketing campaign pages, product display pages and corporate promotion micro-websites. Its advantages lie in cross-platformity and rich interactivity, but its limitations lie in complex interactions and animations, local resource access and offline capabilities.

Is h5 same as HTML5? Is h5 same as HTML5? Apr 08, 2025 am 12:16 AM

"h5" and "HTML5" are the same in most cases, but they may have different meanings in certain specific scenarios. 1. "HTML5" is a W3C-defined standard that contains new tags and APIs. 2. "h5" is usually the abbreviation of HTML5, but in mobile development, it may refer to a framework based on HTML5. Understanding these differences helps to use these terms accurately in your project.

How to make pop-up windows with h5 How to make pop-up windows with h5 Apr 06, 2025 pm 12:12 PM

H5 pop-up window creation steps: 1. Determine the triggering method (click, time, exit, scroll); 2. Design content (title, text, action button); 3. Set style (size, color, font, background); 4. Implement code (HTML, CSS, JavaScript); 5. Test and deployment.

See all articles