Use HTML to create a pancake spreading game

Instead of passively waiting for the arrival of 35, people who are well-established in the industry should take the initiative to explore side jobs and implement an HTML pancake-making game, combining traditional methods and modern technology, and are committed to making delicious and creative pancakes.

Insert image description here

introduction

Introduction

In this article, we will introduce how to use HTML, CSS and JavaScript to create an interesting pancake spreading game. Pancakes are a traditional Chinese delicacy. In the game, players need to simulate making pancakes to get high scores. We will start by making a game interface, gradually add interactive functions, and finally realize a complete mini-game. In addition, we will also share some tips and experiences for optimizing and scaling the game. Even beginners can follow the steps in this article to easily create a unique game and experience the fun of making games.

Game background

In this fast-paced modern society, people are often busy with trivial matters, and it is difficult to find a moment of relaxation and fun. In order to relieve stress and let people regain their love for food, the entire process of making pancakes can be reproduced on the web page by using technologies such as HTML, CSS and JavaScript. In the game, players will play the role of a "pancake master" and need to learn to master the amount of flour and time to spread out perfect pancakes. The difficulty of the game will gradually increase, and players need to continuously improve their skills and pursue higher scores.

Through this small game, we hope to bring joy and challenge to players, and let everyone feel the fun of making food again. This pancake making game will be a fun choice for both professional chefs and people interested in pancakes.

Insert image description here

Materials and tools needed

HTML basics

To master the basic knowledge of HTML, you can start from the following aspects:

  1. What is HTML: Definition, role and historical background of HTML.

  2. Structure of HTML: The basic structure of HTML, including document type, role of head and body, etc.

  3. HTML text tags: HTML text tags, which are HTML elements and tags, such as paragraphs, titles, lists, links, etc. Explain how to write HTML code to implement these tags.

  4. HTML image tag: How HTML embeds images, and learn about some properties and usage of the img tag.

  5. HTML table tags: How to use HTML to create tables, including the use of table, tr, th, td and other tags.

  6. HTML form markup: How to use HTML to create a form, including the use of form, input, textarea and other tags, you can properly understand the use of some common form controls.

  7. HTML style markup: How to use CSS to style HTML.

Through the study of the above aspects, you can understand the basic knowledge of HTML, master the basic structure and markup language of HTML, and implement simple HTML pages.

CSS styles

To master the basics of CSS, you can start from the following aspects:

  1. What is CSS: Definition, role and historical background of CSS.

  2. Three ways of writing CSS styles: the usage, advantages and disadvantages of CSS internal style sheets, external style sheets and inline style sheets.

  3. CSS selectors: Types and usage of CSS selectors, including tag selectors, ID selectors, class selectors, attribute selectors, pseudo-class selectors, etc.

  4. CSS styles: types and usage of CSS styles, including text styles, font styles, background styles, border styles, floating styles, positioning styles, etc.

  5. CSS box model: The concepts and components of the CSS box model, and how to lay out HTML pages through the box model.

  6. CSS cascading and inheritance: Explain the cascading and inheritance mechanisms of CSS, and how to use these mechanisms to improve style reusability and optimize CSS code.

  7. Responsive Design: How to use CSS media queries and elastic layout to implement responsive design to adapt to different devices and screen sizes.

Through the study of the above aspects, you can understand the basic knowledge of CSS, master the writing method and basic grammatical rules of CSS styles, and implement simple CSS style definitions.

JavaScript programming

To master the basics of JavaScript, you can start from the following aspects:

  1. What is JavaScript: Definition, role and historical background of JavaScript.

  2. Basic syntax of JavaScript: JavaScript syntax rules, including basic concepts such as variable declarations, data types, operators, conditional statements, loop statements, etc.

  3. JavaScript functions: The definition and use of functions in JavaScript, including function parameters, return values, scopes, etc. It can also explain the writing of some common built-in functions and custom functions.

  4. JavaScript arrays and objects: The concepts and usage of arrays and objects in JavaScript, including array traversal, addition, deletion and sorting, object properties and methods, etc.

  5. JavaScript DOM operations: How to use JavaScript to manipulate elements in HTML documents, including obtaining elements, modifying element attributes, adding event listeners, etc.

  6. Error handling in JavaScript: Common error types and error handling mechanisms in JavaScript, and how to use try...catch statements to catch and handle errors.

  7. Asynchronous programming in JavaScript: The asynchronous programming model in JavaScript, including callback functions, Promise, async/await, etc., and how to handle asynchronous operations and avoid callback hell.

  8. JavaScript modularization: The concept and usage of JavaScript modularization, including ES6 modular syntax and commonly used modular tools such as Webpack, Babel, etc.

Through the introduction of the above aspects, you can understand the basic knowledge of JavaScript, master the basic syntax and common functions of JavaScript, and be able to write simple JavaScript programs.

Build game interface

Create HTML file

HTML is the basis of web pages. To make a pancake-making game, you need to create an HTML file first. Next, we will introduce how to create an HTML file and some basic code.

  1. Create a new HTML file
    Open the editor and create a new page.

  2. Adding HTML template code
    HTML template code is a standard HTML file structure, including DOCTYPE, html, head and body tags. The following is a basic HTML template code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>摊煎饼小游戏</title>
  </head>
  <body>
    <!-- 在这里加入页面内容 -->
  </body>
</html>
  1. Add page content
    You can add page content inside the body tag. According to the requirements of the pancake-making game, elements such as game screens and related operation buttons need to be added. Here is a simple example code:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>摊煎饼小游戏</title>
  </head>
  <body>
    <h1>欢迎来到摊煎饼小游戏</h1>
    <div id="pancake"></div>
    <button id="flip">翻转</button>
    <button id="stack">叠加</button>
    <script src="game.js"></script>
  </body>
</html>

In this code, we added a h1label to display the game title, a pancakediv element with id to display the pancakes, and two buttons for player operations. It should be noted that we also added a script tag within the body tag and introduced a JavaScript file named game.js.

At this point, the creation of the HTML file and the writing of the basic part of the code have been completed. Next, you need to use CSS styles and JavaScript code to implement the specific functions of the game.

Set up the game canvas

Setting up the game canvas in HTML requires the use of the canvas tag. Here is a sample code that sets up the game canvas

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>摊煎饼小游戏</title>
    <style>
      #gameCanvas {
    
    
        border: 1px solid black;
      }
    </style>
  </head>
  <body>
    <h1>欢迎来到摊煎饼小游戏</h1>
    <canvas id="gameCanvas" width="400" height="300"></canvas>
    <script src="game.js"></script>
  </body>
</html>

In the above code, an element of is added idas gameCanvasthe canvasgame canvas. By setting its widthand heightproperties, you can determine the size of the canvas. canvasAt the same time, some simple styles such as borders are also added.

In this example, canvasset the width to 400 pixels and the height to 300 pixels. Developers can adjust these values ​​to suit your game layout.

You can then use JavaScriptcode to draw pancakes on the canvas, control game logic, etc. The files in the sample code above need to game.jsbe linked to the appropriate locations in order to add the game's specific functionality.

Design pancake elements

In the previous section, a canvas element with the ID gameCanvas has been created for drawing the game canvas. Next, you will write JavaScript code in the game.js file to draw the pancake element.

// 获取canvas元素和上下文
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');

// 绘制摊煎饼的函数
function drawPancake() {
    
    
  ctx.beginPath();
  ctx.arc(200, 150, 50, 0, Math.PI * 2);
  ctx.fillStyle = 'brown';
  ctx.fill();

  ctx.beginPath();
  ctx.arc(185, 130, 8, 0, Math.PI * 2);
  ctx.arc(215, 130, 8, 0, Math.PI * 2);
  ctx.fillStyle = 'white';
  ctx.fill();

  ctx.beginPath();
  ctx.arc(185, 120, 5, 0, Math.PI * 2);
  ctx.arc(215, 120, 5, 0, Math.PI * 2);
  ctx.fillStyle = 'black';
  ctx.fill();
}

// 调用绘制摊煎饼的函数
drawPancake();

First use to document.getElementByIdget the element and use to get the drawing context. Then a function is defined to draw the shape of the pancake.IDgameCanvascanvasgetContext('2d')canvas的2DdrawPancake

Inside drawPancakethe function, a method is used beginPathto start creating a path, and arca method is used to draw a circular pancake, and set the color and fill style. By calling arcmethods and fillmethods multiple times, details like pancakes can be drawn.

Finally, at the end of the code a function is called drawPancaketo perform the drawing operation.

With the above code, a simple pancake shape can be drawn on the game canvas.

Add game interaction

Monitor user operations

Write some JavaScript code to implement the logic of the pancake spreading game. In this game, the player needs to control a spatula to move back and forth on the screen, and press the space bar to flip the pancake over at the appropriate time.

// 获取游戏画布和上下文
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');

// 定义变量
let position = canvas.width / 2; // 煎饼位置
let velocity = 0; // 煎饼速度
let flipped = false; // 是否已经翻面

// 监听键盘事件
document.addEventListener('keydown', event => {
    
    
  if (event.code === 'Space') {
    
    
    flip();
  }
});

// 翻转煎饼
function flip() {
    
    
  if (!flipped) {
    
    
    velocity = -10;
    flipped = true;
  }
}

// 更新游戏状态
function update() {
    
    
  // 清空画布
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // 绘制煎饼
  ctx.fillStyle = '#de9967';
  ctx.fillRect(position - 25, canvas.height - 75, 50, 50);

  // 更新煎饼位置和速度
  position += velocity;
  velocity += 1;

  // 判断煎饼是否落地
  if (canvas.height - 75 < 0) {
    
    
    velocity = 0;
    flipped = false;
    position = canvas.width / 2;
  }

  // 循环更新游戏状态
  requestAnimationFrame(update);
}

// 开始游戏
update();

In the above JavaScriptcode, the canvas element and context object are first obtained, and some variables are defined to save the pancake's position, speed, flip status and other information. Then it listens for keyboard events and calls a function to flip the pancake when the user presses the space bar flip.

Inside updatethe function, first use clearRectthe method to clear the canvas and use fillRectthe method to draw the shape of the pancake. Then the position and speed of the pancake are updated, and whether the game state needs to be reset is determined by judging whether the pancake has landed.

Finally, use requestAnimationFramethe method to update the game status in a loop to achieve the effect of dynamically updating the screen.

Implement pancake spreading animation

In each frame, the canvas needs to be cleared first, and then the pancake's position needs to be redrawn. This ensures that only the latest pancake status is displayed on the canvas to achieve animation effects.

// 清空画布
ctx.clearRect(0, 0, canvas.width, canvas.height);

// 绘制煎饼
ctx.fillStyle = '#de9967';
ctx.fillRect(position - 25, canvas.height - 75, 50, 50);

Use clearRectthe method to clear the canvas. This method receives four parameters: the x coordinate of the upper left corner, the y coordinate of the upper left corner, and the cleared width and height. Then use fillRectthe method to redraw the position of the pancake.

Through the above steps, you can achieve the animation effect of pancakes. In each frame, update the state of the pancake, clear the canvas, and redraw the position of the pancake. Repeat this process to achieve a smooth pancake animation effect.

Calculate score and game over

The player's score is equal to the height of the pancake landing. We can calculate the score when the pancake hits the ground and display the score on the screen.

// 计算得分
if (position + 25 >= canvas.height) {
    
    
    score = Math.floor((canvas.height - 75 - position) / 10);
    isGameOver = true;
}

// 显示得分
if (isGameOver) {
    
    
    ctx.font = 'bold 30px Arial';
    ctx.textAlign = 'center';
    ctx.fillText(`得分: ${
    
    score}`, canvas.width / 2, canvas.height / 2);
}

In the above code, it is determined whether the game is over by judging whether the position of the pancake reaches the bottom of the canvas, and the player's score is calculated. If the game is over, use fillTextthe method to display the score result in the center of the screen.

Game Over
When the player scores, the game is over and we need to stop the game loop and give the option to restart the game.

// 结束游戏
if (isGameOver) {
    
    
    cancelAnimationFrame(gameLoop);
    const restartBtn = document.createElement('button');
    restartBtn.innerText = '重新开始';
    restartBtn.addEventListener('click', () => location.reload());
    document.body.appendChild(restartBtn);
}

Use cancelAnimationFramea method to stop the game loop and create a button to restart the game. When the player clicks this button, the page reloads and the game can start again.

Guess you like

Origin blog.csdn.net/weixin_42794881/article/details/133930291