Home Web Front-end H5 Tutorial HTML5 Canvas API to create a simple guessing game

HTML5 Canvas API to create a simple guessing game

Jul 03, 2018 pm 01:48 PM
canvas html5 game

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>
Copy after login

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");   
    }   
}
Copy after login

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;
Copy after login

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();   
    }
Copy after login

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);
Copy after login

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 = "大了";   
}
Copy after login

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 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)

Table Border in HTML Table Border in HTML Sep 04, 2024 pm 04:49 PM

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

Nested Table in HTML Nested Table in HTML Sep 04, 2024 pm 04:49 PM

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

HTML margin-left HTML margin-left Sep 04, 2024 pm 04:48 PM

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

HTML Table Layout HTML Table Layout Sep 04, 2024 pm 04:54 PM

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

HTML Input Placeholder HTML Input Placeholder Sep 04, 2024 pm 04:54 PM

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

HTML Ordered List HTML Ordered List Sep 04, 2024 pm 04:43 PM

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

Moving Text in HTML Moving Text in HTML Sep 04, 2024 pm 04:45 PM

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

HTML onclick Button HTML onclick Button Sep 04, 2024 pm 04:49 PM

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.

See all articles