Home > Web Front-end > H5 Tutorial > body text

HTML5 Canvas API to create a simple guessing game

不言
Release: 2018-07-03 13:48:38
Original
2747 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!