HTML5 Canvas API制作简单的猜字游戏

不言
Lepaskan: 2018-07-03 13:48:38
asal
2746 orang telah melayarinya

这篇文章主要介绍了借助HTML5 Canvas API制作一个简单的猜字游戏的实例分享,游戏中每局会自动生成一个字母,玩家按键盘来猜测该字母是哪一个,需要的朋友可以参考下

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

HTML代码

<!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>
Salin selepas log masuk

JS代码

/** 
 * @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");   
    }   
}
Salin selepas log masuk

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

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

案例当中涉及的变量。

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

变量的声明

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;
Salin selepas log masuk

初始化游戏

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();   
    }
Salin selepas log masuk

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

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

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

猜测次数+1

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

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

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

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

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

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

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

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

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

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

HTML5 Canvas实现烟花绽放的特效

关于html5 canvas 微信海报的分享介绍

canvas实现动态小球重叠的效果代码

Atas ialah kandungan terperinci HTML5 Canvas API制作简单的猜字游戏. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Label berkaitan:
sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!