Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to write a simple game with JavaScript

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail how to use JavaScript to write a simple game, the content of the article is of high quality, so the editor will share it with you for reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.

Take the first step towards creating interactive and dynamic JavaScript content by using a simple game to practice some basic Web concepts.

It is safe to say that without JavaScript, most modern Web would not exist. It is one of three standard Web technologies (as well as HTML and CSS) that allow anyone to create the interactive, dynamic content we expect in the World wide Web experience. From a framework like React to a data visualization library like D3, it's hard to imagine Web without it.

There's a lot to learn now, and a good way to start learning this popular language is to write a simple application to familiarize yourself with certain concepts. Recently, some people have written articles about how to learn their favorite language by writing simple guessing games, so this is a good starting point!

Let's start now.

There are many styles of JavaScript, but I'll start with the basics, often referred to as "normal JavaScript". JavaScript is primarily a client-side scripting language, so it can run in any standard browser without installing any program. All you need is a code editor (Brackets is a good choice) and a Web browser.

HTML user interface

JavaScript runs in a Web browser and interacts with other standard Web technologies HTML and CSS. To create this game, you first need to use HTML (Hypertext markup language) to create a simple interface for players to use. If you're not clear, HTML is a markup language that provides structure for Web content.

First, create a HTML file. The file should have an .html extension so that the browser knows it is an HTML document. You can name the file guessingGame.html.

Use some basic HTML tags in this file to display the title of the game, instructions on how to play, interactive elements for players to enter and submit their guesses, and placeholders to provide feedback to players:

JavaScript Guessing Game Guess the Number!

I am thinking of a number between 1 and 100. Can you guess what it is?

My Guess

And

Element lets the browser know what type of text is displayed on the page. The label pair represents the text between the tags (Guess the Number!) is the title. The last group

The tag indicates that the short text with instructions is a paragraph. The empty space at the end of this code block

The tag acts as a placeholder to provide some feedback based on the user's input.

Label

There are many ways to include JavaScript in a Web page, but for a short script like this, you can use a set of tags and write the JavaScript directly in the HTML file. These tags should precede the tags near the end of the HTML file.

Now you can start writing JavaScript between the two script tags. The final file is as follows:

JavaScript Guessing Game Guess the Number!

I am thinking of a number between 1 and 100. Can you guess what it is?

My Guess

Const randomNumber = Math.floor (Math.random () * 100) + 1 console.log ('Random Number', randomNumber) function checkGuess () {let myGuess = guess.value if (myGuess = randomNumber) {feedback.textContent = "You got it right!"} else if (myGuess > randomNumber) {feedback.textContent = "Your guess was" + myGuess + ". That's too high. Try Again!"} else if (myGuess

< randomNumber) { feedback.textContent = "Your guess was " + myGuess + ". That's too low. Try Again!" } } submitGuess.addEventListener('click', checkGuess) 要在浏览器中运行此文件,请双击文件或打开你喜欢的浏览器,点击菜单,然后选择文件->

Open the file. (if you use the Brackets software, you can also use the lightning bolt icon in the corner to open the file in the browser.)

Generate pseudorandom numbers

The first step in the guessing game is to generate a number for the player to guess. JavaScript contains several built-in global objects to help you write code. To generate random numbers, use the Math object.

Math in JavaScript has the properties and functions related to mathematics. You will use two mathematical functions to generate random numbers for your players to guess.

Math.random (), will generate a pseudorandom number between 0 and 1. (Math.random contains 0 but does not contain 1. This means that the function can generate 0 and will never produce 1)

For this game, set the random number between 1 and 100 to narrow the player's choice. Take the decimal just generated and multiply it by 100 to produce a decimal number between 0 and... It's not even a decimal between 100. At this point, you will need other steps to solve the problem.

Now, your number is still a decimal, but you want it to be an integer. To do this, you can use another function, Math.floor (), which belongs to the Math object. The purpose of Math.floor () is to return the largest integer that is less than or equal to the number you specify as an argument, which means that it is rounded to the nearest integer:

Math.floor (Math.random () * 100)

This way you will get an integer between 0 and 99, which is not the range you want. You can fix the problem in the last step by adding 1 to the result. Look at that! Now, you have a (somewhat) randomly generated number between 1 and 100:

Math.floor (Math.random () * 100) + 1 variable

Now, you need to store randomly generated numbers so that you can compare them with the player's guesses. To do this, you can store it in a variable.

JavaScript has different types of variables, which you can choose, depending on how you want to use the variable. For this game, use const and let.

Let is used to indicate that variables can be changed throughout the program.

Const is used to indicate that variables should not be modified.

Const and let still have a lot to say, but that's enough for now.

Random numbers are generated only once in the game, so you will use the const variable to save the value. You want to give the variable a name that clearly indicates what value to store, so name it randomNumber:

Const randomNumber

Note about naming: variable and function names in JavaScript are written in hump form. If there is only one word, it is all written in lowercase. If there are multiple words, the first word is lowercase, any other word begins with an uppercase letter, and there are no spaces between the words.

Print to console

Usually, you don't want to display random numbers to anyone, but developers may want to know the generated numbers to use it to help debug code. With JavaScript, you can use another built-in function, console.log (), to output numbers to the browser's console.

Most browsers contain developer tools that you can open by pressing the F12 key on the keyboard. From there, you should see a console tab. All information printed to the console will be displayed here. Since the code written so far will run immediately after the browser loads, if you look at the console, you should see the random number just generated!

Javascript game with console

Function

Next, you need a way to get the player's guess from the number input field, compare it with the random number you just generated, and provide feedback to players to know if they guessed correctly. To do this, write a function. A function is a block of code that performs a task. Functions are reusable, which means that if you need to run the same code multiple times, you can call the function without having to rewrite all the steps required to perform the task.

Depending on the version of JavaScript you use, there are many different ways to write or declare functions. Because this is the basic introduction to the language, declare functions using basic function syntax.

Start with the keyword function, and then give a function name. It is a good practice to use a name that describes the function of the function. In this example, you are checking the number of guesses made by the player, so the name of this function can be checkGuess. After the function name, write a set of parentheses, and then write a set of curly braces. You will write the body of the function between the following curly braces:

Function checkGuess () {} uses DOM

One of the purposes of JavaScript is to interact with HTML on a web page. It does this through the document object Model (DOM), the object that JavaScript uses to access and change web page information. Now, you need to get the player's guess in the number input field from HTML. You can do this using the id attribute assigned to the HTML element (in this case, guess):

JavaScript can get its value by accessing the number that the player enters into the number input field. You can do this by referencing the element's ID and adding .value at the end. This time, use the variables defined by let to hold the user's guess:

Let myGuess = guess.value

Any number entered by the player in the number input field will be assigned to the myGuess variable in the checkGuess function.

Conditional statement

The next step is to compare the player's guess with the random number generated by the game. You also want to give feedback to players to let them know whether their guesses are too high, too low or correct.

You can use a series of conditional statements to determine the feedback the player will receive. The conditional statement checks whether the condition is met before running the code block. If the condition is not met, the code stops, continues to check the next condition, or continues to execute the rest of the code without executing the code in the condition block:

If (myGuess = randomNumber) {feedback.textContent = "You got it right!"} else if (myGuess > randomNumber) {feedback.textContent = "Your guess was" + myGuess + ".That's too high. Try Again!"} else if (myGuess

< randomNumber) { feedback.textContent = "Your guess was " + myGuess + ". That's too low. Try Again!"} 第一个条件块使用比较运算符 === 将玩家的猜测与游戏生成的随机数进行比较。比较运算符检查右侧的值,将其与左侧的值进行比较,如果匹配则返回布尔值 true,否则返回布尔值 false。 如果数字匹配(猜对了!),为了让玩家知道。通过将文本添加到具有 id 属性 feedback 的 标记中来操作 DOM。就像上面的 guess.value 一样,除了不是从 DOM 获取信息,而是更改其中的信息。 元素没有像 元素那样的值,而是具有文本,因此请使用 .textContent 访问元素并设置要显示的文本: feedback.textContent = "You got it right!" 当然,玩家很有可能在第一次尝试时就猜错了,因此,如果 myGuess 和 randomNumber 不匹配,请给玩家一个线索,以帮助他们缩小猜测范围。如果第一个条件失败,则代码将跳过该 if 语句中的代码块,并检查下一个条件是否为 true。 这使你进入 else if 块: else if(myGuess >

RandomNumber) {feedback.textContent = "Your guess was" + myGuess + ".That's too high. Try Again!"}

If you read it as a sentence, it might go something like this: "if the player's guess is equal to a random number, please let them know that they are right. Otherwise, please check whether the player's guess is greater than randomNumber, and if so, show the player's guess and tell them it is too high."

The last possibility is that the player's guess is lower than the random number. To check this, add another else if block:

Else if (myGuess < randomNumber) {feedback.textContent = "Your guess was" + myGuess + ".That's too low. Try Again!"} user events and event listeners

If you look at the code above, you will see that some code runs automatically when the page loads, but some do not. You want to generate a random number before playing the game, but you don't want to check its guess before the player enters the number into the number input field and is ready to check it.

The code that generates a random number and prints it to the console is outside the scope of the function, so it runs automatically when the browser loads the script. However, for the code inside the function to run, you must call it.

There are several ways to call a function. Here, you want the function to run when the user clicks the "Check My Guess" button. Clicking the button creates a user event, which JavaScript can then "listen" on to know when the function needs to be run.

The last line of code adds an event listener to the button to call the function when the button is clicked. When it "hears" the event, it runs the function assigned to the event listener:

SubmitGuess.addEventListener ('click', checkGuess)

Just like accessing other instances of the DOM element, you can use the ID of the button to tell JavaScript which element to interact with. You can then use the built-in addEventListener function to tell JavaScript what events to listen for.

You've seen the function with parameters, but take a moment to see how it works. Parameters are the information a function needs to perform its tasks. Not all functions require arguments, but the addEventListener function requires two arguments. The first parameter it takes is the name of the user event it will listen on. Users can interact with DOM in a variety of ways, such as typing, moving the mouse, TAB on the keyboard, and pasting text. In this case, the user event you are listening for is the click of a button, so the first parameter will be click.

The second required information for addEventListener is the name of the function to run when the user clicks the button. Here we need the checkGuess function.

Now, when the player presses the "Check My Guess" button, the checkGuess function will get the value they entered in the number input field, compare it with a random number, and display feedback in the browser to let the player know what they guessed. great! Your game is ready.

This little bit of mundane JavaScript is only a small part of the function provided by this vast ecosystem. This is a language worth your time to learn, and I encourage you to keep digging and learn more.

On how to use JavaScript to write a simple game to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report