canvas猜数游戏

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>猜数</title>
</head>
<body> <canvas id="box" width="500" height="300"></canvas>
<form>
<input type="text" id="guessValue" placeholder="port Canvas Image">
<button id="createImageData">猜猜看?!</button>
</form>
<script>
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; function initGame() {
var letterIndex = Math.floor(Math.random() * letters.length);
letterToGuess = letters[letterIndex];
guess = 0;
letterGuessed = [];
gameOver = false;
window.addEventListener("keydown", eventKeyPressed, true);
drawScreen();
var formElement = document.querySelector("#createImageData");
formElement.addEventListener("click",createImageDataPressed,false);
} 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);
console.log(guessIndex);
if (guessIndex < 0) {
higherOrLower = "That is not a letter!"
} else if (guessIndex > letterIndex) {
higherOrLower = "Lower";
} else {
higherOrLower = "higher";
}
}
drawScreen();
}
}
var canvas = document.querySelector("#box");
var ctx = canvas.getContext("2d");
function drawScreen(){
//背景
ctx.fillStyle = "#ffffaa";
ctx.fillRect(0,0,500,300);
//边框
ctx.strokeStyle = "#000000";
ctx.strokeRect(5,5,490,290);
ctx.textBaseline = "top";
//日期
ctx.fillStyle = "#000000";
ctx.font = "10px Sans-Serif";
ctx.fillText(today,150,10);
//消息
ctx.fillStyle = "#ff0000";
ctx.font = "14px Sans-serif";
ctx.fillText(message,125,30); //猜的次数
ctx.fillStyle = "#109910";
ctx.font = "16px Sans-serif";
ctx.fillText("guess: "+guesses+"次!",215,50);
//显示higher或lower
ctx.fillStyle = "#000";
ctx.font = "16px Sans-Serif";
ctx.fillText("Higher or Lower: "+higherOrLower,150,125);
//猜过的字母
ctx.fillStyle = "#ff0000";
ctx.font = "16px Sans-Serif";
ctx.fillText("Letters Guessed: "+letterGuessed.toString(),10,260);
if(gameOver){
ctx.fillStyle = "#ff0000";
ctx.font = "40px _sans-serif";
ctx.fillText("You got it!",150,180);
}
}
function createImageDataPressed(e){
window.open(canvas.toDataURL(),"canvasImage","left=0,top=0,width="+canvas.width +",height="+canvas.height +",toolbar=0,resizeable=0");
}
initGame();
</script>
</body>
</html>
上一篇:java 日志脱敏框架 sensitive-新版本0.0.2-深度拷贝,属性为对象和集合的支持


下一篇:Ubuntu读取/root/.profile时发现错误:mesg:ttyname fa