Racing game - [Need for Speed] (include source code inscode to run online)

foreword

insert image description here
"Author's Homepage" : Sprite Youbai Bubbles
"Personal Website" : Sprite's personal website
"Recommendation Column" :

Java one-stop service
Front-end cool code sharing
uniapp-from construction to promotion
From 0 to hero, Vue's road to god
Solving algorithm, one column is enough
Let's talk about architecture from 0
The subtle way of data circulation

Please add a picture description

Get to know inscode

insert image description here
CSDN's latest Inscode service is an online programming tool designed to provide developers with a convenient environment for writing, running and sharing code, allowing developers to quickly write and run code without building a programming environment locally.

Inscode supports multiple programming languages, including Java, Python, C++, etc., and also supports writing HTML, CSS and JavaScript codes. It provides a complete operating environment, allowing the code to run directly on the web page and output the results, real-time debugging, convenient and fast. At the same time, Inscode also provides a sharing function, which can easily share the code with others.

To use Inscode, just visit its website https://inscode.csdn.net/
personal homepage: why_does_it_work

First look at the running effect

insert image description here
Here you can directly view the source code content , refresh , and the last one is to zoom in and jump to the webpage

View source code content

insert image description here

get item

Click on the link: Need for Speed
insert image description here

insert image description here

Simple analysis of the code

insert image description here

body-index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="HandheldFriendly" content="True">
<meta name="apple-touch-fullscreen" content="yes" />
<meta name="viewport" content="initial-scale=1.0,maximum-scale=1.01, minimal-ui" />
<title>极品飞车</title>
<meta name="keywords" content="HTML5,汽车赛道,飙车游戏" />
<meta name="description" content="HTML5汽车赛道飙车游戏代码下载。H5精品短跑赛车俱乐部游戏,赛车游戏源代码。游戏介绍:鼠标,键盘左右键,控制赛车方向,让我们开始赛车比赛游戏吧。兼容手机移动端(横屏模式效果更好,左右晃动控制方向),带背景音效。" /> 
<meta name="author" content="js代码" />
<meta name="copyright" content="js代码" />
<style>
		body {
      
      
			margin: 0px;
			padding: 0px;
			width: 100%;
			background-color:black;
		}	

		canvas {
      
      	
			-ms-touch-action: none;
			image-rendering: -o-crisp-edges;           
			image-rendering: optimize-contrast;        
			-ms-interpolation-mode: nearest-neighbor;  
			-webkit-tap-highlight-color: rgba(0,0,0,0);
			-moz-tap-highlight-color: rgba(0,0,0,0);
			tap-highlight-color: rgba(0,0,0,0);
			user-select: none;
			-webkit-touch-callout: none;
			-webkit-user-select: none;
			-moz-user-select: none;
			-ms-user-select: none;
		} 
	</style>
<script src="viewporter.js"></script>
</head>
<body>
<div id="viewporter">
<canvas id="canvas" moz-opaque></canvas>
</div>
</body>
<script src="TweenMax.min.js"></script>
<script src="howler.js"></script>
<script src="app.js"></script>
</html>
  1. <!DOCTYPE html>: This is the doctype declaration for an HTML document, specifying the version of HTML the document conforms to.

  2. <html lang="en">: The beginning of the HTML tag, the lang attribute specifies that the language used by the page is English.

  3. <head>: Header tag for containing metadata about the document and referencing external resources.

  4. <meta charset="utf-8">: Set the character encoding to UTF-8 to ensure that non-English characters can be displayed correctly on the page.

  5. <meta name="apple-mobile-web-app-capable" content="yes" />: Used to add a web page to the home screen of an iOS device and make it run in full screen mode.

  6. <meta name="HandheldFriendly" content="True">: Tells the browser that this page is suitable for viewing on handheld devices.

  7. <meta name="apple-touch-fullscreen" content="yes" />: Specifies that the page is displayed in full screen mode on Apple devices.

  8. <meta name="viewport" content="initial-scale=1.0,maximum-scale=1.01, minimal-ui" />: Set the initial zoom level and maximum zoom level of the viewport, and enable the Minimal UI mode of iOS.

  9. <title>HTML5汽车赛道飙车游戏</title>: Set the title of the page, which will be displayed on the title bar or tab of the browser.

  10. <meta name="keywords" content="HTML5,汽车赛道,飙车游戏" />: Provide keywords related to the page to help search engines understand the content of the page.

  11. <meta name="description" content="HTML5汽车赛道飙车游戏代码下载。H5精品短跑赛车俱乐部游戏,赛车游戏源代码。游戏介绍:鼠标,键盘左右键,控制赛车方向,让我们开始赛车比赛游戏吧。兼容手机移动端(横屏模式效果更好,左右晃动控制方向),带背景音效。" />: Provide a description of the page for search engine display results and page summaries.

  12. <meta name="author" content="js代码 />

  13. <meta name="copyright" content="js代码(www.jsdaima.com)" />: Claims the copyright information of the page.

  14. <style>: Begin CSS style block, used to define the style of the page.

  15. bodyand canvasStyle: Set the background color and canvas style of the page.

  16. <script src="viewporter.js"></script>: imports an external JavaScript file named "viewporter.js".

  17. <body>: The main body of the page.

  18. <div id="viewporter">: a div element with an id of "viewporter".

  19. <canvas id="canvas" moz-opaque></canvas>: A canvas element with an id of "canvas" used to draw the game interface.

  20. </body>: Closing tag for the main body of the page.

  21. <script src="TweenMax.min.js"></script>: Import an external JavaScript file named "TweenMax.min.js", which may contain some libraries or frameworks for animation effects.

  22. <script src="howler.js"></script>: imports an external JavaScript file named "howler.js", which may contain a library or framework for handling background sound effects.

  23. <script src="app.js"></script>: Imports an external JavaScript file named "app.js" that contains the actual game logic and function code.

  24. </html>: The closing tag of an HTML tag.

Game logic and function code: app.js

insert image description here

Setup before the game starts

function initSplash() {
    gameState = "splash",
    resizeCanvas(),
    1 != audioType || muted || music.play(),
    initStartScreen()
}
  1. gameState = "splash": This line of code gameStatesets the value of the variable to the string "splash", indicating that the game state is "splash".

  2. resizeCanvas(): This function resizes the canvas, possibly based on the window size or other parameters.

  3. 1 != audioType || muted || music.play(): This line of code checks the condition. If audioTypenot equal to 1 (probably meaning some audio type is selected), or muted(mute) is false, then it will execute music.play(), i.e. play music.

  4. initStartScreen(): This function is used to initialize the start interface, which may be to create a start button, load resources, and so on.

Therefore, initSplashthe role of the function is to set the game state to "splash screen" when the game starts, adjust the size of the canvas, play music according to the conditions, and initialize the start interface.

Initialization of the game interface

function initStartScreen() {
    gameState = "start",
    userInput.removeHitArea("moreGames"),
    1 == audioType && (musicTween && musicTween.kill(), musicTween = TweenLite.to(music, 1, {
        volume: .2,
        ease: "Linear.easeNone"
    })),
    background = new Elements.Background(assetLib.getData("mainBackground"), canvas.width, canvas.height),
    userInput.addHitArea("mute", butEventHandler, null, "rect", {
        aRect: [644, 0, canvas.width, 54]
    },
    !0);
    var a = {
        oImgData: assetLib.getData("uiButs"),
        aPos: [620, 340],
        id: "play"
    },
    b = {
        oImgData: assetLib.getData("uiButs"),
        aPos: [98, 359],
        id: "credits"
    };
    userInput.addHitArea("showMapScreen", butEventHandler, null, "image", a),
    userInput.addHitArea("credits", butEventHandler, null, "image", b);
    var c = new Array(a, b);
    panel = new Elements.Panel(assetLib.getData("panels"), assetLib.getData("uiElements"), assetLib.getData("position"), assetLib.getData("numbers"), gameState, c, canvas.width, canvas.height),
    panel.startTween1(),
    previousTime = (new Date).getTime(),
    updateStartScreenEvent()
}
function initCreditsScreen() {
    gameState = "credits";
    var a = {
        oImgData: assetLib.getData("uiButs"),
        aPos: [61, 359],
        id: "back"
    };
    userInput.addHitArea("backFromCredits", butEventHandler, null, "image", a);
    var b = new Array(a);
    panel = new Elements.Panel(assetLib.getData("panels"), assetLib.getData("uiElements"), assetLib.getData("position"), assetLib.getData("numbers"), gameState, b, canvas.width, canvas.height),
    panel.startTween2(),
    previousTime = (new Date).getTime(),
    updateCreditsScreenEvent()
}
function initMapScreen() {
    gameState = "map",
    background = new Elements.Background(assetLib.getData("mainBackground"), canvas.width, canvas.height);
    var a = {
        oImgData: assetLib.getData("uiButs"),
        aPos: [620, 340],
        id: "play"
    },
    b = {
        oImgData: assetLib.getData("uiButs"),
        aPos: [61, 359],
        id: "back"
    },
    c = {
        oImgData: assetLib.getData("uiButs"),
        aPos: [165, 359],
        id: "resetScores"
    };
    userInput.addHitArea("startGame", butEventHandler, null, "image", a),
    userInput.addHitArea("backFromMap", butEventHandler, null, "image", b),
    userInput.addHitArea("resetScores", butEventHandler, null, "image", c);
    var d = new Array(a, b, c),
    e = aMapPointData[8][0],
    f = aMapPointData[8][1];
    totalScore = 0,
    levelTheme = "desert",
    levelNum = 8;
    for (var g = 0; g < aMapPointData.length; g++) if (2 == saveDataHandler.aLevelStore[3 * g]) {
        var h = {
            oImgData: assetLib.getData("uiElements"),
            aPos: aMapPointData[g],
            id: "completedLevel",
            noFloat: !0
        };
        userInput.addHitArea("selectLevel", butEventHandler, {
            id: g
        },
        "image", h),
        d.push(h),
        totalScore += saveDataHandler.aLevelStore[3 * g + 2]
    } else if (1 == saveDataHandler.aLevelStore[3 * g]) {
        levelTheme = "city",
        3 > g ? levelTheme = "forest": g > 5 && (levelTheme = "desert");
        var h = {
            oImgData: assetLib.getData("uiElements"),
            aPos: aMapPointData[g],
            id: levelTheme,
            noFloat: !0
        };
        userInput.addHitArea("selectLevel", butEventHandler, {
            id: g
        },
        "image", h),
        d.push(h),
        e = aMapPointData[g][0],
        f = aMapPointData[g][1],
        levelNum = g,
        g > 1 && (firstPlay = !1)
    }
    for (var g = 0; g < aPowerUpBarData.length; g++) aPowerUpBarData[g] = saveDataHandler.aLevelStore[27 + g];
    winnings = saveDataHandler.aLevelStore[31],
    panel = new Elements.Panel(assetLib.getData("panels"), assetLib.getData("uiElements"), assetLib.getData("position"), assetLib.getData("numbers"), gameState, d, canvas.width, canvas.height),
    panel.highlight.x = e,
    panel.highlight.y = f,
    panel.oScoreData.totalScore = totalScore,
    panel.startTween1(),
    previousTime = (new Date).getTime(),
    updateMapEvent()
}

First, it initializes a variable gameStateand sets it to "start". Then, it removes the user input field called "moreGames".

Next, it checks to see audioTypeif the variable is 1. If it is, it creates a TweenLite animation that fades the volume of the music to 0.2. The TweenLite library is used here to handle animation effects.

It then creates a background object, passing in a data resource called "mainBackground" and the width and height of the canvas.

After that, it adds a user input area called "mute" whose position and shape is a rectangle at (644, 0
) and the same size as the canvas. When the user taps the area, butEventHandlerthe function is called.

Next, it creates two objects aand b, each containing some image data and position information. These objects represent two buttons on the game interface, a "play" button and a "credits" button.

Then, it userInput.addHitArea()adds two user input areas by calling methods, one is "showMapScreen", when the user clicks aon the represented image area, butEventHandlerthe function is called; the other is "credits", when the user clicks on the brepresented image area , which also calls butEventHandlerthe function.

Next, it creates an array ccontaining the two button objects just created aand the b.

It then creates a panel object and passes in some data resources along with the game state, an array of buttons, and the width and height of the canvas. Classes are used here Elements.Panelto create panel objects.

Afterwards, it calls startTween1()a method of the panel object, which starts an animation effect.

Finally, it records a timestamp into a variable previousTimeand calls updateStartScreenEvent()the function to update the event handler for the start screen.

  1. initCreditsScreen()function:

    • Set the game state to "credits".
    • Create an aobject called that contains some image data, location information, and an identifier.
    • Use userInput.addHitArea()the method to add the click area to the user input handler, the area is aassociated with the image, and butEventHandlerthe event handler is called when triggered.
    • Create an barray named and aadd objects to the array.
    • Creates an Panelobject initialized with the provided data and sets its width and height to the width and height of the canvas.
    • Call panel.startTween2()the method to start the animation effect of the panel.
    • Set previousTimethe variable to the current time.
    • Call updateCreditsScreenEvent()the function to update the credits screen event.
  2. initMapScreen()function:

    • Sets the game state to "map".
    • Creates an Backgroundobject initialized with the provided background image data and the width and height of the canvas.
    • Create three objects a, , band c, that contain different image data, location information, and identifiers, respectively.
    • Use the method to add clicked areas to the user input handler, associate each area with a corresponding image, and call the event handler userInput.addHitArea()when triggered .butEventHandler
    • Create an darray named and add the objects a, band cto the array.
    • Set some variables according to specific conditions, for example, the value of eand is set according to the index in the array, and the value of , and is calculated according to the value in the array.faMapPointDatatotalScorelevelThemelevelNumsaveDataHandler.aLevelStore
    • Loop through aMapPointDatathe array and add the hit area to the user input handler based on the condition and add the corresponding object to the array d.
    • Set some variables based on saveDataHandler.aLevelStorethe values ​​in the array.
    • Creates an Panelobject initialized with the provided data and sets its width and height to the width and height of the canvas.
    • Sets the highlight position of the panel.
    • Sets the total score for the panel.
    • Call panel.startTween1()the method to start the animation effect of the panel.
    • Set previousTimethe variable to the current time.
    • Call updateMapEvent()the function to update the map event.

Initialization of elements and states

function initGame() {
    gameState = "game",
    1 == audioType && (musicTween.kill(), musicTween = TweenLite.to(music, 1, {
        volume: .5,
        ease: "Linear.easeNone"
    })),
    userInput.addHitArea("pause", butEventHandler, null, "rect", {
        aRect: [587, 0, 635, 54]
    },
    !0),
    userInput.addHitArea("steerLeft", butEventHandler, {
        multiTouch: !0
    },
    "rect", {
        aRect: [0, 60, canvas.width / 2, canvas.height]
    },
    !0),
    userInput.addHitArea("steerRight", butEventHandler, {
        multiTouch: !0
    },
    "rect", {
        aRect: [canvas.width / 2, 60, canvas.width, canvas.height]
    },
    !0),
    userInput.addKey("steerRight", butEventHandler, null, 39),
    userInput.addKey("steerLeft", butEventHandler, null, 37),
    road = new Elements.Road(assetLib.getData(levelTheme + "Skyline"), assetLib.getData(levelTheme + "Fog"), assetLib.getData(levelTheme + "Road"), assetLib.getData(levelTheme + "Ground"), levelTheme, levelNum, canvas.width, canvas.height, roadCallback),
    hud = new Elements.Hud(assetLib.getData("hud"), assetLib.getData("uiElements"), assetLib.getData("position"), canvas.width, canvas.height),
    userCar = new Elements.UserCar(assetLib.getData("userCar"), canvas.width, canvas.height),
    enemySpeed = 390 + 7.2 * levelNum,
    raceLength = 4e4 + 1e3 * levelNum,
    maxSpeed = 475 + 6.75 * aPowerUpBarData[1],
    accRate = 4 - .32 * aPowerUpBarData[2],
    turnRate = 1.8 + .375 * aPowerUpBarData[0],
    nitroLength = 3 + .6 * aPowerUpBarData[3],
    speed = 200,
    steerX = 0,
    rightSteer = 0,
    leftSteer = 0,
    curveAmount = 0,
    hillAmount = 0,
    tweenScaleTimer = 0,
    levelScore = 0,
    raceProgress = 0,
    leadProgress = raceLength * leadHeadStart,
    racePos = 19,
    carReleasedNum = 19,
    carReleaseDelay = 0,
    speedDifferencial = 0,
    overtakenInc = 1,
    bridgeDistanceTarg = raceLength / 4,
    startTimer = 0,
    endSoundPlayed = !1,
    offRoad = !1,
    startStage = 0,
    justSkid = !1,
    nitroMode = !1,
    curveTween = TweenMax.to(this, 10, {
        curveAmount: 0,
        ease: "Cubic.easeInOut",
        onComplete: setNewCurve,
        onCompleteParams: [this]
    }),
    hillTween = TweenMax.to(this, 2 * Math.random() + 2, {
        hillAmount: -.5,
        ease: "Quad.easeInOut",
        onComplete: setNewHill,
        onCompleteParams: [this]
    }),
    previousTime = (new Date).getTime(),
    updateGameEvent()
}
  1. gameState = "game": Sets the game state to "game".

  2. audioTypeWhen it is 1, do the following:

    • musicTween.kill(): Stops the music fade animation that was in progress.
    • musicTween = TweenLite.to(music, 1, { volume: .5, ease: "Linear.easeNone" }): Create a music gradient animation that gradually changes the volume of the music from the current value to 0.5, and the animation duration is 1 second.
  3. userInput.addHitArea("pause", butEventHandler, null, "rect", { aRect: [587, 0, 635, 54] }, !0): Add a click area to handle the trigger event of the pause button. The location and size of the hit area is determined by the upper-left and lower-right coordinates of the rectangle.

  4. userInput.addHitArea("steerLeft", butEventHandler, { multiTouch: !0 }, "rect", { aRect: [0, 60, canvas.width / 2, canvas.height] }, !0): Adds a click area that handles the trigger event for the turn left button. The location and size of the hit area is determined by the upper-left and lower-right coordinates of the rectangle. Allow multi-touch.

  5. userInput.addHitArea("steerRight", butEventHandler, { multiTouch: !0 }, "rect", { aRect: [canvas.width / 2, 60, canvas.width, canvas.height] }, !0): Adds a click area that handles the trigger event for the turn right button. The location and size of the hit area is determined by the upper-left and lower-right coordinates of the rectangle. Allow multi-touch.

  6. userInput.addKey("steerRight", butEventHandler, null, 39): Associate the key "steerRight" with the event handler, which will be triggered when the right arrow key (key code 39) is pressed on the keyboard.

  7. userInput.addKey("steerLeft", butEventHandler, null, 37): Associate the key "steerLeft" with the event handler, which will be triggered when the left arrow key (key code 37) is pressed on the keyboard.

  8. Create Object: Creates an instance named with road related data roadfrom .assetLibroadElements.Road

  9. Create hudObject: assetLibCreates an instance hudnamed with HUD-related data from Elements.Hud.

  10. Create Object: Create an instance named with the user car related data userCarfrom .assetLibuserCarElements.UserCar

  11. Set some game parameters:

    • enemySpeed: The speed of the enemy car.
    • raceLength: The length of the match.
    • maxSpeed:Maximum speed.
    • accRate: Acceleration.
    • turnRate: Turning speed.
    • nitroLength: Nitrogen duration.
    • speed, steerX, rightSteer, leftSteer, curveAmount, hillAmount, tweenScaleTimerand other parameters are initialized to 0 or default values.
  12. Initialize game state and scoring:

    • levelScore: Level score, the initial value is 0.
    • raceProgress: The progress of the game, the initial value is 0.
    • leadProgress: The leader's progress, calculated based on the distance from the leader's head.
    • racePos: The position of the player in the game, the initial value is 19.
    • carReleasedNum: The number of released cars, the initial value is 19.
    • carReleaseDelay: The delay time of releasing the car, the initial value is 0.
    • speedDifferencial: Speed ​​difference.
    • overtakenInc: Beyond increment.
    • bridgeDistanceTarg: Target bridge distance.
    • startTimer: Start the timer, the initial value is 0.
    • endSoundPlayed: The flag indicating whether the end sound effect has been played, the initial value is false.
    • offRoad: Whether to deviate from the road sign, the initial value is false.
    • startStage: At the beginning stage, the initial value is 0.
    • justSkid: Whether it is a sign of just skidding, the initial value is false.
    • nitroMode: The flag of whether it is in nitrogen mode, the initial value is false.
  13. Create a gradient animation of curves and slopes:

    • curveTween: Change the property thisof the object curveAmountto 0 gradually, the animation duration is 10 seconds, and the easing function is "Cubic.easeInOut". The function is called after the animation is complete setNewCurve, and is passed thisas a parameter.
    • hillTween: Gradient the property thisof the object hillAmountto -0.5, the animation duration is a random value between 2 and 4 seconds, and the easing function is "Quad.easeInOut". The function is called after the animation is complete setNewHill, and is passed thisas a parameter.
  14. Set previousTimeto the milliseconds of the current time.

  15. Call updateGameEvent()the function to start updating the game state.
    insert image description here

summary

Here is a brief summary of implementing a racing game using HTML:

  1. Create HTML structure: Use HTML markup to create game canvas, score display area, control buttons and other elements.

  2. CSS style design: Use CSS style sheets to set the appropriate appearance and layout for game elements, including background color, font style, button style, etc.

  3. JavaScript interaction logic:

    • Handle game initialization: After the page is loaded, initialize the game state and parameters through JavaScript code, and set the initial position and attributes of game elements.
    • Monitor user input: Use JavaScript code to monitor the player's button operations or mouse click events, and control the movement, steering and other behaviors of the car according to the user's input.
    • Game cycle update: Use JavaScript timer functions (such as setIntervalor requestAnimationFrame) to implement game cycle updates, including updating the position of the racing car, detecting collisions, and calculating scores.
    • Display score and game information: According to the game status and data, use JavaScript code to update the score, countdown or other relevant information on the game interface in real time.
  4. Dynamic effects and animations: Use JavaScript and CSS technology to achieve some dynamic effects and animations, such as smooth transition of racing cars, explosion effects, random generation of roads, etc.

  5. Game over and reset: According to game rules or conditions, determine whether the game is over, and display the game over screen or pop-up window. Provides the ability to reset the game so players can start over.

  6. Responsive design: Consider using techniques such as responsive layout or media queries to make the game display and operate well on different screen sizes and devices.

insert image description here

Guess you like

Origin blog.csdn.net/Why_does_it_work/article/details/131767057