foreword
"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 ★
Article Directory
Get to know inscode
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
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
get item
Click on the link: Need for Speed
Simple analysis of the code
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>
<!DOCTYPE html>
: This is the doctype declaration for an HTML document, specifying the version of HTML the document conforms to.
<html lang="en">
: The beginning of the HTML tag, the lang attribute specifies that the language used by the page is English.
<head>
: Header tag for containing metadata about the document and referencing external resources.
<meta charset="utf-8">
: Set the character encoding to UTF-8 to ensure that non-English characters can be displayed correctly on the page.
<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.
<meta name="HandheldFriendly" content="True">
: Tells the browser that this page is suitable for viewing on handheld devices.
<meta name="apple-touch-fullscreen" content="yes" />
: Specifies that the page is displayed in full screen mode on Apple devices.
<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.
<title>HTML5汽车赛道飙车游戏</title>
: Set the title of the page, which will be displayed on the title bar or tab of the browser.
<meta name="keywords" content="HTML5,汽车赛道,飙车游戏" />
: Provide keywords related to the page to help search engines understand the content of the page.
<meta name="description" content="HTML5汽车赛道飙车游戏代码下载。H5精品短跑赛车俱乐部游戏,赛车游戏源代码。游戏介绍:鼠标,键盘左右键,控制赛车方向,让我们开始赛车比赛游戏吧。兼容手机移动端(横屏模式效果更好,左右晃动控制方向),带背景音效。" />
: Provide a description of the page for search engine display results and page summaries.
<meta name="author" content="js代码 />
<meta name="copyright" content="js代码(www.jsdaima.com)" />
: Claims the copyright information of the page.
<style>
: Begin CSS style block, used to define the style of the page.
body
andcanvas
Style: Set the background color and canvas style of the page.
<script src="viewporter.js"></script>
: imports an external JavaScript file named "viewporter.js".
<body>
: The main body of the page.
<div id="viewporter">
: a div element with an id of "viewporter".
<canvas id="canvas" moz-opaque></canvas>
: A canvas element with an id of "canvas" used to draw the game interface.
</body>
: Closing tag for the main body of the page.
<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.
<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.
<script src="app.js"></script>
: Imports an external JavaScript file named "app.js" that contains the actual game logic and function code.
</html>
: The closing tag of an HTML tag.
Game logic and function code: app.js
Setup before the game starts
function initSplash() {
gameState = "splash",
resizeCanvas(),
1 != audioType || muted || music.play(),
initStartScreen()
}
gameState = "splash"
: This line of codegameState
sets the value of the variable to the string "splash", indicating that the game state is "splash".
resizeCanvas()
: This function resizes the canvas, possibly based on the window size or other parameters.
1 != audioType || muted || music.play()
: This line of code checks the condition. IfaudioType
not equal to 1 (probably meaning some audio type is selected), ormuted
(mute) is false, then it will executemusic.play()
, i.e. play music.
initStartScreen()
: This function is used to initialize the start interface, which may be to create a start button, load resources, and so on.Therefore,
initSplash
the 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
gameState
and sets it to "start". Then, it removes the user input field called "moreGames".Next, it checks to see
audioType
if 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,butEventHandler
the function is called.Next, it creates two objects
a
andb
, 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 clicksa
on the represented image area,butEventHandler
the function is called; the other is "credits", when the user clicks on theb
represented image area , which also callsbutEventHandler
the function.Next, it creates an array
c
containing the two button objects just createda
and theb
.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.Panel
to 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
previousTime
and callsupdateStartScreenEvent()
the function to update the event handler for the start screen.
initCreditsScreen()
function:
- Set the game state to "credits".
- Create an
a
object 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 isa
associated with the image, andbutEventHandler
the event handler is called when triggered.- Create an
b
array named anda
add objects to the array.- Creates an
Panel
object 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
previousTime
the variable to the current time.- Call
updateCreditsScreenEvent()
the function to update the credits screen event.
initMapScreen()
function:
- Sets the game state to "map".
- Creates an
Background
object initialized with the provided background image data and the width and height of the canvas.- Create three objects
a
, ,b
andc
, 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
d
array named and add the objectsa
,b
andc
to the array.- Set some variables according to specific conditions, for example, the value of
e
and is set according to the index in the array, and the value of , and is calculated according to the value in the array.f
aMapPointData
totalScore
levelTheme
levelNum
saveDataHandler.aLevelStore
- Loop through
aMapPointData
the array and add the hit area to the user input handler based on the condition and add the corresponding object to the arrayd
.- Set some variables based on
saveDataHandler.aLevelStore
the values in the array.- Creates an
Panel
object 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
previousTime
the 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()
}
gameState = "game"
: Sets the game state to "game".
audioType
When 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.
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.
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.
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.
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.
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.Create Object: Creates an instance named with road related data
road
from .assetLib
road
Elements.Road
Create
hud
Object:assetLib
Creates an instancehud
named with HUD-related data fromElements.Hud
.Create Object: Create an instance named with the user car related data
userCar
from .assetLib
userCar
Elements.UserCar
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
,tweenScaleTimer
and other parameters are initialized to 0 or default values.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.Create a gradient animation of curves and slopes:
curveTween
: Change the propertythis
of the objectcurveAmount
to 0 gradually, the animation duration is 10 seconds, and the easing function is "Cubic.easeInOut". The function is called after the animation is completesetNewCurve
, and is passedthis
as a parameter.hillTween
: Gradient the propertythis
of the objecthillAmount
to -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 completesetNewHill
, and is passedthis
as a parameter.Set
previousTime
to the milliseconds of the current time.Call
updateGameEvent()
the function to start updating the game state.
summary
Here is a brief summary of implementing a racing game using HTML:
-
Create HTML structure: Use HTML markup to create game canvas, score display area, control buttons and other elements.
-
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.
-
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
setInterval
orrequestAnimationFrame
) 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.
-
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.
-
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.
-
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.