Make a simple word guessing game with HTML5 canvas API

Time:2021-7-24

Without saying a word, first on the renderings and source code~
2016325105351695.png (535×346)

HTML code

XML/HTML CodeCopy contents to clipboard
  1. <!doctype html>  
  2. <html lang=“en”>  
  3.     <head>  
  4.         <meta charset=“utf-8” />  
  5.         <script type=“text/javascript” src=“chp1_guess_the_letter.js”></script>  
  6.         <script type=“text/javascript” src=“modernizr.custom.99886.js”></script>  
  7.     </head>  
  8.     <body>  
  9.         <canvas id=“canvas_guess_the_letter” width=“500” height=“300”>  
  10. Your browser does not support HTML5   Canvas
  11.         </canvas>  
  12.         <form>  
  13.             <input type=“button” id=“createImageData” value=“Export Canvas Image” />;   
  14.         </form>  
  15.     </body>  
  16. </html>  

JS code

JavaScript CodeCopy contents to clipboard
  1. /**  
  2.  * @author Rafael  
  3.  */  
  4. window.addEventListener(“load”, eventWindowLoaded, false);   
  5.   
  6. var Debugger = function() {   
  7.        
  8. };   
  9. Debugger.log = function(message) {   
  10.     try {   
  11.         console.log(message);   
  12.     } catch(exception) {   
  13.         return;   
  14.     }   
  15. }   
  16.   
  17. function eventWindowLoaded() {   
  18.     canvasApp();   
  19. }   
  20.   
  21. function canvasSupport() {   
  22.     return Modernizr.canvas;   
  23. }   
  24.   
  25. function canvasApp() {   
  26.     var guesses = 0;   
  27.     var message = “Guess The Letter From a(lower) to z(higher)”;   
  28.     var letters = [“a”,“b”,“c”,“d”,“e”,“f”,“g”,“h”,“i”,“j”,“k”,“l”,   
  29.                     “m”,“n”,“o”,“p”,“q”,“r”,“s”,“t”,“u”,“v”,“w”,“x”,“y”,“z”];   
  30.     var today = new Date();   
  31.     var letterToGuess = “”;   
  32.     var higherOrLower = “”;   
  33.     var letterGuessed = [];   
  34.     var gameOver = false;   
  35.        
  36.     if(!canvasSupport()) {   
  37.         return;   
  38.     }   
  39.        
  40.     var theCanvas = document.getElementById(“canvas_guess_the_letter”);   
  41.     var context = theCanvas.getContext(“2d”);   
  42.        
  43.     initGame();   
  44.        
  45.     function initGame() {   
  46.         var letterIndex = Math.floor(Math.random() * letters.length);   
  47.         letterToGuess = letters[letterIndex];   
  48.         guesses = 0;   
  49.         lettersGuessed = [];   
  50.         gameOver = false;   
  51.         window.addEventListener(“keyup”, eventKeyPressed, true);   
  52.         var formElement = document.getElementById(“createImageData”);   
  53.         formElement.addEventListener(‘click’, createImageDataPressed, false);   
  54.         drawScreen();   
  55.     }   
  56.        
  57.     function eventKeyPressed(e) {   
  58.         if(!gameOver) {   
  59.             var letterPressed = String.fromCharCode(e.keyCode);   
  60.             letterPressed = letterPressed.toLowerCase();   
  61.             guesses++;   
  62.             letterGuessed.push(letterPressed);   
  63.             if(letterPressed == letterToGuess) {   
  64.                 gameOver = true;   
  65.             } else {   
  66.                 letterIndex = letters.indexOf(letterToGuess);   
  67.                 guessIndex = letters.indexOf(letterPressed);   
  68.                 if(guessIndex < 0) {   
  69.                     higherOrLower = “Please enter the correct characters”;   
  70.                 } else if(guessIndex < letterIndex) {   
  71.                     higherOrLower = “Small”;   
  72.                 } else {   
  73.                     higherOrLower = “Big”;   
  74.                 }   
  75.             }   
  76.             drawScreen();   
  77.         }   
  78.     }   
  79.        
  80.     function drawScreen() {   
  81.         //Background  
  82.         context.fillStyle = “#ffffaa”;   
  83.         context.fillRect(0, 0, 500, 300);   
  84.            
  85.         //Box  
  86.         context.strokeStyle = “#000000”;   
  87.         context.strokeRect(5, 5, 490, 290);   
  88.         context.textBaseLine = “top”;   
  89.            
  90.         //Date  
  91.         context.fillStyle = “#000000”;   
  92.         context.font = “10px _sans”;   
  93.         context.fillText(today, 150, 20);   
  94.            
  95.         //News  
  96.         context.fillStyle = “#FF0000”;   
  97.         context.font = “14px _sans”;   
  98.         context.fillText(message, 125, 40);   
  99.            
  100.         //Guess times  
  101.         context.fillStyle = “#109900”;   
  102.         context.font = “16px _sans”;   
  103.         context.fillText(“Guess times:  “+guesses, 215, 60);   
  104.            
  105.         //Big or small  
  106.         context.fillStyle = “#000000”;   
  107.         context.font = “16px _sans”;   
  108.         context.fillText(“Big or small:  “+higherOrLower, 150, 135);   
  109.            
  110.         //Characters that have been guessed  
  111.         context.fillStyle = “#FF0000”;   
  112.         context.font = “16px _sans”;   
  113.         context.fillText(“Characters guessed:  “+letterGuessed.toString(), 10, 260);   
  114.            
  115.         if(gameOver) {   
  116.             context.fillStyle = “#FF0000”;   
  117.             context.font = “40px _sans”;   
  118.             context.fillText(“You guessed right”, 150, 180);   
  119.         }   
  120.     }   
  121.        
  122.     function createImageDataPressed(e) {   
  123.         window.open(theCanvas.toDataURL(), “canvasImage”,“left=0, top=0, width=”+theCanvas.width+“, height=”+theCanvas.height+“, toolbar=0, resizable=0”);   
  124.     }   
  125. }  

As can be seen from the name of the game, the game is a guessing game. Each game system will automatically generate a letter, and players will 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 letter is higher than that of S.

Variables involved in the case.

Guess: guess times
Message: text prompt to guide users how to play the game
Letters: a text array that holds a collection of words we want to guess. This example uses a to Z
Today: today’s date
Letter to guess: the text to guess
Higher or lower: big or small
Letter guessed: text that has been guessed
Gameover: whether the game is over or not is a boolean variable. It is false at the beginning and set to true after guessing correctly

Declaration of variables

JavaScript CodeCopy contents to clipboard
  1. var guesses = 0;   
  2. var message = “Guess The Letter From a(lower) to z(higher)”;   
  3. var letters = [“a”,“b”,“c”,“d”,“e”,“f”,“g”,“h”,“i”,“j”,“k”,“l”,   
  4.                 “m”,“n”,“o”,“p”,“q”,“r”,“s”,“t”,“u”,“v”,“w”,“x”,“y”,“z”];   
  5. var today = new Date();   
  6. var letterToGuess = “”;   
  7. var higherOrLower = “”;   
  8. var letterGuessed = [];   
  9. var gameOver = false;  

Initialize game

JavaScript CodeCopy contents to clipboard
  1. function initGame() {   
  2.         var letterIndex = Math.floor(Math.random() * letters.length);   
  3.         letterToGuess = letters[letterIndex];   
  4.         guesses = 0;   
  5.         lettersGuessed = [];   
  6.         gameOver = false;   
  7.         window.addEventListener(“keyup”, eventKeyPressed, true);   
  8.         var formElement = document.getElementById(“createImageData”);   
  9.         formElement.addEventListener(‘click’, createImageDataPressed, false);   
  10.         drawScreen();   
  11.     }  

By using math’s random () function and floor () function, the text to be guessed is generated according to the array of text.

In addition, when the user presses the keyboard, it listens to the Keyup event and generates the pressed key value according to the passed event.

Since the guessing game is not case sensitive, we need to convert the value to lowercase in order to prevent users from pressing uppercase letters.

Guess times + 1

The guessed text has been added to the guessed array

JavaScript CodeCopy contents to clipboard
  1. var letterPressed = String.fromCharCode(e.keyCode);   
  2. letterPressed = letterPressed.toLowerCase();   
  3. guesses++;   
  4. letterGuessed.push(letterPressed);   

The only thing left is to judge the big and the small.

Through the indexof function, we can judge the text to be guessed and the index value of the text we enter on the character set.

If the input is closer to the front, it will prompt “small” and vice versa

If the end user guesses the text to be guessed correctly, we will display “you guessed right” in large font in the center

JavaScript CodeCopy contents to clipboard
  1. letterIndex = letters.indexOf(letterToGuess);   
  2. guessIndex = letters.indexOf(letterPressed);   
  3. if(guessIndex < 0) {   
  4.     higherOrLower = “Please enter the correct characters”;   
  5. else if(guessIndex < letterIndex) {   
  6.     higherOrLower = “Small”;   
  7. else {   
  8.     higherOrLower = “Big”;   
  9. }  

 

So far, this function is almost completed. We also have a small function, that is, we can grab the screen results by pressing the button.

The function used is todataurl(), which is studied by interested friends.

Recommended Today

VBS obtains the operating system and its version number

VBS obtains the operating system and its version number ? 1 2 3 4 5 6 7 8 9 10 11 12 ‘************************************** ‘*by r05e ‘* operating system and its version number ‘************************************** strComputer = “.” Set objWMIService = GetObject(“winmgmts:” _  & “{impersonationLevel=impersonate}!\\” & strComputer & “\root\cimv2”) Set colOperatingSystems = objWMIService.ExecQuery _  (“Select * from […]