Home  >  Article  >  Web Front-end  >  借助HTML5 Canvas API制作一个简单的猜字游戏_html5教程技巧

借助HTML5 Canvas API制作一个简单的猜字游戏_html5教程技巧

PHP中文网
PHP中文网Original
2016-05-23 14:20:101798browse

二话不说,先上效果图以及源代码~
2016325105351695.png (535×346)

HTML代码

XML/HTML Code复制内容到剪贴板
<!doctype html>  
<html lang="en">  
    <head>  
        <meta charset="utf-8" />  
        <script type="text/javascript" src="chp1_guess_the_letter.js?1.1.5">script>  
        <script type="text/javascript" src="modernizr.custom.99886.js?1.1.5">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代码

JavaScript 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");   
    }   
}


从游戏名称可以看出,该游戏是猜字游戏。每局系统都会自动生成一个字母,玩家会按键盘来猜测该字母是哪一个。

例如生成的是s,玩家按了h,则游戏就会提示《小了》,因为英文字母当中h的索引比s的索引更靠前。

案例当中涉及的变量。

guesses:猜测次数
message:文字提示,指导用户如何玩该游戏
letters:文字数组,存放我们要猜测的文字的集合。这个例子用的是a到z
today:今天的日期
letterToGuess:要猜测的文字
higherOrLower:是《大了》还是《小了》
letterGuessed:已经猜测过得文字
gameOver:游戏是否结束,是布尔变量,开始的时候是false,猜对后设为true

变量的声明


JavaScript Code复制内容到剪贴板

  1. 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;


初始化游戏


JavaScript Code复制内容到剪贴板

  1. 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();
  2.     }  

通过使用Math的random()函数和floor()函数,根据文字的数组生成要猜测的文字。

并且当用户按键盘的时候监听《keyup》事件,根据传递过来的event,生成按下的键值。

因猜测游戏对大小写不敏感,为防止用户按大写字母,我们需要把值转换成小写形式。

猜测次数+1

猜测出来的文字添加到已经猜测的文字数组当中


JavaScript Code复制内容到剪贴板

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

剩下的就只有判断 大和小了。

通过indexOf函数 我们可以判断要猜测的文字和我们输入的文字在字符集上面的索引值。

如果我们输入的更靠前则提示《小了》反之《大了》

最终用户猜对了要猜测的文字 我们会在中央用大号字体显示《你猜对了》


JavaScript Code复制内容到剪贴板

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

 

至此这个功能差不多完成了吧,我们还有一个小功能,那就是通过按下按钮的方式可以把屏幕结果抓去出来。

用的函数为toDataUrl(),有兴趣的朋友研究一下。

 以上就是借助HTML5 Canvas API制作一个简单的猜字游戏_html5教程技巧的内容,更多相关内容请关注PHP中文网(www.php.cn)!


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