Build your First Game with HTML5

本文提供了一篇详细的教程,演示如何利用HTML5和Box2D引擎创建一个简单的游戏。从设置项目开始,到游戏逻辑、物理模拟、绘制及交互功能的实现,全程指导读者完成游戏开发。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

某位有爱同学提供的这篇文章,很好的启蒙教程,我都在看呢

原文:http://net.tutsplus.com/tutorials/html-css-techniques/build-your-first-game-with-html5/


Build your First Game with HTML5

Tutorial Details
  • Technologies Used: HTML5, JS, CSS
  • Difficulty: Intermediate
  • Estimated Completion Time: 45-60 minutes

Final Product What You'll Be Creating

HTML5 is growing up faster than anyone could have imagined. Powerful and professional solutions are already being developed…even in the gaming world! Today, you’ll make your first game using Box2D and HTML5′s canvas tag.


What is Box2D?

Box2D is an open source and popular engine that simulates 2D physics for making games and applications. Primarily written in C++, it has been converted to numerous languages by community contributors.

With the same methods and objects, you have the ability to make your games’ physics in many languages, such as Objective C (iPhone/iPad), Actionscript 3.0 (Web), HTML 5 (Web), etc.


Step 1 - Setting up your Project

To begin developing your demo, download the Box2D engine for HTML5 here. Next, create a new HTML file with the following structure (copy js and lib directories from box2d-js project to your game folder).

Now, you must insert the necessary files to run box2D into your HTML file:

  1. <!--[if IE]><script src="lib/excanvas.js"></script><![endif]-->  
  2.  <script src="lib/prototype-1.6.0.2.js"></script>  
  3. <!-- box2djs -->  
  4.  <script src='js/box2d/common/b2Settings.js'></script>  
  5.  <script src='js/box2d/common/math/b2Vec2.js'></script>  
  6.  <script src='js/box2d/common/math/b2Mat22.js'></script>  
  7.  <script src='js/box2d/common/math/b2Math.js'></script>  
  8.  <script src='js/box2d/collision/b2AABB.js'></script>  
  9.  <script src='js/box2d/collision/b2Bound.js'></script>  
  10.  <script src='js/box2d/collision/b2BoundValues.js'></script>  
  11.  <script src='js/box2d/collision/b2Pair.js'></script>  
  12.  <script src='js/box2d/collision/b2PairCallback.js'></script>  
  13.  <script src='js/box2d/collision/b2BufferedPair.js'></script>  
  14.  <script src='js/box2d/collision/b2PairManager.js'></script>  
  15.  <script src='js/box2d/collision/b2BroadPhase.js'></script>  
  16.  <script src='js/box2d/collision/b2Collision.js'></script>  
  17.  <script src='js/box2d/collision/Features.js'></script>  
  18.  <script src='js/box2d/collision/b2ContactID.js'></script>  
  19.  <script src='js/box2d/collision/b2ContactPoint.js'></script>  
  20.  <script src='js/box2d/collision/b2Distance.js'></script>  
  21.  <script src='js/box2d/collision/b2Manifold.js'></script>  
  22.  <script src='js/box2d/collision/b2OBB.js'></script>  
  23.  <script src='js/box2d/collision/b2Proxy.js'></script>  
  24.  <script src='js/box2d/collision/ClipVertex.js'></script>  
  25.  <script src='js/box2d/collision/shapes/b2Shape.js'></script>  
  26.  <script src='js/box2d/collision/shapes/b2ShapeDef.js'></script>  
  27.  <script src='js/box2d/collision/shapes/b2BoxDef.js'></script>  
  28.  <script src='js/box2d/collision/shapes/b2CircleDef.js'></script>  
  29.  <script src='js/box2d/collision/shapes/b2CircleShape.js'></script>  
  30.  <script src='js/box2d/collision/shapes/b2MassData.js'></script>  
  31.  <script src='js/box2d/collision/shapes/b2PolyDef.js'></script>  
  32.  <script src='js/box2d/collision/shapes/b2PolyShape.js'></script>  
  33.  <script src='js/box2d/dynamics/b2Body.js'></script>  
  34.  <script src='js/box2d/dynamics/b2BodyDef.js'></script>  
  35.  <script src='js/box2d/dynamics/b2CollisionFilter.js'></script>  
  36.  <script src='js/box2d/dynamics/b2Island.js'></script>  
  37.  <script src='js/box2d/dynamics/b2TimeStep.js'></script>  
  38.  <script src='js/box2d/dynamics/contacts/b2ContactNode.js'></script>  
  39.  <script src='js/box2d/dynamics/contacts/b2Contact.js'></script>  
  40.  <script src='js/box2d/dynamics/contacts/b2ContactConstraint.js'></script>  
  41.  <script src='js/box2d/dynamics/contacts/b2ContactConstraintPoint.js'></script>  
  42.  <script src='js/box2d/dynamics/contacts/b2ContactRegister.js'></script>  
  43.  <script src='js/box2d/dynamics/contacts/b2ContactSolver.js'></script>  
  44.  <script src='js/box2d/dynamics/contacts/b2CircleContact.js'></script>  
  45.  <script src='js/box2d/dynamics/contacts/b2Conservative.js'></script>  
  46.  <script src='js/box2d/dynamics/contacts/b2NullContact.js'></script>  
  47.  <script src='js/box2d/dynamics/contacts/b2PolyAndCircleContact.js'></script>  
  48.  <script src='js/box2d/dynamics/contacts/b2PolyContact.js'></script>  
  49.  <script src='js/box2d/dynamics/b2ContactManager.js'></script>  
  50.  <script src='js/box2d/dynamics/b2World.js'></script>  
  51.  <script src='js/box2d/dynamics/b2WorldListener.js'></script>  
  52.  <script src='js/box2d/dynamics/joints/b2JointNode.js'></script>  
  53.  <script src='js/box2d/dynamics/joints/b2Joint.js'></script>  
  54.  <script src='js/box2d/dynamics/joints/b2JointDef.js'></script>  
  55.  <script src='js/box2d/dynamics/joints/b2DistanceJoint.js'></script>  
  56.  <script src='js/box2d/dynamics/joints/b2DistanceJointDef.js'></script>  
  57.  <script src='js/box2d/dynamics/joints/b2Jacobian.js'></script>  
  58.  <script src='js/box2d/dynamics/joints/b2GearJoint.js'></script>  
  59.  <script src='js/box2d/dynamics/joints/b2GearJointDef.js'></script>  
  60.  <script src='js/box2d/dynamics/joints/b2MouseJoint.js'></script>  
  61.  <script src='js/box2d/dynamics/joints/b2MouseJointDef.js'></script>  
  62.  <script src='js/box2d/dynamics/joints/b2PrismaticJoint.js'></script>  
  63.  <script src='js/box2d/dynamics/joints/b2PrismaticJointDef.js'></script>  
  64.  <script src='js/box2d/dynamics/joints/b2PulleyJoint.js'></script>  
  65.  <script src='js/box2d/dynamics/joints/b2PulleyJointDef.js'></script>  
  66.  <script src='js/box2d/dynamics/joints/b2RevoluteJoint.js'></script>  
  67.  <script src='js/box2d/dynamics/joints/b2RevoluteJointDef.js'></script>  

Yep, that’s a huge number of HTTP requests!

Please note that, for deployment, it’s highly recommended that you concatenate all of these resources into one script file.

Next, create two more scripts inside the /js/ folder, called "box2dutils.js" and "game.js".

  • box2dutils.js – it’s a copy and paste from some demos that come with box2dlib, and is important for drawing functions (I will also explain some important parts here).
  • game.js – the game, itself; this is where we create the platforms, the player, apply the keyboard interactions, etc.

Copy and paste the following code into box2dutils.js. Don’t worry! I’ll explain it bit by bit!

  1. function drawWorld(world, context) {  
  2.     for (var j = world.m_jointList; j; j = j.m_next) {  
  3.         drawJoint(j, context);  
  4.     }  
  5.     for (var b = world.m_bodyList; b; b = b.m_next) {  
  6.         for (var s = b.GetShapeList(); s != null; s = s.GetNext()) {  
  7.             drawShape(s, context);  
  8.         }  
  9.     }  
  10. }  
  11. function drawJoint(joint, context) {  
  12.     var b1 = joint.m_body1;  
  13.     var b2 = joint.m_body2;  
  14.     var x1 = b1.m_position;  
  15.     var x2 = b2.m_position;  
  16.     var p1 = joint.GetAnchor1();  
  17.     var p2 = joint.GetAnchor2();  
  18.     context.strokeStyle = '#00eeee';  
  19.     context.beginPath();  
  20.     switch (joint.m_type) {  
  21.     case b2Joint.e_distanceJoint:  
  22.         context.moveTo(p1.x, p1.y);  
  23.         context.lineTo(p2.x, p2.y);  
  24.         break;  
  25.   
  26.     case b2Joint.e_pulleyJoint:  
  27.         // TODO  
  28.         break;  
  29.   
  30.     default:  
  31.         if (b1 == world.m_groundBody) {  
  32.             context.moveTo(p1.x, p1.y);  
  33.             context.lineTo(x2.x, x2.y);  
  34.         }  
  35.         else if (b2 == world.m_groundBody) {  
  36.             context.moveTo(p1.x, p1.y);  
  37.             context.lineTo(x1.x, x1.y);  
  38.         }  
  39.         else {  
  40.             context.moveTo(x1.x, x1.y);  
  41.             context.lineTo(p1.x, p1.y);  
  42.             context.lineTo(x2.x, x2.y);  
  43.             context.lineTo(p2.x, p2.y);  
  44.         }  
  45.         break;  
  46.     }  
  47.     context.stroke();  
  48. }  
  49. function drawShape(shape, context) {  
  50.     context.strokeStyle = '#000000';  
  51.     context.beginPath();  
  52.     switch (shape.m_type) {  
  53.     case b2Shape.e_circleShape:  
  54.         {  
  55.             var circle = shape;  
  56.             var pos = circle.m_position;  
  57.             var r = circle.m_radius;  
  58.             var segments = 16.0;  
  59.             var theta = 0.0;  
  60.             var dtheta = 2.0 * Math.PI / segments;  
  61.             // draw circle  
  62.             context.moveTo(pos.x + r, pos.y);  
  63.             for (var i = 0; i < segments; i++) {  
  64.                 var d = new b2Vec2(r * Math.cos(theta), r * Math.sin(theta));  
  65.                 var v = b2Math.AddVV(pos, d);  
  66.                 context.lineTo(v.x, v.y);  
  67.                 theta += dtheta;  
  68.             }  
  69.             context.lineTo(pos.x + r, pos.y);  
  70.   
  71.             // draw radius  
  72.             context.moveTo(pos.x, pos.y);  
  73.             var ax = circle.m_R.col1;  
  74.             var pos2 = new b2Vec2(pos.x + r * ax.x, pos.y + r * ax.y);  
  75.             context.lineTo(pos2.x, pos2.y);  
  76.         }  
  77.         break;  
  78.     case b2Shape.e_polyShape:  
  79.         {  
  80.             var poly = shape;  
  81.             var tV = b2Math.AddVV(poly.m_position, b2Math.b2MulMV(poly.m_R, poly.m_vertices[0]));  
  82.             context.moveTo(tV.x, tV.y);  
  83.             for (var i = 0; i < poly.m_vertexCount; i++) {  
  84.                 var v = b2Math.AddVV(poly.m_position, b2Math.b2MulMV(poly.m_R, poly.m_vertices[i]));  
  85.                 context.lineTo(v.x, v.y);  
  86.             }  
  87.             context.lineTo(tV.x, tV.y);  
  88.         }  
  89.         break;  
  90.     }  
  91.     context.stroke();  
  92. }  
  93.   
  94. function createWorld() {  
  95.     var worldAABB = new b2AABB();  
  96.     worldAABB.minVertex.Set(-1000, -1000);  
  97.     worldAABB.maxVertex.Set(1000, 1000);  
  98.     var gravity = new b2Vec2(0, 300);  
  99.     var doSleep = true;  
  100.     var world = new b2World(worldAABB, gravity, doSleep);  
  101.     return world;  
  102. }  
  103.   
  104. function createGround(world) {  
  105.     var groundSd = new b2BoxDef();  
  106.     groundSd.extents.Set(1000, 50);  
  107.     groundSd.restitution = 0.2;  
  108.     var groundBd = new b2BodyDef();  
  109.     groundBd.AddShape(groundSd);  
  110.     groundBd.position.Set(-500, 340);  
  111.     return world.CreateBody(groundBd)  
  112. }  
  113.   
  114. function createBall(world, x, y) {  
  115.     var ballSd = new b2CircleDef();  
  116.     ballSd.density = 1.0;  
  117.     ballSd.radius = 20;  
  118.     ballSd.restitution = 1.0;  
  119.     ballSd.friction = 0;  
  120.     var ballBd = new b2BodyDef();  
  121.     ballBd.AddShape(ballSd);  
  122.     ballBd.position.Set(x,y);  
  123.     return world.CreateBody(ballBd);  
  124. }  
  125.   
  126. function createBox(world, x, y, width, height, fixed, userData) {  
  127.     if (typeof(fixed) == 'undefined') fixed = true;  
  128.     var boxSd = new b2BoxDef();  
  129.     if (!fixed) boxSd.density = 1.0;  
  130.   
  131.     boxSd.userData = userData;  
  132.   
  133.     boxSd.extents.Set(width, height);  
  134.     var boxBd = new b2BodyDef();  
  135.     boxBd.AddShape(boxSd);  
  136.     boxBd.position.Set(x,y);  
  137.     return world.CreateBody(boxBd)  
  138. }  

Step 2 - Developing the Game

Open the index.html file that you previously created, and add a canvas element (600x400) within thebody element. This is where we'll work with the HTML5 drawing API:

  1. <canvas id="game" width="600" height="400"></canvas>  

Also, while you're here, reference game.js and box2dutils.js.

  1. <script src='js/box2dutils.js'></script>  
  2. <script src='js/game.js'></script>  

That'll do it for the HTML! Let's work on the fun JavaScript now!

Open game.js, and insert the code below:

  1. // some variables that we gonna use in this demo  
  2. var initId = 0;  
  3. var player = function(){  
  4.     this.object = null;  
  5.     this.canJump = false;  
  6. };  
  7. var world;  
  8. var ctx;  
  9. var canvasWidth;  
  10. var canvasHeight;  
  11. var keys = [];  
  12.   
  13. // HTML5 onLoad event  
  14. Event.observe(window, 'load'function() {  
  15.     world = createWorld(); // box2DWorld  
  16.     ctx = $('game').getContext('2d'); // 2  
  17.     var canvasElm = $('game');  
  18.     canvasWidth = parseInt(canvasElm.width);  
  19.     canvasHeight = parseInt(canvasElm.height);  
  20.     initGame(); // 3  
  21.     step(); // 4  
  22.   
  23. // 5  
  24.     window.addEventListener('keydown',handleKeyDown,true);  
  25.     window.addEventListener('keyup',handleKeyUp,true);  
  26. });  

Box2DWorld - that's why we're here

Okay, let's figure out what this chunk of code does!

Box2DWorld is one of the classes that is made available, via the core of box2d. Its function is simple: combine everything into one class. In box2DWorld, you have the bodies definition and collisions manager of your game or application.

Keep the game.js and box2dutils.js files open, and search for the createWorld() function withinbox2dutils.js.

  1. function createWorld() {  
  2.     // here we create our world settings for collisions  
  3.     var worldAABB = new b2AABB();  
  4.     worldAABB.minVertex.Set(-1000, -1000);  
  5.     worldAABB.maxVertex.Set(1000, 1000);  
  6.     // set gravity vector  
  7.     var gravity = new b2Vec2(0, 300);  
  8.     var doSleep = true;  
  9.     // init our world and return its value  
  10.     var world = new b2World(worldAABB, gravity, doSleep);  
  11.     return world;  
  12. }  

It's quite simple to create the box2DWorld.


Back to game.js

Refer to the commented numbers in the two blocks of code above. On number two, we retrieve the canvaselement's context by using the selector API (looks like jQuery or MooTools selectors, don't they?). On number three, we have a new interesting function: initGame(). This is where we create the scenery.

Copy and paste the code below into game.js, and then we'll review it together.

  1. function initGame(){  
  2.     // create 2 big platforms  
  3.     createBox(world, 3, 230, 60, 180, true'ground');  
  4.     createBox(world, 560, 360, 50, 50, true'ground');  
  5.   
  6.     // create small platforms  
  7.     for (var i = 0; i < 5; i++){  
  8.         createBox(world, 150+(80*i), 360, 5, 40+(i*15), true'ground');  
  9.     }  
  10.   
  11.     // create player ball  
  12.     var ballSd = new b2CircleDef();  
  13.     ballSd.density = 0.1;  
  14.     ballSd.radius = 12;  
  15.     ballSd.restitution = 0.5;  
  16.     ballSd.friction = 1;  
  17.     ballSd.userData = 'player';  
  18.     var ballBd = new b2BodyDef();  
  19.     ballBd.linearDamping = .03;  
  20.     ballBd.allowSleep = false;  
  21.     ballBd.AddShape(ballSd);  
  22.     ballBd.position.Set(20,0);  
  23.     player.object = world.CreateBody(ballBd);  
  24.   
  25. }  
  26.   
  27.  Inside <code>box2dutils.js</code>, we've created a function, called <code>createBox</code>. This creates a static rectangle body.  
  28.  
  29. function createBox(world, x, y, width, height, fixed, userData) { 
  30.     if (typeof(fixed) == 'undefined') fixed = true;  
  31.     //1  
  32. var boxSd = new b2BoxDef();  
  33.     if (!fixed) boxSd.density = 1.0;  
  34.     //2  
  35.     boxSd.userData = userData;  
  36.     //3  
  37.     boxSd.extents.Set(width, height);  
  38.   
  39.     //4  
  40.     var boxBd = new b2BodyDef();  
  41.     boxBd.AddShape(boxSd);  
  42.     //5  
  43.     boxBd.position.Set(x,y);  
  44.     //6  
  45.     return world.CreateBody(boxBd)  
  46. }  

Box2DBody

Box2DBody has some unique characteristics:

  • It can be static (not affected by collisions impacts), kinematic (it isn't affected by collisions, but it can be moved by your mouse, for example), or dynamic (interacts with everything)
  • Must have a shape definition, and should indicate how the object appears
  • May have more than one fixture, which indicates how the object will interact with collisions
  • Its position is set by the center of your object, not the left top edge as many other engines do.
Reviewing the code:
  1. Here, we create one shape definition that will be a square or rectangle, and setup its density (how often it gonna be moved, or rotate by forces).
  2. We setup the userData, usually you setup graphics objects here, but in this example, I just setup strings that will be the identifier of the type of the object for collisions. This parameter doesn't affect physics algorithms.
  3. Setup half of the size of my box (it's a line from the position point, or the center point of the object to a corner)
  4. We create the body definition, and add to it the box shape definition.
  5. Setup the position.
  6. Create the body in the world and return its value.

Creating the Player Ball Body

I've coded the player (ball) directly in the game.js file. It follows the same sequence of creating boxes, but, this time, it's a ball.

  1. var ballSd = new b2CircleDef();  
  2.     ballSd.density = 0.1;  
  3.     ballSd.radius = 12;  
  4.     ballSd.restitution = 0.5;  
  5.     ballSd.friction = 1;  
  6.     ballSd.userData = 'player';  
  7.     var ballBd = new b2BodyDef();  
  8.     ballBd.linearDamping = .03;  
  9.     ballBd.allowSleep = false;  
  10.     ballBd.AddShape(ballSd);  
  11.     ballBd.position.Set(20,0);  
  12.     player.object = world.CreateBody(ballBd);  

So how do we create a body, step by step?

  1. Create the shape, fixture and sensor definition
  2. Create the body definition
  3. Add into the body your shape, fixtures or sensors (not explained in this article)
  4. Create the body in the world

Box2DCircle

As I noted earlier, this follows the same creation process of a box, but now you must set some new parameters.

  • radius - This is the length of a line from the center of the circle to any point on its edge.
  • restitution - How the ball will lose, or gain force when collides with other body.
  • friction - How the ball will roll.

Box2DBody - More Properties

  • damping is used to reduce the velocity of the body - there's angular damping and linear damping.
  • sleep in box2D, bodies can sleep to solve performance issues. For example, let's suppose you are developing a platform game, and the level is defined by a 6000x400 screen. Why do you need to perform physics for objects that are off screen? You don't; that's the point! So the correct choice is to put them to sleep, and improve your game's performance.

We've already created our world; you can test the code that you have so far. You'll see the player falling above the west platform.

Now, if you tried to run the demo, you should be wondering, why is the page as barren as white paper?

Always remember: Box2D doesn't render; it only calculates physics.


Step 3 - Rendering Time

Next, let's render the box2DWorld.

Open your game.js script, and add the following code:

  1. function step() {  
  2.   
  3.     var stepping = false;  
  4.     var timeStep = 1.0/60;  
  5.     var iteration = 1;  
  6.     // 1  
  7.     world.Step(timeStep, iteration);  
  8.     // 2  
  9.     ctx.clearRect(0, 0, canvasWidth, canvasHeight);  
  10.     drawWorld(world, ctx);  
  11.     // 3  
  12.     setTimeout('step()', 10);  
  13. }  
What we accomplish here:
  1. Instructed box2dWorld to perform physics simulations
  2. Cleared canvas screen and draw again
  3. Execute the step() function again in ten milliseconds

With this bit of code, we are now working with physics and drawing. You can test yourself, and watch for a falling ball, as demonstrated below:


drawWorld in box2dutils.js

  1. function drawWorld(world, context) {  
  2.     for (var j = world.m_jointList; j; j = j.m_next) {  
  3.         drawJoint(j, context);  
  4.     }  
  5.     for (var b = world.m_bodyList; b; b = b.m_next) {  
  6.         for (var s = b.GetShapeList(); s != null; s = s.GetNext()) {  
  7.             drawShape(s, context);  
  8.         }  
  9.     }  
  10. }  

What we've written above is a debug function that draws our world into the canvas, using the graphics API provided by HTML5's Canvas API.

The first loop draws all joints. We didn't use joints in this article. They are a bit complex for a first demo, but, nonetheless, they're essential for your games. They allow you to create very interesting bodies.

The second loop draws all bodies, which is why we're here!

  1. function drawShape(shape, context) {  
  2.     context.strokeStyle = '#000000';  
  3.     context.beginPath();  
  4.     switch (shape.m_type) {  
  5.     case b2Shape.e_circleShape:  
  6.         {  
  7.             var circle = shape;  
  8.             var pos = circle.m_position;  
  9.             var r = circle.m_radius;  
  10.             var segments = 16.0;  
  11.             var theta = 0.0;  
  12.             var dtheta = 2.0 * Math.PI / segments;  
  13.             // draw circle  
  14.             context.moveTo(pos.x + r, pos.y);  
  15.             for (var i = 0; i < segments; i++) {  
  16.                 var d = new b2Vec2(r * Math.cos(theta), r * Math.sin(theta));  
  17.                 var v = b2Math.AddVV(pos, d);  
  18.                 context.lineTo(v.x, v.y);  
  19.                 theta += dtheta;  
  20.             }  
  21.             context.lineTo(pos.x + r, pos.y);  
  22.   
  23.             // draw radius  
  24.             context.moveTo(pos.x, pos.y);  
  25.             var ax = circle.m_R.col1;  
  26.             var pos2 = new b2Vec2(pos.x + r * ax.x, pos.y + r * ax.y);  
  27.             context.lineTo(pos2.x, pos2.y);  
  28.         }  
  29.         break;  
  30.     case b2Shape.e_polyShape:  
  31.         {  
  32.             var poly = shape;  
  33.             var tV = b2Math.AddVV(poly.m_position, b2Math.b2MulMV(poly.m_R, poly.m_vertices[0]));  
  34.             context.moveTo(tV.x, tV.y);  
  35.             for (var i = 0; i < poly.m_vertexCount; i++) {  
  36.                 var v = b2Math.AddVV(poly.m_position, b2Math.b2MulMV(poly.m_R, poly.m_vertices[i]));  
  37.                 context.lineTo(v.x, v.y);  
  38.             }  
  39.             context.lineTo(tV.x, tV.y);  
  40.         }  
  41.         break;  
  42.     }  
  43.     context.stroke();  
  44. }  

We're looping through every vertices of the object and drawing it with lines (context.moveTo andcontext.lineTo). Now, it's useful to have an example... but not so useful in practice. When you use graphics, you only need to pay attention to the bodies' positioning. You don't need to loop vertices, as this demo does.


Step 4 - Interactivity

A game without interactivity is a movie, and a movie with interactivity is a game.

Let's develop the keyboard arrow functionality to jump and move the ball.

Add the following code to your game.js file:

  1. function handleKeyDown(evt){  
  2.     keys[evt.keyCode] = true;  
  3. }  
  4.   
  5. function handleKeyUp(evt){  
  6.     keys[evt.keyCode] = false;  
  7. }  
  8.   
  9. // disable vertical scrolling from arrows :)  
  10. document.οnkeydοwn=function(){return event.keyCode!=38 && event.keyCode!=40}  

With handleKeyDown and handleKeyUp, we setup an array which tracks every key the user types. Withdocument.onkeydown, we disable the browser's native vertical scrolling function for up and down arrows. Have you ever played an HTML5 game, and when you jump, the player, enemies and objects go off screen? That won't be an issue now.

Add this next bit of code to the beginning of your step() function:

  1. handleInteractions();  

And outside, declare the function:

  1. function handleInteractions(){  
  2.     // up arrow  
  3.     // 1  
  4.     var collision = world.m_contactList;  
  5.     player.canJump = false;  
  6.     if (collision != null){  
  7.         if (collision.GetShape1().GetUserData() == 'player' || collision.GetShape2().GetUserData() == 'player'){  
  8.             if ((collision.GetShape1().GetUserData() == 'ground' || collision.GetShape2().GetUserData() == 'ground')){  
  9.                 var playerObj = (collision.GetShape1().GetUserData() == 'player' ? collision.GetShape1().GetPosition() :  collision.GetShape2().GetPosition());  
  10.                 var groundObj = (collision.GetShape1().GetUserData() == 'ground' ? collision.GetShape1().GetPosition() :  collision.GetShape2().GetPosition());  
  11.                 if (playerObj.y < groundObj.y){  
  12.                     player.canJump = true;  
  13.                 }  
  14.             }  
  15.         }  
  16.     }  
  17.     // 2  
  18.     var vel = player.object.GetLinearVelocity();  
  19.     // 3  
  20.     if (keys[38] && player.canJump){  
  21.         vel.y = -150;  
  22.     }  
  23.   
  24.     // 4  
  25.     // left/right arrows  
  26.     if (keys[37]){  
  27.         vel.x = -60;  
  28.     }  
  29.     else if (keys[39]){  
  30.         vel.x = 60;  
  31.     }  
  32.   
  33.     // 5  
  34.     player.object.SetLinearVelocity(vel);  
  35. }  

The most complicated piece of the code above is the first one, where we check for a collision, and write some conditions to determine if the shape1 or the shape2 is the player. If it is, we verify if shape1 orshape2 is a ground object. Again, if so, the player is colliding with the ground. Next, we check if the player is above the ground. If that's the case, then the player can jump.

On the second commented line (2), we retrieve the LinearVelocity of the player.

The third and forth commented regions verify if arrows are being pressed, and adjust the velocity vector, accordingly.

In the fifth region, we setup the player with the new velocity vector.

The interactions are now done! But there's no objective, We just jump, jump, jump… and jump!


Step 5 - "You Win" Message

Add the code below to the beginning of your LinearVelocity function:

  1. if (player.object.GetCenterPosition().y > canvasHeight){  
  2.     player.object.SetCenterPosition(new b2Vec2(20,0),0)  
  3. }  
  4. else if (player.object.GetCenterPosition().x > canvasWidth-50){  
  5.     showWin();  
  6.     return;  
  7. }  
  • The first condition determines if the player falls, and should be transported back to the start point (above the west platform).
  • The second condition checks if the player is above the second platform, and won the game. Here's the showWin() function.
  1. function showWin(){  
  2.     ctx.fillStyle    = '#000';  
  3.     ctx.font         = '30px verdana';  
  4.     ctx.textBaseline = 'top';  
  5.     ctx.fillText('Ye! you made it!', 30, 0);  
  6.     ctx.fillText('thank you, andersonferminiano.com', 30, 30);  
  7.     ctx.fillText('@andferminiano', 30, 60);  
  8. }  

And that's it! You've just completed your first simple game with HTML5 and Box2D. Congratulations!


The programme should have the following features: ● A menu including Open and Exit where Open starts a JFileChooser to select the file with the questions inside and Exit ends the programme. ● Once a file is loaded, the GUI should display one question and its answers at a time. ● The user should be able to select an answer and they should be informed if they were correct or not. ● The user should be made aware of the number of correctly answered and the total number of questions answered. ● The user should only be able to proceed to the next question once they answered the current one. ● Once all questions have been answered, the user should be informed of their overall score and that the game has finished. The Open menu item should now be enabled to start a new quiz. Optionally, you can add a restart menu item to redo the current quiz. Concrete sub-tasks: a) define a class called Question to hold a single question, i.e. the text, the possible answers, and the correct answer index; (0.25P) b) write a method to select a file via a JFileChooser and to read all the questions from that file into an array/list of Question objects (assume that file has the structure mentioned above); (0.25P) c) design and implement a GUI with the components mentioned above: A menu, ability to display the question and answers, ability to select an answer, show the outcome and score, and proceed to the next question. (Appropriate layout: 1P, Class extends JFrame: 0.25P, Class follows OOP principles: 0.25P, Global set-up in main method: 0.25P)1 d) write a method to display a question on the GUI you designed; (0.25P) e) implement an actionPerformed method to respond to user interactions with the GUI. Make sure to enable and disable interactive components as required, e.g. the user should not be able to skip to the next question without selecting an answer first and they should not be able to load a new quiz before finishing the current one;
05-29
Thank you for your detailed requirements. Based on your requirements, here are the steps you can follow to build the program: 1. Define a class called `Question` that holds a single question, i.e. the text, the possible answers, and the correct answer index. Here's an example implementation: ``` class Question: def __init__(self, text, answers, correct_answer_index): self.text = text self.answers = answers self.correct_answer_index = correct_answer_index ``` 2. Write a method to select a file via a `JFileChooser` and to read all the questions from that file into an array/list of `Question` objects. Here's an example implementation: ``` def load_questions(): file_chooser = JFileChooser() result = file_chooser.showOpenDialog(None) if result == JFileChooser.APPROVE_OPTION: file = file_chooser.getSelectedFile() questions = [] with open(file) as f: for line in f: parts = line.strip().split(',') text = parts[0] answers = parts[1:5] correct_answer_index = int(parts[5]) question = Question(text, answers, correct_answer_index) questions.append(question) return questions ``` Assuming the file has the structure mentioned in your requirements, this method will read all the questions from the file into a list of `Question` objects. 3. Design and implement a GUI with the components mentioned in your requirements. Here's an example implementation: ``` class QuizApp(JFrame): def __init__(self): super().__init__() self.questions = [] self.current_question_index = 0 self.correct_answers_count = 0 self.init_ui() def init_ui(self): self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) self.setTitle('Quiz App') self.create_menu() self.create_question_panel() self.create_answers_panel() self.create_buttons_panel() self.create_status_panel() self.pack() self.setLocationRelativeTo(None) def create_menu(self): menu_bar = JMenuBar() file_menu = JMenu('File') open_item = JMenuItem('Open') open_item.addActionListener(self.handle_open) exit_item = JMenuItem('Exit') exit_item.addActionListener(self.handle_exit) file_menu.add(open_item) file_menu.add(exit_item) menu_bar.add(file_menu) self.setJMenuBar(menu_bar) def create_question_panel(self): self.question_label = JLabel() self.add(self.question_label) def create_answers_panel(self): self.answers_button_group = ButtonGroup() self.answer_1_button = JRadioButton() self.answer_2_button = JRadioButton() self.answer_3_button = JRadioButton() self.answer_4_button = JRadioButton() self.answers_button_group.add(self.answer_1_button) self.answers_button_group.add(self.answer_2_button) self.answers_button_group.add(self.answer_3_button) self.answers_button_group.add(self.answer_4_button) answers_panel = JPanel() answers_panel.add(self.answer_1_button) answers_panel.add(self.answer_2_button) answers_panel.add(self.answer_3_button) answers_panel.add(self.answer_4_button) self.add(answers_panel) def create_buttons_panel(self): self.submit_button = JButton('Submit') self.submit_button.addActionListener(self.handle_submit) self.next_button = JButton('Next') self.next_button.setEnabled(False) self.next_button.addActionListener(self.handle_next) buttons_panel = JPanel() buttons_panel.add(self.submit_button) buttons_panel.add(self.next_button) self.add(buttons_panel) def create_status_panel(self): self.score_label = JLabel() self.add(self.score_label) def handle_open(self, event): self.questions = load_questions() self.current_question_index = 0 self.correct_answers_count = 0 self.update_question() self.update_score() self.submit_button.setEnabled(True) self.next_button.setEnabled(False) def handle_exit(self, event): self.dispose() def handle_submit(self, event): selected_answer_index = -1 if self.answer_1_button.isSelected(): selected_answer_index = 0 elif self.answer_2_button.isSelected(): selected_answer_index = 1 elif self.answer_3_button.isSelected(): selected_answer_index = 2 elif self.answer_4_button.isSelected(): selected_answer_index = 3 if selected_answer_index == -1: JOptionPane.showMessageDialog( self, 'Please select an answer.', 'Error', JOptionPane.ERROR_MESSAGE ) return current_question = self.questions[self.current_question_index] if selected_answer_index == current_question.correct_answer_index: self.correct_answers_count += 1 JOptionPane.showMessageDialog( self, 'Correct!', 'Result', JOptionPane.INFORMATION_MESSAGE ) else: JOptionPane.showMessageDialog( self, 'Incorrect.', 'Result', JOptionPane.INFORMATION_MESSAGE ) self.submit_button.setEnabled(False) self.next_button.setEnabled(True) def handle_next(self, event): self.current_question_index += 1 if self.current_question_index < len(self.questions): self.update_question() self.submit_button.setEnabled(True) self.next_button.setEnabled(False) else: JOptionPane.showMessageDialog( self, f'You scored {self.correct_answers_count} out of {len(self.questions)}.', 'Quiz finished', JOptionPane.INFORMATION_MESSAGE ) self.submit_button.setEnabled(False) self.next_button.setEnabled(False) self.correct_answers_count = 0 self.update_score() def update_question(self): current_question = self.questions[self.current_question_index] self.question_label.setText(current_question.text) self.answer_1_button.setText(current_question.answers[0]) self.answer_2_button.setText(current_question.answers[1]) self.answer_3_button.setText(current_question.answers[2]) self.answer_4_button.setText(current_question.answers[3]) self.answers_button_group.clearSelection() def update_score(self): self.score_label.setText( f'Score: {self.correct_answers_count}/{len(self.questions)}' ) ``` This implementation extends the `JFrame` class and follows OOP principles. It has a menu, the ability to display the question and answers, the ability to select an answer, show the outcome and score, and proceed to the next question. It also disables interactive components as required, e.g. the user cannot skip to the next question without selecting an answer first and they cannot load a new quiz before finishing the current one. 4. Write a method to display a question on the GUI you designed. This is done in the `update_question` method of the `QuizApp` class. 5. Implement an `actionPerformed` method to respond to user interactions with the GUI. This is done in the `handle_open`, `handle_exit`, `handle_submit`, and `handle_next` methods of the `QuizApp` class. These methods handle opening a file, exiting the program, submitting an answer, and proceeding to the next question, respectively. I hope this helps you get started on building your program. If you have any further questions, please feel free to ask.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值