search
HomeWeb Front-endH5 TutorialHTML5 Canvas API to create a simple guessing game

HTML5 Canvas API to create a simple guessing game

Jul 03, 2018 pm 01:48 PM
canvashtml5game

This article mainly introduces the example sharing of making a simple guessing game with the help of HTML5 Canvas API. Each game in the game will automatically generate a letter. The player presses the keyboard to guess which letter the letter is. Friends in need can refer to it.

Without further ado, let’s start with the renderings and source code~
2016325105351695.png (535×346)

HTML code

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <script type="text/javascript" src="chp1_guess_the_letter.js"></script>
        <script type="text/javascript" src="modernizr.custom.99886.js"></script>
    </head>
    <body>
        <canvas id="canvas_guess_the_letter" width="500" height="300">
            你的浏览器不支持HTML5 Canvas   
        </canvas>
        <form>
            <input type="button" id="createImageData" value="Export Canvas Image" />;   
        </form>
    </body>
</html>

JS code

/** 
 * @author Rafael 
 */
window.addEventListener("load", eventWindowLoaded, false);   
var Debugger = function() {   
};   
Debugger.log = function(message) {   
    try {   
        console.log(message);   
    } catch(exception) {   
        return;   
    }   
}   
function eventWindowLoaded() {   
    canvasApp();   
}   
function canvasSupport() {   
    return Modernizr.canvas;   
}   
function canvasApp() {   
    var guesses = 0;   
    var message = "Guess The Letter From a(lower) to z(higher)";   
    var letters = ["a","b","c","d","e","f","g","h","i","j","k","l",   
                    "m","n","o","p","q","r","s","t","u","v","w","x","y","z"];   
    var today = new Date();   
    var letterToGuess = "";   
    var higherOrLower = "";   
    var letterGuessed = [];   
    var gameOver = false;   
    if(!canvasSupport()) {   
        return;   
    }   
    var theCanvas = document.getElementById("canvas_guess_the_letter");   
    var context = theCanvas.getContext("2d");   
    initGame();   
    function initGame() {   
        var letterIndex = Math.floor(Math.random() * letters.length);   
        letterToGuess = letters[letterIndex];   
        guesses = 0;   
        lettersGuessed = [];   
        gameOver = false;   
        window.addEventListener("keyup", eventKeyPressed, true);   
        var formElement = document.getElementById("createImageData");   
        formElement.addEventListener(&#39;click&#39;, createImageDataPressed, false);   
        drawScreen();   
    }   
    function eventKeyPressed(e) {   
        if(!gameOver) {   
            var letterPressed = String.fromCharCode(e.keyCode);   
            letterPressed = letterPressed.toLowerCase();   
            guesses++;   
            letterGuessed.push(letterPressed);   
            if(letterPressed == letterToGuess) {   
                gameOver = true;   
            } else {   
                letterIndex = letters.indexOf(letterToGuess);   
                guessIndex = letters.indexOf(letterPressed);   
                if(guessIndex < 0) {   
                    higherOrLower = "请输入正确的字符";   
                } else if(guessIndex < letterIndex) {   
                    higherOrLower = "小了";   
                } else {   
                    higherOrLower = "大了";   
                }   
            }   
            drawScreen();   
        }   
    }   
    function drawScreen() {   
        //背景 
        context.fillStyle = "#ffffaa";   
        context.fillRect(0, 0, 500, 300);   
        //箱子 
        context.strokeStyle = "#000000";   
        context.strokeRect(5, 5, 490, 290);   
        context.textBaseLine = "top";   
        //日期 
        context.fillStyle = "#000000";   
        context.font = "10px _sans";   
        context.fillText(today, 150, 20);   
        //消息 
        context.fillStyle = "#FF0000";   
        context.font = "14px _sans";   
        context.fillText(message, 125, 40);   
        //猜测次数 
        context.fillStyle = "#109900";   
        context.font = "16px _sans";   
        context.fillText("猜测次数: "+guesses, 215, 60);   
        //大还是小 
        context.fillStyle = "#000000";   
        context.font = "16px _sans";   
        context.fillText("大还是小: "+higherOrLower, 150, 135);   
        //已经猜测的字符 
        context.fillStyle = "#FF0000";   
        context.font = "16px _sans";   
        context.fillText("已经猜测的字符: "+letterGuessed.toString(), 10, 260);   
        if(gameOver) {   
            context.fillStyle = "#FF0000";   
            context.font = "40px _sans";   
            context.fillText("你猜中了", 150, 180);   
        }   
    }   
    function createImageDataPressed(e) {   
        window.open(theCanvas.toDataURL(), "canvasImage","left=0, top=0, width="+theCanvas.width+", height="+theCanvas.height+", toolbar=0, resizable=0");   
    }   
}

As can be seen from the name of the game, this game is a guessing game. The system automatically generates a letter in each game, and players press the keyboard to guess which letter it is.

For example, if s is generated and the player presses h, the game will prompt "Small" because the index of h in the English alphabet is higher than the index of s.

Variables involved in the case.

guesses: number of guesses
message: text prompts, instructing users how to play the game
letters: text array, storing the collection of words we want to guess. This example uses a to z
today: today’s date
letterToGuess: the text to be guessed
higherOrLower: whether it is "bigger" or "smaller"
letterGuessed: the text has been guessed
gameOver: Whether the game is over or not is a Boolean variable. It is false at the beginning and is set to true after guessing correctly

Declaration of variable

var guesses = 0;   
var message = "Guess The Letter From a(lower) to z(higher)";   
var letters = ["a","b","c","d","e","f","g","h","i","j","k","l",   
                "m","n","o","p","q","r","s","t","u","v","w","x","y","z"];   
var today = new Date();   
var letterToGuess = "";   
var higherOrLower = "";   
var letterGuessed = [];   
var gameOver = false;

Initialize the game

function initGame() {   
        var letterIndex = Math.floor(Math.random() * letters.length);   
        letterToGuess = letters[letterIndex];   
        guesses = 0;   
        lettersGuessed = [];   
        gameOver = false;   
        window.addEventListener("keyup", eventKeyPressed, true);   
        var formElement = document.getElementById("createImageData");   
        formElement.addEventListener(&#39;click&#39;, createImageDataPressed, false);   
        drawScreen();   
    }

By using Math’s random() function and floor() function, generate the text to be guessed based on the text array.

And listen to the "keyup" event when the user presses the keyboard, and generate the pressed key value based on the passed event.

Because the guessing game is not case-sensitive, to prevent users from pressing uppercase letters, we need to convert the value to lowercase.

Number of guesses 1

The guessed text is added to the already guessed text array

var letterPressed = String.fromCharCode(e.keyCode);   
letterPressed = letterPressed.toLowerCase();   
guesses++;   
letterGuessed.push(letterPressed);

The rest is Only the judgment of big and small can be made.

Through the indexOf function, we can determine the index value of the text to be guessed and the text we input in the character set.

If we enter further forward, it will prompt "Small", otherwise "Big"

If the end user guesses the text to be guessed correctly, we will display "You" in a large font in the center Guessed it”

letterIndex = letters.indexOf(letterToGuess);   
guessIndex = letters.indexOf(letterPressed);   
if(guessIndex < 0) {   
    higherOrLower = "请输入正确的字符";   
} else if(guessIndex < letterIndex) {   
    higherOrLower = "小了";   
} else {   
    higherOrLower = "大了";   
}

Now this function is almost completed, we still have a small function, that is, you can grab the screen results by pressing the button.

The function used is toDataUrl(), friends who are interested can study it.

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

HTML5 Canvas realizes the special effects of fireworks blooming

Sharing introduction about html5 canvas WeChat poster

Canvas realizes the effect code of dynamic ball overlapping

The above is the detailed content of HTML5 Canvas API to create a simple guessing game. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
H5: New Features and Capabilities for Web DevelopmentH5: New Features and Capabilities for Web DevelopmentApr 29, 2025 am 12:07 AM

H5 brings a number of new functions and capabilities, greatly improving the interactivity and development efficiency of web pages. 1. Semantic tags such as enhance SEO. 2. Multimedia support simplifies audio and video playback through and tags. 3. Canvas drawing provides dynamic graphics drawing tools. 4. Local storage simplifies data storage through localStorage and sessionStorage. 5. The geolocation API facilitates the development of location-based services.

H5: Key Improvements in HTML5H5: Key Improvements in HTML5Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

HTML5: The Standard and its Impact on Web DevelopmentHTML5: The Standard and its Impact on Web DevelopmentApr 27, 2025 am 12:12 AM

The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

H5 Code Examples: Practical Applications and TutorialsH5 Code Examples: Practical Applications and TutorialsApr 25, 2025 am 12:10 AM

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

The Connection Between H5 and HTML5: Similarities and DifferencesThe Connection Between H5 and HTML5: Similarities and DifferencesApr 24, 2025 am 12:01 AM

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

The Building Blocks of H5 Code: Key Elements and Their PurposeThe Building Blocks of H5 Code: Key Elements and Their PurposeApr 23, 2025 am 12:09 AM

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

HTML5 and H5: Understanding the Common UsageHTML5 and H5: Understanding the Common UsageApr 22, 2025 am 12:01 AM

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5: The Building Blocks of the Modern Web (H5)HTML5: The Building Blocks of the Modern Web (H5)Apr 21, 2025 am 12:05 AM

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

See all articles

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment